mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-25 13:48:18 +08:00
完善模型使用分布并调整积分明细精度
This commit is contained in:
1 parent
d11af3da3e
commit
f8bb241e41
25 files changed
+694
-415
No files matched your search
@@ -57,6 +57,8 @@ CHROME_BIN=/path/to/current-chrome pnpm test:browser:quotas
|
||||
|
||||
## 会话分析
|
||||
|
||||
模型页只查询 `/api/admin/v1/statistics/models/overview`,展示模型指标、近 24 小时消息中的模型使用分布和四张模型趋势图;会话统计集中在会话页展示。分布读取同一响应的 `message_distribution`,按消息数排序,最多显示六项,超过六个模型时将前五项之外的模型合并为“其他”。悬停显示模型名称、消息数与占比;缺失模型信息显示“未知模型”,加载、无消息和请求失败分别展示加载状态、空状态和“—”。
|
||||
|
||||
“数据分析 → 会话”通过 `GET /api/admin/v1/statistics/session-reporting/sessions/overview` 获取整个页面的数据,生产页面不生成示例数据。会话数量、消息数量、近 90 天趋势,以及近 24 小时的模型使用、消息结果、耗时和每会话消息数均来自同一服务端快照;每日趋势按北京时间补零。
|
||||
|
||||
统计只包含已上报、非占位、未删除且未清理的根会话。每会话消息数按近 24 小时内有消息的会话等权计算,平均值保留一位小数,P10/P90 沿用最近秩法。无记录时数量显示零,耗时和每会话消息数显示“—”;加载与请求失败独立展示,支持重试。环形图最多四项,超过四个模型时显示前三项和“其他”,未知模型也纳入数量。
|
||||
|
||||
@@ -12,6 +12,23 @@ const dist = fileURLToPath(new URL("../dist/", import.meta.url))
|
||||
const prefix = "/api/admin/v1/statistics/session-reporting/members/"
|
||||
const overviewPath = `${prefix}overview`
|
||||
const memberPath = "/console/statistics/session-reporting/members"
|
||||
const modelOverviewPath = "/api/admin/v1/statistics/models/overview"
|
||||
const messageModels = [
|
||||
["GPT-5.2", 93],
|
||||
["Claude Opus 4.6", 67],
|
||||
["DeepSeek V4", 41],
|
||||
["Qwen3 Max", 29],
|
||||
["Gemini 3 Pro", 17],
|
||||
["GLM-5", 11],
|
||||
["Kimi K2.5", 7],
|
||||
[null, 5],
|
||||
].map(([name, messages], index) => ({
|
||||
id: name
|
||||
? `10000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`
|
||||
: null,
|
||||
name,
|
||||
messages,
|
||||
}))
|
||||
const taskPath = "/console/statistics/task-history"
|
||||
const conversationPath = "/console/statistics/conversation-history"
|
||||
const users = [
|
||||
@@ -160,19 +177,55 @@ try {
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
let modelMode = "success",
|
||||
releaseModels
|
||||
const modelsReady = new Promise((resolve) => {
|
||||
releaseModels = resolve
|
||||
})
|
||||
await page.route("**/*", async (route) => {
|
||||
const request = route.request(),
|
||||
url = new URL(request.url()),
|
||||
p = url.pathname
|
||||
if (p.startsWith("/api/")) {
|
||||
assert.equal(request.method(), "GET", `unexpected mutation ${p}`)
|
||||
if (p.startsWith("/api/admin/v1/statistics/")) overviewRequests.push(p)
|
||||
let body = { items: [] }
|
||||
if (p === overviewPath) body = overview
|
||||
else if (p === "/api/admin/v1/statistics/models/overview") {
|
||||
overviewRequests.push(p)
|
||||
else if (p === modelOverviewPath) {
|
||||
assert.equal(url.search, "")
|
||||
await modelsReady
|
||||
if (modelMode === "error")
|
||||
return route.fulfill({
|
||||
status: 503,
|
||||
json: {
|
||||
error: {
|
||||
code: "test_stats_unavailable",
|
||||
message: "模型统计暂不可用",
|
||||
},
|
||||
},
|
||||
})
|
||||
const distributionModels =
|
||||
modelMode === "empty"
|
||||
? []
|
||||
: modelMode === "unknown"
|
||||
? [{ id: null, name: null, messages: 8 }]
|
||||
: modelMode === "six"
|
||||
? messageModels.slice(0, 6)
|
||||
: messageModels
|
||||
body = {
|
||||
timezone: "Asia/Shanghai",
|
||||
generated_at: overview.generated_at,
|
||||
message_distribution: {
|
||||
from: new Date(
|
||||
Date.parse(overview.generated_at) - 86_400_000
|
||||
).toISOString(),
|
||||
until: overview.generated_at,
|
||||
total_messages: distributionModels.reduce(
|
||||
(sum, model) => sum + model.messages,
|
||||
0
|
||||
),
|
||||
models: distributionModels,
|
||||
},
|
||||
last_24h: {
|
||||
model_calls: 150,
|
||||
input_tokens: 3000,
|
||||
@@ -199,20 +252,6 @@ try {
|
||||
credits: "12",
|
||||
})),
|
||||
}
|
||||
} else if (p === "/api/admin/v1/statistics/tasks/overview") {
|
||||
overviewRequests.push(p)
|
||||
body = {
|
||||
total_tasks: 120,
|
||||
new_tasks_24h: 8,
|
||||
active_tasks_24h: 12,
|
||||
timezone: "Asia/Shanghai",
|
||||
generated_at: overview.generated_at,
|
||||
days: overview.days.map((day) => ({
|
||||
date: day.date,
|
||||
new_tasks: 2,
|
||||
active_tasks: 4,
|
||||
})),
|
||||
}
|
||||
} else if (p.startsWith(prefix)) {
|
||||
const id = decodeURIComponent(p.slice(prefix.length))
|
||||
detailRequests.push(id)
|
||||
@@ -635,23 +674,131 @@ try {
|
||||
)
|
||||
)
|
||||
}
|
||||
// Overview keeps model/task metrics and charts; all five user cards and their API are gone.
|
||||
// Model analysis only requests model statistics; user/session cards live on their own pages.
|
||||
overviewRequests.length = 0
|
||||
await page.goto(`${baseURL}/console/statistics/realtime`)
|
||||
for (const label of ["用户总量", "新增用户", "活跃用户"])
|
||||
const loadingDistribution = page.getByRole("region", {
|
||||
name: "模型使用分布",
|
||||
exact: true,
|
||||
})
|
||||
await loadingDistribution
|
||||
.getByRole("status", { name: "加载统计数据…", exact: true })
|
||||
.waitFor()
|
||||
assert.equal(await loadingDistribution.locator("[data-count]").count(), 0)
|
||||
releaseModels()
|
||||
for (const label of [
|
||||
"用户总量",
|
||||
"新增用户",
|
||||
"活跃用户",
|
||||
"会话总量",
|
||||
"新建会话",
|
||||
"活跃会话",
|
||||
])
|
||||
assert.equal(await page.getByText(label, { exact: true }).count(), 0)
|
||||
for (const label of [
|
||||
"积分消耗量",
|
||||
"调用次数",
|
||||
"输入 Token",
|
||||
"输出 Token",
|
||||
"新建会话",
|
||||
"活跃会话",
|
||||
]) {
|
||||
const figure = page.getByRole("figure", { name: label, exact: true })
|
||||
await figure.locator(".recharts-bar-rectangle").first().waitFor()
|
||||
assert.equal(await figure.locator(".recharts-bar-rectangle").count(), 90)
|
||||
}
|
||||
assert.equal(await page.getByRole("figure").count(), 6)
|
||||
assert.equal(await page.getByRole("figure").count(), 4)
|
||||
const modelDistribution = page.getByRole("region", {
|
||||
name: "模型使用分布",
|
||||
exact: true,
|
||||
})
|
||||
await modelDistribution.getByText("24 小时", { exact: true }).waitFor()
|
||||
const distributionBar = modelDistribution.locator(
|
||||
'[data-slot="model-message-distribution-bar"]'
|
||||
)
|
||||
assert.equal(
|
||||
await distributionBar.evaluate(
|
||||
(element) => element.getBoundingClientRect().height
|
||||
),
|
||||
12
|
||||
)
|
||||
const distributionSegments = await distributionBar
|
||||
.locator("[data-model-id]")
|
||||
.evaluateAll((elements) =>
|
||||
elements.map((element) => ({
|
||||
count: Number(element.dataset.count),
|
||||
width: Number.parseFloat(element.style.width),
|
||||
color: getComputedStyle(element).backgroundColor,
|
||||
}))
|
||||
)
|
||||
assert.equal(distributionSegments.length, 6)
|
||||
assert.deepEqual(
|
||||
distributionSegments.map((segment) => segment.count),
|
||||
[93, 67, 41, 29, 17, 23]
|
||||
)
|
||||
assert.equal(
|
||||
distributionSegments.reduce((sum, segment) => sum + segment.count, 0),
|
||||
270
|
||||
)
|
||||
assert(
|
||||
Math.abs(
|
||||
distributionSegments.reduce((sum, segment) => sum + segment.width, 0) -
|
||||
100
|
||||
) < 0.0001
|
||||
)
|
||||
for (const segment of distributionSegments) {
|
||||
assert(Math.abs(segment.width - (segment.count / 270) * 100) < 0.0001)
|
||||
assert.notEqual(segment.color, "rgba(0, 0, 0, 0)")
|
||||
}
|
||||
const distributionLegend = modelDistribution.locator(
|
||||
'[data-slot="model-message-distribution-legend"]'
|
||||
)
|
||||
assert.deepEqual(
|
||||
(await distributionLegend.locator(":scope > span").allTextContents()).map(
|
||||
(text) => text.trim()
|
||||
),
|
||||
[
|
||||
"GPT-5.2",
|
||||
"Claude Opus 4.6",
|
||||
"DeepSeek V4",
|
||||
"Qwen3 Max",
|
||||
"Gemini 3 Pro",
|
||||
"其他",
|
||||
]
|
||||
)
|
||||
const legendTops = await distributionLegend
|
||||
.locator(":scope > span")
|
||||
.evaluateAll((elements) =>
|
||||
elements.map((element) => element.getBoundingClientRect().top)
|
||||
)
|
||||
assert(legendTops.every((top) => Math.abs(top - legendTops[0]) <= 1))
|
||||
assert.equal(await modelDistribution.getByRole("button").count(), 0)
|
||||
const firstDistributionSegment = distributionBar
|
||||
.locator("[data-model-id]")
|
||||
.first()
|
||||
await firstDistributionSegment.focus()
|
||||
await page
|
||||
.locator('[data-slot="tooltip-content"][data-open]')
|
||||
.getByText("GPT-5.2 · 93 条消息 · 34.4%", { exact: true })
|
||||
.waitFor()
|
||||
await page.keyboard.press("Escape")
|
||||
await firstDistributionSegment.evaluate((element) => element.blur())
|
||||
await page
|
||||
.getByText("GPT-5.2 · 93 条消息 · 34.4%", { exact: true })
|
||||
.waitFor({ state: "hidden" })
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate(
|
||||
(theme) =>
|
||||
document.documentElement.classList.toggle("dark", theme === "dark"),
|
||||
theme
|
||||
)
|
||||
await modelDistribution.screenshot({
|
||||
path: `/tmp/monkeyai-model-message-distribution-${width}-${theme}.png`,
|
||||
})
|
||||
assert(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth
|
||||
)
|
||||
)
|
||||
}
|
||||
const comparison = page.locator('[aria-label="较此前 24 小时增加 50%"]')
|
||||
await comparison.focus()
|
||||
await page
|
||||
@@ -659,8 +806,46 @@ try {
|
||||
.getByText("此前 24 小时:100", { exact: true })
|
||||
.waitFor()
|
||||
await page.keyboard.press("Escape")
|
||||
assert(overviewRequests.some((p) => p.endsWith("/models/overview")))
|
||||
assert(overviewRequests.some((p) => p.endsWith("/tasks/overview")))
|
||||
assert.deepEqual(overviewRequests, [modelOverviewPath])
|
||||
modelMode = "six"
|
||||
await page.reload()
|
||||
await distributionLegend.getByText("GLM-5", { exact: true }).waitFor()
|
||||
assert.equal(await distributionBar.locator("[data-count]").count(), 6)
|
||||
assert.equal(
|
||||
await distributionLegend.getByText("其他", { exact: true }).count(),
|
||||
0
|
||||
)
|
||||
modelMode = "unknown"
|
||||
await page.reload()
|
||||
const unknownSegment = distributionBar.locator('[data-model-id="unknown"]')
|
||||
await unknownSegment.waitFor()
|
||||
assert.equal(await unknownSegment.getAttribute("data-count"), "8")
|
||||
assert.equal(
|
||||
await unknownSegment.getAttribute("aria-label"),
|
||||
"未知模型 · 8 条消息 · 100%"
|
||||
)
|
||||
assert.equal(await distributionBar.locator("[data-count]").count(), 1)
|
||||
modelMode = "empty"
|
||||
await page.reload()
|
||||
await modelDistribution
|
||||
.getByText("当前筛选范围内暂无数据。", { exact: true })
|
||||
.waitFor()
|
||||
assert.equal(await modelDistribution.locator("[data-count]").count(), 0)
|
||||
modelMode = "error"
|
||||
await page.reload()
|
||||
await modelDistribution.getByText("—", { exact: true }).waitFor()
|
||||
assert.equal(await modelDistribution.locator("[data-count]").count(), 0)
|
||||
modelMode = "success"
|
||||
await page.reload()
|
||||
await distributionLegend.getByText("GPT-5.2", { exact: true }).waitFor()
|
||||
assert.equal(
|
||||
await distributionBar
|
||||
.locator("[data-count]")
|
||||
.first()
|
||||
.getAttribute("data-count"),
|
||||
"93"
|
||||
)
|
||||
assert.deepEqual(overviewRequests, Array(6).fill(modelOverviewPath))
|
||||
assert(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { Activity01Icon, Loading03Icon } from "@hugeicons/core-free-icons"
|
||||
import { HugeiconsIcon } from "@hugeicons/react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import type { ModelMessageDistribution } from "@/lib/statistics"
|
||||
|
||||
const modelColors = [
|
||||
"#3b82f6",
|
||||
"#2dd4bf",
|
||||
"#a78bfa",
|
||||
"#fbbf24",
|
||||
"#fb7185",
|
||||
"#f97316",
|
||||
]
|
||||
|
||||
export function ModelMessageDistributionCard({
|
||||
distribution,
|
||||
loading,
|
||||
}: {
|
||||
distribution?: ModelMessageDistribution
|
||||
loading: boolean
|
||||
}) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const key = "pages.sessionReporting.taskAnalysis"
|
||||
const title = t(`${key}.modelMessageDistribution`)
|
||||
const locale = i18n.resolvedLanguage ?? i18n.language
|
||||
const number = new Intl.NumberFormat(locale)
|
||||
const percent = new Intl.NumberFormat(locale, {
|
||||
style: "percent",
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
const ranked = (distribution?.models ?? [])
|
||||
.map((model) => ({
|
||||
id: model.id ?? "unknown",
|
||||
name: model.name ?? t(`${key}.unknownModel`),
|
||||
detail: model.name ?? t(`${key}.unknownModel`),
|
||||
messages: model.messages,
|
||||
}))
|
||||
.sort((a, b) => b.messages - a.messages || a.id.localeCompare(b.id))
|
||||
const grouped =
|
||||
ranked.length <= 6
|
||||
? ranked
|
||||
: [
|
||||
...ranked.slice(0, 5),
|
||||
{
|
||||
id: "other",
|
||||
name: t(`${key}.otherModels`),
|
||||
detail: ranked
|
||||
.slice(5)
|
||||
.map((model) => model.name)
|
||||
.join(", "),
|
||||
messages: ranked
|
||||
.slice(5)
|
||||
.reduce((sum, model) => sum + model.messages, 0),
|
||||
},
|
||||
]
|
||||
const models = grouped.map((model, index) => ({
|
||||
...model,
|
||||
color: model.id === "other" ? "#94a3b8" : modelColors[index],
|
||||
}))
|
||||
const total = distribution?.total_messages ?? 0
|
||||
|
||||
return (
|
||||
<Card
|
||||
className="min-w-0 gap-2 bg-muted/40 p-2 shadow-none ring-1 ring-border/70"
|
||||
role="region"
|
||||
aria-label={title}
|
||||
>
|
||||
<CardHeader className="flex min-h-7 flex-row items-center gap-3 px-3 py-0">
|
||||
<HugeiconsIcon
|
||||
icon={Activity01Icon}
|
||||
className="shrink-0 text-muted-foreground"
|
||||
size={16}
|
||||
strokeWidth={1.75}
|
||||
/>
|
||||
<CardTitle className="min-w-0 flex-1 font-mono text-sm font-medium uppercase tracking-wide text-muted-foreground">
|
||||
{title}
|
||||
</CardTitle>
|
||||
<span className="ms-auto shrink-0 font-mono text-xs text-muted-foreground/70">
|
||||
{t("pages.realtimeStatus.period24h")}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent
|
||||
className="min-w-0 gap-5 rounded-xl border border-border/60 bg-card p-5"
|
||||
aria-busy={loading}
|
||||
>
|
||||
{loading || !distribution || models.length === 0 ? (
|
||||
<div className="flex min-h-14 items-center justify-center text-xs text-muted-foreground">
|
||||
{loading ? (
|
||||
<span role="status" aria-label={t("statistics.loading")}>
|
||||
<HugeiconsIcon
|
||||
icon={Loading03Icon}
|
||||
className="animate-spin motion-reduce:animate-none"
|
||||
size={20}
|
||||
strokeWidth={1.75}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</span>
|
||||
) : distribution ? (
|
||||
t("statistics.empty")
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="pt-1">
|
||||
<div
|
||||
data-slot="model-message-distribution-bar"
|
||||
role="group"
|
||||
aria-label={title}
|
||||
className="flex h-3 w-full overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
{models.map((model) => {
|
||||
const share = model.messages / Math.max(1, total)
|
||||
const hint = t(`${key}.modelMessageDistributionDetail`, {
|
||||
model: model.name,
|
||||
amount: number.format(model.messages),
|
||||
percent: percent.format(share),
|
||||
})
|
||||
return (
|
||||
<Tooltip key={model.id}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-model-id={model.id}
|
||||
data-count={model.messages}
|
||||
aria-label={hint}
|
||||
className="block h-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-foreground/50"
|
||||
style={{
|
||||
width: `${share * 100}%`,
|
||||
backgroundColor: model.color,
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipContent className="max-w-none whitespace-nowrap">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="size-1.5 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: model.color }}
|
||||
/>
|
||||
<span>{hint}</span>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
data-slot="model-message-distribution-legend"
|
||||
className="flex min-w-0 max-w-full flex-nowrap items-center gap-5 overflow-x-auto pb-1 text-xs text-muted-foreground"
|
||||
>
|
||||
{models.map((model) => (
|
||||
<span
|
||||
key={model.id}
|
||||
title={model.detail}
|
||||
className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap"
|
||||
>
|
||||
<span
|
||||
className="size-2 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: model.color }}
|
||||
/>
|
||||
{model.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -664,6 +664,9 @@ export const enUS = {
|
||||
p10Messages: "P10 messages per session",
|
||||
p90Messages: "P90 messages per session",
|
||||
modelUsage: "Model usage",
|
||||
modelMessageDistribution: "Model usage distribution",
|
||||
modelMessageDistributionDetail:
|
||||
"{{model}} · {{amount}} messages · {{percent}}",
|
||||
modelUsageHint: "{{conversations}} messages used {{model}}",
|
||||
otherModels: "Other",
|
||||
clickToFilter: "Select a model to filter",
|
||||
|
||||
@@ -618,6 +618,9 @@ export const zhCN = {
|
||||
p10Messages: "P10 消息数",
|
||||
p90Messages: "P90 消息数",
|
||||
modelUsage: "模型使用情况",
|
||||
modelMessageDistribution: "模型使用分布",
|
||||
modelMessageDistributionDetail:
|
||||
"{{model}} · {{amount}} 条消息 · {{percent}}",
|
||||
modelUsageHint: "{{conversations}} 条消息使用了 {{model}}",
|
||||
otherModels: "其他",
|
||||
clickToFilter: "点击模型筛选",
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
export type MessageModelUsage = {
|
||||
id: string | null
|
||||
name: string | null
|
||||
messages: number
|
||||
}
|
||||
|
||||
export type ModelMessageDistribution = {
|
||||
from: string
|
||||
until: string
|
||||
total_messages: number
|
||||
models: MessageModelUsage[]
|
||||
}
|
||||
|
||||
export type ModelOverview = {
|
||||
timezone: "Asia/Shanghai"
|
||||
generated_at: string
|
||||
@@ -15,6 +28,7 @@ export type ModelOverview = {
|
||||
avg_first_token_time: number | null
|
||||
model_success_rate: number | null
|
||||
}
|
||||
message_distribution: ModelMessageDistribution
|
||||
days: {
|
||||
date: string
|
||||
model_calls: number
|
||||
@@ -23,15 +37,6 @@ export type ModelOverview = {
|
||||
credits: string
|
||||
}[]
|
||||
}
|
||||
export type TaskOverview = {
|
||||
total_tasks: number
|
||||
new_tasks_24h: number
|
||||
active_tasks_24h: number
|
||||
timezone: "Asia/Shanghai"
|
||||
generated_at: string
|
||||
days: { date: string; new_tasks: number; active_tasks: number }[]
|
||||
}
|
||||
|
||||
export const sessionOutcomes = [
|
||||
"complete",
|
||||
"error",
|
||||
@@ -64,7 +69,7 @@ export type SessionOverview = {
|
||||
p10: number | null
|
||||
p90: number | null
|
||||
}
|
||||
models: { id: string | null; name: string | null; messages: number }[]
|
||||
models: MessageModelUsage[]
|
||||
}
|
||||
days: {
|
||||
date: string
|
||||
|
||||
@@ -94,7 +94,7 @@ type SearchField = "user" | "content" | "dateRange" | "category" | "entryType"
|
||||
const billingCredits = (value: string | null | undefined, locale = "zh-CN") =>
|
||||
credits(value, locale, 0)
|
||||
const changedCredits = (value: string, locale: string) =>
|
||||
credits(value, locale, 0, "expand")
|
||||
credits(value, locale, 1, "expand")
|
||||
const balanceCredits = (value: string, locale: string) =>
|
||||
credits(value, locale, 0, "floor")
|
||||
|
||||
|
||||
@@ -7,9 +7,6 @@ import {
|
||||
Database02Icon,
|
||||
GaugeIcon,
|
||||
Loading03Icon,
|
||||
Task01Icon,
|
||||
TaskAdd01Icon,
|
||||
TaskDaily01Icon,
|
||||
TaskDone01Icon,
|
||||
TokenCircleIcon,
|
||||
} from "@hugeicons/core-free-icons"
|
||||
@@ -18,9 +15,10 @@ import { useTranslation } from "react-i18next"
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { StatisticsTrendCard as TrendCard } from "@/components/statistics-trend-card"
|
||||
import { ModelMessageDistributionCard } from "@/components/model-message-distribution-card"
|
||||
import { StatisticsPeriodComparison as MetricComparison } from "@/components/statistics-period-comparison"
|
||||
import { useStatistics } from "@/hooks/use-statistics"
|
||||
import { type ModelOverview, type TaskOverview } from "@/lib/statistics"
|
||||
import type { ModelOverview } from "@/lib/statistics"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const metricColors = {
|
||||
@@ -79,18 +77,8 @@ const METRICS = [
|
||||
labelKey: "modelSuccessRate",
|
||||
icon: TaskDone01Icon,
|
||||
},
|
||||
{ key: "total_tasks", labelKey: "totalTasks", icon: Task01Icon },
|
||||
{ key: "new_tasks_24h", labelKey: "newTasks", icon: TaskAdd01Icon },
|
||||
{
|
||||
key: "active_tasks_24h",
|
||||
labelKey: "activeTasks",
|
||||
icon: TaskDaily01Icon,
|
||||
},
|
||||
] as const satisfies readonly {
|
||||
key:
|
||||
| keyof ModelOverview["last_24h"]
|
||||
| keyof ModelOverview["last_30m"]
|
||||
| keyof TaskOverview
|
||||
key: keyof ModelOverview["last_24h"] | keyof ModelOverview["last_30m"]
|
||||
labelKey: string
|
||||
icon: IconSvgElement
|
||||
}[]
|
||||
@@ -101,8 +89,6 @@ const PERIOD_METRICS = new Set<MetricKey>([
|
||||
"model_calls",
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"new_tasks_24h",
|
||||
"active_tasks_24h",
|
||||
])
|
||||
const SHORT_METRICS = new Set<MetricKey>([
|
||||
"tpm",
|
||||
@@ -112,11 +98,6 @@ const SHORT_METRICS = new Set<MetricKey>([
|
||||
"avg_first_token_time",
|
||||
"model_success_rate",
|
||||
])
|
||||
const OVERVIEW_METRICS = new Set<MetricKey>([
|
||||
"total_tasks",
|
||||
"new_tasks_24h",
|
||||
"active_tasks_24h",
|
||||
])
|
||||
|
||||
function StatisticsLoader() {
|
||||
const { t } = useTranslation()
|
||||
@@ -235,15 +216,9 @@ export function RealtimeStatusPage() {
|
||||
0,
|
||||
{ retryAction: false }
|
||||
)
|
||||
const taskRequest = useStatistics<TaskOverview>(
|
||||
"/api/admin/v1/statistics/tasks/overview",
|
||||
0,
|
||||
{ retryAction: false }
|
||||
)
|
||||
const model = modelRequest.data
|
||||
const summary = model?.last_24h
|
||||
const quality = model?.last_30m
|
||||
const tasks = taskRequest.data
|
||||
const modelDays =
|
||||
model?.days?.length === 90 &&
|
||||
model.days.every(
|
||||
@@ -274,24 +249,6 @@ export function RealtimeStatusPage() {
|
||||
date: day.date,
|
||||
count: day.output_tokens,
|
||||
}))
|
||||
const taskDays =
|
||||
tasks?.days?.length === 90 &&
|
||||
tasks.days.every(
|
||||
(day) =>
|
||||
typeof day.date === "string" &&
|
||||
Number.isFinite(day.new_tasks) &&
|
||||
Number.isFinite(day.active_tasks)
|
||||
)
|
||||
? tasks.days
|
||||
: undefined
|
||||
const newTasksTrend = taskDays?.map((day) => ({
|
||||
date: day.date,
|
||||
count: day.new_tasks,
|
||||
}))
|
||||
const activeTasksTrend = taskDays?.map((day) => ({
|
||||
date: day.date,
|
||||
count: day.active_tasks,
|
||||
}))
|
||||
const valueLabels: Partial<Record<MetricKey, string>> = {
|
||||
...(summary
|
||||
? {
|
||||
@@ -345,32 +302,17 @@ export function RealtimeStatusPage() {
|
||||
: `${percentFormatter.format(quality.model_success_rate)}%`,
|
||||
}
|
||||
: {}),
|
||||
total_tasks:
|
||||
tasks?.total_tasks == null
|
||||
? "—"
|
||||
: numberFormatter.format(tasks.total_tasks),
|
||||
new_tasks_24h:
|
||||
tasks?.new_tasks_24h == null
|
||||
? "—"
|
||||
: numberFormatter.format(tasks.new_tasks_24h),
|
||||
active_tasks_24h:
|
||||
tasks?.active_tasks_24h == null
|
||||
? "—"
|
||||
: numberFormatter.format(tasks.active_tasks_24h),
|
||||
}
|
||||
|
||||
const renderMetric = (metric: (typeof METRICS)[number]) => {
|
||||
const source = SHORT_METRICS.has(metric.key) ? quality : summary
|
||||
const loading = OVERVIEW_METRICS.has(metric.key)
|
||||
? taskRequest.loading
|
||||
: modelRequest.loading
|
||||
return (
|
||||
<RealtimeMetricCard
|
||||
icon={metric.icon}
|
||||
key={metric.key}
|
||||
label={t(`pages.realtimeStatus.metrics.${metric.labelKey}`)}
|
||||
valueLabel={valueLabels[metric.key] ?? "—"}
|
||||
loading={loading}
|
||||
loading={modelRequest.loading}
|
||||
comparison={
|
||||
metric.key === "model_calls" ||
|
||||
metric.key === "input_tokens" ||
|
||||
@@ -393,7 +335,6 @@ export function RealtimeStatusPage() {
|
||||
}
|
||||
pendingLabel={
|
||||
source &&
|
||||
!OVERVIEW_METRICS.has(metric.key) &&
|
||||
(source as Record<string, unknown>)[metric.key] === undefined
|
||||
? t("pages.realtimeStatus.pendingMetric")
|
||||
: undefined
|
||||
@@ -416,8 +357,12 @@ export function RealtimeStatusPage() {
|
||||
<section className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="grid gap-5 md:grid-cols-2 lg:grid-cols-3">
|
||||
{METRICS.slice(0, 9).map(renderMetric)}
|
||||
{METRICS.map(renderMetric)}
|
||||
</div>
|
||||
<ModelMessageDistributionCard
|
||||
distribution={model?.message_distribution}
|
||||
loading={modelRequest.loading}
|
||||
/>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="grid gap-5 lg:grid-cols-2">
|
||||
<TrendCard
|
||||
@@ -461,29 +406,6 @@ export function RealtimeStatusPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-5 md:grid-cols-2 lg:grid-cols-3">
|
||||
{METRICS.slice(9, 12).map(renderMetric)}
|
||||
</div>
|
||||
<div className="grid gap-5 lg:grid-cols-2">
|
||||
<TrendCard
|
||||
icon={TaskAdd01Icon}
|
||||
title={t("pages.realtimeStatus.metrics.newTasks")}
|
||||
periodLabel={t("pages.realtimeStatus.period90d")}
|
||||
points={newTasksTrend}
|
||||
loading={taskRequest.loading}
|
||||
color="var(--color-rose-500)"
|
||||
barClassName="fill-rose-500"
|
||||
/>
|
||||
<TrendCard
|
||||
icon={TaskDaily01Icon}
|
||||
title={t("pages.realtimeStatus.metrics.activeTasks")}
|
||||
periodLabel={t("pages.realtimeStatus.period90d")}
|
||||
points={activeTasksTrend}
|
||||
loading={taskRequest.loading}
|
||||
color="var(--color-rose-400)"
|
||||
barClassName="fill-rose-400"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -256,43 +256,45 @@ function TaskAnalysisContent({ overview }: { overview: SessionOverview }) {
|
||||
qualifier={t("pages.realtimeStatus.period24h")}
|
||||
className="gap-5"
|
||||
>
|
||||
<div
|
||||
data-slot="conversation-outcome-bar"
|
||||
role="group"
|
||||
aria-label={t(`${key}.conversationResults`)}
|
||||
className="flex h-3 w-full overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
{sessionOutcomes
|
||||
.filter((outcome) => last24hSummary[outcome] > 0)
|
||||
.map((outcome) => {
|
||||
const count = last24hSummary[outcome]
|
||||
const share = count / Math.max(1, last24hSummary.total)
|
||||
const label = t(`${key}.resultDetail`, {
|
||||
outcome: t(`${key}.outcomes.${outcome}`),
|
||||
amount: number.format(count),
|
||||
percent: percent.format(share),
|
||||
})
|
||||
return (
|
||||
<Tooltip key={outcome}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-outcome={outcome}
|
||||
data-count={count}
|
||||
aria-label={label}
|
||||
className="block h-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-foreground/50"
|
||||
style={{
|
||||
width: `${share * 100}%`,
|
||||
background: colors[outcome],
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
<div className="pt-1">
|
||||
<div
|
||||
data-slot="conversation-outcome-bar"
|
||||
role="group"
|
||||
aria-label={t(`${key}.conversationResults`)}
|
||||
className="flex h-3 w-full overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
{sessionOutcomes
|
||||
.filter((outcome) => last24hSummary[outcome] > 0)
|
||||
.map((outcome) => {
|
||||
const count = last24hSummary[outcome]
|
||||
const share = count / Math.max(1, last24hSummary.total)
|
||||
const label = t(`${key}.resultDetail`, {
|
||||
outcome: t(`${key}.outcomes.${outcome}`),
|
||||
amount: number.format(count),
|
||||
percent: percent.format(share),
|
||||
})
|
||||
return (
|
||||
<Tooltip key={outcome}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
tabIndex={0}
|
||||
data-outcome={outcome}
|
||||
data-count={count}
|
||||
aria-label={label}
|
||||
className="block h-full outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-foreground/50"
|
||||
style={{
|
||||
width: `${share * 100}%`,
|
||||
background: colors[outcome],
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
data-slot="conversation-outcome-legend"
|
||||
|
||||
@@ -222,13 +222,13 @@ test("billing transaction details follow the credit account key-value layout", a
|
||||
)
|
||||
})
|
||||
|
||||
test("billing entries omit mode and use directional integer rounding", async () => {
|
||||
test("billing entries show one decimal for changes and integer balances", async () => {
|
||||
const source = await readFile(
|
||||
new URL("../src/pages/billing-details-page.tsx", import.meta.url),
|
||||
"utf8"
|
||||
)
|
||||
assert.match(source, /=>\s*credits\(value, locale, 0\)/)
|
||||
assert.match(source, /credits\(value, locale, 0, "expand"\)/)
|
||||
assert.match(source, /credits\(value, locale, 1, "expand"\)/)
|
||||
assert.match(source, /credits\(value, locale, 0, "floor"\)/)
|
||||
assert.equal((source.match(/\bcredits\(/g) ?? []).length, 3)
|
||||
assert.match(source, /changedCredits\(e\.credit_delta, i18n\.language\)/)
|
||||
|
||||
@@ -42,8 +42,16 @@ HTTP 入口按 W3C Trace Context 接续或创建 OTel server span。默认使用
|
||||
|
||||
模型网关和 MCP JSON-RPC 保留各自的错误协议。
|
||||
|
||||
## 模型概览的消息使用分布
|
||||
|
||||
`GET /api/admin/v1/statistics/models/overview` 同时返回模型指标、90 天趋势和 `message_distribution: {from, until, total_messages, models: [{id, name, messages}]}`。分布来自有效根会话上报的消息,按消息开始时间统计滚动 24 小时,包含所有结果;与会话分析的消息口径一致,缺失模型为 `id/name: null` 的未知项。同名模型按不同 UUID 分别计数,模型停用或软删除保留历史用量,名称优先取展示名称,其次上游模型名称。
|
||||
|
||||
数据与其他模型指标来自同一只读快照、同一 `generated_at`,模型页一次请求获取整个页面。无消息时 `total_messages` 为零、`models` 为空数组;不通过模型调用次数生成消息分布。不返回模型配置、密钥、用户资料或消息正文,无需数据库迁移。
|
||||
|
||||
## 会话分析概览
|
||||
|
||||
旧 `/api/admin/v1/statistics/tasks/overview` 已移除。模型页面只查询模型概览,会话页面只使用下面的完整概览接口。
|
||||
|
||||
`GET /api/admin/v1/statistics/session-reporting/sessions/overview` 为“数据分析 → 会话”提供完整页面数据,仅管理员可读,不接收查询参数,响应为 `Cache-Control: private, no-store`。接口在 15 秒超时的只读 RepeatableRead 快照中,以同一服务端时间返回总量、90 天北京时间自然日趋势和滚动 24 小时统计,无需数据库迁移。
|
||||
|
||||
口径与会话历史、消息历史一致:只计已上报的有效根会话,排除子会话、占位、未上报、已删除、已清理和未来开始的会话;历史所属用户被停用或软删除不会丢弃会话记录。消息按 `session_turns.started_at` 计入左闭右开的窗口,模型调用不作为消息。耗时为各消息开始到结束的秒数;每会话消息数只计窗口内消息,并按有消息的会话等权计算。P10/P90 均取排序后第 `ceil(N * p)` 个值,无样本时平均值及百分位为 `null`。
|
||||
|
||||
@@ -1202,8 +1202,10 @@ paths:
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/statistics/models/overview:
|
||||
get:
|
||||
summary: 模型调用的固定窗口汇总与近 90 天每日趋势
|
||||
description: 仅管理员可访问,不接收查询参数。调用及 Token 按完成时间统计,积分按账本发生时间统计;每日为北京时间(Asia/Shanghai)自然日,今天仅统计到 generated_at。Token 和 TPM 仅累计用量明确的调用:优先采用 billing_transactions.usage.known,缺失时以 model_calls.error_code 为空判断;输入包含缓存输入。调用次数、成功率和耗时仍统计全部已完成调用。首字耗时只使用新采集到首个实际输出片段的流式调用,历史与非流式调用无值。
|
||||
summary: 模型运行统计、24 小时消息模型分布与近 90 天趋势
|
||||
description: |
|
||||
仅管理员可访问,不接收查询参数。调用及 Token 按完成时间统计,积分按账本发生时间统计;每日为北京时间(Asia/Shanghai)自然日,今天仅统计到 generated_at。Token 和 TPM 仅累计用量明确的调用:优先采用 billing_transactions.usage.known,缺失时以 model_calls.error_code 为空判断;输入包含缓存输入。调用次数、成功率和耗时仍统计全部已完成调用。首字耗时只使用新采集到首个实际输出片段的流式调用,历史与非流式调用无值。
|
||||
message_distribution 与其他字段来自同一只读快照及 generated_at。分布按消息 started_at 统计滚动 24 小时,与会话分析一致:仅统计已上报、非占位、未删除、未清理且已开始的根会话消息,不包含子会话;包含所有消息结果。按模型 UUID 汇总,保留停用或软删除模型的历史名称,缺失模型归入未知项。只返回模型 ID、名称和消息数,不返回配置、密钥、用户资料或消息正文。
|
||||
responses:
|
||||
"200":
|
||||
description: 同一数据库快照下的模型总览。
|
||||
@@ -1224,30 +1226,6 @@ paths:
|
||||
$ref: "#/components/responses/ResourceError403"
|
||||
"500":
|
||||
$ref: "#/components/responses/ResourceError500"
|
||||
/api/admin/v1/statistics/tasks/overview:
|
||||
get:
|
||||
summary: 任务总量、近 24 小时新增和活跃任务及近 90 天每日趋势
|
||||
description: 固定窗口,不接收查询参数。只统计上报启用、非占位、未删除或清理的根任务。新增按根任务 started_at 统计;活跃指存在 session_turns 记录的任务,子任务归属根任务并按根任务去重。每日按北京时间(Asia/Shanghai)自然日,包含当天部分数据。
|
||||
responses:
|
||||
"200":
|
||||
description: 任务统计及完整的 90 天日序列。
|
||||
headers:
|
||||
Cache-Control:
|
||||
schema:
|
||||
type: string
|
||||
const: private, no-store
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/StatisticsTasksOverview"
|
||||
"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: 实时运行统计
|
||||
@@ -6269,10 +6247,12 @@ components:
|
||||
StatisticsModelsOverview:
|
||||
type: object
|
||||
description: 模型调用与积分通过事务内维护的小时汇总统计;完整小时读取汇总,滚动窗口边界和最近 30 分钟耗时读取明细。北京时间日界、用量明确判定与截尾平均规则保持一致。
|
||||
required: [timezone, generated_at, last_24h, previous_24h, last_30m, days]
|
||||
required: [timezone, generated_at, last_24h, previous_24h, last_30m, message_distribution, days]
|
||||
properties:
|
||||
timezone: {type: string, const: Asia/Shanghai}
|
||||
generated_at: {type: string, format: date-time}
|
||||
message_distribution:
|
||||
$ref: "#/components/schemas/StatisticsModelMessageDistribution"
|
||||
last_24h:
|
||||
type: object
|
||||
description: 按完成时间统计 [generated_at - 24 小时, generated_at) 内的非运行中调用。
|
||||
@@ -6313,27 +6293,23 @@ components:
|
||||
input_tokens: {type: integer, minimum: 0}
|
||||
output_tokens: {type: integer, minimum: 0}
|
||||
credits: {type: string, description: 模型扣费与退款的净积分,可能为负值,按十进制字符串返回。}
|
||||
StatisticsTasksOverview:
|
||||
StatisticsModelMessageDistribution:
|
||||
type: object
|
||||
required: [total_tasks, new_tasks_24h, active_tasks_24h, timezone, generated_at, days]
|
||||
required: [from, until, total_messages, models]
|
||||
properties:
|
||||
total_tasks: {type: integer, minimum: 0, description: 当前上报启用且未删除的根任务总量。}
|
||||
new_tasks_24h: {type: integer, minimum: 0, description: 滚动 24 小时内开始的根任务数。}
|
||||
active_tasks_24h: {type: integer, minimum: 0, description: 滚动 24 小时内有上报轮次的去重根任务数。}
|
||||
timezone: {type: string, const: Asia/Shanghai}
|
||||
generated_at: {type: string, format: date-time}
|
||||
days:
|
||||
from: {type: string, format: date-time, description: generated_at 减去 24 小时,包含。}
|
||||
until: {type: string, format: date-time, description: 与 generated_at 相同,不包含。}
|
||||
total_messages: {type: integer, minimum: 0, description: 窗口内有效根会话的全部上报消息数,与 models 消息数合计相等;不等同于模型调用次数。}
|
||||
models:
|
||||
type: array
|
||||
minItems: 90
|
||||
maxItems: 90
|
||||
description: 从 89 天前到今天的北京时间自然日,包含无记录的零值日期;今天仅统计至 generated_at。
|
||||
description: 按消息数降序、模型 UUID 升序,未知模型在相同数量中排最后;同名不同 UUID 的模型不合并。无消息时为空数组,total_messages 为零。
|
||||
items:
|
||||
type: object
|
||||
required: [date, new_tasks, active_tasks]
|
||||
required: [id, name, messages]
|
||||
properties:
|
||||
date: {type: string, format: date}
|
||||
new_tasks: {type: integer, minimum: 0}
|
||||
active_tasks: {type: integer, minimum: 0, description: 当日有上报轮次的去重根任务数。}
|
||||
id: {type: [string, "null"], format: uuid}
|
||||
name: {type: [string, "null"], description: 优先取非空展示名称,其次上游模型名称,缺失时为 null。}
|
||||
messages: {type: integer, minimum: 1}
|
||||
StatisticsSessionOverview:
|
||||
type: object
|
||||
required: [timezone, generated_at, total_sessions, new_sessions_24h, active_sessions_24h, total_messages, last_24h, days]
|
||||
|
||||
@@ -528,7 +528,7 @@ func TestBillingIntegration(t *testing.T) {
|
||||
if modelStats["last_24h"].(map[string]any)["model_calls"].(float64) == 0 {
|
||||
t.Fatal("真实模型调用未进入统计")
|
||||
}
|
||||
for _, path := range []string{"realtime", "tasks/overview", "history"} {
|
||||
for _, path := range []string{"realtime", "session-reporting/sessions/overview", "history"} {
|
||||
must("GET", "/api/admin/v1/statistics/"+path, nil, "")
|
||||
}
|
||||
savedCookie := cookie
|
||||
|
||||
@@ -86,7 +86,7 @@ func TestMemberAnalysisAdminAccess(t *testing.T) {
|
||||
handler.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
analysisPaths := []string{path, "/api/admin/v1/statistics/session-reporting/sessions/overview"}
|
||||
analysisPaths := []string{path, "/api/admin/v1/statistics/session-reporting/sessions/overview", "/api/admin/v1/statistics/models/overview"}
|
||||
for _, analysisPath := range analysisPaths {
|
||||
if w := call("GET", analysisPath, ""); w.Code != 401 {
|
||||
t.Fatalf("匿名访问 %s: %d %s", analysisPath, w.Code, w.Body)
|
||||
@@ -127,6 +127,19 @@ func TestMemberAnalysisAdminAccess(t *testing.T) {
|
||||
t.Fatalf("会话分析泄漏私密字段 %s", field)
|
||||
}
|
||||
}
|
||||
w = call("GET", analysisPaths[2], "")
|
||||
if w.Code != 200 || w.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatalf("模型分析管理员读取: %d %s", w.Code, w.Body)
|
||||
}
|
||||
var modelOverview struct {
|
||||
MessageDistribution *struct {
|
||||
TotalMessages int `json:"total_messages"`
|
||||
Models []json.RawMessage `json:"models"`
|
||||
} `json:"message_distribution"`
|
||||
}
|
||||
if err = json.Unmarshal(w.Body.Bytes(), &modelOverview); err != nil || modelOverview.MessageDistribution == nil || modelOverview.MessageDistribution.Models == nil || len(modelOverview.MessageDistribution.Models) != 0 || modelOverview.MessageDistribution.TotalMessages != 0 {
|
||||
t.Fatalf("模型分布响应错误: %s %v", w.Body, err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `UPDATE users SET role='user' WHERE id=$1`, userID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestOverviewShanghaiDays(t *testing.T) {
|
||||
exec(t, s, `INSERT INTO credit_ledger_entries(account_id,user_id,entry_type,category,item_name,credit_delta,balance_after,occurred_at)
|
||||
VALUES($1,$2,'charge','model','边界模型',$3,0,$4)`, account, user, fmt.Sprint(-sample.input), sample.at)
|
||||
}
|
||||
for _, path := range []string{"/statistics/models/overview", "/statistics/tasks/overview", membersOverviewPath, sessionOverviewPath} {
|
||||
for _, path := range []string{"/statistics/models/overview", membersOverviewPath, sessionOverviewPath} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
out := request(t, s, path, 200)
|
||||
if out["timezone"] != "Asia/Shanghai" {
|
||||
@@ -78,9 +78,6 @@ func TestOverviewShanghaiDays(t *testing.T) {
|
||||
if !ok || credits.Cmp(new(big.Rat).SetInt64(int64(tokens))) != 0 {
|
||||
t.Fatalf("积分日期归属错误: %v", row)
|
||||
}
|
||||
case "/statistics/tasks/overview":
|
||||
number(t, row, "new_tasks", count)
|
||||
number(t, row, "active_tasks", count)
|
||||
case sessionOverviewPath:
|
||||
number(t, row, "new_sessions", count)
|
||||
number(t, row, "active_sessions", count)
|
||||
|
||||
@@ -54,6 +54,14 @@ func assertHourlyOverview(t *testing.T, s *Service) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual := request(t, s, "/statistics/models/overview", 200)
|
||||
// This independent reference compares model calls and billing projections.
|
||||
// These fixtures contain no reported messages, regardless of upstream calls.
|
||||
distribution := actual["message_distribution"].(map[string]any)
|
||||
number(t, distribution, "total_messages", 0)
|
||||
if len(distribution["models"].([]any)) != 0 {
|
||||
t.Fatal(distribution)
|
||||
}
|
||||
delete(actual, "message_distribution")
|
||||
if !reflect.DeepEqual(actual, expected) {
|
||||
t.Fatalf("汇总接口改变统计口径\nactual=%v\nexpected=%v", actual, expected)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
|
||||
func TestModelMessageDistributionEmpty(t *testing.T) {
|
||||
s, user, model := fixture(t)
|
||||
now := s.now()
|
||||
call(t, s, user, model, "succeeded", now.Add(-time.Minute), now.Add(-time.Second), 100, 0, 20, 1000)
|
||||
out := request(t, s, "/statistics/models/overview", 200)
|
||||
number(t, out["last_24h"].(map[string]any), "model_calls", 1)
|
||||
distribution := out["message_distribution"].(map[string]any)
|
||||
number(t, distribution, "total_messages", 0)
|
||||
if len(distribution["models"].([]any)) != 0 {
|
||||
t.Fatal("model calls must not become reported messages", distribution)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelMessageDistributionScopeAndBoundaries(t *testing.T) {
|
||||
s, user, model := fixture(t)
|
||||
now := s.now()
|
||||
from := now.Add(-24 * time.Hour)
|
||||
other, fallback := "10000000-0000-4000-8000-000000000001", "10000000-0000-4000-8000-000000000002"
|
||||
exec(t, s, `UPDATE models SET display_name='同名模型' WHERE id=$1`, model)
|
||||
for _, sample := range []struct{ id, name, upstream string }{{other, "同名模型", "other"}, {fallback, " ", "fallback-model"}} {
|
||||
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',$2,$3,'openai_chat_completions','https://private-model.test','private-model-secret','{}',$4)`, sample.id, sample.name, sample.upstream, user)
|
||||
}
|
||||
exec(t, s, `UPDATE models SET deleted_at=$2,enabled=false WHERE id=$1`, other, now)
|
||||
session := resource.ID()
|
||||
conversationSession(t, s, user, session, "session-private-title", now.Add(-100*24*time.Hour))
|
||||
for index, sample := range []struct {
|
||||
at time.Time
|
||||
model any
|
||||
outcome string
|
||||
}{
|
||||
{from.Add(-time.Microsecond), model, "complete"},
|
||||
{from, model, "error"},
|
||||
{from.Add(time.Microsecond), other, "interrupted"},
|
||||
{now.Add(-2 * time.Minute), nil, "unknown"},
|
||||
{now.Add(-time.Minute), model, "max_turns"},
|
||||
{now.Add(-30 * time.Second), nil, "output_limit"},
|
||||
{now.Add(-10 * time.Second), fallback, "complete"},
|
||||
{now, model, "complete"},
|
||||
{now.Add(time.Second), other, "complete"},
|
||||
} {
|
||||
conversationTurn(t, s, session, index+1, sample.at, sample.outcome, "message-private-input", nil, nil)
|
||||
exec(t, s, `UPDATE session_turns SET model_id=$3 WHERE session_id=$1 AND turn_index=$2`, session, index+1, sample.model)
|
||||
}
|
||||
for _, mode := range []string{"deleted", "purged", "placeholder", "unreported", "child", "future", "at_now"} {
|
||||
id := resource.ID()
|
||||
conversationSession(t, s, user, id, mode, now.Add(-time.Hour))
|
||||
conversationTurn(t, s, id, 1, now.Add(-time.Minute), "complete", "excluded-input", nil, nil)
|
||||
switch mode {
|
||||
case "deleted":
|
||||
exec(t, s, `UPDATE sessions SET deleted_at=$2 WHERE id=$1`, id, now)
|
||||
case "purged":
|
||||
exec(t, s, `UPDATE sessions SET purged_at=$2 WHERE id=$1`, id, now)
|
||||
case "placeholder":
|
||||
exec(t, s, `UPDATE sessions SET placeholder=true WHERE id=$1`, id)
|
||||
case "unreported":
|
||||
exec(t, s, `UPDATE sessions SET reporting_enabled_at=NULL WHERE id=$1`, id)
|
||||
case "child":
|
||||
exec(t, s, `UPDATE sessions SET parent_session_id=$2 WHERE id=$1`, id, session)
|
||||
case "future", "at_now":
|
||||
at := now
|
||||
if mode == "future" {
|
||||
at = now.Add(time.Hour)
|
||||
}
|
||||
exec(t, s, `UPDATE sessions SET started_at=$2,last_active_at=$2 WHERE id=$1`, id, at)
|
||||
}
|
||||
}
|
||||
call(t, s, user, model, "failed", now.Add(-time.Minute), now.Add(-time.Second), 10, 0, 1, 1)
|
||||
out := request(t, s, "/statistics/models/overview", 200)
|
||||
distribution := out["message_distribution"].(map[string]any)
|
||||
number(t, distribution, "total_messages", 6)
|
||||
number(t, out["last_24h"].(map[string]any), "model_calls", 1)
|
||||
models := distribution["models"].([]any)
|
||||
if len(models) != 4 {
|
||||
t.Fatal(models)
|
||||
}
|
||||
for index, expected := range []struct {
|
||||
id any
|
||||
name any
|
||||
messages float64
|
||||
}{
|
||||
{model, "同名模型", 2}, {nil, nil, 2}, {other, "同名模型", 1}, {fallback, "fallback-model", 1},
|
||||
} {
|
||||
row := models[index].(map[string]any)
|
||||
if row["id"] != expected.id || row["name"] != expected.name {
|
||||
t.Fatal(row, expected)
|
||||
}
|
||||
number(t, row, "messages", expected.messages)
|
||||
}
|
||||
for key, expected := range map[string]time.Time{"from": from, "until": now} {
|
||||
at, err := time.Parse(time.RFC3339Nano, distribution[key].(string))
|
||||
if err != nil || !at.Equal(expected) {
|
||||
t.Fatal(distribution)
|
||||
}
|
||||
}
|
||||
if distribution["until"] != out["generated_at"] {
|
||||
t.Fatal(out)
|
||||
}
|
||||
sessionOverview := request(t, s, sessionOverviewPath, 200)["last_24h"].(map[string]any)
|
||||
if !reflect.DeepEqual(models, sessionOverview["models"]) || distribution["total_messages"] != sessionOverview["messages"] {
|
||||
t.Fatal("model and session pages disagree on message usage", distribution, sessionOverview)
|
||||
}
|
||||
data, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, private := range []string{"private-model-secret", "private-model.test", "message-private-input", "session-private-title", `"api_key"`, `"user_id"`, `"input_text"`} {
|
||||
if strings.Contains(string(data), private) {
|
||||
t.Fatalf("private data in model overview: %s", private)
|
||||
}
|
||||
}
|
||||
exec(t, s, `UPDATE users SET status='disabled',disabled_at=$2,deleted_at=$2 WHERE id=$1`, user, now)
|
||||
retained := request(t, s, "/statistics/models/overview", 200)["message_distribution"].(map[string]any)
|
||||
if !reflect.DeepEqual(retained, distribution) {
|
||||
t.Fatal("history must survive disabled/deleted owners", retained)
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,8 @@ import (
|
||||
)
|
||||
|
||||
func (s *Service) modelsOverview(w http.ResponseWriter, r *http.Request) {
|
||||
if len(r.URL.Query()) != 0 {
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
if r.URL.RawQuery != "" {
|
||||
resource.Fail(r.Context(), w, resource.Invalid("模型总览不支持查询参数"))
|
||||
return
|
||||
}
|
||||
@@ -28,6 +29,5 @@ func (s *Service) modelsOverview(w http.ResponseWriter, r *http.Request) {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
resource.JSON(r.Context(), w, http.StatusOK, out)
|
||||
}
|
||||
@@ -218,6 +218,13 @@ WITH bounds AS NOT MATERIALIZED (
|
||||
AND e.category = 'model' AND e.entry_type IN ('charge', 'refund') GROUP BY 1
|
||||
), credits_by_day AS (
|
||||
SELECT day, sum(credits) AS credits FROM daily_credit_parts GROUP BY day
|
||||
), message_models AS (
|
||||
SELECT t.model_id, count(*) AS messages
|
||||
FROM session_turns t JOIN sessions s ON s.id = t.session_id CROSS JOIN bounds b
|
||||
WHERE s.parent_session_id IS NULL AND s.reporting_enabled_at IS NOT NULL
|
||||
AND NOT s.placeholder AND s.deleted_at IS NULL AND s.purged_at IS NULL AND s.started_at < b.now_at
|
||||
AND t.started_at >= b.now_at - interval '24 hours' AND t.started_at < b.now_at
|
||||
GROUP BY t.model_id
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
'timezone', 'Asia/Shanghai', 'generated_at', (SELECT now_at FROM bounds),
|
||||
@@ -233,48 +240,19 @@ SELECT jsonb_build_object(
|
||||
'avg_response_time', (SELECT duration_ms FROM trimmed_durations WHERE metric = 'response'),
|
||||
'avg_first_token_time', (SELECT duration_ms FROM trimmed_durations WHERE metric = 'first_token'))
|
||||
FROM detail_calls WHERE completed_at >= sqlc.arg(at)::timestamptz - interval '30 minutes'),
|
||||
'message_distribution', jsonb_build_object(
|
||||
'from', (SELECT now_at - interval '24 hours' FROM bounds), 'until', (SELECT now_at FROM bounds),
|
||||
'total_messages', (SELECT coalesce(sum(messages), 0) FROM message_models),
|
||||
'models', coalesce((SELECT jsonb_agg(jsonb_build_object('id', p.model_id,
|
||||
'name', coalesce(nullif(btrim(m.display_name), ''), nullif(btrim(m.model_id), '')), 'messages', p.messages)
|
||||
ORDER BY p.messages DESC, p.model_id NULLS LAST)
|
||||
FROM message_models p LEFT JOIN models m ON m.id = p.model_id), '[]'::jsonb)),
|
||||
'days', (SELECT jsonb_agg(jsonb_build_object('date', d.day::text,
|
||||
'model_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) ORDER BY d.day)
|
||||
FROM days d LEFT JOIN calls_by_day c ON c.day = d.day LEFT JOIN credits_by_day e ON e.day = d.day)
|
||||
);
|
||||
|
||||
-- name: ReportingTasksOverview :one
|
||||
WITH bounds AS (
|
||||
SELECT sqlc.arg(at)::timestamptz AS now_at,
|
||||
(sqlc.arg(at)::timestamptz AT TIME ZONE 'Asia/Shanghai')::date AS today
|
||||
), roots AS (
|
||||
SELECT id, started_at FROM sessions
|
||||
WHERE parent_session_id IS NULL AND reporting_enabled_at IS NOT NULL
|
||||
AND placeholder = false AND deleted_at IS NULL AND purged_at IS NULL
|
||||
), days AS (
|
||||
SELECT d.day::date AS day
|
||||
FROM bounds b CROSS JOIN LATERAL generate_series((b.today - 89)::timestamp, b.today::timestamp, interval '1 day') AS d(day)
|
||||
), turns AS (
|
||||
SELECT t.started_at, root.id AS root_id
|
||||
FROM session_turns t JOIN sessions s ON s.id = t.session_id
|
||||
JOIN roots root ON root.id = coalesce(s.parent_session_id, s.id)
|
||||
CROSS JOIN bounds b
|
||||
WHERE s.reporting_enabled_at IS NOT NULL AND s.placeholder = false AND s.deleted_at IS NULL AND s.purged_at IS NULL
|
||||
AND t.started_at >= ((b.today - 89)::timestamp AT TIME ZONE 'Asia/Shanghai') AND t.started_at < b.now_at
|
||||
), new_by_day AS (
|
||||
SELECT (root.started_at AT TIME ZONE 'Asia/Shanghai')::date AS day, count(*) AS total
|
||||
FROM roots root CROSS JOIN bounds b
|
||||
WHERE root.started_at >= ((b.today - 89)::timestamp AT TIME ZONE 'Asia/Shanghai') AND root.started_at < b.now_at
|
||||
GROUP BY 1
|
||||
), active_by_day AS (
|
||||
SELECT (t.started_at AT TIME ZONE 'Asia/Shanghai')::date AS day, count(DISTINCT t.root_id) AS total
|
||||
FROM turns t GROUP BY 1
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
'total_tasks', (SELECT count(*) FROM roots),
|
||||
'new_tasks_24h', (SELECT count(*) FROM roots root CROSS JOIN bounds b WHERE root.started_at >= b.now_at - interval '24 hours' AND root.started_at < b.now_at),
|
||||
'active_tasks_24h', (SELECT count(DISTINCT t.root_id) FROM turns t CROSS JOIN bounds b WHERE t.started_at >= b.now_at - interval '24 hours'),
|
||||
'timezone', 'Asia/Shanghai', 'generated_at', (SELECT now_at FROM bounds),
|
||||
'days', (SELECT jsonb_agg(jsonb_build_object('date', d.day::text, 'new_tasks', coalesce(n.total, 0), 'active_tasks', coalesce(a.total, 0)) ORDER BY d.day)
|
||||
FROM days d LEFT JOIN new_by_day n ON n.day = d.day LEFT JOIN active_by_day a ON a.day = d.day)
|
||||
);
|
||||
|
||||
-- name: ReportingSessionOverview :one
|
||||
WITH bounds AS (
|
||||
SELECT sqlc.arg(at)::timestamptz AS now_at,
|
||||
|
||||
@@ -61,7 +61,6 @@ func (s *Service) RegisterAdmin(r chi.Router) {
|
||||
r.Get("/statistics/session-reporting/sessions/overview", s.sessionOverview)
|
||||
r.Get("/statistics/session-reporting/members/overview", s.membersOverview)
|
||||
r.Get("/statistics/session-reporting/members/{id}", s.memberAnalysis)
|
||||
r.Get("/statistics/tasks/overview", s.tasksOverview)
|
||||
r.Get("/statistics/models/overview", s.modelsOverview)
|
||||
r.Get("/statistics/history", s.history)
|
||||
r.Get("/statistics/conversations", s.conversations)
|
||||
|
||||
@@ -114,11 +114,12 @@ func TestOldModelsEndpointRemoved(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestModelsOverviewRejectsFilters(t *testing.T) {
|
||||
s := &Service{}
|
||||
w := httptest.NewRecorder()
|
||||
s.modelsOverview(w, httptest.NewRequest("GET", "/statistics/models/overview?range=7d", nil))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("不应接受时间筛选: %d %s", w.Code, w.Body.String())
|
||||
for _, query := range []string{"?range=7d", "?model_id=x", "?from=", "?%zz"} {
|
||||
w := httptest.NewRecorder()
|
||||
(&Service{}).modelsOverview(w, httptest.NewRequest("GET", "/statistics/models/overview"+query, nil))
|
||||
if w.Code != http.StatusBadRequest || w.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatalf("不应接受查询参数 %s: %d %s", query, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,85 +313,15 @@ func TestUsersOverviewEndpointRemoved(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTasksOverviewRejectsTimeFilters(t *testing.T) {
|
||||
service := &Service{}
|
||||
w := httptest.NewRecorder()
|
||||
service.tasksOverview(w, httptest.NewRequest("GET", "/statistics/tasks/overview?range=7d", nil))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("时间筛选应被拒绝: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTasksOverview(t *testing.T) {
|
||||
s, user, _ := fixture(t)
|
||||
now := s.now()
|
||||
makeSession := func(parent string, at time.Time, reporting, deleted, placeholder bool) string {
|
||||
t.Helper()
|
||||
var parentID, reportingAt, deletedAt any
|
||||
if parent != "" {
|
||||
parentID = parent
|
||||
func TestTasksOverviewRemoved(t *testing.T) {
|
||||
r := chi.NewRouter()
|
||||
(&Service{}).RegisterAdmin(r)
|
||||
for _, path := range []string{"/statistics/tasks/overview", "/statistics/tasks/overview?range=7d"} {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("旧会话统计接口应已移除 %s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
if reporting {
|
||||
reportingAt = at
|
||||
}
|
||||
if deleted {
|
||||
deletedAt = now
|
||||
}
|
||||
var id string
|
||||
err := s.pool.QueryRow(t.Context(), `INSERT INTO sessions(owner_user_id,parent_session_id,title,session_type,client_type,client_name,started_at,last_active_at,reporting_enabled_at,deleted_at,placeholder) VALUES($1,$2,'测试任务','conversation','desktop','客户端',$3,$3,$4,$5,$6) RETURNING id::text`, user, parentID, at, reportingAt, deletedAt, placeholder).Scan(&id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
makeTurns := func(sessionID string, at time.Time, count int) {
|
||||
t.Helper()
|
||||
exec(t, s, `INSERT INTO session_resource_snapshots(session_id,snapshot_id,items) VALUES($1,'snapshot','[]')`, sessionID)
|
||||
for index := range count {
|
||||
started := at.Add(time.Duration(index) * time.Minute)
|
||||
exec(t, s, `INSERT INTO session_turns(session_id,turn_index,facts_version,report_hash,input_seq,started_at,ended_at,stop_reason,resources_snapshot_id,input_kind) VALUES($1,$2::integer,1,'hash',$2::bigint,$3,$4,'complete','snapshot','text')`, sessionID, index+1, started, started.Add(time.Second))
|
||||
}
|
||||
}
|
||||
old := makeSession("", now.AddDate(0, 0, -100), true, false, false)
|
||||
makeTurns(old, now.Add(-40*time.Minute), 2)
|
||||
child := makeSession(old, now.Add(-35*time.Minute), true, false, false)
|
||||
makeTurns(child, now.Add(-30*time.Minute), 2)
|
||||
recent := makeSession("", now.Add(-2*time.Hour), true, false, false)
|
||||
makeTurns(recent, now.Add(-20*time.Minute), 1)
|
||||
previous := makeSession("", now.Add(-25*time.Hour), true, false, false)
|
||||
makeTurns(previous, now.Add(-25*time.Hour), 1)
|
||||
for _, flags := range []struct{ reporting, deleted, placeholder bool }{
|
||||
{true, true, false}, {true, false, true}, {false, false, false},
|
||||
} {
|
||||
excluded := makeSession("", now.Add(-time.Hour), flags.reporting, flags.deleted, flags.placeholder)
|
||||
makeTurns(excluded, now.Add(-10*time.Minute), 1)
|
||||
}
|
||||
out := request(t, s, "/statistics/tasks/overview", 200)
|
||||
for key, want := range map[string]float64{"total_tasks": 3, "new_tasks_24h": 1, "active_tasks_24h": 2} {
|
||||
number(t, out, key, want)
|
||||
}
|
||||
if out["timezone"] != "Asia/Shanghai" {
|
||||
t.Fatalf("时区错误: %v", out["timezone"])
|
||||
}
|
||||
days, ok := out["days"].([]any)
|
||||
if !ok || len(days) != 90 {
|
||||
t.Fatalf("应返回完整 90 天: %v", out["days"])
|
||||
}
|
||||
for i, point := range days {
|
||||
day := point.(map[string]any)
|
||||
wantDate := now.AddDate(0, 0, i-89).Format("2006-01-02")
|
||||
if day["date"] != wantDate {
|
||||
t.Fatalf("第 %d 天日期不连续: got %v, want %s", i, day["date"], wantDate)
|
||||
}
|
||||
wantNew, wantActive := float64(0), float64(0)
|
||||
if i == 88 {
|
||||
wantNew, wantActive = 1, 1
|
||||
}
|
||||
if i == 89 {
|
||||
wantNew, wantActive = 1, 2
|
||||
}
|
||||
number(t, day, "new_tasks", wantNew)
|
||||
number(t, day, "active_tasks", wantActive)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -557,7 +488,7 @@ func TestReportingDetailAndTombstone(t *testing.T) {
|
||||
|
||||
func TestEmptyAndInvalid(t *testing.T) {
|
||||
s, _, _ := fixture(t)
|
||||
for _, path := range []string{"/statistics/models/overview", "/statistics/tasks/overview", "/statistics/realtime", "/statistics/history", "/statistics/conversations", "/statistics/session-reporting/resources", "/statistics/session-reporting/clients", "/statistics/session-reporting/clients/overview"} {
|
||||
for _, path := range []string{"/statistics/models/overview", sessionOverviewPath, "/statistics/realtime", "/statistics/history", "/statistics/conversations", "/statistics/session-reporting/resources", "/statistics/session-reporting/clients", "/statistics/session-reporting/clients/overview"} {
|
||||
request(t, s, path, 200)
|
||||
}
|
||||
out := request(t, s, "/statistics/realtime", 200)
|
||||
|
||||
@@ -666,6 +666,13 @@ WITH bounds AS NOT MATERIALIZED (
|
||||
AND e.category = 'model' AND e.entry_type IN ('charge', 'refund') GROUP BY 1
|
||||
), credits_by_day AS (
|
||||
SELECT day, sum(credits) AS credits FROM daily_credit_parts GROUP BY day
|
||||
), message_models AS (
|
||||
SELECT t.model_id, count(*) AS messages
|
||||
FROM session_turns t JOIN sessions s ON s.id = t.session_id CROSS JOIN bounds b
|
||||
WHERE s.parent_session_id IS NULL AND s.reporting_enabled_at IS NOT NULL
|
||||
AND NOT s.placeholder AND s.deleted_at IS NULL AND s.purged_at IS NULL AND s.started_at < b.now_at
|
||||
AND t.started_at >= b.now_at - interval '24 hours' AND t.started_at < b.now_at
|
||||
GROUP BY t.model_id
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
'timezone', 'Asia/Shanghai', 'generated_at', (SELECT now_at FROM bounds),
|
||||
@@ -681,6 +688,13 @@ SELECT jsonb_build_object(
|
||||
'avg_response_time', (SELECT duration_ms FROM trimmed_durations WHERE metric = 'response'),
|
||||
'avg_first_token_time', (SELECT duration_ms FROM trimmed_durations WHERE metric = 'first_token'))
|
||||
FROM detail_calls WHERE completed_at >= $1::timestamptz - interval '30 minutes'),
|
||||
'message_distribution', jsonb_build_object(
|
||||
'from', (SELECT now_at - interval '24 hours' FROM bounds), 'until', (SELECT now_at FROM bounds),
|
||||
'total_messages', (SELECT coalesce(sum(messages), 0) FROM message_models),
|
||||
'models', coalesce((SELECT jsonb_agg(jsonb_build_object('id', p.model_id,
|
||||
'name', coalesce(nullif(btrim(m.display_name), ''), nullif(btrim(m.model_id), '')), 'messages', p.messages)
|
||||
ORDER BY p.messages DESC, p.model_id NULLS LAST)
|
||||
FROM message_models p LEFT JOIN models m ON m.id = p.model_id), '[]'::jsonb)),
|
||||
'days', (SELECT jsonb_agg(jsonb_build_object('date', d.day::text,
|
||||
'model_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) ORDER BY d.day)
|
||||
@@ -994,50 +1008,6 @@ func (q *Queries) ReportingSessionStatus(ctx context.Context, sessionID string)
|
||||
return jsonb_build_object, err
|
||||
}
|
||||
|
||||
const reportingTasksOverview = `-- name: ReportingTasksOverview :one
|
||||
WITH bounds AS (
|
||||
SELECT $1::timestamptz AS now_at,
|
||||
($1::timestamptz AT TIME ZONE 'Asia/Shanghai')::date AS today
|
||||
), roots AS (
|
||||
SELECT id, started_at FROM sessions
|
||||
WHERE parent_session_id IS NULL AND reporting_enabled_at IS NOT NULL
|
||||
AND placeholder = false AND deleted_at IS NULL AND purged_at IS NULL
|
||||
), days AS (
|
||||
SELECT d.day::date AS day
|
||||
FROM bounds b CROSS JOIN LATERAL generate_series((b.today - 89)::timestamp, b.today::timestamp, interval '1 day') AS d(day)
|
||||
), turns AS (
|
||||
SELECT t.started_at, root.id AS root_id
|
||||
FROM session_turns t JOIN sessions s ON s.id = t.session_id
|
||||
JOIN roots root ON root.id = coalesce(s.parent_session_id, s.id)
|
||||
CROSS JOIN bounds b
|
||||
WHERE s.reporting_enabled_at IS NOT NULL AND s.placeholder = false AND s.deleted_at IS NULL AND s.purged_at IS NULL
|
||||
AND t.started_at >= ((b.today - 89)::timestamp AT TIME ZONE 'Asia/Shanghai') AND t.started_at < b.now_at
|
||||
), new_by_day AS (
|
||||
SELECT (root.started_at AT TIME ZONE 'Asia/Shanghai')::date AS day, count(*) AS total
|
||||
FROM roots root CROSS JOIN bounds b
|
||||
WHERE root.started_at >= ((b.today - 89)::timestamp AT TIME ZONE 'Asia/Shanghai') AND root.started_at < b.now_at
|
||||
GROUP BY 1
|
||||
), active_by_day AS (
|
||||
SELECT (t.started_at AT TIME ZONE 'Asia/Shanghai')::date AS day, count(DISTINCT t.root_id) AS total
|
||||
FROM turns t GROUP BY 1
|
||||
)
|
||||
SELECT jsonb_build_object(
|
||||
'total_tasks', (SELECT count(*) FROM roots),
|
||||
'new_tasks_24h', (SELECT count(*) FROM roots root CROSS JOIN bounds b WHERE root.started_at >= b.now_at - interval '24 hours' AND root.started_at < b.now_at),
|
||||
'active_tasks_24h', (SELECT count(DISTINCT t.root_id) FROM turns t CROSS JOIN bounds b WHERE t.started_at >= b.now_at - interval '24 hours'),
|
||||
'timezone', 'Asia/Shanghai', 'generated_at', (SELECT now_at FROM bounds),
|
||||
'days', (SELECT jsonb_agg(jsonb_build_object('date', d.day::text, 'new_tasks', coalesce(n.total, 0), 'active_tasks', coalesce(a.total, 0)) ORDER BY d.day)
|
||||
FROM days d LEFT JOIN new_by_day n ON n.day = d.day LEFT JOIN active_by_day a ON a.day = d.day)
|
||||
)
|
||||
`
|
||||
|
||||
func (q *Queries) ReportingTasksOverview(ctx context.Context, at time.Time) ([]byte, error) {
|
||||
row := q.db.QueryRow(ctx, reportingTasksOverview, at)
|
||||
var jsonb_build_object []byte
|
||||
err := row.Scan(&jsonb_build_object)
|
||||
return jsonb_build_object, err
|
||||
}
|
||||
|
||||
const taskTurnBounds = `-- name: TaskTurnBounds :one
|
||||
SELECT jsonb_build_object('backfilling',session_turns_backfilling(),'first_at',b.first_at,'last_at',b.last_at)
|
||||
FROM session_turn_bounds($1::uuid) AS b(first_at,last_at)
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
package stats
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/stats/sqlc"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// tasksOverview returns a fixed rolling 24-hour summary and 90 Asia/Shanghai calendar days.
|
||||
func (s *Service) tasksOverview(w http.ResponseWriter, r *http.Request) {
|
||||
if len(r.URL.Query()) != 0 {
|
||||
resource.Fail(r.Context(), w, resource.Invalid("任务统计不支持查询参数"))
|
||||
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(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
defer rollbackStats(ctx, tx, "tasks_overview")
|
||||
out, err := resource.DecodeObject(sqlc.New(tx).ReportingTasksOverview(ctx, s.now().UTC()))
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "private, no-store")
|
||||
resource.JSON(r.Context(), w, http.StatusOK, out)
|
||||
}
|
||||
@@ -135,7 +135,6 @@ user 搜索条件过长 The user search query is too long.
|
||||
从成员列表或根分组移动到根分组不会改变成员关系 Moving users from the user list or root group into the root group does not change membership.
|
||||
任务恢复数量无效 The task recovery count is invalid.
|
||||
任务结果无效 The task result is invalid.
|
||||
任务统计不支持查询参数 Task statistics do not support query parameters.
|
||||
会话分析不支持查询参数 Session analysis does not support query parameters.
|
||||
会话 ID 无效 The session ID is invalid.
|
||||
会话上报已关闭 Session reporting is disabled.
|
||||
|
||||
|
@@ -4,7 +4,7 @@
|
||||
|
||||
## 时间口径
|
||||
|
||||
- 模型、用户、任务总览的近 90 天趋势统一按北京时间(`Asia/Shanghai`)自然日汇总,与 Pro 实例使用统计上报一致。接口的 `timezone` 返回 `Asia/Shanghai`。
|
||||
- 模型、成员、会话分析的近 90 天趋势统一按北京时间(`Asia/Shanghai`)自然日汇总,与 Pro 实例使用统计上报一致。接口的 `timezone` 返回 `Asia/Shanghai`。
|
||||
- 每日窗口为 `[当天 00:00, 次日 00:00)`,以北京时间解释日期。今天仅统计到 `generated_at`,空白日期补零。每日模型积分也使用同一时区。
|
||||
- 最近 24 小时、上一段 24 小时、最近 30 分钟及实时状态仍为滚动窗口,统一使用 `[from, until)`。滚动 24 小时与自然日是不同指标。
|
||||
- 前端直接使用服务端返回的 `date` 绘制每日趋势,不按浏览器时区重新划分日期。
|
||||
@@ -13,6 +13,8 @@
|
||||
|
||||
`/api/admin/v1/statistics/models/overview` 按 `model_calls.completed_at` 统计已完成、非 `running` 的模型调用,返回近 24 小时、上一段 24 小时、近 30 分钟指标及 90 天趋势。
|
||||
|
||||
同一响应的 `message_distribution` 为模型页提供消息中的模型使用分布:按 `session_turns.started_at` 统计 `[generated_at - 24 小时, generated_at)` 的有效根会话消息,排除子会话、未上报、占位、已删除、已清理或未来开始的会话。按模型 UUID 汇总,保留历史模型名称,缺失模型归入未知项;模型名称和 API 配置分别处理,仅返回名称及计数。分布与模型指标使用同一快照和服务端截止时间;前端不再生成示例分布,也不额外查询会话概览接口。
|
||||
|
||||
Token 和 TPM 与 Pro 上报采用同一用量判定:
|
||||
|
||||
1. 优先采用同 ID 的 `billing_transactions.usage.known`。
|
||||
@@ -43,11 +45,12 @@ Token 和 TPM 与 Pro 上报采用同一用量判定:
|
||||
|
||||
升级在一个事务中锁定相关写入、回填历史用量标记及小时汇总并安装触发器,避免回填与并发新增遗漏。首次升级会扫描历史调用和模型账本,`model_calls` 的结构变更锁会在该迁移事务内阻塞该表读写,需停止旧后端并安排迁移窗口;完成后增量维护,不会在首页请求中回填。回滚仅移除统计投影、触发器及新增标记,不改变调用、交易和账本事实;再次升级会从事实重建汇总。
|
||||
|
||||
## 用户与任务
|
||||
## 成员与会话
|
||||
|
||||
- `/statistics/users` 返回全部用户数、滚动 24 小时新增与活跃用户及每日趋势。新增按 `users.created_at`,包含软删除和停用用户;活跃按有 `session_turns` 记录的会话所属用户去重,以轮次开始时间归日。
|
||||
- `/statistics/tasks/overview` 只统计上报启用、非占位、未删除或清理的根任务。新增按根任务开始时间;活跃按轮次开始时间,子任务归属根任务并去重。
|
||||
- `/statistics/history` 按任务开始时间倒序并以 UUID 稳定排序,支持标题 / UUID、姓名 / 邮箱、时间与分页筛选。只展示上报启用、非占位、未删除或清理的根任务。
|
||||
- 模型页只请求 `/statistics/models/overview`,展示模型指标、24 小时消息模型分布与四张模型趋势图。会话总量、新建和活跃会话及其趋势集中在会话分析页面展示;旧 `/statistics/tasks/overview` 已移除。
|
||||
- `/statistics/session-reporting/members/overview` 提供成员总数、7 天和 24 小时活跃成员以及近 90 天新增和活跃趋势,只统计当前未软删除成员。
|
||||
- `/statistics/session-reporting/sessions/overview` 以一个接口提供会话分析整个页面的数据:会话及消息总量、90 天趋势、24 小时模型使用、消息结果、耗时与每会话消息数的平均值及 P10/P90。全部来自同一只读快照与服务端时间;只统计已上报、非占位、未删除和未清理的根会话,不包含子会话。每会话消息数仅统计窗口内有消息的会话,跨模型合并。
|
||||
- `/statistics/history` 按会话开始时间倒序并以 UUID 稳定排序,支持标题 / UUID、姓名 / 邮箱、时间与分页筛选。只展示上报启用、非占位、未删除或清理的根会话。
|
||||
- `/statistics/realtime` 的活跃用户按有完成模型 / MCP 调用、有会话活动或仍在执行计费调用的真实用户 ID 去重,不代表登录 DAU。
|
||||
|
||||
Pro 上报使用独立统计台账,保留业务数据清理前的调用事实;管理后台查询业务表。清理过的历史记录仍可能导致两边总数不同。当日上报为最近成功发送的快照,可能落后于实时查询;对账时应使用相同实例、日期和截止时间。
|
||||
|
||||
Reference in new issue
Block a user