diff --git a/src-tauri/src/dashboard.rs b/src-tauri/src/dashboard.rs index f7de1007..2e082cce 100644 --- a/src-tauri/src/dashboard.rs +++ b/src-tauri/src/dashboard.rs @@ -7,10 +7,10 @@ use crate::{ error::{Out, text}, }; -/// 今天的汇总、历史、延迟、存储状态。 +/// 一段时间的汇总、趋势、延迟、存储状态,和上一个等长区间的汇总。 /// -/// **四个一起取。**界面上它们是同一块,分四次 invoke 会让那一块在几十 -/// 毫秒里分四次跳变。 +/// **一起取。**界面上它们是同一块,分几次 invoke 会让那一块在几十毫秒里分几次 +/// 跳变。 #[tauri::command] pub async fn dashboard( state: tauri::State<'_, AppState>, @@ -41,22 +41,14 @@ pub async fn dashboard( .call::(&[], &window(Some(since), None)) .await .map_err(text)?, + // 延迟和汇总**同一个时间窗**。不给窗口的话 core 按「今天零点至今」算,而 + // 界面上它和上面的数字摆在一起,读的人会当成同一段时间 latency: c - .call::(&[], &tw_api::Window::default()) + .call::(&[], &window(Some(since), None)) .await .unwrap_or_default(), latency_by_provider: c - .call::(&[], &tw_api::Window::default()) - .await - .unwrap_or_default(), - history: c - .call::( - &[], - &tw_api::ListQuery { - limit: Some(200), - ..Default::default() - }, - ) + .call::(&[], &window(Some(since), None)) .await .unwrap_or_default(), storage: c.call::(&[], &()).await.ok(), @@ -99,10 +91,10 @@ pub async fn dashboard( #[derive(serde::Serialize)] pub struct Dashboard { summary: tw_api::Summary, + /// 首字节时间的分位,按模型分。和 `summary` 同一个时间窗 latency: Vec, /// 按上游分。**和按模型分是两个问题** latency_by_provider: Vec, - history: Vec, /// 拿不到就是没有 —— 存储层不在的时候网关照常跑 storage: Option, /// 按界面给的格宽分格。**稀疏的** —— 空桶由界面补 diff --git a/src/App.tsx b/src/App.tsx index 028b0317..7832b7d4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -18,7 +18,6 @@ import McpPage from "./mcp/McpPage"; import TrafficPage from "./traffic/TrafficPage"; import { useTrafficView } from "./traffic/view"; import { useSessions } from "./traffic/useSessions"; -import { presetRange } from "@/ui/range"; import { Notices } from "./Notices"; import { Tip, TooltipRoot } from "@/ui/tip"; import { @@ -33,7 +32,7 @@ import { IconSettings, } from "./ui/icons"; import { isMac, isMod } from "@/platform"; -import Dashboard from "./Dashboard"; +import OverviewPage from "./overview/OverviewPage"; import type { CoreStatus, Overview } from "./types"; import { stageLabel } from "./labels"; import { textOf, useText } from "@/i18n"; @@ -992,19 +991,7 @@ function Shell({ first }: { first: boolean }) { ) ) : tab === "dashboard" ? ( - setLanded(true)} - onShowSecurity={(range) => - // 实时档的计数按 24 小时算(见 `windowStart`),日志也按 24 小时看 - open("security", { - focus: { range: range.live ? presetRange("1d") : range, at: Date.now() }, - }) - } - // 归组态下「哪些模型没定价」看不出来:那是一行一行的问题 - onShowUnpriced={() => open("requests", { grouped: false, filter: { unpricedOnly: true } })} - /> + setLanded(true)} /> ) : tab === "clients" ? ( ) : tab === "mcp" ? ( diff --git a/src/Dashboard.tsx b/src/Dashboard.tsx deleted file mode 100644 index 95b0959a..00000000 --- a/src/Dashboard.tsx +++ /dev/null @@ -1,1151 +0,0 @@ -import { useEffect, useRef, useState } from "react"; -import { ChevronRightIcon } from "lucide-react"; -import { useStableState } from "./useStable"; -import { Tip } from "@/ui/tip"; -import { invoke } from "@tauri-apps/api/core"; -import RequestDrawer from "./RequestDrawer"; -import { triggers } from "./triggers"; -import { StackedArea, Y_AXIS_WIDTH } from "@/ui/charts"; -import { compact, densify } from "./format"; -import { usd, type Dashboard as Data, type Guard, type LatencyView, type Overview } from "./types"; -import { Alert, AlertDescription } from "@/ui/alert"; -import { RangePicker, bucketFor, useRange, windowStart, type Range } from "@/ui/range"; -import { Segmented } from "@/ui/segmented"; -import { Skeleton } from "@/ui/skeleton"; -import { LIVE_BUCKET_MS, LIVE_REACH_MS, liveRate, useLive } from "./useLive"; -import { useCountUp } from "./useCountUp"; -import { useText } from "@/i18n"; -import { dashboardText } from "./Dashboard.i18n"; - -const HOUR = 3_600_000; -const DAY = 24 * HOUR; - -/** 每一栏最多列几项。超出的写出来有几项,**不静默丢掉**。 */ -const ROWS = 6; - -/** 往上取到最近的 1/2/5 × 10ⁿ。纵轴上界用它,刻度才落在整数上。 */ -function niceCeil(v: number): number { - if (!(v > 0)) return 1; - const e = Math.pow(10, Math.floor(Math.log10(v))); - const m = v / e; - return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * e; -} - -/** - * 一格的时间标签。跨度大到按天分格时就只写日期。 - * - * 不到一分钟的格子(实时档)**写到秒,也带上小时**:只写「07:12」读起来 - * 像七点十二分,而十分钟的窗口随时会跨过整点。 - */ -function fmtBucket(atMs: number, bucketMs: number): string { - const t = new Date(atMs); - const p = (n: number) => String(n).padStart(2, "0"); - if (bucketMs >= DAY) return `${t.getMonth() + 1}/${t.getDate()}`; - if (bucketMs < 60_000) - return `${p(t.getHours())}:${p(t.getMinutes())}:${p(t.getSeconds())}`; - return `${t.getMonth() + 1}/${t.getDate()} ${p(t.getHours())}:${p(t.getMinutes())}`; -} - -/** - * 读数据时的骨架。 - * - * **不是一句「读取中…」。**那一行字占的地方和真正的内容差着两百像素, - * 读完之后整页会跳一次;而这一页最大的那几个数字恰好在跳动的位置上。 - */ -function OverviewSkeleton() { - return ( - <> -
- {[0, 1, 2].map((i) => ( -
- - -
- ))} -
- -
- - - -
- - ); -} - -/** 一块密排信息。左边那列标签把所有块钉在同一条竖线上。 */ -function Block({ name, children }: { name: string; children: React.ReactNode }) { - return ( -
- {name} -
{children}
-
- ); -} - -/** - * 延迟的分位区间。 - * - * **区间条,不是两列数字。**并排的两列毫秒数要逐行读才能比较,而这张 - * 图要回答的是「哪个又慢又不稳定」—— 那是条的起点加长度,一次扫视 - * 就能得到。亮线标的是 P50:多数请求落在它附近。 - * - * 用分位数不用平均值:AI 延迟是长尾分布,平均值会被极端值拉偏。 - */ -function Spread({ rows, max }: { rows: LatencyView[]; max: number }) { - const t = useText(dashboardText); - const shown = [...rows].sort((a, b) => b.samples - a.samples).slice(0, ROWS); - return ( - <> - {shown.map((l) => ( -
- - {l.model} - - {/* 条宽固定:两栏的条这样才对齐,能横着比 */} - - - - - - {l.p50} – {l.p95}ms - - {/* - **样本数要显示**:「800ms」是 3 个样本还是 300 个,含义完全 - 不同。不可靠的是**样本数**,不是延迟值 —— 所以只标这个数。 - */} - - {t.times(l.samples)} - -
- ))} - {rows.length > shown.length && ( -

- {t.moreNotListed(rows.length - shown.length)} -

- )} - - ); -} - -/** - * 页眉上的一个大数。 - * - * **三栏等宽,说明那一行固定占两行高。**在此之前这三组是并排的弹性 - * 块,而「较上一个区间」在没有可比数据时整个消失 —— 于是切一次时间 - * 范围,三个数字的横向位置全变了,眼睛每次都要重新找。 - * - * 所以限定语一律放到第二行:第一行只留那个数和单位,宽度由它决定, - * 而它在各种区间下长得都差不多。 - */ -function Stat({ - n, - unit, - after, - note, -}: { - n: string; - unit?: string; - after?: React.ReactNode; - note: React.ReactNode; -}) { - return ( -
-
- {n} - {unit && {unit}} - {after} -
- {/* 高度写死两行:少一条限定语时不该把整页往上收 */} -

- {note} -

-
- ); -} - -/** - * 一个环比。 - * - * **没有参照系的数字只能读,不能判断。**只有花费那一侧有「好坏」: - * 少花是好事,所以降下来才上色。用量那一侧两个方向都不上色 —— 多用掉 - * 一些 token 不是问题,少用也不是成绩。 - */ -function Delta({ v, more, good }: { v: number; more: string; good?: "down" }) { - const t = useText(dashboardText); - const better = good === "down" && v < 0; - return ( - - {t.delta(more, v < 0 ? "↓" : "↑", Math.abs(v * 100).toFixed(0))} - - ); -} - -/** 缓存构成条上的一段。 */ -function Swatch({ color, name, n }: { color: string; name: string; n: number }) { - const t = useText(dashboardText); - return ( - - - - {name} {compact(n)} - - - ); -} - -/** - * 用量概览。 - * - * 这一页的每一个数字都受那条约束:**绝不让估算值混进精确数字里 - * 假装准确。**所以金额旁边永远跟着它的限定词。 - * - * 版面上只有一个视觉锚点:那张图。其余全是发丝线分隔的密排行,左边 - * 一列标签把它们钉在同一条竖线上 —— **参照物是原生监控工具,不是网页 - * 后台**。圆角卡片的网格恰恰是最像后台的做法。 - */ -export default function Dashboard({ - tick, - ov, - onShowSecurity, - onShowUnpriced, - onLanded, -}: { - tick: number; - ov: Overview | null; - /** 安全计数不为零时可以点:打开安全日志,带上这段时间 */ - onShowSecurity: (range: Range) => void; - /** 「N 条无法计价」是个可以点进去的问题,不只是一个数字 */ - onShowUnpriced: () => void; - /** 第一份数据到了。启动画面等它再交接 */ - onLanded?: () => void; -}) { - const t = useText(dashboardText); - const [range, setRange] = useRange(); - /** - * 图按哪个口径画。 - * - * **默认 token。**这一页看的是用量,而按金额画时一次 opus 突发会把 - * 前后一周压平 —— 那张图好看,但除了「opus 贵」说不出别的。 - */ - const [by, setBy] = useState<"token" | "cost">("token"); - /* - 纵轴的上界**不跟着每一帧的峰值走**。 - - 自动域下,一个大请求进出窗口就让整条曲线连同刻度一起上下弹 —— - 看起来像图在抖,其实抖的是尺子。所以上界取一个整齐的数(1/2/5 - 档),而且只在实际峰值掉到它一半以下时才降档:在档位边界上来回 - 过线的话,抖得比不取整还厉害。 - - 口径和区间一换,量级差几个数量级,得重新起。 - */ - const yHold = useRef({ key: "", v: 0 }); - /* - 上一次的堆叠次序。**名次要有滞回。** - - 两个模型量级接近时,没有滞回就会在名次边界上来回过线,而每过一次 - 线,整条带子在纵向跳过另一条、颜色还跟着换(颜色是按名次给的)。 - 实测这个演示实例的流量:按实时窗口(当时是两分钟)排,十分钟里换位 - 145 次;改按 24 小时排降到 14 次;要到零得让换位本身有门槛。 - */ - const stack = useRef([]); - const live = range.live === true; - /* - **实时档只有图是实时的。**十分钟里的样本撑不起有意义的延迟分位,也 - 统计不出像样的缓存命中率;那些仍然按 24 小时算,图下面有一行小字说明。 - 所以这里查的窗口(`windowStart`)和图的窗口是两回事。 - */ - const bucketMs = live ? LIVE_BUCKET_MS : bucketFor(range.ms); - /* - **多留一个核宽的样本。**最左边那一格的鼓包有一半来自图外的那几秒; - 按图的宽度留样本的话,左端会凭空塌下去一个口子。 - */ - const { samples, fails, inFlight } = useLive(live, range.ms + LIVE_REACH_MS); - /** - * **只在内容真的变了的时候才换。**每次 `invoke` 回来都是一个新对象, - * 直接 setState 会让整页重画一遍,而这一切发生在什么都没发生的时候。 - */ - const [d, setD] = useStableState(null); - const gatewayHint = t.gatewayHint; - const [error, setError] = useState(null); - /** 点开的那一条。**抽屉是右侧覆盖的,不是跳页** */ - const [open, setOpen] = useState(null); - - /* - 三个大数会走过去,不是跳过去。 - - **只在同一个口径里走**:换时间范围时那不是「涨了」,是换了一个东西 - 在看 —— 从 251k 滚到 661k 看起来像用量突然翻了三倍,所以 - `range.label` 一变就直接落值。**第一份数据也直接落值**:从零走到实际值, - 读起来是「用量刚刚涨上来」,而那只是刚读到。 - - **这三个 hook 必须站在早返回之前。**下面有「还没读到数据」和 - 「出错了」两条 return,而 React 要求每次渲染调用的 hook 数量一致 - —— 放在后面的话,数据第一次到达的那一刻整页会崩。所以这里用 - `d?.` 取值,读不到就是 0。 - */ - const sum = d?.summary; - const scope = sum ? range.label : ""; - const tokensAt = useCountUp( - sum - ? sum.input_tokens + sum.cache_read_tokens + sum.cache_write_tokens + sum.output_tokens - : 0, - scope, - ); - const spentAt = useCountUp( - sum ? sum.cost_micros_exact + sum.cost_micros_estimated : 0, - scope, - ); - const requestsAt = useCountUp(sum?.requests ?? 0, scope); - const landed = useRef(onLanded); - landed.current = onLanded; - useEffect(() => { - if (d) landed.current?.(); - }, [d]); - - useEffect(() => { - let alive = true; - (async () => { - try { - // 窗口起点对齐到格子边界,格宽一起送过去 —— 两边各算一遍的话, - // 补空桶时格子对不上,整张图会是零。见 bucketStart 的注释。 - // - // 实时档下这次查询要的是 24 小时的汇总,图另有来路,所以格宽 - // 取一小时就够 —— 五秒一格去查二十四小时是一万七千多个分组。 - const q = live ? HOUR : bucketMs; - const sinceMs = windowStart(range); - const x = await invoke("dashboard", { sinceMs, bucketMs: q }); - if (alive) { - setD(x); - setError(null); - } - } catch { - /* - **读不到不在这一层报。**连不上控制面是启动过程中的预期状态, - 而 App 那边已经用一整面(或一条带子)在说这件事了 —— 这儿再弹 - 一条 toast,就是同一件事说两遍,而且说得更难懂。 - - 上一次读到的值留着不动:一个凝固的旧数字加上面那句「已断开」, - 比清空成骨架有用。 - */ - } - })(); - return () => { - alive = false; - }; - }, [tick, range, bucketMs, live, setD]); - - /** - * 图按什么口径画。**两档都在实时下可用** —— core 会在算完价钱之后 - * 补一条 `request_priced`,所以金额也是推过来的,只比用量晚一拍。 - */ - const metric = ( - - label={t.metric} - value={by} - options={[ - { id: "token", label: t.byTokens }, - { id: "cost", label: t.byCost }, - ]} - onChange={setBy} - /> - ); - - /* - **页面顶上没有标题**,导航里选中的那一项已经说了这是哪一页。 - - 两组控件分在这一行的两头:时间范围管的是整页(下面每一块都跟着它 - 走),靠左、第一眼就看到;口径只管图和模型排行,靠右。**不挨在 - 一起** —— 两个不同维度的东西并排成一串同样的药丸,读起来就是一排 - 七个平级选项。 - */ - const header = ( -
- -
{metric}
-
- ); - - if (error) { - return ( -
- - {error} - -
- ); - } - if (!d) { - return ( -
-
- {header} - -
-
- ); - } - - const s = d.summary; - const has = triggers(null, d); - const spent = s.cost_micros_exact + s.cost_micros_estimated; - const nothingYet = !has.cost; - - /* - **「输入」是送往上游的全部上下文,包含命中缓存的那部分。** - `input_tokens` 单独一个字段说的是「没命中缓存的那部分」—— 命中率 - 高的时候它只有真实输入的零头,标成「输入」会让人以为自己几乎没用。 - */ - const ctx = s.input_tokens + s.cache_read_tokens + s.cache_write_tokens; - const tokensTotal = ctx + s.output_tokens; - const beforeCost = d.prev ? d.prev.cost_micros_exact + d.prev.cost_micros_estimated : 0; - const beforeTokens = d.prev - ? d.prev.input_tokens + - d.prev.cache_read_tokens + - d.prev.cache_write_tokens + - d.prev.output_tokens - : 0; - const hit = ctx > 0 ? s.cache_read_tokens / ctx : null; - const ratio = s.cache_write_tokens > 0 ? s.cache_read_tokens / s.cache_write_tokens : null; - - - /* - 趋势图按模型分层。**只保留前五项,其余合并为「其他」** —— 一家上游 - 可能报出十几个模型名,十几层叠在两百像素里已经分辨不出,而排在后面 - 的那些合计往往不到百分之一。 - */ - /* - 实时档的格子**不对齐格宽的整数倍**:最右边那一格就是此刻,往左每格 - 五秒。对齐的话,格子只在跨过边界的那一帧整体挪一格,曲线于是每五秒 - 跳一次;而高斯核在任意时刻都求得出值,格子没有必须落在边界上的理由。 - - **两头都算**:十分钟是一百二十段、一百二十一个点,最左边那个点正好是 - 十分钟前。少一个点的话,整张图只铺了九分五十五秒,底下的刻度按十分钟 - 标,就差出几个像素。 - */ - const nowMs = Date.now(); - const liveSpan = Math.round(range.ms / LIVE_BUCKET_MS) + 1; - const liveAt = live - ? Array.from( - { length: liveSpan }, - (_, i) => nowMs - (liveSpan - 1 - i) * LIVE_BUCKET_MS, - ) - : []; - const byBucket = new Map>(); - const money = new Map(); - const volume = new Map(); - const count = new Map(); - const add = (at: number, name: string, v: number) => { - const slot = byBucket.get(at) ?? new Map(); - slot.set(name, (slot.get(name) ?? 0) + v); - byBucket.set(at, slot); - }; - if (live) { - /* - **一条请求摊成一个高斯鼓包,不是一根针也不是一个方块。** - 核归一到总权重 1,所以摊完之后每一格读作速率:token 口径是 - token/秒,费用口径乘 3600 换成每小时 —— 实时看网关,想知道的 - 是此刻烧钱多快,而「这一秒花了 $0.0003」没有人读得出大小。 - - 排行和总量不走这条路:它们数的是这十分钟里实际发生的量, - 一条请求只算一次,在上面。 - */ - /* - 核在**格子的时刻**上求值,不在「第几格」上求值 —— 这样格子挪到 - 哪儿都对得上,曲线是平移的,不会因为重新分桶而抖。 - */ - for (const x of samples) { - volume.set(x.model, (volume.get(x.model) ?? 0) + x.tokens); - money.set(x.model, (money.get(x.model) ?? 0) + (x.cost ?? 0)); - count.set(x.model, (count.get(x.model) ?? 0) + 1); - const amount = by === "token" ? x.tokens : (x.cost ?? 0) * 3600; - // 只碰核够得着的那几格 - const lo = Math.max( - 0, - Math.ceil((x.at - LIVE_REACH_MS - (liveAt[0] ?? 0)) / LIVE_BUCKET_MS), - ); - const hi = Math.min( - liveAt.length - 1, - Math.floor((x.at + LIVE_REACH_MS - (liveAt[0] ?? 0)) / LIVE_BUCKET_MS), - ); - for (let i = lo; i <= hi; i++) { - const t = liveAt[i]; - if (t === undefined) continue; - add(t, x.model, liveRate(amount, t - x.at)); - } - } - } else { - for (const b of d.buckets_by_model) { - const name = b.name || t.unknownModel; - const cost = b.cost_micros_exact + b.cost_micros_estimated; - const tok = b.input_tokens + b.output_tokens + b.cache_read_tokens + b.cache_write_tokens; - money.set(name, (money.get(name) ?? 0) + cost); - volume.set(name, (volume.get(name) ?? 0) + tok); - count.set(name, (count.get(name) ?? 0) + b.requests); - add(b.at_ms, name, by === "token" ? tok : cost); - } - } - const useTokens = by === "token"; - /* - **堆叠的次序不跟着实时窗口走。** - - 按窗口内的用量排的话,几个模型量级接近时排名一两秒就翻一次 —— - 一翻,整条带子在纵向跳过另一条,颜色还跟着换(颜色是按名次给的)。 - 那比曲线自己的移动剧烈得多,看起来就是图在抽。 - - 所以实时档按**最近 24 小时**的用量定次序:那份数据本来就在手上 - (见上面查询里的 `q`),而且只随慢刷新变。历史档按它自己那段排, - 那段本来就不会在两帧之间变。量相同时按名字定,免得 Map 的插入 - 顺序泄漏进来。 - */ - const steady = new Map(); - if (live) { - for (const b of d.buckets_by_model) { - const name = b.name || t.unknownModel; - const v = useTokens - ? b.input_tokens + b.output_tokens + b.cache_read_tokens + b.cache_write_tokens - : b.cost_micros_exact + b.cost_micros_estimated; - steady.set(name, (steady.get(name) ?? 0) + v); - } - } - // 排行按当前口径排 —— 切到 token 之后,最贵的那个未必是用得最多的 - const here = useTokens ? volume : money; - // 排行按当前口径排 —— 切到 token 之后,最贵的那个未必是用得最多的。 - // **这是给人读的列表,它就该从大到小**,和图的堆叠次序不是一回事。 - const ranked = [...here.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); - const top = ranked.slice(0, 5).map(([name]) => name); - const rest = ranked.slice(5); - - /* - 图里的堆叠次序另算。画的顺序是从下往上:**占得少的垫底、占得多的 - 在上**,最重的那一层在视觉上也该最重;颜色跟着走,chart-1 最亮给 - 最多的那个。要紧的是这个次序**不能每帧都重算一遍**。 - - 记住的次序里还在的那些保持相对位置,新出现的按量插进去;之后只在 - 一个模型**明显**超过它上一名(两成)时才换位。历史档不需要这一层 - —— 那段数据两帧之间本来就不变。 - */ - const val = (m: string) => (live ? steady : here).get(m) ?? 0; - const byVolume = [...top].sort((a, b) => val(b) - val(a) || a.localeCompare(b)); - let stacked = byVolume; - if (live) { - const kept = stack.current.filter((m) => top.includes(m)); - for (const m of byVolume) if (!kept.includes(m)) kept.splice(byVolume.indexOf(m), 0, m); - for (let i = kept.length - 1; i > 0; i--) { - const up = kept[i - 1]; - const down = kept[i]; - if (up === undefined || down === undefined) continue; - if (val(down) > val(up) * 1.2) { - kept[i - 1] = down; - kept[i] = up; - } - } - stack.current = kept; - stacked = kept; - } - const otherKey = t.other; - const keys = - rest.length > 0 ? [otherKey, ...[...stacked].reverse()] : [...stacked].reverse(); - const shade = [ - "var(--chart-5)", - "var(--chart-4)", - "var(--chart-3)", - "var(--chart-2)", - "var(--chart-1)", - ]; - const colors = keys.map( - (_, i) => shade[Math.max(0, shade.length - keys.length + i)] ?? "var(--chart-1)", - ); - // **色块按名字查。**列表按用量排、图按堆叠次序排,两边要对得上同一个色 - const colorOf = new Map(keys.map((k, i) => [k, colors[i] ?? "var(--chart-1)"])); - const restMoney = rest.reduce((a, x) => a + (money.get(x[0]) ?? 0), 0); - const restVolume = rest.reduce((a, x) => a + (volume.get(x[0]) ?? 0), 0); - const restCount = rest.reduce((a, x) => a + (count.get(x[0]) ?? 0), 0); - // 条长按当前口径里**最大的那一项**归一。按总量归一的话,一个占七成 - // 的模型会把其余几条压成看不见的短线,而排行要比的正是它们的差距。 - const topBar = Math.max( - 1, - useTokens ? Math.max(restVolume, ...volume.values()) : Math.max(restMoney, ...money.values()), - ); - - /* - 实时档的格子自己铺:十分钟、五秒一格,一路铺到「现在」。 - 历史档沿用后端给的桶 —— 空桶由 `densify` 补成 0,这是面积图不会把 - 空档画成「连续在用」的前提。 - */ - const now = nowMs; - const grid = live - ? liveAt.map((at_ms) => ({ - at_ms, - requests: 0, - failed: 0, - cost_micros_exact: 0, - cost_micros_estimated: 0, - unpriced_requests: 0, - no_usage_requests: 0, - })) - : densify(d.buckets, d.since_ms, now, bucketMs); - if (live) { - const from = liveAt[0] ?? 0; - for (const f of fails) { - const g = grid[Math.round((f.at - from) / LIVE_BUCKET_MS)]; - if (g) g.failed += 1; - } - } - const area = grid.map((g) => { - const slot = byBucket.get(g.at_ms); - const sum = [...(slot?.values() ?? [])].reduce((a, v) => a + v, 0); - const row: Record = { - label: live - ? t.liveBucket( - fmtBucket(g.at_ms, bucketMs), - useTokens - ? t.tokenRate(compact(Math.round(sum))) - : t.costRate(usd(sum)), - ) - : t.bucket( - fmtBucket(g.at_ms, bucketMs), - useTokens - ? t.tokens(compact(sum), sum) - : usd(g.cost_micros_exact + g.cost_micros_estimated), - g.requests, - g.failed, - ), - }; - let other = 0; - for (const [name, v] of slot ?? []) { - // 金额从微分换成千分之一美元:纵轴上那几位小数没有意义 - const y = useTokens ? v : v / 1000; - if (top.includes(name)) row[name] = y; - else other += y; - } - // 没有值的那几层要显式给 0,否则 recharts 会把这一格整条断开 - for (const k of top) row[k] ??= 0; - if (rest.length > 0) row[otherKey] = other; - return row; - }); - - const peak = area.reduce((hi, row) => { - let sum = 0; - for (const k of keys) { - const v = row[k]; - if (typeof v === "number") sum += v; - } - return Math.max(hi, sum); - }, 0); - const yKey = `${by}/${range.label}`; - if (yHold.current.key !== yKey) yHold.current = { key: yKey, v: 0 }; - if (peak > yHold.current.v || peak < yHold.current.v * 0.5) - yHold.current = { key: yKey, v: niceCeil(peak * 1.08) }; - const yMax = yHold.current.v || undefined; - /** 图下面那排刻度。实时档按固定间隔写,历史档只写起点和「现在」 */ - const ticks = [...(live ? t.liveTicks : [fmtBucket(d.since_ms, bucketMs)]), t.now]; - /** 图画出来了才有纵轴那一栏(见 `StackedArea` 的空态) */ - const axis = keys.length > 0 && area.length > 0 ? Y_AXIS_WIDTH : 0; - - const latMax = - Math.max(1, ...d.latency.map((l) => l.p95), ...d.latency_by_provider.map((l) => l.p95)) * 1.04; - - /* - 各项防护现在各在哪一档,以及这段时间各自看见了什么。 - - **档位和所见要一起说。**只说所见的话,「未发现」在关闭档下是句 - 空话;只说档位的话,用户不知道它到底拦下过什么。 - - **数的是安全日志里的条数**,和从这里点进去看到的是同一批(起点都按 - `windowStart` 算)。数不为零时整句可点。 - */ - const sec = ov?.security; - const label = (m: string) => - m === "enforce" ? t.modeEnforce : m === "off" ? t.modeOff : t.modeObserve; - const counts = s.security; - const guards: { - key: Guard; - name: string; - mode: string; - hits: number; - /** 没被处置的那几处。**有它才标红** —— 全换掉了、全切断了,说明防护在起作用 */ - open: number; - saw: string; - }[] = sec - ? [ - { - key: "redact", - name: t.redact, - mode: sec.redact, - hits: counts.secrets, - open: counts.secrets - counts.secrets_replaced, - saw: - counts.secrets > 0 - ? t.secrets(counts.secrets, counts.secrets_replaced) - : sec.redact === "off" - ? t.notChecked - : t.noSecrets, - }, - { - key: "inspect_tools", - name: t.inspect, - mode: sec.inspect_tools, - hits: counts.tool_calls, - open: counts.tool_calls - counts.tool_calls_cut, - saw: - counts.tool_calls > 0 - ? t.toolCalls(counts.tool_calls, counts.tool_calls_cut) - : sec.inspect_tools === "off" - ? t.notChecked - : t.noToolCalls, - }, - { - key: "hidden_text", - name: t.hiddenText, - mode: sec.hidden_text, - hits: counts.hidden_text, - open: counts.hidden_text - counts.hidden_text_blocked, - saw: - counts.hidden_text > 0 - ? t.hiddenFound(counts.hidden_text, counts.hidden_text_blocked) - : sec.hidden_text === "off" - ? t.notChecked - : t.noHidden, - }, - { - key: "content", - name: t.content, - mode: sec.content, - hits: counts.content, - open: counts.content - counts.content_blocked, - saw: - counts.content > 0 - ? t.contentMatched(counts.content, counts.content_blocked) - : sec.content === "off" - ? t.notChecked - : t.noContent, - }, - { - key: "output_limit", - name: t.outputLimit, - mode: sec.output_limit, - hits: counts.output_limit, - open: counts.output_limit - counts.output_limit_cut, - saw: - counts.output_limit > 0 - ? t.overLimit(counts.output_limit, counts.output_limit_cut) - : sec.output_limit === "off" - ? t.notChecked - : t.noOverLimit, - }, - ] - : []; - - return ( -
- {header} - - {/* - 三个数并排:**做了多少、花了多少、发了多少次**。它们是同一层的 - 事实,所以同一个字号、同一个宽度的栏。 - - **等宽栏,而不是并排的弹性块。**后者会让「较上一个区间」这类 - 时有时无的限定语改变每一栏的宽度,切一次范围三个数字就横向 - 挪一次位置。 - */} -
- - {beforeTokens > 0 && ( - - )} - - {t.inputOutput(compact(ctx), compact(s.output_tokens))} - - - } - /> - - - {beforeCost > 0 && ( - - )} - {s.cost_micros_estimated > 0 && ( - - - {t.estimated(usd(s.cost_micros_estimated))} - - - )} - {s.unpriced_requests > 0 && ( - /* - **这个数字要能点。**「533 条无法计价」说的是有一批请求 - 没进账,却不说是哪些模型 —— 而「去哪儿补这个价」正是 - 看到它之后唯一想做的事。点进去就是流量页筛好的那一批。 - */ - - - - )} - {s.no_usage_requests > 0 && ( - - - {t.noUsage(s.no_usage_requests)} - - - )} - {s.cost_micros_estimated === 0 && - s.unpriced_requests === 0 && - s.no_usage_requests === 0 && {t.allMeasured}} - - } - /> - - 0 && {t.failed(s.failed)} - } - note={ - <> - {t.failureRate(((s.failed / Math.max(1, s.requests)) * 100).toFixed(1))} - {live && {inFlight > 0 ? t.inFlight(inFlight) : t.idle}} - - } - /> -
- -
- (useTokens ? compact(v) : usd(v * 1000))} - /* - 悬停里每个模型那一行**和刻度同一种写法**,先取整:实时档的 - 速率是摊出来的浮点,`compact` 在一千以下原样照写。 - */ - valueFormat={(v) => - useTokens ? compact(Math.round(v)) : usd(Math.round(v * 1000)) - } - yMax={yMax} - liveEdge={live} - /> - {/* - 基线和刻度**只铺到画图区域的右边界**,右边那一栏是纵轴的刻度 - (见 `Y_AXIS_WIDTH`)。图空着的时候没有纵轴,就铺满。 - */} -
- {/* - 有失败的时段画在基线上。**不往高度里加** —— 加一格固定高度的 - 话,那一格在大桶上看不见、在小桶上直接翻倍,而它本来就不代表 - 任何数量。 - */} -
- {grid.map((g) => ( - 0 ? "bg-destructive" : "")} /> - ))} -
- {/* - 刻度**标在它说的那个时刻的正下方**。用 `justify-between` 排开的 - 话,每个字落在哪儿取决于前后几个字有多宽,而不是它说的是几点。 - 第一个靠左对齐,免得伸出图外;最后一个压在「现在」那一点下面, - 右边有纵轴那一栏让它伸过去。 - */} -
- {ticks.map((x, i) => { - const last = i === ticks.length - 1; - return ( - - {x} - - ); - })} -
-
- {/* 这一行有没有话说都占一行高:少一句就把下面整块往上提, - 正是切换时的那种来回动 */} -

- {grid.some((g) => g.failed > 0) && ( - <> - - {t.failureMarks} - - )} - {/* - 实时档下这一页有两个口径,必须说清哪个是哪个:**模型排行 - 是这张图的图例**(色块要对得上曲线里那一层),所以跟着图 - 走;而十分钟里算不出像样的分位延迟和命中率,那些连同顶部的数字 - 一起按 24 小时算。 - */} - {live && {t.liveScope}} -

-
- - {nothingYet && ( -

- {t.pointClients(gatewayHint)} - {s.locally_answered > 0 && t.probesAnswered(s.locally_answered)} -

- )} - -
- {/* - 图例和构成合成一张排行。**药丸式的一行图例在模型一多就会折行, - 而且不携带比例。**这里的条长就是占比,色块和曲线里那一层同色 - —— 图例的职责就是那个映射,保留下来了。 - */} - {/* - **这一块永远在。**它在「有数据」和「没数据」之间消失的话, - 切一次时间范围整页就上下弹一次。没有数据时留一行字占住。 - */} - - {keys.length === 0 && ( -

- {live ? t.waiting : t.noRequests} -

- )} - {[...top, ...(rest.length > 0 ? [otherKey] : [])].map((k) => { - const c = k === otherKey ? restMoney : (money.get(k) ?? 0); - const v = k === otherKey ? restVolume : (volume.get(k) ?? 0); - const n = k === otherKey ? restCount : (count.get(k) ?? 0); - const color = colorOf.get(k); - return ( -
- - - {k === otherKey ? t.otherCount(rest.length) : k} - - - - - - - {compact(v)} - - - - {usd(c)} - - - {t.times(n)} - -
- ); - })} -
- - {/* - 缓存。**要的是率,不是累计量** —— 「省了多少」在一个长会话里 - 只会一路涨,它回答不了「缓存到底有没有在起作用」。 - */} - - {ctx === 0 ? ( -

{t.noTokens}

- ) : ( - <> -
- - {hit == null ? "—" : `${Math.round(hit * 100)}%`} - - {t.hitRate} - {/* 这根条**就是命中率的公式本身**:三段按单价排,亮的越长越省 */} - - - - - - {/* - **净额,不是毛额。**缓存写入通常按高于输入的单价计费, - 只统计命中省下的部分,等于声称缓存永远只会降低支出 —— - 而一份反复重建缓存、命中很少的用法,实际账单高于不使用 - 缓存。倍率各家不同,这个数是按每个模型自己的价目算的。 - */} - - {s.cache_saved_micros < 0 ? t.netCost : t.netSavings}{" "} - - {usd(Math.abs(s.cache_saved_micros))} - - - {/* - **不解释倍率。**读写各按几倍计费是某一家的价目,而这一 - 页上的模型可能来自任何一家上游 —— 把一家的计费规则写死 - 在界面上,对别家就是错的。 - - 旁边那个净节省已经说清了结论,而它是按**每个模型自己的 - 价目**算出来的;读写比只是那个结论的来路,摆在这里让人 - 能自己看一眼比例,不需要再加一段说明。 - */} - {ratio != null && ( - - {t.readWrite} {ratio.toFixed(1)} : 1 - - )} -
- {/* 同上:不标倍率。三段的顺序本身就是从便宜到贵 */} -
- - - -
- - )} -
- - {/* - **左右两栏,各自纵向长。**「哪个模型慢」的下一步是换模型, - 「哪家上游慢」的下一步是换上游 —— 两个问题各占一栏。排成一行 - 的话,上游一多就横向挤爆了。 - */} - - {d.latency.length === 0 ? ( -

{t.notEnoughSamples}

- ) : ( -
-
-

{t.byModel}

- -
- {has.comparison && d.latency_by_provider.length > 0 && ( -
-

{t.byUpstream}

- -
- )} -
- )} -
- - {/* - 安全。**没有发现时也在,而且说「未发现」。**这一页别处的纪律 - 是「条件不满足就不出现」—— 那条对成本面板成立:一排零不构成 - 安心。但安全是反过来的:**看不见的防护会被当成没开**。 - */} - {guards.length > 0 && ( - - {guards.map((g) => ( -
- 0 - ? "bg-destructive" - : "bg-cache-hit") - } - /> - {g.name} - {/* 56px:Observe 要 51,44 的话会压到后面那一列上 */} - {label(g.mode)} - {g.hits > 0 ? ( - - - - ) : ( - {g.saw} - )} -
- ))} -
- )} -
- - {open != null && setOpen(null)} />} - - {/* 存储状态。**正常时不显示** —— 没问题的时候不该占地方 */} - {d.storage && !d.storage.recording && ( - - - {t.recordingUnavailable} - {!d.storage.forwarding_affected && t.forwardingUnaffected} - - - )} -
- ); -} diff --git a/src/index.css b/src/index.css index 7f9d6e22..2fb9d977 100644 --- a/src/index.css +++ b/src/index.css @@ -63,6 +63,7 @@ --color-chart-3: var(--chart-3); --color-chart-4: var(--chart-4); --color-chart-5: var(--chart-5); + --color-chart-other: var(--chart-other); --color-cache-hit: var(--cache-hit); --color-cache-plain: var(--cache-plain); --color-cache-write: var(--cache-write); @@ -169,6 +170,9 @@ --chart-3: oklch(0.72 0.07 249); --chart-4: oklch(0.8 0.05 246); --chart-5: oklch(0.86 0.032 243); + /* 前五项以外合并成的「其他」那一层:灰的。它不是一个模型,不该和排第五的那个 + * 模型同色 —— 两层同色叠在一起就读成了一层 */ + --chart-other: oklch(0.84 0.004 250); /* 缓存构成条的三段。**排列依据是计费单价,不是类别**:命中 0.1 倍、 * 新输入 1 倍、写入 1.25 倍 —— 亮的那一段越长越省。写入用一档收敛的 * 琥珀(不是告警用的 `--warning`):它是唯一会抬高总支出的部分。 */ @@ -220,6 +224,7 @@ --chart-3: oklch(0.51 0.065 251); --chart-4: oklch(0.42 0.045 247); --chart-5: oklch(0.35 0.03 244); + --chart-other: oklch(0.4 0.006 250); --cache-hit: oklch(0.76 0.12 174); --code-key: oklch(97% 0 none); --code-string: oklch(0.78 0.11 160); @@ -376,6 +381,16 @@ box-shadow: 0 0 0 5px color-mix(in oklab, currentColor 0%, transparent); } } +@keyframes tw-ping { + from { + transform: scale(1); + opacity: 0.6; + } + to { + transform: scale(3.4); + opacity: 0; + } +} @keyframes tw-shimmer { 0%, 100% { @@ -413,6 +428,14 @@ @utility motion-live { animation: tw-live 1.6s var(--motion-ease) infinite; } +/* 新数据落地:一个点向外闪一圈,放一次(不循环)。SVG 元素也能用 —— 缩放按它自己 + * 的中心。要再闪一次就换 React key 重新挂上(概览图上「现在」那一点) */ +@utility motion-ping { + transform-box: fill-box; + transform-origin: center; + animation: tw-ping 900ms var(--motion-ease) both; + pointer-events: none; +} /* 骨架的明暗。比 `animate-pulse` 慢、幅度小,读起来是「在取」而不是「在闪」 */ @utility motion-shimmer { animation: tw-shimmer 1.6s ease-in-out infinite; @@ -433,6 +456,10 @@ .motion-row-out { animation-duration: 1ms; } + .motion-ping { + animation: none; + visibility: hidden; + } .motion-bar, .motion-list-height { transition: none; diff --git a/src/overview/CacheSection.tsx b/src/overview/CacheSection.tsx new file mode 100644 index 00000000..db1ec70b --- /dev/null +++ b/src/overview/CacheSection.tsx @@ -0,0 +1,135 @@ +import { cn } from "@/lib/utils"; +import { PageSection } from "@/ui/page"; +import { AnimatedNumber, rowMotion, usePresentList } from "@/ui/motion"; +import { Tip } from "@/ui/tip"; +import { useNav } from "@/nav"; +import { compact } from "@/format"; +import { usd, type Dashboard } from "@/types"; +import { useText } from "@/i18n"; +import { cacheByModel, ROWS } from "./series"; +import { ColumnHead, LinkRow, Meter, ModelMark, Scope } from "./parts"; +import { overviewText } from "./overview.i18n"; + +const pct = (n: number) => `${Math.round(n)}%`; +const fmtTokens = (n: number) => compact(Math.round(n)); +const fmtRatio = (n: number) => `${n.toFixed(1)} : 1`; + +/** + * 缓存。**要的是率,不是累计量** —— 「省了多少」在一个长会话里只会一路涨,它 + * 回答不了「缓存到底有没有在起作用」。 + * + * 左边是这段时间的总账:命中率和净节省,一根构成条,条下面逐项列出三段各多少、 + * 占几成,最后是读写比;右边是各模型的命中率,回答「是哪个模型的缓存没起作用」。 + * 点一个模型落到流量页,看它的请求。 + */ +export function CacheSection({ d, scope, scoped }: { d: Dashboard; scope: string; scoped?: string }) { + const t = useText(overviewText); + const nav = useNav(); + const s = d.summary; + /* + **「输入」是送往上游的全部上下文,包含命中缓存的那部分。**`input_tokens` 单独 + 一个字段说的是「没命中缓存的那部分」。 + */ + const ctx = s.input_tokens + s.cache_read_tokens + s.cache_write_tokens; + const hit = ctx > 0 ? s.cache_read_tokens / ctx : 0; + const ratio = s.cache_write_tokens > 0 ? s.cache_read_tokens / s.cache_write_tokens : null; + const models = cacheByModel(d, t.unknownModel); + const shown = usePresentList(models.slice(0, ROWS - 1), (r) => r.name); + const saved = s.cache_saved_micros; + /* 三段按单价从低到高排:读缓存最便宜、写缓存最贵。**不标倍率** —— 读写各按几倍计费 + 是某一家的价目,而这一页上的模型可能来自任何一个上游 */ + const parts = [ + { key: "read", color: "bg-cache-hit", name: t.cacheReads, n: s.cache_read_tokens }, + { key: "plain", color: "bg-cache-plain", name: t.uncachedInput, n: s.input_tokens }, + { key: "write", color: "bg-cache-write", name: t.cacheWrites, n: s.cache_write_tokens }, + ]; + + return ( + {scoped} : undefined}> + {ctx === 0 ? ( +

{t.noTokens}

+ ) : ( +
+
+
+
+ + {t.hitRate} + {/* + **净额,不是毛额。**缓存写入通常按高于输入的单价计费,只统计命中省下 + 的部分,等于声称缓存永远只会降低支出 —— 而一份反复重建缓存、命中很少 + 的用法,实际费用高于不使用缓存。这个数按每个模型自己的价目算。 + */} + + {saved < 0 ? t.netCost : t.netSavings}{" "} + + +
+ {/* 这根条**就是命中率的公式本身**:三段按单价排,亮的越长越省 */} +
+ {parts.map((p) => ( + + ))} +
+
+ {parts.map((p) => ( + +
+ + {p.name} + + +
+
+ ))} + {ratio != null && ( +
+ + {t.readWrite} + +
+ )} +
+
+ +
+ {t.hitByModel} + {shown.map(({ item: r, key, presence }) => ( + nav.open("requests", { grouped: false, filter: { q: r.name } })} + > + + + {r.name} + + + + + + + + + ))} + {models.length > ROWS - 1 && ( +

{t.moreNotListed(models.length - (ROWS - 1))}

+ )} +
+
+
+ )} +
+ ); +} diff --git a/src/overview/HeroStats.tsx b/src/overview/HeroStats.tsx new file mode 100644 index 00000000..4843f65c --- /dev/null +++ b/src/overview/HeroStats.tsx @@ -0,0 +1,223 @@ +import type { ReactNode } from "react"; +import { ArrowDownRightIcon, ArrowRightIcon, ArrowUpRightIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { AnimatedNumber } from "@/ui/motion"; +import { Tip } from "@/ui/tip"; +import type { Range } from "@/ui/range"; +import { useNav } from "@/nav"; +import { compact } from "@/format"; +import { usd, type Dashboard, type Summary } from "@/types"; +import { useText } from "@/i18n"; +import { LinkText } from "./parts"; +import { overviewText } from "./overview.i18n"; + +/** 一段时间里的 token 合计。**「输入」含命中缓存的那部分**,见下面 `ctx` */ +function tokensOf(s: Summary): number { + return s.input_tokens + s.cache_read_tokens + s.cache_write_tokens + s.output_tokens; +} + +function costOf(s: Summary): number { + return s.cost_micros_exact + s.cost_micros_estimated; +} + +const fmtTokens = (n: number) => compact(Math.round(n)); +const fmtCount = (n: number) => Math.round(n).toLocaleString(); + +/** + * 页头下面的三个大数:**用了多少、费用多少、发了多少次**。 + * + * 它们是同一层的事实,所以同一个字号、同一个宽度的栏,中间一道细竖线。每一栏 + * 四层,从上到下一层比一层轻:名目、数、环比、限定语。 + * + * **等宽栏,而不是并排的弹性块。**后者会让「较上一个区间」这类时有时无的限定语 + * 改变每一栏的宽度,切一次范围三个数字就横向挪一次位置。环比和限定语那两行也 + * 定高:少一条时不该把整页往上收。 + * + * 数字走过去,不跳过去 —— 限定语里的数也一样;**只在同一个口径里走** + * (`scope`):换时间范围时那不是「涨了」,是换了一个东西在看。 + */ +export function HeroStats({ d, range, scope }: { d: Dashboard; range: Range; scope: string }) { + const t = useText(overviewText); + const nav = useNav(); + const s = d.summary; + const p = d.prev; + /* + **「输入」是送往上游的全部上下文,包含命中缓存的那部分。**`input_tokens` + 单独一个字段说的是「没命中缓存的那部分」—— 命中率高的时候它只有真实输入的 + 零头,标成「输入」会让人以为自己几乎没用。 + */ + const ctx = s.input_tokens + s.cache_read_tokens + s.cache_write_tokens; + const tokens = tokensOf(s); + const cost = costOf(s); + const rate = (s.failed / Math.max(1, s.requests)) * 100; + /* + **和上一个区间比。**上一个区间是零(刚开始用、或者那段时间没用)时没有可比的 + 幅度,写一个「—」占住这一格,而不是空着 —— 空着的那一行读起来像少画了什么。 + 取不到上一个区间(`prev` 为空)时整行空着:那是读取失败,不是「没有」。 + */ + const vs = (now: number, before: number | undefined, good?: "down") => + before === undefined ? null : before > 0 ? ( + + ) : ( + + ); + + return ( +
+ } + delta={vs(tokens, p ? tokensOf(p) : undefined)} + detail={ + + + {t.input} + {" · "} + {t.output} + + + } + /> + } + delta={vs(cost, p ? costOf(p) : undefined, "down")} + detail={ + <> + {s.cost_micros_estimated > 0 && ( + + + t.estimated(usd(n))} + scope={scope} + /> + + + )} + {s.unpriced_requests > 0 && ( + /* + **这个数字要能点。**「533 条无法计价」说的是有一批请求没进账,却不说 + 是哪些模型 —— 而「去哪儿补这个价」正是看到它之后唯一想做的事。点进去 + 就是流量页筛好的那一批(归组态下看不出是哪些模型,所以不归组)。 + */ + + nav.open("requests", { grouped: false, filter: { unpricedOnly: true } })} + > + t.unpriced(Math.round(n))} + scope={scope} + /> + + + )} + {s.no_usage_requests > 0 && ( + + + t.noUsage(Math.round(n))} + scope={scope} + /> + + + )} + {s.cost_micros_estimated === 0 && s.unpriced_requests === 0 && s.no_usage_requests === 0 && ( + {t.allMeasured} + )} + + } + /> + } + delta={vs(s.requests, p?.requests)} + detail={ + <> + {s.failed > 0 && ( + + nav.open("requests", { grouped: false, filter: { failedOnly: true } })} + > + t.failed(Math.round(n))} scope={scope} /> + + + )} + t.failureRate(n.toFixed(1))} scope={scope} /> + + } + /> +
+ ); +} + +function Stat({ + label, + value, + delta, + detail, +}: { + label: ReactNode; + value: ReactNode; + delta: ReactNode; + detail: ReactNode; +}) { + return ( +
+

{label}

+

{value}

+
{delta}
+
+ {detail} +
+
+ ); +} + +/** + * 一个环比:左边一小块写方向和幅度,右边写和什么比。 + * + * **没有参照系的数字只能读,不能判断。**只有费用那一侧有「好坏」:少花是好事, + * 所以降下来才上色。用量和请求数两个方向都不上色 —— 多用掉一些 token 不是问题, + * 少用也不是成绩。不到百分之一算持平,箭头放平。 + */ +function Delta({ v, period, good }: { v: number; period: string; good?: "down" }) { + const t = useText(overviewText); + const shown = Math.round(Math.abs(v * 100)); + const flat = shown === 0; + const better = !flat && good === "down" && v < 0; + const Icon = flat ? ArrowRightIcon : v < 0 ? ArrowDownRightIcon : ArrowUpRightIcon; + return ( + <> + + + {shown.toLocaleString()}% + + {t.deltaVs(period)} + + ); +} + +/** 上一个区间没有数据:幅度那一格写「—」,和有幅度时同一个形状 */ +function NoDelta({ period }: { period: string }) { + const t = useText(overviewText); + return ( + <> + + + — + + + {t.deltaVs(period)} + + ); +} diff --git a/src/overview/LatencySection.tsx b/src/overview/LatencySection.tsx new file mode 100644 index 00000000..698fc015 --- /dev/null +++ b/src/overview/LatencySection.tsx @@ -0,0 +1,186 @@ +import type { ReactNode } from "react"; +import { cn } from "@/lib/utils"; +import { PageSection } from "@/ui/page"; +import { AnimatedNumber, rowMotion, usePresentList } from "@/ui/motion"; +import { Tip } from "@/ui/tip"; +import { UpstreamLogo } from "@/ui/logos"; +import { useNav } from "@/nav"; +import type { Dashboard, LatencyView, Overview } from "@/types"; +import { useText } from "@/i18n"; +import { fmtMs, latencyRows, ROWS } from "./series"; +import { LinkRow, ModelMark, Scope } from "./parts"; +import { overviewText } from "./overview.i18n"; + +/** 样本少于这个数,分位数不可靠:样本数那一格标黄 */ +const FEW = 10; + +/** + * 一行里数字那几列的宽度。**表头和每一行用同一套**,列才对得齐。条宽固定: + * 两栏的条这样才对齐,能横着比。 + */ +const COL = { + bar: "w-20", + p50: "w-12", + p95: "w-12", + samples: "w-9", +} as const; + +/** + * 延迟:首字节时间的 P50 和 P95。 + * + * **左右两栏,各自纵向长。**「哪个模型慢」的下一步是换模型,「哪个上游慢」的 + * 下一步是换上游 —— 两个问题各占一栏。只有一个上游时右栏没有可比的,不画。 + * 窄窗口里两栏上下排:并排的话模型名会被挤成省略号,而名字是这一栏最要紧的字。 + * + * 用分位数不用平均值:AI 延迟是长尾分布,平均值会被极端值拉偏。点一行落到流量 + * 页:模型填进搜索框,上游选进「上游」筛选。 + */ +export function LatencySection({ + d, + ov, + scope, + scoped, +}: { + d: Dashboard; + ov: Overview | null; + scope: string; + scoped?: string; +}) { + const t = useText(overviewText); + const nav = useNav(); + // 两栏的条按同一把尺子画,才能横着比 + const max = Math.max(1, ...d.latency.map((l) => l.p95), ...d.latency_by_provider.map((l) => l.p95)) * 1.04; + const upstreams = d.latency_by_provider.length >= 2; + const providers = new Map((ov?.providers ?? []).map((p) => [p.name, p])); + return ( + + {t.latencyWhat} + {scoped && ` · ${scoped}`} + + } + > + {d.latency.length === 0 ? ( +

{t.notEnoughSamples}

+ ) : ( + // 并排按这一块自己的宽度判断,不按窗口:源列表收起、展开时内容区宽度不一样 +
+
+ } + onOpen={(name) => nav.open("requests", { grouped: false, filter: { q: name } })} + /> + {upstreams && ( + { + const p = providers.get(name); + return ( + + ); + }} + onOpen={(name) => nav.open("requests", { grouped: false, filter: { provider: name } })} + /> + )} +
+
+ )} +
+ ); +} + +/** + * 一栏分位区间,带一行表头。 + * + * **区间条,不是只有两列数字。**并排的两列时间要逐行读才能比较,而这一栏要回答 + * 的是「哪个又慢又不稳定」—— 那是条的起点加长度,一次扫视就能得到。条左端那道 + * 竖线是 P50:多数请求落在它附近;条伸到 P95。 + */ +function Spreads({ + head, + rows, + max, + scope, + mark, + onOpen, +}: { + head: string; + rows: LatencyView[]; + max: number; + scope: string; + mark: (name: string) => ReactNode; + onOpen: (name: string) => void; +}) { + const t = useText(overviewText); + const sorted = latencyRows(rows); + const shown = usePresentList(sorted.slice(0, ROWS), (l) => l.model); + return ( +
+ {/* 表头:和下面每一行同一套列宽,行尾留出箭头那一格 */} +
+ {head} + + P50 + P95 + {t.samples} + +
+ {shown.map(({ item: l, key, presence }) => ( + onOpen(l.model)} + > + {mark(l.model)} + + {l.model} + + + + + + + + + + + + + + {/* + **样本数要显示**:「800ms」是 3 个样本还是 300 个,含义完全不同。不可靠的 + 是**样本数**,不是延迟值 —— 所以只标这个数。 + */} + {l.samples < FEW ? ( + + {l.samples} + + ) : ( + + {l.samples} + + )} + + ))} + {rows.length > ROWS &&

{t.moreNotListed(rows.length - ROWS)}

} +
+ ); +} diff --git a/src/overview/ModelRanking.tsx b/src/overview/ModelRanking.tsx new file mode 100644 index 00000000..0846a5fc --- /dev/null +++ b/src/overview/ModelRanking.tsx @@ -0,0 +1,90 @@ +import { cn } from "@/lib/utils"; +import { AnimatedNumber, rowMotion, usePresentList } from "@/ui/motion"; +import { Tip } from "@/ui/tip"; +import { useNav } from "@/nav"; +import { compact } from "@/format"; +import { usd } from "@/types"; +import { useText } from "@/i18n"; +import type { Metric, RankRow } from "./series"; +import { LinkRow, MarkSpace, Meter, ModelMark } from "./parts"; +import { overviewText } from "./overview.i18n"; + +const fmtTokens = (n: number) => compact(Math.round(n)); + +/** + * 模型排行,也是上面那张图的图例:条的颜色就是图里那一层的颜色,条长按当前口径 + * 里最大的那一项归一。 + * + * **药丸式的一行图例在模型一多就会折行,而且不携带比例。**这里的条长就是占比, + * 图例的职责(颜色 ↔ 模型的映射)留下来了。 + * + * **这一块永远在。**它在「有数据」和「没数据」之间消失的话,切一次时间范围整页 + * 就上下弹一次。没有数据时留一行字占住。 + * + * 点一行:落到流量页,搜索框里填上这个模型名。合并的「其他」那一行不能点 —— + * 它不是一个模型。 + */ +export function ModelRanking({ + rows, + by, + topBar, + scope, + empty, + onFocus, +}: { + rows: RankRow[]; + by: Metric; + topBar: number; + scope: string; + empty: string; + /** 指着(悬停、键盘聚焦)哪一行:图里突出那一层。离开时是 `null` */ + onFocus: (name: string | null) => void; +}) { + const t = useText(overviewText); + const nav = useNav(); + const shown = usePresentList(rows, (r) => r.name); + if (rows.length === 0 && shown.length === 0) + return

{empty}

; + const tokensMode = by === "token"; + return ( +
+ {shown.map(({ item: r, key, presence }) => ( + nav.open("requests", { grouped: false, filter: { q: r.name } })} + onPoint={(on) => onFocus(on ? r.name : null)} + > + {r.merged ? : } + + {r.merged ? t.otherCount(r.merged) : r.name} + + + + + + + + + {/* + **用了 token 却没有费用,不写「$0」。**那可能是未定价(费用没算进来),也 + 可能是不计费(本地模型)—— 分组的格子里没有「无法计价」的条数,分不出是哪 + 一种,而「$0」只在后一种情况下是真的。 + */} + {r.cost === 0 && r.tokens > 0 ? ( + + — + + ) : ( + + )} + + + t.times(Math.round(n))} scope={scope} /> + + + ))} +
+ ); +} diff --git a/src/overview/OverviewPage.tsx b/src/overview/OverviewPage.tsx new file mode 100644 index 00000000..63f87e3f --- /dev/null +++ b/src/overview/OverviewPage.tsx @@ -0,0 +1,210 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; +import { Page, PageHeader } from "@/ui/page"; +import { Banner } from "@/ui/banner"; +import { Button } from "@/ui/button"; +import { EmptyState, ErrorState } from "@/ui/states"; +import { RangePicker, useRange } from "@/ui/range"; +import { IconDashboard } from "@/ui/icons"; +import { rangeText } from "@/ui/range.i18n"; +import { useNav } from "@/nav"; +import type { Dashboard, Overview } from "@/types"; +import { useText } from "@/i18n"; +import { useOverview, type Shown } from "./useOverview"; +import { OverviewStatus } from "./OverviewStatus"; +import { OverviewSkeleton } from "./OverviewSkeleton"; +import { HeroStats } from "./HeroStats"; +import { TrendSection } from "./TrendSection"; +import { CacheSection } from "./CacheSection"; +import { LatencySection } from "./LatencySection"; +import { SecuritySection } from "./SecuritySection"; +import type { Metric } from "./series"; +import { overviewText } from "./overview.i18n"; + +/** 图的口径记在这里:换页、重开窗口回来还是上次那一档 */ +const METRIC_KEY = "tw-overview-metric"; + +function useMetric(): [Metric, (m: Metric) => void] { + const [by, set] = useState(() => { + try { + return window.localStorage.getItem(METRIC_KEY) === "cost" ? "cost" : "token"; + } catch { + // 隐私窗口、禁用站点数据都会在这里抛。记不住就用默认的 + return "token"; + } + }); + const put = useCallback((m: Metric) => { + set(m); + try { + window.localStorage.setItem(METRIC_KEY, m); + } catch { + // 存不下就只在这一程里记着 + } + }, []); + return [by, put]; +} + +/** + * 一次请求都还没记下过:只有本地应答的探测(或者什么都没有)。这时一排零和一张 + * 空图什么都说明不了,换成一块空状态,说清怎样才会有数据。 + * + * **看的是库里一共记了多少条**,不是所选区间里有几条:用过、只是这一天没用的, + * 仍然是那张有零有图的页 —— 它能换区间看以前的。库没起来(`recording` 为假)时 + * 不算:那时顶上有一条横幅在说这件事。 + */ +function neverUsed(d: Dashboard): boolean { + const st = d.storage; + return st !== null && st.recording && d.summary.requests === 0 && st.rows <= d.summary.locally_answered; +} + +/** + * 用量概览。 + * + * 这一页的每一个数字都受那条约束:**绝不让估算值混进精确数字里假装准确。**所以 + * 金额旁边永远跟着它的限定词。 + * + * 版面:页头(状态一行、时间范围),三个大数,一张按模型分层的趋势图和它的图例 + * (模型排行),然后是缓存、延迟、安全三节。**参照物是原生监控工具,不是网页 + * 后台** —— 没有卡片网格,节与节之间只有留白和细线。 + * + * 实时档只有图和模型排行是实时的(十分钟,跟着事件流走);大数、缓存、延迟、安全 + * 按最近 24 小时算,节标题右边标着。 + */ +export default function OverviewPage({ + tick, + ov, + onLanded, +}: { + /** 库里多了请求、手动刷新:重取 */ + tick: number; + ov: Overview | null; + /** 第一份数据到了(或者确定取不到了)。启动画面等它再交接 */ + onLanded?: () => void; +}) { + const t = useText(overviewText); + const rt = useText(rangeText); + const nav = useNav(); + const [range, setRange] = useRange(); + const [by, setBy] = useMetric(); + const o = useOverview(range, tick); + + const landed = useRef(onLanded); + landed.current = onLanded; + const settled = o.shown !== null || o.failed; + useEffect(() => { + if (settled) landed.current?.(); + }, [settled]); + + return ( + + } + actions={} + /> + {o.failed ? ( + void o.reload()} retrying={o.retrying} /> + ) : o.shown === null ? ( + + ) : ( + + ov && ov.providers.length === 0 ? nav.open("upstreams", { create: "upstream" }) : nav.open("clients") + } + /> + )} + + ); +} + +function Body({ + shown, + ov, + by, + onBy, + switching, + day, + onSetUp, +}: { + shown: Shown; + ov: Overview | null; + by: Metric; + onBy: (m: Metric) => void; + /** 选中的区间还在取,画的是上一个区间的 */ + switching: boolean; + /** 「24 小时」:实时档下不跟着图走的那几节按它算 */ + day: string; + onSetUp: () => void; +}) { + const t = useText(overviewText); + const { data: d, range, id } = shown; + const live = range.live === true; + // 实时档下,不跟着图走的那几节标出它们的口径 + const scoped = live ? day : undefined; + const recording = d.storage === null || d.storage.recording; + const noUpstreams = ov !== null && ov.providers.length === 0; + return ( +
+ {/* 存储状态。**正常时不显示** —— 没问题的时候不该占地方 */} + + {d.storage && !d.storage.forwarding_affected && t.forwardingUnaffected} + + + {neverUsed(d) ? ( + } + title={t.emptyTitle} + description={ + <> + {noUpstreams ? t.emptyHintNoUpstream : t.emptyHint} + {d.summary.locally_answered > 0 && ( + <> +
+ {t.probesAnswered(d.summary.locally_answered)} + + )} + + } + action={ + + } + /> + ) : ( + <> + + + + + + )} + +
+ ); +} diff --git a/src/overview/OverviewSkeleton.tsx b/src/overview/OverviewSkeleton.tsx new file mode 100644 index 00000000..58faba8a --- /dev/null +++ b/src/overview/OverviewSkeleton.tsx @@ -0,0 +1,80 @@ +import type { ReactNode } from "react"; +import { cn } from "@/lib/utils"; +import { Skeleton } from "@/ui/skeleton"; + +/** + * 第一次读数据时的骨架,**和读完之后的版面逐块对齐**:三栏大数、趋势图(连同基线、 + * 刻度和图下那一行)、模型排行。每一块的外框和真实版面同高 —— 数据到了,骨架原地 + * 换成内容,下面的东西一个像素都不挪。 + * + * **不是一句「读取中…」。**那一行字占的地方和真正的内容差着好几百像素,读完之后 + * 整页会跳一次;而这一页最大的那几个数字恰好在跳动的位置上。 + */ +export function OverviewSkeleton() { + return ( +
+ {/* 三个大数:名目 19、数 42、环比 20、限定语 16,间距同 `Stat` */} +
+ {[0, 1, 2].map((i) => ( +
+ + + + + + + + + + + + + +
+ ))} +
+ + {/* 趋势:标题行 28(右边是口径的分段控件),图 200,基线和刻度 30,图下一行 16 */} +
+
+ + +
+ +
+ +
+ {[0, 1, 2, 3, 4, 5].map((i) => ( + + ))} +
+
+
+
+ + {/* 模型排行:标题 19,行 32 */} +
+ + + + {[0.9, 0.35, 0.22, 0.12].map((w, i) => ( +
+ + +
+ +
+ + + +
+ ))} +
+
+ ); +} + +/** 一格定高的外框:里面的骨架条竖着居中 */ +function Box({ h, children }: { h: string; children: ReactNode }) { + return
{children}
; +} diff --git a/src/overview/OverviewStatus.tsx b/src/overview/OverviewStatus.tsx new file mode 100644 index 00000000..2b52e340 --- /dev/null +++ b/src/overview/OverviewStatus.tsx @@ -0,0 +1,62 @@ +import { SummaryItem } from "@/ui/page"; +import { StatusDot } from "@/ui/status-dot"; +import { AnimatedNumber } from "@/ui/motion"; +import { Tip } from "@/ui/tip"; +import { useNav } from "@/nav"; +import type { Overview, ProviderView } from "@/types"; +import { useText } from "@/i18n"; +import { useInFlight } from "./useLive"; +import { LinkText } from "./parts"; +import { overviewText } from "./overview.i18n"; + +/** + * 上游现在用不了:熔断中、凭据被拒、登录失效。**停用的不算** —— 那是有意关掉的。 + * 和上游页那一行上的三个标记是同一套判断。 + */ +function unavailable(p: ProviderView): boolean { + return !p.disabled && (p.health === "open" || p.auth_rejected != null || p.oauth?.needs_login === true); +} + +/** + * 页头下面那一行:此刻的状态。**只有数字和状态点,不写说明。** + * + * · 有几个请求在跑。跑着的时候点在跳,一直显示,不只在实时档:这是「网关此刻 + * 在不在干活」。它自己订阅事件流,一变只重画这一小块。 + * · 有几个上游,其中几个用不了。用不了的那一项可以点,落到上游页并定位到它。 + * 还没有上游时说「尚未添加上游」,同样可以点。 + */ +export function OverviewStatus({ ov }: { ov: Overview | null }) { + const t = useText(overviewText); + const nav = useNav(); + const n = useInFlight(); + const providers = ov?.providers.filter((p) => !p.disabled); + const down = ov?.providers.filter(unavailable) ?? []; + return ( + <> + {n > 0 ? ( + } value={} label={t.inFlight(n)} /> + ) : ( + } label={t.idle} /> + )} + {providers && + (providers.length === 0 ? ( + nav.open("upstreams")}> + } label={t.noUpstreams} /> + + ) : ( + } label={t.upstreams(providers.length)} /> + ))} + {down.length > 0 && ( + + nav.open("upstreams", { upstream: down[0]?.name })}> + } + value={} + label={t.unavailable(down.length)} + /> + + + )} + + ); +} diff --git a/src/overview/SecuritySection.tsx b/src/overview/SecuritySection.tsx new file mode 100644 index 00000000..b4007a3a --- /dev/null +++ b/src/overview/SecuritySection.tsx @@ -0,0 +1,134 @@ +import { cn } from "@/lib/utils"; +import { PageSection } from "@/ui/page"; +import { StatusDot, type StatusTone } from "@/ui/status-dot"; +import { presetRange, type Range } from "@/ui/range"; +import { useNav } from "@/nav"; +import type { Dashboard, Guard, Overview } from "@/types"; +import { useText } from "@/i18n"; +import { LinkRow, Scope } from "./parts"; +import { overviewText } from "./overview.i18n"; + +/** + * 安全:各项防护现在各在哪一档,以及这段时间各自看见了什么。 + * + * **档位和所见要一起说。**只说所见的话,「未发现」在关闭档下是句空话;只说档位 + * 的话,不知道它到底拦下过什么。 + * + * **没有发现时也在,而且说「未发现」。**这一页别处的纪律是「条件不满足就不 + * 出现」—— 那条对费用面板成立:一排零不构成安心。但安全是反过来的:**看不见的 + * 防护会被当成没开**。 + * + * **数的是安全日志里的条数**,和从这里点进去看到的是同一批(起点都按 + * `windowStart` 算)。有发现的那一行可以点,落到安全日志的这一段时间。 + */ +export function SecuritySection({ + d, + ov, + range, + scoped, +}: { + d: Dashboard; + ov: Overview | null; + range: Range; + scoped?: string; +}) { + const t = useText(overviewText); + const nav = useNav(); + const sec = ov?.security; + if (!sec) return null; + const c = d.summary.security; + const mode = (m: string) => (m === "enforce" ? t.modeEnforce : m === "off" ? t.modeOff : t.modeObserve); + const guards: { + key: Guard; + name: string; + mode: string; + hits: number; + /** + * 没被处置、照常放行了的那几处。**有它才标琥珀** —— 全换掉了、全切断了,说明防护 + * 在起作用。和安全日志同一套语气(`outcomeTone`):仅记录的是琥珀,值得看一眼; + * 红色留给「请求的结局变了」,而概览这一行说的不是某一次请求。 + */ + open: number; + saw: string; + }[] = [ + { + key: "redact", + name: t.redact, + mode: sec.redact, + hits: c.secrets, + open: c.secrets - c.secrets_replaced, + saw: c.secrets > 0 ? t.secrets(c.secrets, c.secrets_replaced) : sec.redact === "off" ? t.notChecked : t.noSecrets, + }, + { + key: "inspect_tools", + name: t.inspect, + mode: sec.inspect_tools, + hits: c.tool_calls, + open: c.tool_calls - c.tool_calls_cut, + saw: + c.tool_calls > 0 + ? t.toolCalls(c.tool_calls, c.tool_calls_cut) + : sec.inspect_tools === "off" + ? t.notChecked + : t.noToolCalls, + }, + { + key: "hidden_text", + name: t.hiddenText, + mode: sec.hidden_text, + hits: c.hidden_text, + open: c.hidden_text - c.hidden_text_blocked, + saw: + c.hidden_text > 0 + ? t.hiddenFound(c.hidden_text, c.hidden_text_blocked) + : sec.hidden_text === "off" + ? t.notChecked + : t.noHidden, + }, + { + key: "content", + name: t.content, + mode: sec.content, + hits: c.content, + open: c.content - c.content_blocked, + saw: + c.content > 0 ? t.contentMatched(c.content, c.content_blocked) : sec.content === "off" ? t.notChecked : t.noContent, + }, + { + key: "output_limit", + name: t.outputLimit, + mode: sec.output_limit, + hits: c.output_limit, + open: c.output_limit - c.output_limit_cut, + saw: + c.output_limit > 0 + ? t.overLimit(c.output_limit, c.output_limit_cut) + : sec.output_limit === "off" + ? t.notChecked + : t.noOverLimit, + }, + ]; + // 实时档的计数按 24 小时算(见 `windowStart`),日志也按 24 小时看 + const openLog = () => + nav.open("security", { focus: { range: range.live ? presetRange("1d") : range, at: Date.now() } }); + + return ( + {scoped} : undefined}> + {guards.map((g) => { + const tone: StatusTone = g.mode === "off" && g.hits === 0 ? "idle" : g.open > 0 ? "warn" : "ok"; + return ( + 0 ? t.showLog : undefined} onOpen={g.hits > 0 ? openLog : undefined}> + + {g.name} + {/* 56px:Observe 要 51,44 的话会压到后面那一列上 */} + {mode(g.mode)} + {/* 颜色只在点上。有发现的那句用正文色 —— 一整句染色读起来像报错 */} + + {g.saw} + + + ); + })} + + ); +} diff --git a/src/overview/TrendSection.tsx b/src/overview/TrendSection.tsx new file mode 100644 index 00000000..34c91106 --- /dev/null +++ b/src/overview/TrendSection.tsx @@ -0,0 +1,248 @@ +import { useEffect, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; +import { StackedArea, Y_AXIS_WIDTH } from "@/ui/charts"; +import { PageSection } from "@/ui/page"; +import { Segmented } from "@/ui/segmented"; +import { Tip } from "@/ui/tip"; +import { prefersReducedMotion } from "@/ui/motion"; +import { bucketFor, type Range } from "@/ui/range"; +import { useNav } from "@/nav"; +import { compact } from "@/format"; +import { usd, type CostBucket, type Dashboard } from "@/types"; +import { useText } from "@/i18n"; +import { LIVE_BUCKET_MS, LIVE_REACH_MS, useLiveWindow } from "./useLive"; +import { buildTrend, fmtBucket, historyTicks, holdY, liveTicks, type Metric, type Tick } from "./series"; +import { ModelRanking } from "./ModelRanking"; +import { LiveBadge, Scope } from "./parts"; +import { overviewText } from "./overview.i18n"; + +/** 图多高。KPI 下面这一块是整页唯一的视觉锚点 */ +const CHART_H = 200; + +/** + * 趋势图和它的图例(模型排行)。 + * + * **放在一起是因为排行就是图例**:色块和图里那一层同色,口径(token / 费用) + * 两边一起换。实时档下两者都跟着事件流走(十分钟),每半秒往左挪一步 —— 所以 + * 事件流的订阅在这一层,页面上别的几块不跟着每一帧重画。 + */ +export function TrendSection({ + d, + range, + scope, + by, + onBy, +}: { + d: Dashboard; + range: Range; + /** 数据属于哪个区间(`rangeId`) */ + scope: string; + by: Metric; + onBy: (m: Metric) => void; +}) { + const t = useText(overviewText); + const nav = useNav(); + const live = range.live === true; + /* + **多留一个核宽的样本。**最左边那一格的鼓包有一半来自图外的那几秒;按图的 + 宽度留样本的话,左端会凭空塌下去一个口子。 + */ + const win = useLiveWindow(live, range.ms + LIVE_REACH_MS); + /** 上一次的堆叠次序:**名次要有滞回**,见 `buildTrend` */ + const stack = useRef([]); + /** 图例(模型排行)上指着的那一项:图里突出那一层 */ + const [focus, setFocus] = useState(null); + const yHold = useRef({ key: "", v: 0 }); + const bucketMs = bucketFor(range.ms); + const trend = buildTrend({ + d, + live, + by, + bucketMs, + rangeMs: range.ms, + samples: win.samples, + fails: win.fails, + now: Date.now(), + prevStack: stack.current, + t, + }); + stack.current = trend.stack; + yHold.current = holdY(yHold.current, `${by}/${scope}`, trend.peak, !live); + const yMax = yHold.current.v || undefined; + const tokensMode = by === "token"; + + /* + **动画只在换了看法的那一下放一次**:挂上(打开这一页、换了区间 —— 外面按 + 区间换 key,这一块整个重挂)时整张图从左往右铺开;换口径时同一批格子的形状 + 变过去。之后的刷新一律不动(见 `StackedArea`)。实时档从不动。 + */ + const [anim, setAnim] = useState(() => !live && !prefersReducedMotion()); + const [lastBy, setLastBy] = useState(by); + if (lastBy !== by) { + setLastBy(by); + if (!live && !prefersReducedMotion()) setAnim(true); + } + useEffect(() => { + if (!anim) return; + const h = setTimeout(() => setAnim(false), 400); + return () => clearTimeout(h); + }, [anim, by]); + + const ticks: Tick[] = live + ? liveTicks(t.liveTicks, t.now) + : historyTicks(d.since_ms, bucketMs, trend.grid.length, t.now); + /** 图画出来了才有纵轴那一栏(见 `StackedArea` 的空态) */ + const axis = trend.keys.length > 0 && trend.rows.length > 0 ? Y_AXIS_WIDTH : 0; + const failures = trend.grid.some((g) => g.failed > 0); + const openFailed = () => nav.open("requests", { grouped: false, filter: { failedOnly: true } }); + + return ( + <> + + {t.trend} + {live && } + + } + actions={ + /* + 口径只管这张图和下面的模型排行,所以放在这一节的标题行上,不和页头的 + 时间范围挨在一起 —— 两个不同维度的选择并排成一串,读起来就是一排平级选项。 + */ + + label={t.metric} + value={by} + options={[ + { id: "token", label: t.byTokens }, + { id: "cost", label: t.byCost }, + ]} + onChange={onBy} + /> + } + > + (tokensMode ? compact(v) : usd(v * 1000))} + // 悬停里每个模型那一行**和刻度同一种写法**,先取整:实时档的速率是摊出来的浮点 + valueFormat={(v) => (tokensMode ? compact(Math.round(v)) : usd(Math.round(v * 1000)))} + yMax={yMax} + liveEdge={live} + pulse={win.arrived} + animate={anim} + /> + {/* + 基线、失败标记和刻度**只铺到画图区域的右边界**,右边那一栏是纵轴的刻度 + (见 `Y_AXIS_WIDTH`)。图空着的时候没有纵轴,就铺满。 + */} +
+ + +
+ {/* 这一行有没有话说都占一行高:少一句就把下面整块往上提,正是切换时的那种来回动 */} +

+ {failures && ( + <> + + {t.failureMarks} + + )} +

+
+ + {t.liveWindow} : undefined}> + + + + ); +} + +/** + * 基线上的失败标记:有失败的时段在基线下面画一小段红。 + * + * **不往图的高度里加** —— 加一格固定高度的话,那一格在大桶上看不见、在小桶上 + * 直接翻倍,而它本来就不代表任何数量。每一段**对着图上那一格的点**居中(图上的 + * 点是等距排开、首尾顶格的),不是按「第几格占几分之一」平铺 —— 平铺的话越往右 + * 越偏。可以点:落到流量页,只看失败的请求。 + */ +function FailureStrip({ + grid, + stepMs, + onOpen, +}: { + grid: CostBucket[]; + stepMs: number; + onOpen: () => void; +}) { + const t = useText(overviewText); + const n = grid.length; + return ( +
+ + {n > 1 && + grid.map((g, i) => { + if (g.failed === 0) return null; + const w = 100 / (n - 1); + const left = Math.max(0, (i - 0.5) * w); + const right = Math.min(100, (i + 0.5) * w); + return ( + + + + + + ); + })} +
+ ); +} + +/** + * 图下面那排刻度。**标在它说的那个时刻的正下方**:第一个靠左对齐,免得伸出图外; + * 最后一个(「现在」)压在最后一点下面,右边有纵轴那一栏让它伸过去。 + */ +function TickRow({ ticks, live, axis }: { ticks: Tick[]; live: boolean; axis: number }) { + return ( +
+ {ticks.map((x, i) => ( + + {x.label} + + ))} +
+ ); +} diff --git a/src/Dashboard.i18n.ts b/src/overview/overview.i18n.ts similarity index 58% rename from src/Dashboard.i18n.ts rename to src/overview/overview.i18n.ts index d33c3a1f..6c9620d6 100644 --- a/src/Dashboard.i18n.ts +++ b/src/overview/overview.i18n.ts @@ -1,26 +1,43 @@ import { messages } from "@/i18n"; /** 概览页的文案。 */ -export const dashboardText = messages( +export const overviewText = messages( { - // 图的口径。`metric` 是读屏读出来的这一组的名字 - metric: "图表口径", - byTokens: "token", - byCost: "费用", + title: "概览", + /** 读取失败时 ErrorState 的标题 */ + loadFailed: "概览数据读取失败", - // 延迟的样本数、模型排行里的请求数。那一栏很窄 - times: (n: number) => `${n} 次`, - moreNotListed: (n: number) => `另有 ${n} 项未列出`, + // 页头摘要:此刻的状态。数字和状态,不写说明 + inFlight: (_n: number) => "个进行中", + idle: "当前空闲", + upstreams: (_n: number) => "个上游", + unavailable: (_n: number) => "个不可用", + noUpstreams: "尚未添加上游", + showUpstreams: "在上游页中查看", - /** 环比。`period` 是时间范围给的「24 小时」「7 天」 */ - delta: (period: string, arrow: string, pct: string) => `较上一个${period} ${arrow} ${pct}%`, + /** 实时档的标记 */ + live: "实时", + /** 实时档下,不跟着图走的那几块按这个区间统计 */ + liveWindow: "10 分钟", + // 三个大数 + kpiTokens: "Token", + kpiCost: "费用", + kpiRequests: "请求", + /** + * 环比。`period` 是时间范围给的「24 小时」「7 天」「等长区间」;带箭头的幅度另画。 + * 数字开头的和前面的汉字之间空一格,和别处「另有 3 项」的写法一致 + */ + deltaVs: (period: string) => `较上一个${/^[0-9]/.test(period) ? " " : ""}${period}`, + /** 上一个区间没有数据时,幅度那一格(「—」)的悬停说明 */ + noPrior: (period: string) => `上一个${/^[0-9]/.test(period) ? " " : ""}${period}无记录`, /** token 数。`shown` 是写出来的样子(缩写或精确值),`n` 决定英文的单复数 */ tokens: (shown: string, _n: number) => `${shown} token`, - tokenUnit: (_n: number) => "token", - inputOutput: (input: string, output: string) => `输入 ${input} · 输出 ${output}`, + /** token 那一栏的限定语:「输入 10.5M · 输出 356k」,两个数各自走 */ + input: "输入", + output: "输出", - // 费用那一栏的限定语。**估算、无法计价、无用量、订阅各说各的** + // 费用那一栏的限定语。**估算、无法计价、无用量各说各的** estimated: (amount: string) => `含估算 ${amount}`, estimatedTip: "此部分金额为估算值:请求在响应结束前断开或中断,输出用量计至断开时;或该模型的单价取自其他平台。", @@ -33,44 +50,46 @@ export const dashboardText = messages( allMeasured: "全部按价目表实测", // 请求数那一栏 - requestUnit: (_n: number) => "次请求", failed: (n: number) => `${n} 次失败`, failureRate: (pct: string) => `失败率 ${pct}%`, - inFlight: (n: number) => `${n} 个进行中`, - idle: "当前空闲", + showFailed: "在流量中查看失败的请求", // 图 + trend: "趋势", + /** 图的口径。读屏读出来的这一组的名字 */ + metric: "图表口径", + byTokens: "token", + byCost: "费用", unknownModel: "未知模型", /** 前五项以外合并成的那一层。**它同时是图里那一层的名字** */ other: "其他", otherCount: (n: number) => `其他 ${n} 项`, - /** 图里每一格的 `label`。**实时档读的是速率,不是那一格的量** */ - liveBucket: (at: string, rate: string) => `${at} ${rate}`, + /** 悬停提示的抬头。**实时档读的是速率,不是那一格的量** */ tokenRate: (shown: string) => `${shown} token/秒`, costRate: (amount: string) => `${amount}/小时`, - bucket: (at: string, amount: string, requests: number, failed: number) => - `${at} ${amount} ${requests} 次${failed ? `(${failed} 次失败)` : ""}`, - waiting: "等待请求。", - noRequests: "所选区间内无请求记录。", + /** 悬停提示抬头下面那一句:这一格有几次请求 */ + tipRequests: (requests: number, failed: number) => `${requests} 次请求${failed ? `,${failed} 次失败` : ""}`, + tipNone: "无请求", + waiting: "等待请求", + noRequests: "所选区间内无请求记录", liveTicks: ["10 分钟前", "8 分钟", "6 分钟", "4 分钟", "2 分钟"], now: "现在", - failureMarks: "基线上的红色标出存在失败的时段", - liveScope: "顶部数字与缓存、延迟、安全按最近 24 小时统计;模型排行跟随上图", - - // 还没有请求时 - gatewayHint: "本机网关地址", - pointClients: (gateway: string) => `将客户端指向${gateway}后,用量与费用将在此处显示。`, - probesAnswered: (n: number) => - `已本地应答 ${n} 次客户端探测。客户端已连接网关,这些探测未产生费用。`, + failureMarks: "存在失败的时段", + /** 基线上一段红色的悬停说明 */ + failedAt: (at: string, n: number) => `${at} ${n} 次失败`, - // 左边那一列 + // 模型排行 models: "模型", - cache: "缓存", - latency: "延迟", - security: "安全", + times: (n: number) => `${n} 次`, + /** 用了 token 却没有费用的那一格(「—」)的悬停说明 */ + noCost: "无费用记录:模型未定价或不计费", + moreNotListed: (n: number) => `另有 ${n} 项未列出`, + /** 可以点的一行,读屏读出来的后半句 */ + viewInTraffic: "在流量中查看", // 缓存 - noTokens: "所选区间内无 token 记录。", + cache: "缓存", + noTokens: "所选区间内无 token 记录", hitRate: "命中", netCost: "净增费用", netSavings: "净节省", @@ -78,13 +97,21 @@ export const dashboardText = messages( cacheReads: "缓存读取", uncachedInput: "新输入", cacheWrites: "缓存写入", + hitByModel: "各模型命中率", // 延迟 - notEnoughSamples: "所选区间内样本不足,暂无分位数据。", - byModel: "按模型 · 首字节 P50 至 P95", - byUpstream: "按上游 · 同上", + latency: "延迟", + latencyWhat: "首字节时间", + notEnoughSamples: "所选区间内样本不足,暂无分位数据", + byModel: "按模型", + byUpstream: "按上游", + /** 延迟表头的最后一列:每一行的分位数由几个请求算出 */ + samples: "样本", + /** 样本太少的那一格的悬停说明 */ + fewSamples: "样本较少,分位数仅供参考", // 安全:各项防护的档位和这段时间各自看见了什么。数的是安全日志里的条数 + security: "安全", modeOff: "关闭", modeObserve: "观察", modeEnforce: "拦截", @@ -111,24 +138,40 @@ export const dashboardText = messages( noOverLimit: "无回答超过上限", showLog: "在安全日志中查看", - /** 后面可能接「。转发不受影响。」,所以不带句号 */ + // 请求记录没起来。正常时不显示 recordingUnavailable: "请求记录未能启动", - forwardingUnaffected: "。转发不受影响。", + forwardingUnaffected: "转发不受影响。", + + // 还没有任何请求时 + emptyTitle: "尚无请求记录", + emptyHint: "将客户端指向本机网关后,用量与费用将在此处显示。", + emptyHintNoUpstream: "添加上游并将客户端指向本机网关后,用量与费用将在此处显示。", + probesAnswered: (n: number) => `已本地应答 ${n} 次客户端探测,客户端已连接网关。`, + setUpClients: "设置客户端", + addUpstream: "添加上游", }, { - metric: "Chart measure", - byTokens: "Tokens", - byCost: "Cost", + title: "Overview", + loadFailed: "Could not load the overview", - times: (n: number) => `${n}×`, - moreNotListed: (n: number) => `${n} more not listed`, + inFlight: (_n: number) => "in progress", + idle: "Idle", + upstreams: (n: number) => (n === 1 ? "upstream" : "upstreams"), + unavailable: (_n: number) => "unavailable", + noUpstreams: "No upstreams yet", + showUpstreams: "View in Upstreams", - // 大数下面那两行是定高的:英文要和中文一样在两行里放得下,所以用短的说法 - delta: (period: string, arrow: string, pct: string) => `${arrow} ${pct}% vs. prior ${period}`, + live: "Live", + liveWindow: "10 minutes", + kpiTokens: "Tokens", + kpiCost: "Cost", + kpiRequests: "Requests", + deltaVs: (period: string) => `vs. prior ${period}`, + noPrior: (period: string) => `No data for the prior ${period}`, tokens: (shown: string, n: number) => `${shown} ${n === 1 ? "token" : "tokens"}`, - tokenUnit: (n: number) => (n === 1 ? "token" : "tokens"), - inputOutput: (input: string, output: string) => `Input ${input} · Output ${output}`, + input: "Input", + output: "Output", estimated: (amount: string) => `Incl. ${amount} estimated`, estimatedTip: @@ -141,44 +184,37 @@ export const dashboardText = messages( "These requests have no usage data: the upstream did not report it, or the connection ended before it was reported. Their cost cannot be calculated and is not included in the amount above.", allMeasured: "All measured at price-sheet rates", - requestUnit: (n: number) => (n === 1 ? "request" : "requests"), failed: (n: number) => `${n} failed`, failureRate: (pct: string) => `Failure rate ${pct}%`, - inFlight: (n: number) => `${n} in progress`, - idle: "Idle", + showFailed: "View failed requests in Traffic", + trend: "Trend", + metric: "Chart measure", + byTokens: "Tokens", + byCost: "Cost", unknownModel: "Unknown model", other: "Other", otherCount: (n: number) => (n === 1 ? "1 other" : `${n} others`), - liveBucket: (at: string, rate: string) => `${at} · ${rate}`, tokenRate: (shown: string) => `${shown} tokens/s`, costRate: (amount: string) => `${amount}/hour`, - bucket: (at: string, amount: string, requests: number, failed: number) => - `${at} · ${amount} · ${requests === 1 ? "1 request" : `${requests} requests`}${ - failed ? ` (${failed} failed)` : "" - }`, - waiting: "Waiting for requests.", - noRequests: "No requests recorded in the selected range.", + tipRequests: (requests: number, failed: number) => + `${requests === 1 ? "1 request" : `${requests} requests`}${failed ? `, ${failed} failed` : ""}`, + tipNone: "No requests", + waiting: "Waiting for requests", + noRequests: "No requests recorded in the selected range", liveTicks: ["10 min ago", "8 min", "6 min", "4 min", "2 min"], now: "Now", - failureMarks: "Red on the baseline marks periods with failures", - liveScope: - "Top figures, cache, latency and security cover the last 24 hours; the model ranking follows the chart above", - - gatewayHint: "the local gateway address", - pointClients: (gateway: string) => `Usage and cost appear here once clients point to ${gateway}.`, - // 接在上一句后面:英文两句之间要一个空格,中文不要 - probesAnswered: (n: number) => - n === 1 - ? " 1 client probe was answered locally. A client is already connected to the gateway; the probe incurred no cost." - : ` ${n} client probes were answered locally. A client is already connected to the gateway; these probes incurred no cost.`, + failureMarks: "Periods with failures", + failedAt: (at: string, n: number) => `${at} · ${n} failed`, models: "Models", - cache: "Cache", - latency: "Latency", - security: "Security", + times: (n: number) => `${n}×`, + noCost: "No cost recorded: the model is unpriced or not billed", + moreNotListed: (n: number) => `${n} more not listed`, + viewInTraffic: "View in Traffic", - noTokens: "No tokens recorded in the selected range.", + cache: "Cache", + noTokens: "No tokens recorded in the selected range", hitRate: "hit rate", netCost: "Net cost increase", netSavings: "Net savings", @@ -186,11 +222,17 @@ export const dashboardText = messages( cacheReads: "Cache reads", uncachedInput: "Uncached input", cacheWrites: "Cache writes", + hitByModel: "Hit rate by model", - notEnoughSamples: "Not enough samples in the selected range; no percentiles yet.", - byModel: "By model · TTFB P50 to P95", - byUpstream: "By upstream · same as above", + latency: "Latency", + latencyWhat: "Time to first byte", + notEnoughSamples: "Not enough samples in the selected range; no percentiles yet", + byModel: "By model", + byUpstream: "By upstream", + samples: "Samples", + fewSamples: "Few samples; the percentiles are only indicative", + security: "Security", modeOff: "Off", modeObserve: "Observe", modeEnforce: "Enforce", @@ -223,6 +265,17 @@ export const dashboardText = messages( showLog: "View in the security log", recordingUnavailable: "Request recording could not start", - forwardingUnaffected: ". Forwarding is not affected.", + forwardingUnaffected: "Forwarding is not affected.", + + emptyTitle: "No requests yet", + emptyHint: "Usage and cost appear here once clients point to the local gateway.", + emptyHintNoUpstream: + "Usage and cost appear here once an upstream is added and clients point to the local gateway.", + probesAnswered: (n: number) => + n === 1 + ? "1 client probe was answered locally; a client is already connected to the gateway." + : `${n} client probes were answered locally; a client is already connected to the gateway.`, + setUpClients: "Set up clients", + addUpstream: "Add upstream", }, ); diff --git a/src/overview/parts.tsx b/src/overview/parts.tsx new file mode 100644 index 00000000..0cf3a730 --- /dev/null +++ b/src/overview/parts.tsx @@ -0,0 +1,176 @@ +import type { KeyboardEvent, ReactNode } from "react"; +import { ChevronRightIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Badge } from "@/ui/badge"; +import { LetterTile, Logo } from "@/ui/logos"; +import { StatusDot } from "@/ui/status-dot"; +import { useText } from "@/i18n"; +import { modelGlyph } from "./series"; +import { overviewText } from "./overview.i18n"; + +/** + * 概览里几张排行共用的小零件。 + */ + +/** Enter 和空格都算「打开」:可以点的行、可以点的字,键盘上和鼠标一样 */ +function onActivate(open: () => void) { + return (e: KeyboardEvent) => { + if (e.key === "Enter" || e.key === " ") { + e.preventDefault(); + open(); + } + }; +} + +/** + * 排行里的一行。给了 `onOpen` 就可以点:悬停整行压暗一档、行尾出现箭头,点下去 + * 落到流量页筛好的那一批(或别的页)。没给就是一行普通的字,行尾留出同样宽的 + * 空位,和能点的行对齐。 + * + * **不是按钮**:它是去另一页的入口,读屏读作链接,Enter 和空格都能打开。 + */ +export function LinkRow({ + onOpen, + onPoint, + hint, + className, + children, +}: { + onOpen?: () => void; + /** 指针移进、移出这一行(能点的行,键盘聚焦、失焦也算)。图例用它突出图里那一层 */ + onPoint?: (on: boolean) => void; + /** 读屏在这一行后面读出来的去向(「在流量中查看」) */ + hint?: string; + className?: string; + children: ReactNode; +}) { + const base = "group/row -mx-2 flex h-8 min-w-0 items-center gap-3 rounded-md px-2 tw-body"; + const point = onPoint && { + onMouseEnter: () => onPoint(true), + onMouseLeave: () => onPoint(false), + }; + if (!onOpen) + return ( +
+ {children} + +
+ ); + return ( +
onPoint(true))} + onBlur={onPoint && (() => onPoint(false))} + className={cn( + base, + "cursor-pointer outline-none transition-colors duration-(--motion-fast) ease-(--motion-ease)", + "hover:bg-foreground/[0.045] focus-visible:bg-foreground/[0.045] focus-visible:ring-2 focus-visible:ring-ring/40", + className, + )} + > + {children} + {hint && {hint}} + +
+ ); +} + +/** + * 一段可以点的字(「6 次失败」「3 条无法计价」)。悬停出下划线,键盘同样能打开。 + */ +export function LinkText({ + onOpen, + className, + children, +}: { + onOpen: () => void; + className?: string; + children: ReactNode; +}) { + return ( + + {children} + + ); +} + +/** 模型所属厂商的标志;认不出来画首字母方块。**单色**,跟着文字色走 */ +export function ModelMark({ name, className }: { name: string; className?: string }) { + const g = modelGlyph(name); + const cls = cn("text-muted-foreground", className); + return g ? : ; +} + +/** 合并的「其他」那一行没有标志:留同样宽的空位,名字才对得齐 */ +export function MarkSpace() { + return ; +} + +/** 节标题右边的一小行:这一块按什么口径统计(实时档下的「24 小时」) */ +export function Scope({ children }: { children: ReactNode }) { + return {children}; +} + +/** 实时档的标记:绿点在跳,说的是真的 —— 那条曲线确实在动 */ +export function LiveBadge() { + const t = useText(overviewText); + return ( + + + {t.live} + + ); +} + +/** + * 一根横条:底是一道浅灰的槽,按 `value / max` 填上颜色。宽度变化时走过去 + * (`motion-bar`),不跳。 + */ +export function Meter({ + value, + max, + color, + className, +}: { + value: number; + max: number; + /** 填充色。CSS 颜色值(`var(--chart-1)`) */ + color: string; + className?: string; +}) { + const pct = max > 0 ? Math.max(0, Math.min(100, (value / max) * 100)) : 0; + return ( + + + + ); +} + +/** 一栏的小标题(「各模型命中率」)。和旁边那栏的抬头一样高:24px */ +export function ColumnHead({ children, aside }: { children: ReactNode; aside?: ReactNode }) { + return ( +

+ {children} + {aside} +

+ ); +} diff --git a/src/overview/series.test.ts b/src/overview/series.test.ts new file mode 100644 index 00000000..99b2b1c7 --- /dev/null +++ b/src/overview/series.test.ts @@ -0,0 +1,327 @@ +import { describe, expect, it } from "vitest"; +import type { CostBucketGroup, Dashboard, Summary } from "@/types"; +import { + buildTrend, + cacheByModel, + fmtBucket, + fmtMs, + historyTicks, + holdY, + latencyRows, + liveTicks, + modelGlyph, + niceCeil, +} from "./series"; +import { overviewText } from "./overview.i18n"; +import { LIVE_BUCKET_MS } from "./useLive"; + +const t = overviewText.zh; +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +function summary(over: Partial = {}): Summary { + return { + requests: 0, + failed: 0, + locally_answered: 0, + input_tokens: 0, + output_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, + cost_micros_exact: 0, + cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, + cache_saved_micros: 0, + security: { + secrets: 0, + secrets_replaced: 0, + tool_calls: 0, + tool_calls_cut: 0, + hidden_text: 0, + hidden_text_blocked: 0, + content: 0, + content_blocked: 0, + output_limit: 0, + output_limit_cut: 0, + }, + pricing_date: "2026-09-20", + ...over, + }; +} + +/** 一个模型在一格里的量。`tokens` 全记成输入,`cost` 全记成实测 */ +function group(at_ms: number, name: string, tokens: number, cost = 0, requests = 1): CostBucketGroup { + return { + at_ms, + name, + requests, + failed: 0, + cost_micros_exact: cost, + cost_micros_estimated: 0, + input_tokens: tokens, + output_tokens: 0, + cache_read_tokens: 0, + cache_write_tokens: 0, + }; +} + +function dashboard(since: number, groups: CostBucketGroup[]): Dashboard { + const buckets = new Map(); + for (const g of groups) { + const b = buckets.get(g.at_ms) ?? { requests: 0, cost: 0 }; + b.requests += g.requests; + b.cost += g.cost_micros_exact; + buckets.set(g.at_ms, b); + } + return { + summary: summary(), + latency: [], + latency_by_provider: [], + storage: null, + buckets: [...buckets].map(([at_ms, b]) => ({ + at_ms, + requests: b.requests, + failed: 0, + cost_micros_exact: b.cost, + cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, + })), + buckets_by_model: groups, + prev: null, + since_ms: since, + }; +} + +describe("纵轴上界", () => { + it("粗档是 1 / 2 / 5", () => { + expect(niceCeil(0)).toBe(1); + expect(niceCeil(0.7)).toBe(1); + expect(niceCeil(1.3)).toBe(2); + expect(niceCeil(3)).toBe(5); + expect(niceCeil(7)).toBe(10); + expect(niceCeil(2_300)).toBe(5_000); + }); + + it("细档在两档之间补上中间的数,浮点的整数不往上多跳一档", () => { + expect(niceCeil(1.1, true)).toBe(1.2); + expect(niceCeil(2.9e6, true)).toBe(3e6); + expect(niceCeil(3e6, true)).toBe(3e6); + expect(niceCeil(3.01, true)).toBe(4); + expect(niceCeil(0.3, true)).toBeCloseTo(0.3, 12); + }); + + /** + * 这就是细档的理由:1/2/5 下峰值刚过 2 就得取 5,图只占下面四成。细档下最坏 + * 也占到四分之三。 + */ + it("细档下图至少占满四分之三的高", () => { + for (let v = 0.011; v < 1e7; v *= 1.037) { + const top = niceCeil(v, true); + expect(top).toBeGreaterThanOrEqual(v); + expect(v / top).toBeGreaterThan(0.74); + } + }); + + /** 刻度写的是上界和它的一半,所以一半也要是整齐的数(最多一位小数) */ + it("每一档的一半也是整齐的数", () => { + for (const s of [1, 1.2, 1.6, 2, 2.4, 3, 4, 5, 6, 8, 10]) { + const half = niceCeil(s * 1000, true) / 2; + expect(half % 100).toBe(0); + } + }); + + it("峰值涨过上界就重取,掉得不多不动,掉到一半以下才降档", () => { + let y = holdY({ key: "", v: 0 }, "token/last:1d", 900); + expect(y.v).toBe(1000); + y = holdY(y, "token/last:1d", 600); + expect(y.v).toBe(1000); + y = holdY(y, "token/last:1d", 1300); + expect(y.v).toBe(2000); + y = holdY(y, "token/last:1d", 700); + expect(y.v).toBe(1000); + }); + + it("口径或区间一换,从头取", () => { + const y = holdY({ key: "token/last:1d", v: 5_000_000 }, "cost/last:1d", 3_000); + expect(y).toEqual({ key: "cost/last:1d", v: 5_000 }); + }); +}); + +describe("时间刻度", () => { + it("24 小时:起点、每 4 小时一个整点(零点写日期)、现在", () => { + const since = new Date(2026, 8, 24, 16, 0).getTime(); + const ticks = historyTicks(since, HOUR / 2, 49, t.now); + expect(ticks.map((x) => x.label)).toEqual(["9/24 16:00", "20:00", "9/25", "04:00", "08:00", "12:00", "现在"]); + expect(ticks[0]?.at).toBe(0); + expect(ticks.at(-1)).toMatchObject({ at: 1, now: true }); + // 标在它说的那个时刻:20:00 是 24 小时里的第 4 个小时 + expect(ticks[1]?.at).toBeCloseTo(4 / 24, 9); + }); + + it("7 天:按天写,离两头太近的不写", () => { + const since = new Date(2026, 8, 18, 16, 0).getTime(); + const ticks = historyTicks(since, 2 * HOUR, 85, t.now); + // 9/19 零点离起点只有 8 小时(<12%),9/25 零点离「现在」太近 + expect(ticks.map((x) => x.label)).toEqual(["9/18 16:00", "9/20", "9/21", "9/22", "9/23", "9/24", "现在"]); + }); + + it("只有一格时只写起点和现在", () => { + expect(historyTicks(0, HOUR, 1, "now").map((x) => x.label)).toEqual([fmtBucket(0, HOUR), "now"]); + }); + + it("实时档:等距,最后一个是亮着的「现在」", () => { + const ticks = liveTicks(t.liveTicks, t.now); + expect(ticks).toHaveLength(6); + expect(ticks.map((x) => x.at)).toEqual([0, 0.2, 0.4, 0.6, 0.8, 1]); + expect(ticks.filter((x) => x.now).map((x) => x.label)).toEqual(["现在"]); + }); + + it("一格的时间标签:按天、按分钟、实时档到秒", () => { + const at = new Date(2026, 8, 25, 7, 5, 9).getTime(); + expect(fmtBucket(at, DAY)).toBe("9/25"); + expect(fmtBucket(at, HOUR)).toBe("9/25 07:05"); + expect(fmtBucket(at, LIVE_BUCKET_MS)).toBe("07:05:09"); + }); +}); + +describe("趋势图和模型排行", () => { + const since = new Date(2026, 8, 24, 0, 0).getTime(); + // 三点过五分:最后一格(3:00)刚开始 + const now = since + 3 * HOUR + 5 * 60_000; + const models = ["a", "b", "c", "d", "e", "f", "g"]; + // a 最多、g 最少;f 和 g 合并成「其他」 + const groups = models.map((m, i) => group(since + HOUR, m, (7 - i) * 1000, (i + 1) * 100)); + const d = dashboard(since, groups); + const base = { d, live: false, bucketMs: HOUR, rangeMs: DAY, samples: [], fails: [], now, prevStack: [], t }; + + it("按 token 排:前五项各一层,其余合并成「其他」,排行从大到小", () => { + const tr = buildTrend({ ...base, by: "token" }); + expect(tr.ranking.map((r) => r.name)).toEqual(["a", "b", "c", "d", "e", t.other]); + expect(tr.ranking.at(-1)).toMatchObject({ merged: 2, tokens: 2000 + 1000, requests: 2 }); + // 图的层从下往上:「其他」垫底,量大的在上 + expect(tr.keys).toEqual([t.other, "e", "d", "c", "b", "a"]); + // 最大的那层颜色最深;「其他」是灰的,不和最小的那个模型撞色;排行里同一个模型 + // 是同一个颜色 + expect(tr.colors).toEqual([ + "var(--chart-other)", + "var(--chart-5)", + "var(--chart-4)", + "var(--chart-3)", + "var(--chart-2)", + "var(--chart-1)", + ]); + for (const r of tr.ranking) expect(r.color).toBe(tr.colors[tr.keys.indexOf(r.name)]); + expect(tr.topBar).toBe(7000); + }); + + it("按费用排:次序跟着费用走", () => { + const tr = buildTrend({ ...base, by: "cost" }); + expect(tr.ranking.slice(0, 5).map((r) => r.name)).toEqual(["g", "f", "e", "d", "c"]); + }); + + it("空桶补成 0,每一格每一层都有值", () => { + const tr = buildTrend({ ...base, by: "token" }); + // 0:00 到 3:00,一小时一格:四格 + expect(tr.rows).toHaveLength(4); + for (const row of tr.rows) for (const k of tr.keys) expect(typeof row[k]).toBe("number"); + expect(tr.rows[0]?.a).toBe(0); + expect(tr.rows[1]?.a).toBe(7000); + expect(tr.peak).toBe(28_000); + }); + + it("悬停抬头:时刻、合计,空格写「无请求」", () => { + const tr = buildTrend({ ...base, by: "token" }); + expect(tr.tips[0]).toEqual({ title: fmtBucket(since, HOUR), value: t.tokens("0", 0), note: t.tipNone }); + expect(tr.tips[1]).toMatchObject({ value: t.tokens("28k", 28_000), note: t.tipRequests(7, 0) }); + }); + + it("费用口径的图值是千分之一美元", () => { + const tr = buildTrend({ ...base, by: "cost" }); + expect(tr.rows[1]?.g).toBe(0.7); + }); + + /** + * 实时档的堆叠次序有滞回:两个量级接近的模型不因为一点起伏就互换位置(一换, + * 整条带子在纵向跳过另一条,颜色也跟着换)。 + */ + describe("实时档的堆叠次序", () => { + const at = since + HOUR; + const live = { ...base, live: true, by: "token" as const, rangeMs: 10 * 60_000 }; + const sample = (id: number, model: string) => ({ id, at: now - 30_000, model, tokens: 100 }); + + it("差不到两成:保持上一次的次序", () => { + const d2 = dashboard(since, [group(at, "a", 1000), group(at, "b", 1150)]); + const tr = buildTrend({ ...live, d: d2, samples: [sample(1, "a"), sample(2, "b")], prevStack: ["a", "b"] }); + expect(tr.stack).toEqual(["a", "b"]); + }); + + it("超过两成:换位", () => { + const d2 = dashboard(since, [group(at, "a", 1000), group(at, "b", 1300)]); + const tr = buildTrend({ ...live, d: d2, samples: [sample(1, "a"), sample(2, "b")], prevStack: ["a", "b"] }); + expect(tr.stack).toEqual(["b", "a"]); + }); + + it("格子一路铺到「现在」,失败落在它那一格上", () => { + const tr = buildTrend({ ...live, samples: [sample(1, "a")], fails: [{ id: 9, at: now - 12_000 }] }); + expect(tr.grid).toHaveLength(121); + expect(tr.grid.at(-1)?.at_ms).toBe(now); + expect(tr.grid.at(-3)?.failed).toBe(1); + expect(tr.tips.at(-1)?.note).toBeUndefined(); + }); + }); +}); + +describe("各模型的缓存", () => { + it("按上下文量从大到小,跨格合计,没有上下文的不列", () => { + const g = (name: string, read: number, plain: number, write: number): CostBucketGroup => ({ + ...group(0, name, plain), + cache_read_tokens: read, + cache_write_tokens: write, + }); + const d = dashboard(0, [g("a", 80, 10, 10), g("b", 900, 50, 50), g("a", 0, 100, 0), g("", 5, 5, 0), g("z", 0, 0, 0)]); + const rows = cacheByModel(d, t.unknownModel); + expect(rows.map((r) => r.name)).toEqual(["b", "a", t.unknownModel]); + expect(rows[0]).toMatchObject({ ctx: 1000, hit: 0.9 }); + expect(rows[1]).toMatchObject({ read: 80, plain: 110, write: 10, ctx: 200, hit: 0.4 }); + }); +}); + +describe("延迟", () => { + it("样本多的在前", () => { + const rows = latencyRows([ + { model: "b", p50: 1, p95: 2, samples: 3 }, + { model: "a", p50: 1, p95: 2, samples: 30 }, + { model: "c", p50: 1, p95: 2, samples: 3 }, + ]); + expect(rows.map((r) => r.model)).toEqual(["a", "b", "c"]); + }); + + it("一秒以内写毫秒,以上写秒", () => { + expect(fmtMs(0)).toBe("0ms"); + expect(fmtMs(438.4)).toBe("438ms"); + expect(fmtMs(999)).toBe("999ms"); + expect(fmtMs(1182)).toBe("1.18s"); + expect(fmtMs(12_345)).toBe("12.3s"); + expect(fmtMs(123_456)).toBe("123s"); + }); +}); + +describe("模型的厂商标志", () => { + it("按名字认", () => { + expect(modelGlyph("claude-sonnet-5")).toBe("claude"); + expect(modelGlyph("gpt-5.5-codex")).toBe("openai"); + expect(modelGlyph("o3-mini")).toBe("openai"); + expect(modelGlyph("openai/gpt-oss-120b")).toBe("openai"); + expect(modelGlyph("gemini-2.5-pro")).toBe("gemini"); + expect(modelGlyph("deepseek-chat")).toBe("deepseek"); + expect(modelGlyph("qwen/qwen3-coder")).toBe("qwen"); + expect(modelGlyph("glm-4.6")).toBe("zhipu"); + }); + + it("认不出来是 null(画首字母方块)", () => { + expect(modelGlyph("llama3.1:8b")).toBeNull(); + expect(modelGlyph("未知模型")).toBeNull(); + }); +}); diff --git a/src/overview/series.ts b/src/overview/series.ts new file mode 100644 index 00000000..5f54b374 --- /dev/null +++ b/src/overview/series.ts @@ -0,0 +1,509 @@ +import { compact, densify } from "@/format"; +import type { ChartTip } from "@/ui/charts"; +import { upstreamGlyph, type GlyphId } from "@/ui/logos"; +import { usd, type CostBucket, type Dashboard, type LatencyView } from "@/types"; +import { LIVE_BUCKET_MS, LIVE_REACH_MS, liveRate, type LiveFail, type LiveSample } from "./useLive"; +import type { overviewText } from "./overview.i18n"; + +/** + * 概览上那张图和几张排行的数,从一份 `Dashboard`(和实时档的样本)算出来。 + * + * **抽成纯函数是为了能测。**堆叠次序的滞回、纵轴上界的钉住、刻度落在哪一刻, + * 写在 JSX 里没有任何东西会回答「边界上会不会来回跳」。 + */ + +type Text = (typeof overviewText)["zh"]; + +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +/** 图的口径 */ +export type Metric = "token" | "cost"; + +/** + * 图里最多分几层。**只保留前五项,其余合并为「其他」** —— 一个上游可能报出 + * 十几个模型名,十几层叠在两百像素里已经分辨不出,而排在后面的那些合计往往 + * 不到百分之一。 + */ +export const LAYERS = 5; + +/** 每一张排行最多列几项。超出的写出来有几项,**不静默丢掉**。 */ +export const ROWS = 6; + +/** 纵轴上界的档位(× 10ⁿ)。**每一档的一半也是整齐的数**:刻度写的是上界和它的一半 */ +const COARSE = [1, 2, 5, 10]; +const FINE = [1, 1.2, 1.6, 2, 2.4, 3, 4, 5, 6, 8, 10]; + +/** + * 往上取到最近的一档。 + * + * 历史档用细的那套(`fine`):1/2/5 三档之间差着一倍多,峰值刚过 2 就得取 5, + * 图只占下面四成,上面一大片空着。细档下最坏也占到四分之三。实时档用粗的: + * 曲线每半秒都在动,档位越密,尺子换得越勤(见 `holdY`)。 + */ +export function niceCeil(v: number, fine = false): number { + if (!(v > 0)) return 1; + const e = Math.pow(10, Math.floor(Math.log10(v))); + const m = v / e; + // 浮点:0.3 / 0.1 = 2.9999999999999996,3 / 1 这类要落在「3」这一档上 + const step = (fine ? FINE : COARSE).find((s) => m <= s * (1 + 1e-9)) ?? 10; + return step * e; +} + +const pad = (n: number) => String(n).padStart(2, "0"); + +/** + * 一格的时间标签。跨度大到按天分格时就只写日期。 + * + * 不到一分钟的格子(实时档)**写到秒,也带上小时**:只写「07:12」读起来 + * 像七点十二分,而十分钟的窗口随时会跨过整点。 + */ +export function fmtBucket(atMs: number, bucketMs: number): string { + const t = new Date(atMs); + if (bucketMs >= DAY) return `${t.getMonth() + 1}/${t.getDate()}`; + if (bucketMs < 60_000) return `${pad(t.getHours())}:${pad(t.getMinutes())}:${pad(t.getSeconds())}`; + return `${t.getMonth() + 1}/${t.getDate()} ${pad(t.getHours())}:${pad(t.getMinutes())}`; +} + +/** 一格里四类 token 的合计 */ +function tokensOf(b: { + input_tokens: number; + output_tokens: number; + cache_read_tokens: number; + cache_write_tokens: number; +}): number { + return b.input_tokens + b.output_tokens + b.cache_read_tokens + b.cache_write_tokens; +} + +/** 排行里的一行,也是图里的一层 */ +export interface RankRow { + /** 模型名;合并的那一行是 `Text.other` */ + name: string; + /** 合并了几项。单个模型是 0 */ + merged: number; + tokens: number; + /** 微分 */ + cost: number; + requests: number; + /** 图里那一层的颜色 */ + color: string; +} + +export interface Trend { + /** 图的每一格:`label` 是这一格的时刻(横轴的键,每格不同),其余键是各层的值 */ + rows: Record[]; + /** 每一格的悬停抬头,和 `rows` 一一对应(见 `ChartTip`) */ + tips: ChartTip[]; + /** 图的层,**从下往上** */ + keys: string[]; + colors: string[]; + /** 排行,按当前口径从大到小;合并的「其他」在最后 */ + ranking: RankRow[]; + /** 排行的条长按它归一:当前口径里最大的那一项 */ + topBar: number; + /** 格子本身(历史档是后端给的桶,补过空桶)。`failed` 画在基线上 */ + grid: CostBucket[]; + /** 各格总高的最大值,定纵轴用 */ + peak: number; + /** 这一次的堆叠次序,下一次比着它换位(实时档) */ + stack: string[]; +} + +/** + * 图里的层从下往上的颜色。**同一个色相的深浅**,占得多的在上、颜色最深。 + */ +const SHADES = ["var(--chart-5)", "var(--chart-4)", "var(--chart-3)", "var(--chart-2)", "var(--chart-1)"]; +/** + * 合并的「其他」那一层是灰的。它不是一个模型,**不该和排在第五的那个模型同色** + * —— 两层同色叠在一起,就读成了一层。 + */ +const OTHER = "var(--chart-other)"; + +export function buildTrend({ + d, + live, + by, + bucketMs, + rangeMs, + samples, + fails, + now, + prevStack, + t, +}: { + d: Dashboard; + live: boolean; + by: Metric; + /** 历史档的格宽 */ + bucketMs: number; + /** 实时档的窗口 */ + rangeMs: number; + samples: readonly LiveSample[]; + fails: readonly LiveFail[]; + now: number; + /** 上一次的堆叠次序(实时档的滞回) */ + prevStack: readonly string[]; + t: Text; +}): Trend { + const tokensMode = by === "token"; + /* + 实时档的格子**不对齐格宽的整数倍**:最右边那一格就是此刻,往左每格 + 五秒。对齐的话,格子只在跨过边界的那一帧整体挪一格,曲线于是每五秒 + 跳一次;而高斯核在任意时刻都求得出值,格子没有必须落在边界上的理由。 + + **两头都算**:十分钟是一百二十段、一百二十一个点,最左边那个点正好是 + 十分钟前。 + */ + const liveSpan = Math.round(rangeMs / LIVE_BUCKET_MS) + 1; + const liveAt = live + ? Array.from({ length: liveSpan }, (_, i) => now - (liveSpan - 1 - i) * LIVE_BUCKET_MS) + : []; + const byBucket = new Map>(); + const money = new Map(); + const volume = new Map(); + const count = new Map(); + const add = (at: number, name: string, v: number) => { + const slot = byBucket.get(at) ?? new Map(); + slot.set(name, (slot.get(name) ?? 0) + v); + byBucket.set(at, slot); + }; + if (live) { + /* + **一条请求摊成一个高斯鼓包,不是一根针也不是一个方块。**核归一到总 + 权重 1,所以摊完之后每一格读作速率:token 口径是 token/秒,费用口径 + 乘 3600 换成每小时。 + + 排行和总量不走这条路:它们数的是这段时间里实际发生的量,一条请求只算 + 一次。核在**格子的时刻**上求值,不在「第几格」上求值 —— 这样格子挪到 + 哪儿都对得上,曲线是平移的。 + */ + const from = liveAt[0] ?? 0; + for (const x of samples) { + volume.set(x.model, (volume.get(x.model) ?? 0) + x.tokens); + money.set(x.model, (money.get(x.model) ?? 0) + (x.cost ?? 0)); + count.set(x.model, (count.get(x.model) ?? 0) + 1); + const amount = tokensMode ? x.tokens : (x.cost ?? 0) * 3600; + // 只碰核够得着的那几格 + const lo = Math.max(0, Math.ceil((x.at - LIVE_REACH_MS - from) / LIVE_BUCKET_MS)); + const hi = Math.min(liveAt.length - 1, Math.floor((x.at + LIVE_REACH_MS - from) / LIVE_BUCKET_MS)); + for (let i = lo; i <= hi; i++) { + const at = liveAt[i]; + if (at !== undefined) add(at, x.model, liveRate(amount, at - x.at)); + } + } + } else { + for (const b of d.buckets_by_model) { + const name = b.name || t.unknownModel; + const cost = b.cost_micros_exact + b.cost_micros_estimated; + const tok = tokensOf(b); + money.set(name, (money.get(name) ?? 0) + cost); + volume.set(name, (volume.get(name) ?? 0) + tok); + count.set(name, (count.get(name) ?? 0) + b.requests); + add(b.at_ms, name, tokensMode ? tok : cost); + } + } + + /* + **堆叠的次序不跟着实时窗口走。**按窗口内的用量排的话,几个模型量级接近时 + 排名一两秒就翻一次 —— 一翻,整条带子在纵向跳过另一条,颜色还跟着换。 + 所以实时档按**最近 24 小时**的用量定次序(那份数据本来就在手上,只随慢 + 刷新变)。量相同时按名字定,免得 Map 的插入顺序泄漏进来。 + */ + const steady = new Map(); + if (live) { + for (const b of d.buckets_by_model) { + const name = b.name || t.unknownModel; + const v = tokensMode ? tokensOf(b) : b.cost_micros_exact + b.cost_micros_estimated; + steady.set(name, (steady.get(name) ?? 0) + v); + } + } + // 排行按当前口径排 —— 切到 token 之后,费用最高的那个未必是用得最多的。 + // **这是给人读的列表,它就该从大到小**,和图的堆叠次序不是一回事 + const here = tokensMode ? volume : money; + const ranked = [...here.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + const top = ranked.slice(0, LAYERS).map(([name]) => name); + const rest = ranked.slice(LAYERS); + + /* + 图里的堆叠次序另算:**占得少的垫底、占得多的在上**,颜色跟着走。实时档 + 记住的次序里还在的那些保持相对位置,新出现的按量插进去;之后只在一个模型 + **明显**超过它上一名(两成)时才换位。实测按窗口排十分钟里换位 145 次, + 有了门槛才降到接近零。 + */ + const val = (m: string) => (live ? steady : here).get(m) ?? 0; + const byVolume = [...top].sort((a, b) => val(b) - val(a) || a.localeCompare(b)); + let stacked = byVolume; + if (live) { + const kept = prevStack.filter((m) => top.includes(m)); + for (const m of byVolume) if (!kept.includes(m)) kept.splice(byVolume.indexOf(m), 0, m); + for (let i = kept.length - 1; i > 0; i--) { + const up = kept[i - 1]; + const down = kept[i]; + if (up === undefined || down === undefined) continue; + if (val(down) > val(up) * 1.2) { + kept[i - 1] = down; + kept[i] = up; + } + } + stacked = kept; + } + const otherKey = t.other; + const models = [...stacked].reverse(); + const keys = rest.length > 0 ? [otherKey, ...models] : models; + const colors = [ + ...(rest.length > 0 ? [OTHER] : []), + ...models.map((_, i) => SHADES[SHADES.length - models.length + i] ?? "var(--chart-1)"), + ]; + // **色块按名字查。**列表按用量排、图按堆叠次序排,两边要对得上同一个色 + const colorOf = new Map(keys.map((k, i) => [k, colors[i] ?? "var(--chart-1)"])); + + const sum = (m: Map) => rest.reduce((a, x) => a + (m.get(x[0]) ?? 0), 0); + const ranking: RankRow[] = top.map((name) => ({ + name, + merged: 0, + tokens: volume.get(name) ?? 0, + cost: money.get(name) ?? 0, + requests: count.get(name) ?? 0, + color: colorOf.get(name) ?? "var(--chart-1)", + })); + if (rest.length > 0) + ranking.push({ + name: otherKey, + merged: rest.length, + tokens: sum(volume), + cost: sum(money), + requests: sum(count), + color: OTHER, + }); + // 条长按当前口径里**最大的那一项**归一。按总量归一的话,一个占七成的模型会 + // 把其余几条压成看不见的短线,而排行要比的正是它们的差距 + const topBar = Math.max(1, ...ranking.map((r) => (tokensMode ? r.tokens : r.cost))); + + /* + 实时档的格子自己铺:十分钟、五秒一格,一路铺到「现在」。历史档沿用后端给的 + 桶 —— 空桶由 `densify` 补成 0,这是面积图不会把空档画成「连续在用」的前提。 + */ + const grid: CostBucket[] = live + ? liveAt.map((at_ms) => ({ + at_ms, + requests: 0, + failed: 0, + cost_micros_exact: 0, + cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, + })) + : densify(d.buckets, d.since_ms, now, bucketMs); + if (live) { + const from = liveAt[0] ?? 0; + for (const f of fails) { + const g = grid[Math.round((f.at - from) / LIVE_BUCKET_MS)]; + if (g) g.failed += 1; + } + } + const stepMs = live ? LIVE_BUCKET_MS : bucketMs; + let peak = 0; + const tips: ChartTip[] = []; + const rows = grid.map((g) => { + const slot = byBucket.get(g.at_ms); + const total = [...(slot?.values() ?? [])].reduce((a, v) => a + v, 0); + const at = fmtBucket(g.at_ms, stepMs); + /* + **实时档读的是速率,不是那一格的量**(见 `liveRate`);历史档是这一格的 + 合计,下面补一句这一格有几次请求 —— 空的那格说「无请求」,而不是一排 0。 + */ + tips.push( + live + ? { + title: at, + value: tokensMode ? t.tokenRate(compact(Math.round(total))) : t.costRate(usd(Math.round(total))), + } + : { + title: at, + value: tokensMode + ? t.tokens(compact(Math.round(total)), total) + : usd(g.cost_micros_exact + g.cost_micros_estimated), + note: g.requests > 0 ? t.tipRequests(g.requests, g.failed) : t.tipNone, + }, + ); + // `label` 是横轴的键:每一格各不相同(到分钟,实时档到秒),「现在」那一点靠它找位置 + const row: Record = { label: at }; + let other = 0; + let height = 0; + for (const [name, v] of slot ?? []) { + // 费用从微分换成千分之一美元:纵轴上那几位小数没有意义 + const y = tokensMode ? v : v / 1000; + height += y; + if (top.includes(name)) row[name] = y; + else other += y; + } + // 没有值的那几层要显式给 0,否则 recharts 会把这一格整条断开 + for (const k of top) row[k] ??= 0; + if (rest.length > 0) row[otherKey] = other; + peak = Math.max(peak, height); + return row; + }); + + return { rows, tips, keys, colors, ranking, topBar, grid, peak, stack: stacked }; +} + +/** + * 纵轴的上界。**不跟着每一帧的峰值走**:自动域下,一个大请求进出窗口就让整条 + * 曲线连同刻度一起上下弹 —— 看起来像图在抖,其实抖的是尺子。所以上界取一个 + * 整齐的数(1/2/5 档),而且只在实际峰值掉到它一半以下时才降档。口径和区间一 + * 换(`key` 变了),量级差几个数量级,得重新起。 + */ +export function holdY( + prev: { key: string; v: number }, + key: string, + peak: number, + fine = false, +): { key: string; v: number } { + const base = prev.key === key ? prev : { key, v: 0 }; + if (peak > base.v || peak < base.v * 0.5) return { key, v: niceCeil(peak * 1.08, fine) }; + return base; +} + +/** 图下面的一个刻度:`at` 是它在画图区域里的横向位置(0…1) */ +export interface Tick { + at: number; + label: string; + /** 「现在」那一个。实时档里它是亮的 */ + now?: boolean; +} + +/** 下一个本地的整 `hours` 小时(0 点起算) */ +function nextHour(ms: number, hours: number): number { + const d = new Date(ms); + d.setMinutes(0, 0, 0); + do { + d.setHours(d.getHours() + 1); + } while (d.getHours() % hours !== 0 || d.getTime() <= ms); + return d.getTime(); +} + +/** 下一个本地零点 */ +function nextMidnight(ms: number): number { + const d = new Date(ms); + d.setHours(24, 0, 0, 0); + return d.getTime(); +} + +/** + * 历史档图下面的刻度:起点、「现在」,中间落在**本地的整点或零点**上。 + * + * **刻度标在它说的那个时刻的正下方。**用 `justify-between` 排开的话,每个字落在 + * 哪儿取决于前后几个字有多宽,而不是它说的是几点。离两头太近的不写,免得和起点 + * 或「现在」挤在一起。 + * + * `n` 是格数:图上的点按格等距排开,第一个点是第一格的起点,最后一个点是最后 + * 一格的起点。 + */ +export function historyTicks(sinceMs: number, bucketMs: number, n: number, nowLabel: string): Tick[] { + const first: Tick = { at: 0, label: fmtBucket(sinceMs, bucketMs) }; + const last: Tick = { at: 1, label: nowLabel, now: true }; + const span = (n - 1) * bucketMs; + if (!(span > 0)) return [first, last]; + const hourSteps = [1, 2, 3, 4, 6, 12]; + const daySteps = [1, 2, 5, 7, 14]; + const inner: Tick[] = []; + const push = (at: number, label: string) => { + const x = (at - sinceMs) / span; + if (x > 0.12 && x < 0.88) inner.push({ at: x, label }); + }; + const h = hourSteps.find((s) => span / (s * HOUR) <= 7); + if (h !== undefined) { + for (let at = nextHour(sinceMs, h); at < sinceMs + span; at = nextHour(at, h)) { + const d = new Date(at); + // 零点写日期:「00:00」不如「9/25」说得清是哪一天 + push(at, d.getHours() === 0 ? `${d.getMonth() + 1}/${d.getDate()}` : `${pad(d.getHours())}:00`); + } + } else { + const k = daySteps.find((s) => span / (s * DAY) <= 7) ?? 30; + let at = nextMidnight(sinceMs); + let i = 0; + while (at < sinceMs + span) { + if (i % k === 0) { + const d = new Date(at); + push(at, `${d.getMonth() + 1}/${d.getDate()}`); + } + at = nextMidnight(at); + i += 1; + } + } + return [first, ...inner, last]; +} + +/** 实时档图下面的刻度:固定的几个「N 分钟」,最后是亮着的「现在」 */ +export function liveTicks(labels: readonly string[], nowLabel: string): Tick[] { + const all = [...labels, nowLabel]; + return all.map((label, i) => ({ at: i / (all.length - 1), label, ...(i === all.length - 1 ? { now: true } : {}) })); +} + +/** 一个模型在缓存上的构成 */ +export interface CacheRow { + name: string; + read: number; + plain: number; + write: number; + /** 送往上游的上下文:三者之和 */ + ctx: number; + /** 命中率 */ + hit: number; +} + +/** + * 各模型的缓存构成,按上下文量从大到小。 + * + * **率,不是累计量**:要回答的是「哪个模型的缓存没起作用」。没有上下文的模型 + * 不列(命中率无从谈起)。 + */ +export function cacheByModel(d: Dashboard, unknownModel: string): CacheRow[] { + const by = new Map(); + for (const b of d.buckets_by_model) { + const name = b.name || unknownModel; + const x = by.get(name) ?? { read: 0, plain: 0, write: 0 }; + x.read += b.cache_read_tokens; + x.plain += b.input_tokens; + x.write += b.cache_write_tokens; + by.set(name, x); + } + return [...by.entries()] + .map(([name, x]) => { + const ctx = x.read + x.plain + x.write; + return { name, ...x, ctx, hit: ctx > 0 ? x.read / ctx : 0 }; + }) + .filter((r) => r.ctx > 0) + .sort((a, b) => b.ctx - a.ctx || a.name.localeCompare(b.name)); +} + +/** 延迟排行:样本多的在前(样本少的分位数不可靠,放后面) */ +export function latencyRows(rows: readonly LatencyView[]): LatencyView[] { + return [...rows].sort((a, b) => b.samples - a.samples || a.model.localeCompare(b.model)); +} + +/** + * 一段延迟怎么写。一秒以内写毫秒,以上写秒、留两位有效的小数。 + * + * **不写成 `1,182ms`**:并排两列四位数的毫秒要逐位读,而「1.18s」一眼就是一秒出头 + * —— 这一栏要比的是快慢的量级和差距,不是个位上的那几毫秒(精确值在流量里)。 + */ +export function fmtMs(ms: number): string { + const n = Math.max(0, Math.round(ms)); + if (n < 1000) return `${n}ms`; + if (n < 10_000) return `${(n / 1000).toFixed(2)}s`; + if (n < 100_000) return `${(n / 1000).toFixed(1)}s`; + return `${Math.round(n / 1000)}s`; +} + +/** + * 模型是哪家的。**按名字认**:模型没有地址可看。Claude 用 Claude 的标志而不是 + * Anthropic 的字母,o 系列和 GPT、Codex 归 OpenAI;其余交给上游那一套名字规则 + * (`qwen/qwen3-coder` 这种带厂商前缀的也认)。认不出来返回 `null`,画首字母方块。 + */ +export function modelGlyph(model: string): GlyphId | null { + const m = model.toLowerCase(); + if (/claude/.test(m)) return "claude"; + if (/(^|\/)(o\d|gpt|chatgpt|codex)/.test(m)) return "openai"; + return upstreamGlyph({ name: m }); +} diff --git a/src/useLive.i18n.ts b/src/overview/useLive.i18n.ts similarity index 100% rename from src/useLive.i18n.ts rename to src/overview/useLive.i18n.ts diff --git a/src/useLive.test.ts b/src/overview/useLive.test.ts similarity index 100% rename from src/useLive.test.ts rename to src/overview/useLive.test.ts diff --git a/src/useLive.ts b/src/overview/useLive.ts similarity index 71% rename from src/useLive.ts rename to src/overview/useLive.ts index 57bbd63b..adda1fe1 100644 --- a/src/useLive.ts +++ b/src/overview/useLive.ts @@ -2,7 +2,7 @@ import { useEffect, useReducer, useRef } from "react"; import { call } from "@/control"; import { listen } from "@tauri-apps/api/event"; import { textOf } from "@/i18n"; -import type { CoreEvent } from "./types"; +import type { CoreEvent } from "@/types"; import { liveText } from "./useLive.i18n"; /** @@ -90,77 +90,49 @@ export interface LiveFail { } /** - * 最近这十分钟,直接从事件流上攒出来。 - * - * **不查库、不轮询。**概览别的部分问的是 SQLite,而那条路的最小延迟是 - * 「落库 + 下一次刷新」;实时档要的是请求到达的那一刻曲线就动,那只有 - * 事件流给得了。每条请求要画的东西都在它的结局里:模型和用量一起到 - * (`request_finished`、`request_failed`、`request_cancelled`)。 - * - * **模型名从结局里拿,不从开始事件里记。**这个钩子只在概览开着时才挂 - * 上,打开的那一刻正在跑的请求,它的开始事件早就过去了;以前按 id 去 - * 找开始时记下的模型,这些请求就全落进了「未知模型」那一层。 - * `request_started` 现在只用来数「进行中」(怎么数见 `resync`)。 + * 按帧合并的重画。一阵并发的请求一起落地时,一帧里只画一次。 + */ +function useFrame(): [() => void, () => void] { + const [, frame] = useReducer((n: number) => n + 1, 0); + const raf = useRef(null); + const soon = useRef(() => { + if (raf.current === null) + raf.current = requestAnimationFrame(() => { + raf.current = null; + frame(); + }); + }); + useEffect( + () => () => { + if (raf.current !== null) cancelAnimationFrame(raf.current); + }, + [], + ); + return [frame, soon.current]; +} + +/** + * 此刻有几个请求在跑。概览的页头一直显示它,不只在实时档。 * - * 金额比用量晚一拍:它是存储层落库时按价目表算的,core 算完会补一条 - * `request_priced`。所以实时档也画得出花费,只是那一格会在请求结束之后 - * 的几十毫秒里先长出 token、再长出钱。 + * **从 core 的快照起步,之后跟着事件流加减。**只靠事件流数有两处数不对:挂上 + * 之前就开始了的请求,开始事件早就过去了,一直少数到它结束;core 重启时正在跑 + * 的请求再也不会有结局,一直挂在「进行中」里。所以挂上时问一次「此刻还在跑 + * 的」,core 重启回来再问一次(`resync`),平时照旧按事件加减。 * - * 那个定时器**不是轮询**:它什么都不查,只是让曲线往左走。不走的话, - * 一段没有请求的空闲看起来会像界面卡住了。只在这一档挂着。 + * **快照在路上的时候事件照样在来。**它是 core 在某一刻拍下的,到这边时已经晚了 + * 一截:这中间开始的它没有,这中间结束的它还有。所以从问出去的那一刻起,把事件 + * 流上见到的开始和结局都记下来(`since`),快照到了再合在一起:快照里的,加上 + * 中途开始的,减去中途结束的。 * - * **进这一档先把已经发生过的那十分钟补上。**只挂事件流的话,曲线永远 - * 从切进来的那一刻开始长 —— 刚打完一批请求切过来,看到的是一张空图加 - * 一句「等待请求」,而顶上的数字说有几十次。请求发生过,没人看着不 - * 等于没发生;流量列表早就是这么填的(见 `recent_requests`)。 + * **别拿 `Status::in_flight`**:那个从连接进数据面就算,鉴权失败、排队的都在 + * 里面。 */ -export function useLive(active: boolean, windowMs: number) { - const samples = useRef([]); - const fails = useRef([]); +export function useInFlight(): number { const flying = useRef(new Set()); - const [, frame] = useReducer((n: number) => n + 1, 0); + const [, soon] = useFrame(); useEffect(() => { - if (!active) { - // 切走就把攒的东西扔掉。**留着的话,切回来画的是一段过期的窗口** - // —— 重新进来时按当下的时间补,比拿旧样本往左挪准。 - samples.current = []; - fails.current = []; - flying.current.clear(); - return; - } let alive = true; - /* - 事件当场重画,**按帧合并**:一阵并发的请求一起落地时,一帧里只画 - 一次。 - */ - let raf: number | null = null; - const soon = () => { - if (raf === null) - raf = requestAnimationFrame(() => { - raf = null; - frame(); - }); - }; - /* - 事件流和补回来的历史会说到同一次请求,而且**谁先到都有可能**:落库 - 和事件是两条路。所以两边落样本之前都要看一眼对方记过没有。 - */ - const counted = (id: number) => samples.current.some((s) => s.id === id); - const failedAlready = (id: number) => fails.current.some((f) => f.id === id); - /* - **「进行中」从 core 的快照起步,之后跟着事件流加减。** - - 只靠事件流数有两处数不对:挂上之前就开始了的请求,开始事件早就过去 - 了,一直少数到它结束;core 重启时正在跑的请求再也不会有结局,一直挂在 - 「进行中」里。所以挂上时问一次「此刻还在跑的」,core 重启回来再问一次 - (`resync`),平时照旧按事件加减。 - - **快照在路上的时候事件照样在来。**它是 core 在某一刻拍下的,到这边时 - 已经晚了一截:这中间开始的它没有,这中间结束的它还有。所以从问出去的 - 那一刻起,把事件流上见到的开始和结局都记下来(`since`),快照到了再 - 合在一起:快照里的,加上中途开始的,减去中途结束的。 - */ let since: { started: Set; ended: Set } | null = null; const start = (id: number) => { flying.current.add(id); @@ -172,55 +144,18 @@ export function useLive(active: boolean, windowMs: number) { }; const un = listen("core-event", (e) => { const ev = e.payload; - if (ev.kind === "request_started") { - start(ev.id); - } else if (ev.kind === "request_finished" || ev.kind === "request_cancelled") { - // 取消的也画进曲线:**上游已经为它计了费**,那些 token 真实发生过 - end(ev.id); - if (ev.usage && !counted(ev.id)) { - const u = ev.usage; - samples.current.push({ - id: ev.id, - at: Date.now(), - model: ev.model || textOf(liveText).unknownModel, - tokens: u.input + u.output + u.cache_read + u.cache_write, - }); - } - } else if (ev.kind === "request_priced") { - // 价钱补在那一格原来的位置上,**不是补在「现在」** —— 它说的 - // 是那次请求花了多少,而那次请求发生在几十毫秒之前。 - // 倒着找:刚落地的那条几乎总在末尾。 - for (let i = samples.current.length - 1; i >= 0; i--) { - const x = samples.current[i]; - if (x && x.id === ev.id) { - if (ev.cost_micros != null) x.cost = ev.cost_micros; - break; - } - } - } else if (ev.kind === "request_failed") { + if (ev.kind === "request_started") start(ev.id); + else if ( + ev.kind === "request_finished" || + ev.kind === "request_cancelled" || + ev.kind === "request_failed" + ) end(ev.id); - // 断在中间的失败也带着用量:**上游已经为它计了费**,曲线上要有它 - if (ev.usage && !counted(ev.id)) { - const u = ev.usage; - samples.current.push({ - id: ev.id, - at: Date.now(), - model: ev.model || textOf(liveText).unknownModel, - tokens: u.input + u.output + u.cache_read + u.cache_write, - }); - } - if (!failedAlready(ev.id)) fails.current.push({ id: ev.id, at: Date.now() }); - } else if (ev.kind === "events_dropped") { - /* - **丢过事件:进行中的重新对账,丢掉的结局从库里补进曲线。**落库要一点 - 时间,等一会儿再补;补的时候按 id 去重,事件流上已经画了的不会画两遍。 - */ + else if (ev.kind === "events_dropped") { + // 丢过事件:重新对账 void resync(); - setTimeout(() => void seed(), REFILL_MS); return; - } else { - return; - } + } else return; soon(); }); const resync = async () => { @@ -258,12 +193,108 @@ export function useLive(active: boolean, windowMs: number) { soon(); } }); + return () => { + alive = false; + void un.then((f) => f()); + void unState.then((f) => f()); + }; + }, [soon]); + + return flying.current.size; +} + +/** + * 最近这一段(实时档的十分钟),直接从事件流上攒出来。 + * + * **不查库、不轮询。**概览别的部分问的是 SQLite,而那条路的最小延迟是 + * 「落库 + 下一次刷新」;实时档要的是请求到达的那一刻曲线就动,那只有 + * 事件流给得了。每条请求要画的东西都在它的结局里:模型和用量一起到 + * (`request_finished`、`request_failed`、`request_cancelled`)。 + * + * **模型名从结局里拿,不从开始事件里记。**这个钩子只在实时档挂上,打开的 + * 那一刻正在跑的请求,它的开始事件早就过去了。 + * + * 金额比用量晚一拍:它是存储层落库时按价目表算的,core 算完会补一条 + * `request_priced`。所以实时档也画得出费用,只是那一格会在请求结束之后 + * 的几十毫秒里先长出 token、再长出费用。 + * + * 那个定时器**不是轮询**:它什么都不查,只是让曲线往左走。不走的话, + * 一段没有请求的空闲看起来会像界面卡住了。只在这一档挂着。 + * + * **进这一档先把已经发生过的那一段补上。**只挂事件流的话,曲线永远从切进来 + * 的那一刻开始长 —— 刚打完一批请求切过来,看到的是一张空图加一句「等待 + * 请求」,而顶上的数字说有几十次。请求发生过,没人看着不等于没发生。 + * + * `arrived`:事件流上落地了几条带用量的请求(补回来的历史不算)。每涨一次, + * 图上「现在」那一点闪一下 —— 新数据到了。 + */ +export function useLiveWindow(active: boolean, windowMs: number) { + const samples = useRef([]); + const fails = useRef([]); + const arrived = useRef(0); + const [frame, soon] = useFrame(); + + useEffect(() => { + if (!active) { + // 切走就把攒的东西扔掉。**留着的话,切回来画的是一段过期的窗口** + // —— 重新进来时按当下的时间补,比拿旧样本往左挪准。 + samples.current = []; + fails.current = []; + return; + } + let alive = true; + /* + 事件流和补回来的历史会说到同一次请求,而且**谁先到都有可能**:落库 + 和事件是两条路。所以两边落样本之前都要看一眼对方记过没有。 + */ + const counted = (id: number) => samples.current.some((s) => s.id === id); + const failedAlready = (id: number) => fails.current.some((f) => f.id === id); + const land = (id: number, model: string | null | undefined, u: { input: number; output: number; cache_read: number; cache_write: number }) => { + if (counted(id)) return; + samples.current.push({ + id, + at: Date.now(), + model: model || textOf(liveText).unknownModel, + tokens: u.input + u.output + u.cache_read + u.cache_write, + }); + arrived.current += 1; + }; + const un = listen("core-event", (e) => { + const ev = e.payload; + if (ev.kind === "request_finished" || ev.kind === "request_cancelled") { + // 取消的也画进曲线:**上游已经为它计了费**,那些 token 真实发生过 + if (ev.usage) land(ev.id, ev.model, ev.usage); + } else if (ev.kind === "request_priced") { + // 费用补在那一格原来的位置上,**不是补在「现在」** —— 它说的 + // 是那次请求的费用,而那次请求发生在几十毫秒之前。 + // 倒着找:刚落地的那条几乎总在末尾。 + for (let i = samples.current.length - 1; i >= 0; i--) { + const x = samples.current[i]; + if (x && x.id === ev.id) { + if (ev.cost_micros != null) x.cost = ev.cost_micros; + break; + } + } + } else if (ev.kind === "request_failed") { + // 断在中间的失败也带着用量:**上游已经为它计了费**,曲线上要有它 + if (ev.usage) land(ev.id, ev.model, ev.usage); + if (!failedAlready(ev.id)) fails.current.push({ id: ev.id, at: Date.now() }); + } else if (ev.kind === "events_dropped") { + // 丢过事件:丢掉的结局从库里补进曲线。落库要一点时间,等一会儿再补; + // 补的时候按 id 去重,事件流上已经画了的不会画两遍 + setTimeout(() => void seed(), REFILL_MS); + return; + } else { + return; + } + soon(); + }); /* 先挂事件流再补历史:反过来的话,这两者之间结束的请求谁都不记。 */ const seed = async () => { try { - // 挂上了再补 —— `listen` 是异步注册的,理由同上 + // 挂上了再补 —— `listen` 是异步注册的 await un; /* **按时间取,不按条数取。**十分钟里有多少条请求说不准:取固定的 @@ -303,9 +334,7 @@ export function useLive(active: boolean, windowMs: number) { }); } // **按时间排好**:`request_priced` 是从末尾倒着找那一条的 - samples.current = [...seeded, ...samples.current].sort( - (a, b) => a.at - b.at, - ); + samples.current = [...seeded, ...samples.current].sort((a, b) => a.at - b.at); fails.current = [...seededFails, ...fails.current]; frame(); } catch { @@ -323,15 +352,13 @@ export function useLive(active: boolean, windowMs: number) { return () => { alive = false; void un.then((f) => f()); - void unState.then((f) => f()); clearInterval(h); - if (raf !== null) cancelAnimationFrame(raf); }; - }, [active, windowMs]); + }, [active, windowMs, frame, soon]); return { samples: samples.current, fails: fails.current, - inFlight: flying.current.size, + arrived: arrived.current, }; } diff --git a/src/overview/useOverview.ts b/src/overview/useOverview.ts new file mode 100644 index 00000000..0b41f595 --- /dev/null +++ b/src/overview/useOverview.ts @@ -0,0 +1,100 @@ +import { useEffect, useRef, useState } from "react"; +import { invoke } from "@tauri-apps/api/core"; +import { useResource } from "@/lib/resource"; +import { bucketFor, windowStart, type Range } from "@/ui/range"; +import type { Dashboard } from "@/types"; + +const HOUR = 3_600_000; + +/** + * 一个区间的标识。**缓存按它分份,数字的口径也按它换**:换了区间,数字直接落到 + * 新值,不从旧值滚过去 —— 那不是「涨了」,是换了一个东西在看。 + */ +export function rangeId(r: Range): string { + if (r.live) return "live"; + if (r.custom) return `from:${new Date(Date.now() - r.ms).toDateString()}`; + return `last:${r.ms}`; +} + +/** 历史档的格宽;实时档的汇总按一小时一格取(图另有来路) */ +export function bucketOf(r: Range): number { + return r.live ? HOUR : bucketFor(r.ms); +} + +/** 画在页面上的那一份:数据,和它属于哪个区间 */ +export interface Shown { + id: string; + range: Range; + data: Dashboard; +} + +/** + * 概览的数据。 + * + * **每个区间各缓存一份**(`useResource`):回到概览、切回刚看过的区间,立刻画上 + * 一次的数,后台再取。`tick` 一变(库里多了请求、手动刷新)就重取当前这一份。 + * + * **画出来的数和它的区间绑在一起。**切到一个还没取过的区间时,新数据到之前继续画 + * 旧区间的那一份(`switching`,页面把它压暗)—— 而不是拿旧数据套新区间的格宽和 + * 标签去画,那会先画出一张对不上的图、数字再从旧值滚到新值。新数据到了,区间、 + * 数字、图一起换。 + * + * 内容没变的重取不换引用:每次 `invoke` 回来都是新对象,直接换的话整页会在什么 + * 都没发生的时候重画一遍。 + */ +export function useOverview(range: Range, tick: number) { + const id = rangeId(range); + const r = useResource( + `overview:${id}`, + () => invoke("dashboard", { sinceMs: windowStart(range), bucketMs: bucketOf(range) }), + { deps: [tick] }, + ); + const last = useRef(null); + /** 上一份的序列化结果,和 `last` 一起换 */ + const lastJson = useRef(""); + /** 最近一次比过的那个对象:同一个对象不用再序列化一遍 */ + const seen = useRef(undefined); + if (r.data !== undefined && (seen.current !== r.data || last.current?.id !== id)) { + seen.current = r.data; + const json = JSON.stringify(r.data); + if (last.current?.id !== id || lastJson.current !== json) { + last.current = { id, range, data: r.data }; + lastJson.current = json; + } + } + const shown = last.current; + const pending = r.data === undefined && shown !== null && r.error === undefined; + /* + **失败了就一直是失败的样子,重试时也是**:点「重试」之后错误还在(`useResource` + 在下一次成功之前留着它),这时画的是同一个错误加上转圈的按钮,而不是先闪回骨架 + 再闪回错误。 + */ + const failed = r.data === undefined && r.error !== undefined; + return { + shown, + /** 选中的区间还没有数据,画的是上一个区间的 */ + switching: useLagging(pending, 120), + /** 选中的区间读取失败,而且没有它的数据可画 */ + failed, + error: r.error, + /** 失败之后又在取(点了重试,或者库里又多了请求) */ + retrying: failed && r.loading, + reload: r.reload, + }; +} + +/** + * `on` 持续了 `ms` 才算数。快的切换(缓存里有、或者几十毫秒就回来)不闪一下。 + */ +function useLagging(on: boolean, ms: number): boolean { + const [late, setLate] = useState(false); + useEffect(() => { + if (!on) { + setLate(false); + return; + } + const h = setTimeout(() => setLate(true), ms); + return () => clearTimeout(h); + }, [on, ms]); + return on && late; +} diff --git a/src/triggers.ts b/src/triggers.ts deleted file mode 100644 index 09fe093b..00000000 --- a/src/triggers.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { Dashboard, Overview } from "./types"; - -/** - * 高级功能的触发条件。 - * - * **不是「折叠到高级设置里」。**折叠面板仍然在告诉用户「这里有你不懂的 - * 东西」,那种焦虑不比直接显示小多少。条件不满足就**不出现**。 - * - * 而条件要绑在「这个功能解决的问题存在吗」上,**不能绑在某个数量上** —— - * 数量是偷懒的代理指标,很容易绑错。这个项目已经绑错过一次:把「路由」 - * 整体绑到 provider 数量,就把**单上游多模型**这个最常见的场景一起挡在 - * 了门外。 - * - * 全都写在一个文件里,是为了让那条反面判据能被真的执行: - * - * > 一个只配了一个 API 的用户,会因为这个功能而多看到一样东西吗? - * - * 散在各个组件里的 `providers.length >= 2` 回答不了这个问题。 - */ -export interface Triggers { - /** - * **一直有。**一个上游就有几十个模型 —— 让 opus 实际打到 sonnet、 - * 长上下文走 1M 版本、按模型限额,全都只需要一家上游,而这个问题从 - * 第一天就存在。 - */ - modelRouting: true; - /** 有 ≥2 个 provider。只有一家的时候「切到哪儿」这个问题不存在 */ - failover: boolean; - /** 有 ≥3 个 provider,且其中至少两个同类 */ - groups: boolean; - /** 有 ≥2 个 provider **且** ≥2 个客户端在发请求 */ - perClientRouting: boolean; - /** 熔断状态。只有一家时熔断本来就是旁路的,显示它没有意义 */ - health: boolean; - /** 上游之间的对比(测速、延迟排行)。一家没得比 */ - comparison: boolean; - /** 成本相关。**有过请求才出现** —— 一条都没有的时候它是个空壳 */ - cost: boolean; -} - -// 订阅额度那条触发条件**故意不在这里**:界面上现在只有菜单栏显示它, -// 而那条路自己就能判断(有额度头就是订阅账号)。提前在这里接一个没人 -// 用的开关,是在制造一个以后没人记得为什么存在的分支。 - -export function triggers(ov: Overview | null, d: Dashboard | null): Triggers { - // 没有 overview 时(Dashboard 那条路),从历史里的上游名字数 —— - // **问题存不存在,看的是实际发生过什么,不是配置里写了几个** - const providers = - ov?.providers.length ?? - new Set((d?.history ?? []).filter((r) => !r.local && r.provider).map((r) => r.provider)).size; - // 「在发请求的客户端」不是「配置里的客户端」—— 配了三把 key 却只有 - // 一个客户端在用,那个问题同样不存在 - const activeClients = new Set((d?.history ?? []).filter((r) => !r.local).map((r) => r.client)); - const s = d?.summary; - - return { - modelRouting: true, - failover: providers >= 2, - // 「至少两个同类」现在用协议近似:同协议的上游才是彼此的替补 - groups: providers >= 3 && hasTwoOfAKind(ov), - perClientRouting: providers >= 2 && activeClients.size >= 2, - health: providers >= 2, - comparison: providers >= 2, - // **有过请求才出现。**一个还没有任何数据的成本面板是在展示一个 - // 空壳,而它占的地方本来可以放「接下来该做什么」 - cost: !!s && (s.requests > 0 || s.locally_answered > 0), - }; -} - -function hasTwoOfAKind(ov: Overview | null): boolean { - const byProtocol = new Map(); - for (const p of ov?.providers ?? []) { - const k = p.protocol ?? null; - byProtocol.set(k, (byProtocol.get(k) ?? 0) + 1); - } - return [...byProtocol.values()].some((n) => n >= 2); -} diff --git a/src/types.ts b/src/types.ts index ed1b7f9c..ab4a26de 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,7 +14,6 @@ import type { CostBucketGroup, Event, Guard, - HistoryRow, LatencyView, Msg, SecretItem, @@ -328,10 +327,10 @@ export function interruptInFlight(rows: Map): boolean { /** 概览要的全部数据,Rust 侧 `dashboard` 命令一次拼好 */ export interface Dashboard { summary: Summary; + /** 首字节时间的分位,按模型分。和 `summary` 同一个时间窗 */ latency: LatencyView[]; /** 按上游分。**和按模型分是两个问题** */ latency_by_provider: LatencyView[]; - history: HistoryRow[]; storage: StorageStatus | null; /** * 按所选时间范围分格。**稀疏的** —— core 那边只产出有数据的桶, diff --git a/src/ui/README.md b/src/ui/README.md index 700e13d4..79508256 100644 --- a/src/ui/README.md +++ b/src/ui/README.md @@ -152,7 +152,7 @@ All colours are CSS tokens (`src/index.css`) exposed as Tailwind colours. **Neve | `destructive` | failed, stopped, unavailable, dangerous action | | `idle` | not working but not a fault: unused, disabled, no data yet | | `warning-foreground`, `destructive-foreground`, `success-foreground` | **Text** in that hue on a tinted background (`bg-warning/10`). Not text on a solid fill — that is `text-white`. | -| `chart-1…5`, `cache-*` | Data visualisation only | +| `chart-1…5`, `chart-other`, `cache-*` | Data visualisation only (`chart-other` is the grey "Other" series) | | `--chrome-*` | Window chrome (sidebar, toolbar). Shell only. | Tinted status backgrounds are the status colour at low alpha: `bg-warning/10`, @@ -320,6 +320,7 @@ movement. Do not write your own `@keyframes` or `transition-all` in pages. | Numbers that change | `` (`@/ui/motion`), built on `useCountUp`. Change `scope` when the meaning changes (time range) so it jumps instead of counting. | | Bars, meters, progress | `motion-bar` on the element whose width/height changes. | | Live / in-flight | `` or `motion-live` on a dot. | +| New data at a live edge | `motion-ping` on a dot (HTML or SVG): one ring, not looping. Re-key the element to play it again. | | Skeleton shimmer | Built into `Skeleton` (`motion-shimmer`). | | Hover / press | `transition-colors duration-(--motion-fast)`. | diff --git a/src/ui/chart.tsx b/src/ui/chart.tsx index 897bd44b..6895495c 100644 --- a/src/ui/chart.tsx +++ b/src/ui/chart.tsx @@ -1,50 +1,25 @@ import * as React from "react" import { cn } from "@/lib/utils" import * as RechartsPrimitive from "recharts" -import type { TooltipValueType } from "recharts" const INITIAL_DIMENSION = { width: 320, height: 200 } as const -type TooltipNameType = number | string /** - * 每个系列的名字和图标。**没有 shadcn 原版的 `color` / `theme`**:原版把它们拼成 - * `--color-<键>` 写进一段 `