From a90f2cebc37e350401105c52448377a7ec0a05fd Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 28 Sep 2026 01:34:41 +0800 Subject: [PATCH] Use core v0.54.0: time to first token and generation speed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Core 0.54.0 records when each response's first token arrives and how fast it is generated, and fixes the live rate, which a single response that is not streamed could push to tens of thousands of tokens per second. - Traffic: the latency cell shows time to first token → total time. Hovering it lists the first token, the total, the generation time and the speed. The table gets no new column, because at the default window size the English table would no longer fit. A running request shows its first token as soon as it arrives. - Request details: five figures (first token, total time, speed, tokens, cost). The bar is split into waiting for the first token and generating, and the response-header time moves into the rows below. A response that is not streamed shows "—" for the first token and the speed, and no bar. - Overview: the latency section reports time to first token. A new Generation speed section gives the median speed by model and by upstream, aligned with the latency section above it. - Upstreams: the timing column reads "TTFT / speed", with the median first token above and the median speed below, in the same two-line layout as the 24-hour column. - The menu bar keeps its wording; its figure now comes from the corrected live rate. Upgrading empties the request history: the request store schema moved from 21 to 22. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- README.zh-CN.md | 6 +- scripts/shots/core/en/status.json | 4 +- scripts/shots/core/zh/status.json | 4 +- scripts/shots/mock/commands.ts | 3 +- scripts/shots/mock/traffic.ts | 49 +++++++- src-tauri/Cargo.lock | 44 +++---- src-tauri/Cargo.toml | 12 +- src-tauri/src/dashboard.rs | 18 ++- src-tauri/src/upstreams.rs | 11 +- src/RequestDrawer.i18n.tsx | 16 ++- src/RequestDrawer.tsx | 42 ++++--- src/events.test.ts | 42 ++++++- src/format.ts | 18 +-- src/generated/tw-api.ts | 60 ++++++++-- src/overview/LatencySection.tsx | 2 +- src/overview/OverviewPage.tsx | 2 + src/overview/SpeedSection.tsx | 174 ++++++++++++++++++++++++++++ src/overview/overview.i18n.ts | 14 ++- src/overview/series.test.ts | 2 + src/overview/useLive.test.ts | 4 +- src/traffic/RequestTable.tsx | 42 ++++++- src/traffic/Traffic.i18n.tsx | 13 +++ src/types.ts | 21 +++- src/upstreams/UpstreamTable.i18n.ts | 14 ++- src/upstreams/UpstreamTable.tsx | 29 ++++- src/upstreams/api.ts | 3 + src/upstreams/data.test.ts | 5 +- src/upstreams/data.ts | 4 +- src/useRequests.ts | 5 + 30 files changed, 561 insertions(+), 113 deletions(-) create mode 100644 src/overview/SpeedSection.tsx diff --git a/README.md b/README.md index 98b5225f..a127b8b8 100644 --- a/README.md +++ b/README.md @@ -151,8 +151,9 @@ The Overview page reports tokens, cost and requests for the last 24 hours, follows the last ten minutes. A trend chart stacks tokens or cost by model, and the model ranking beneath it opens the matching requests. Further sections cover the prompt cache (hit rate, the net savings it brought and the hit rate -per model), latency (median and 95th-percentile time to first byte, per model -and per upstream) and what each protection found. +per model), latency (median and 95th-percentile time to first token, per model +and per upstream), generation speed (median tokens per second, per model and +per upstream) and what each protection found. The cost figure states how much of it is estimated, for instance for a response that was cut off before it finished. Requests whose model has no @@ -169,7 +170,8 @@ and the date of the prices it was costed with. ### Traffic and sessions The Traffic page lists requests as they arrive: status, key, model, upstream, -time to first byte and total time, tokens and cost, with marks for a converted +time to first token and total time (with the generation speed on hover), tokens +and cost, with marks for a converted API format, redacted keys and a blocked or suspicious tool call. The list can be filtered by key, upstream and model, or narrowed to failed or unpriced requests. The Sessions view groups the requests of one conversation into @@ -426,7 +428,8 @@ Settings can reduce the item to the icon or to the numbers.

-Clicking it opens a native menu with the gateway's address and state, unread +Clicking it opens a native menu with the gateway's address, its generation speed +over the last minute and its state, unread notices, today's requests, tokens and cost, the quotas and reset times of each subscription account and GLM Coding Plan upstream (with the credits left under the bar on a plan billed in credits), and the requests in progress, followed by diff --git a/README.zh-CN.md b/README.zh-CN.md index 899745e9..f7efe64e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -90,13 +90,13 @@ AppImage 通过 FUSE 挂载自身,需要 fuse3 软件包中的 `fusermount3` ### 用量与费用 -概览页按最近 24 小时、7 天、30 天或自定义区间统计 token、费用与请求数,并与上一个同等长度的区间对比;实时档显示最近十分钟。趋势图按模型分层显示 token 或费用,其下的模型排行可以直接打开对应的请求。页面下方依次是缓存(命中率、缓存带来的净节省、各模型的命中率)、延迟(首字节时间的中位数与 P95,按模型和按上游)以及各项防护的检出情况。 +概览页按最近 24 小时、7 天、30 天或自定义区间统计 token、费用与请求数,并与上一个同等长度的区间对比;实时档显示最近十分钟。趋势图按模型分层显示 token 或费用,其下的模型排行可以直接打开对应的请求。页面下方依次是缓存(命中率、缓存带来的净节省、各模型的命中率)、延迟(首 token 时间的中位数与 P95,按模型和按上游)、生成速度(每秒 token 数的中位数,按模型和按上游)以及各项防护的检出情况。 费用会注明其中估算的部分,例如响应结束前被中断的请求。模型未定价的请求和上游未报告用量的请求单独计数,从不按零计入。价格来自价目表:默认价目表采用 LiteLLM 的公开价格,每天更新一次;自定义价目表在其基础上设置倍率,并可单独为个别模型定价,适用于价格与官方不同的中转服务。ChatGPT 这类订阅账号同样按价目表计价,本地模型等上游可设为不计费。每个请求的费用在请求结束时确定,并注明计价所用的价目表及其数据日期。 ### 流量与会话 -流量页实时列出请求:状态、密钥、模型、上游、首字节时间与总耗时、token 和费用,并标出格式转换、被脱敏的密钥,以及被拦截或可疑的工具调用。列表可以按密钥、上游和模型筛选,或只看失败、无法计价的请求。「会话」视图把同一段对话的请求归为若干轮次,给出每一轮的输入 token 与费用。 +流量页实时列出请求:状态、密钥、模型、上游、首 token 时间与总耗时(悬停时显示生成速度)、token 和费用,并标出格式转换、被脱敏的密钥,以及被拦截或可疑的工具调用。列表可以按密钥、上游和模型筛选,或只看失败、无法计价的请求。「会话」视图把同一段对话的请求归为若干轮次,给出每一轮的输入 token 与费用。 打开一个请求可以查看时间线、路由(命中的规则、经过的策略组,以及每一次尝试的状态与耗时)、请求与响应正文、用量与费用。DeepSeek Harness 发出的请求还会显示所带会话日志的大小:这是客户端随每个请求附带的整段对话记录,发往 DeepSeek 以外的上游之前由网关去除。已结束的请求可以在预估费用后原样发送到另一个上游,两次的响应并排对照。 @@ -206,7 +206,7 @@ macOS 菜单栏显示今日 token 与今日费用,订阅额度紧张时数字

-点开是原生菜单:网关地址与状态、未读的提醒、今日的请求数、token 与费用、各订阅账号与 GLM Coding Plan 上游的额度与重置时间(积分制套餐在额度条下方显示剩余积分)、进行中的请求,以及切换手动选择策略组中的上游、复制网关地址和默认密钥、切换连接、检查更新等常用操作,不必先打开主界面。 +点开是原生菜单:网关地址、最近一分钟的生成速度与状态、未读的提醒、今日的请求数、token 与费用、各订阅账号与 GLM Coding Plan 上游的额度与重置时间(积分制套餐在额度条下方显示剩余积分)、进行中的请求,以及切换手动选择策略组中的上游、复制网关地址和默认密钥、切换连接、检查更新等常用操作,不必先打开主界面。 diff --git a/scripts/shots/core/en/status.json b/scripts/shots/core/en/status.json index 758d4e01..cb70b99e 100644 --- a/scripts/shots/core/en/status.json +++ b/scripts/shots/core/en/status.json @@ -1,5 +1,5 @@ { - "api_version": 24, + "api_version": 27, "clients": 4, "config_path": "", "gateway_addr": null, @@ -14,5 +14,5 @@ "reachable": [] }, "uptime_secs": 0, - "version": "0.51.0" + "version": "0.54.0" } diff --git a/scripts/shots/core/zh/status.json b/scripts/shots/core/zh/status.json index 758d4e01..cb70b99e 100644 --- a/scripts/shots/core/zh/status.json +++ b/scripts/shots/core/zh/status.json @@ -1,5 +1,5 @@ { - "api_version": 24, + "api_version": 27, "clients": 4, "config_path": "", "gateway_addr": null, @@ -14,5 +14,5 @@ "reachable": [] }, "uptime_secs": 0, - "version": "0.51.0" + "version": "0.54.0" } diff --git a/scripts/shots/mock/commands.ts b/scripts/shots/mock/commands.ts index 6ec25370..9cc1e043 100644 --- a/scripts/shots/mock/commands.ts +++ b/scripts/shots/mock/commands.ts @@ -17,7 +17,7 @@ import type { UpstreamStats } from "@/upstreams/api"; import type { ClientsResponse, CoreStatus, Dashboard, KeyUsage, McpTargetView, PlanView, ScanReport } from "@/types"; import { CORE, CHATGPT_WINDOWS } from "./core"; import { LOCAL_GATEWAY, status } from "./config"; -import { IN_FLIGHT, costBucketsBy, costBy, dashboard, upstreamLatency } from "./traffic"; +import { IN_FLIGHT, costBucketsBy, costBy, dashboard, upstreamLatency, upstreamTokenRate } from "./traffic"; import { clientsResponse, mcpTargets, plan, scanReport } from "./clients"; import { NOTICES, APP_VERSION, SERVER, autostart, connView, langView, menubar, noticeMode, tested, themeView, updateView } from "./app"; import { P } from "./params"; @@ -121,6 +121,7 @@ const COMMANDS: Table = { return { costs: costBy(sinceMs, (h) => h.provider || null), latency: upstreamLatency(sinceMs), + token_rate: upstreamTokenRate(sinceMs), quotas: [{ provider: "chatgpt", windows: CHATGPT_WINDOWS() }], // Rust 侧把格宽压到不小于一分钟(upstreams.rs 的 `MIN_BUCKET_MS`) buckets: costBucketsBy(sinceMs, Math.max(60_000, bucketMs), (h) => h.provider), diff --git a/scripts/shots/mock/traffic.ts b/scripts/shots/mock/traffic.ts index fd282006..fdf93a32 100644 --- a/scripts/shots/mock/traffic.ts +++ b/scripts/shots/mock/traffic.ts @@ -17,6 +17,7 @@ import type { HistoryRow, InFlightRequest, LatencyView, + TokenRateView, Msg, PriceFields, RouteHits, @@ -195,6 +196,8 @@ function makeRow(s: Spec, r: () => number): HistoryRow { const price = priceFor(provider, s.model); const wait = outcome.kind === "fallback" ? Math.round(1_200 + r() * 1_400) : 0; const duration = wait + ttfb + Math.round((usage.out / perSec) * 1000); + // `ttfb` is when the first token arrives; a stream's response headers come back well before that + const headers = wait + Math.round(ttfb * 0.3); // 收到了响应的一跳只记状态码,`error` 留给没收到响应的(tw-gateway 的 `hop`) const attempts: AttemptView[] = outcome.kind === "fallback" @@ -215,8 +218,10 @@ function makeRow(s: Spec, r: () => number): HistoryRow { model: s.model, path, status: 200, - ttfb_ms: wait + ttfb, + ttfb_ms: headers, + ttft_ms: wait + ttfb, duration_ms: duration, + tokens_per_sec: rate(usage.out, duration - wait - ttfb), bytes: Math.round(usage.out * 5.2 + 900), input_tokens: usage.in, output_tokens: usage.out, @@ -244,7 +249,9 @@ function makeRow(s: Spec, r: () => number): HistoryRow { Object.assign(row, { status: null, ttfb_ms: null, + ttft_ms: null, duration_ms: ttfb, + tokens_per_sec: null, bytes: null, input_tokens: null, output_tokens: null, @@ -261,6 +268,8 @@ function makeRow(s: Spec, r: () => number): HistoryRow { Object.assign(row, { output_tokens: out, duration_ms: ttfb + Math.round((out / perSec) * 1000), + // 没跑完的没有速度(tw-gateway 的 `ending::rate`) + tokens_per_sec: null, bytes: Math.round(out * 5.2 + 900), cost_micros: price ? costOf(price, cut) : null, cost_estimated: true, @@ -282,7 +291,9 @@ function localRow(who: Who, at: number, probe: "health_check" | "warmup"): Histo path: probe, status: 200, ttfb_ms: 0, + ttft_ms: null, duration_ms: 0, + tokens_per_sec: null, bytes: null, input_tokens: null, output_tokens: null, @@ -470,7 +481,8 @@ function generate() { attempts: [{ provider: plan.order[0]!, outcome: "served", status: 200, error: null, ms: 1_320 }], billing: "per-token", }, - { kind: "request_headers", id, status: 200, ttfb_ms: 1_320 }, + { kind: "request_headers", id, status: 200, ttfb_ms: 400 }, + { kind: "request_first_token", id, ttft_ms: 1_320 }, ], }); @@ -590,16 +602,16 @@ export function summary(from: number, to = Infinity): Summary { } /** - * 首字节的 P50 / P95,按模型或按上游,照 tw-store 的 `latency_by_model` / `latency_by_provider`: - * 本地应答的和没收到首字节的不算,按名字排,分位取第 ⌈p·n/100⌉ 个 + * 第一个 token 的 P50 / P95,按模型或按上游,照 tw-store 的 `latency_by_model` / `latency_by_provider`: + * 本地应答的和没有第一个 token 的不算,按名字排,分位取第 ⌈p·n/100⌉ 个 */ function latency(rows: HistoryRow[], key: (h: HistoryRow) => string): LatencyView[] { const by = new Map(); for (const h of rows) { - if (h.local || h.ttfb_ms == null) continue; + if (h.local || h.ttft_ms == null) continue; const k = key(h); if (!k) continue; - by.set(k, [...(by.get(k) ?? []), h.ttfb_ms]); + by.set(k, [...(by.get(k) ?? []), h.ttft_ms]); } return [...by.entries()] .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) @@ -610,6 +622,28 @@ function latency(rows: HistoryRow[], key: (h: HistoryRow) => string): LatencyVie }); } +/** 生成速度,照 tw-gateway 的 `ending::rate`:生成不到半秒的没有 */ +function rate(output: number, genMs: number): number | null { + return output > 0 && genMs >= 500 ? Math.floor((output * 1000) / genMs) : null; +} + +/** 生成速度的中位数,按模型或按上游,照 tw-store 的 `token_rate`:分位同 `latency` */ +function tokenRate(rows: HistoryRow[], key: (h: HistoryRow) => string): TokenRateView[] { + const by = new Map(); + for (const h of rows) { + if (h.local || h.tokens_per_sec == null) continue; + const k = key(h); + if (!k) continue; + by.set(k, [...(by.get(k) ?? []), h.tokens_per_sec]); + } + return [...by.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([model, xs]) => { + xs.sort((a, b) => a - b); + return { model, p50: xs[Math.max(0, Math.ceil(xs.length / 2) - 1)]!, samples: xs.length }; + }); +} + export function dashboard(sinceMs: number, bucketMs: number): Dashboard { const rows = rowsBetween(sinceMs).filter((h) => !h.local); const buckets = new Map(); @@ -659,6 +693,8 @@ export function dashboard(sinceMs: number, bucketMs: number): Dashboard { prev: summary(sinceMs - span, sinceMs), latency: latency(window, (h) => h.model), latency_by_provider: latency(window, (h) => h.provider), + token_rate: tokenRate(window, (h) => h.model), + token_rate_by_provider: tokenRate(window, (h) => h.provider), storage: { recording: true, rows: HISTORY.length, blob_bytes: 412 * 1024 ** 2, forwarding_affected: false }, buckets: [...buckets.values()].sort((a, b) => a.at_ms - b.at_ms), buckets_by_model: [...byModel.values()].sort((a, b) => a.at_ms - b.at_ms), @@ -729,6 +765,7 @@ export function costBucketsBy(from: number, bucketMs: number, key: (h: HistoryRo } export const upstreamLatency = (from: number) => latency(rowsBetween(from), (h) => h.provider); +export const upstreamTokenRate = (from: number) => tokenRate(rowsBetween(from), (h) => h.provider); /** * 各条路由、各条规则命中了多少(`GET /summary/routes`),照 tw-store 的 `route_stats`:按每一行 diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 6f4f7675..be6a3dc7 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -82,7 +82,7 @@ dependencies = [ "objc2-foundation", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.59.0", "wl-clipboard-rs", "x11rb", ] @@ -974,7 +974,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.3", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -1175,7 +1175,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2651,7 +2651,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3591,7 +3591,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3647,7 +3647,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -4733,7 +4733,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5278,8 +5278,8 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "serde", "serde_json", @@ -5289,8 +5289,8 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "serde", "serde_json", @@ -5298,8 +5298,8 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "base64 0.22.1", "regex", @@ -5312,8 +5312,8 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "serde", "serde_json", @@ -5339,8 +5339,8 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "serde", "ts-rs", @@ -5348,8 +5348,8 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "notify", "thiserror 2.0.21", @@ -5358,8 +5358,8 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.53.0" -source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.53.0#9b4b2f76faa7d4f5deef8b1c7e99a4116bf3c8e0" +version = "0.54.0" +source = "git+https://github.com/ThinkWatchProject/ThinkWatch-Core.git?tag=v0.54.0#3f68ecfa55fd0c22646880356e6eb8633cf7047b" dependencies = [ "saphyr-parser", "thiserror 2.0.21", @@ -5856,7 +5856,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 74dc7fda..4342810a 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -26,12 +26,12 @@ license = "MIT" # twcore 二进制必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是 # 从 tw-api 锁到的 tag 去取二进制的(见 scripts/fetch-core.sh)。 [workspace.dependencies] -tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.53.0" } -tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.53.0" } -tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.53.0" } -tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.53.0" } -tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.53.0" } -tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.53.0" } +tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.54.0" } +tw-types = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.54.0" } +tw-yaml = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.54.0" } +tw-guard = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.54.0" } +tw-watch = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.54.0" } +tw-link = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.54.0" } [lib] name = "thinkwatch_lite_lib" diff --git a/src-tauri/src/dashboard.rs b/src-tauri/src/dashboard.rs index a9d61cf9..95d55feb 100644 --- a/src-tauri/src/dashboard.rs +++ b/src-tauri/src/dashboard.rs @@ -1,4 +1,4 @@ -//! 概览页:一次取齐的汇总、趋势和延迟。 +//! 概览页:一次取齐的汇总、趋势、延迟和生成速度。 use tw_api::ep; @@ -7,7 +7,7 @@ use crate::{ error::{Out, text}, }; -/// 一段时间的汇总、趋势、延迟、存储状态,和上一个等长区间的汇总。 +/// 一段时间的汇总、趋势、延迟、生成速度、存储状态,和上一个等长区间的汇总。 /// /// **一起取。**界面上它们是同一块,分几次 invoke 会让那一块在几十毫秒里分几次 /// 跳变。 @@ -52,6 +52,14 @@ pub async fn dashboard( .call::(&[], &window(Some(since), None)) .await .ok(), + token_rate: c + .call::(&[], &window(Some(since), None)) + .await + .ok(), + token_rate_by_provider: c + .call::(&[], &window(Some(since), None)) + .await + .ok(), storage: c.call::(&[], &()).await.ok(), // 趋势和分组。**拿不到不该让整页失败** —— 这一页别的部分照样有用(同一条: // 观测层的缺失不该扩散)。但拿不到是 `None`,**不是空的**:空的在界面上就是 @@ -93,13 +101,17 @@ pub async fn dashboard( #[derive(serde::Serialize)] pub struct Dashboard { summary: tw_api::Summary, - /// 首字节时间的分位,按模型分。和 `summary` 同一个时间窗。 + /// 第一个 token 到的时刻的分位,按模型分。和 `summary` 同一个时间窗。 /// /// 下面这几样**拿不到是 `None`,不是空的**:空的是「没有样本、没有请求」, /// 取数失败时那样说就是编了一个零。界面见到 `None` 写「暂时取不到」 latency: Option>, /// 按上游分。**和按模型分是两个问题** latency_by_provider: Option>, + /// 生成速度的中位数,按模型分。同一个时间窗 + token_rate: Option>, + /// 按上游分 + token_rate_by_provider: Option>, /// 拿不到就是没有 —— 存储层不在的时候网关照常跑 storage: Option, /// 按界面给的格宽分格。**稀疏的** —— 空桶由界面补 diff --git a/src-tauri/src/upstreams.rs b/src-tauri/src/upstreams.rs index 319c66b4..e8d77629 100644 --- a/src-tauri/src/upstreams.rs +++ b/src-tauri/src/upstreams.rs @@ -7,21 +7,22 @@ use tw_api::ep; use crate::AppState; use crate::error::Out; -/// 上游列表那几列统计:一段时间里的请求与费用、首字节耗时、订阅额度,以及同一段 -/// 时间按上游分格的请求数(每一行的走势)。 +/// 上游列表那几列统计:一段时间里的请求与费用、第一个 token 到的时刻、生成速度、订阅 +/// 额度,以及同一段时间按上游分格的请求数(每一行的走势)。 /// /// **一起取。**列表上它们是同一行的几格,分几次 invoke 会让一行数字分几次 /// 跳变。拿不到的那一样是 `None`,不让整张列表打不开 —— 存储层不在的时候网关照常 /// 转发,列表也该照常打开。**但不是空的**:空的在界面上读作「24 小时里 0 次请求、 /// $0」,那是一个编出来的零(同一条见 `keys::key_usage`)。 /// -/// **四样同时问,不排队。**额度那一问可能要等几秒:GLM Coding Plan 的额度不在响应头 +/// **几样同时问,不排队。**额度那一问可能要等几秒:GLM Coding Plan 的额度不在响应头 /// 里,core 答 `/quota` 时现去问账号的额度接口(最多等 5 秒)。排着队问的话,费用和 /// 走势要白白跟着等。 #[derive(serde::Serialize)] pub struct UpstreamStats { costs: Option>, latency: Option>, + token_rate: Option>, quotas: Option>, /// 按界面给的格宽、按上游分格。**稀疏的** —— 没有请求的格子不在里面,由界面补 buckets: Option>, @@ -51,15 +52,17 @@ pub async fn upstream_stats( bucket_ms: Some(bucket_ms.max(MIN_BUCKET_MS)), dim: tw_api::CostDim::Provider, }; - let (costs, latency, quotas, buckets) = tokio::join!( + let (costs, latency, token_rate, quotas, buckets) = tokio::join!( c.call::(&[], &costs), c.call::(&[], &window), + c.call::(&[], &window), c.call::(&[], &()), c.call::(&[], &buckets), ); Ok(UpstreamStats { costs: costs.ok(), latency: latency.ok(), + token_rate: token_rate.ok(), quotas: quotas.ok(), buckets: buckets.ok(), }) diff --git a/src/RequestDrawer.i18n.tsx b/src/RequestDrawer.i18n.tsx index f3a32fb3..2cd3484a 100644 --- a/src/RequestDrawer.i18n.tsx +++ b/src/RequestDrawer.i18n.tsx @@ -30,6 +30,9 @@ export const requestDrawerText = messages( // 时间线。左边那一列标签只有 80px 宽 ttfb: "首字节", + ttft: "首 token", + speed: "生成速度", + speedValue: (n: string) => `${n} token/秒`, totalTime: "总耗时", generationTime: "生成用时", upstream: "上游", @@ -59,10 +62,10 @@ export const requestDrawerText = messages( bytes: "字节", /** 顶上那一排数字 */ tokens: "token", - /** 首字节和生成的比例条:两段的名字,和读屏念的那一句 */ - waiting: "等待首字节", + /** 首 token 和生成的比例条:两段的名字,和读屏念的那一句 */ + waiting: "等待首 token", generating: "生成", - timingLabel: (ttfb: string, gen: string) => `等待首字节 ${ttfb},生成 ${gen}`, + timingLabel: (ttft: string, gen: string) => `等待首 token ${ttft},生成 ${gen}`, /** 选定上游之后被规则拒绝的请求,「上游」那一行名字后面的标记 */ notSentSuffix: "(未发送)", @@ -162,6 +165,9 @@ export const requestDrawerText = messages( // 标签列放不下术语表里的全称时用短的那半:Generation、Conversion、Dropped ttfb: "TTFB", + ttft: "First token", + speed: "Speed", + speedValue: (n: string) => `${n} tokens/s`, totalTime: "Total time", generationTime: "Generation", upstream: "Upstream", @@ -185,9 +191,9 @@ export const requestDrawerText = messages( cancelled: "Canceled: the client disconnected before the response finished", bytes: "Bytes", tokens: "Tokens", - waiting: "Waiting for first byte", + waiting: "Waiting for first token", generating: "Generating", - timingLabel: (ttfb: string, gen: string) => `Waiting for first byte ${ttfb}, generating ${gen}`, + timingLabel: (ttft: string, gen: string) => `Waiting for first token ${ttft}, generating ${gen}`, notSentSuffix: " (not sent)", diff --git a/src/RequestDrawer.tsx b/src/RequestDrawer.tsx index df12a501..3c699168 100644 --- a/src/RequestDrawer.tsx +++ b/src/RequestDrawer.tsx @@ -157,7 +157,10 @@ function Detail({ id, onClose }: { id: number; onClose: () => void }) { const un = listen("core-event", (e) => { const ev = e.payload; const mine = - (ev.kind === "request_headers" || ev.kind === "request_routed" || ev.kind === "request_priced") && + (ev.kind === "request_headers" || + ev.kind === "request_first_token" || + ev.kind === "request_routed" || + ev.kind === "request_priced") && ev.id === id; // 事件流丢过事件的话,结局可能就在里面 if (mine || ev.kind === "events_dropped") void load(() => alive); @@ -352,11 +355,14 @@ function Stat({ label, value, muted }: { label: string; value: ReactNode; muted? const ms = (n: number) => `${Math.round(n).toLocaleString()}ms`; /** - * 时间线:首字节、总耗时、token、费用四个数,一条「等首字节 / 生成」的比例条, - * 下面是这一条的身份和经过(上游、密钥、路径、转换、防护、状态、字节)。 + * 时间线:首 token、总耗时、生成速度、token、费用五个数,一条「等首 token / 生成」的 + * 比例条,下面是这一条的身份和经过(上游、密钥、路径、转换、防护、状态、字节)。 * - * **TTFT 放在最显眼的位置。**对 AI 来说它才是体感的一切 —— 一眼看出慢在网络还是 - * 慢在模型。比例条回答的是同一件事:灰的那段是在等,蓝的那段是在生成。 + * **TTFT 放在最显眼的位置。**对 AI 来说它才是体感的一切 —— 一眼看出慢在排队、读输入 + * 还是慢在生成。比例条回答的是同一件事:灰的那段是在等,蓝的那段是在生成。首字节 + * (响应头到的时刻)在下面的明细里:流式响应的响应头一般马上就回,它说的是连没连上。 + * + * 非流式的没有首 token(整段一起到),也就没有速度和比例条。 */ function Timeline({ d, state }: { d: RequestDetail; state: ReturnType }) { const t = useText(requestDrawerText); @@ -365,11 +371,11 @@ function Timeline({ d, state }: { d: RequestDetail; state: ReturnType -
- : "—"} muted={r.ttfb_ms == null} /> +
+ : "—"} muted={r.ttft_ms == null} /> {/* 还在跑的,总耗时是到现在为止跑了多久,每秒走一格;和流量表那一格同一个写法 */} + } muted={r.cost_micros == null} />
- {r.duration_ms != null && r.ttfb_ms != null && r.duration_ms > 0 && gen !== null && ( - + {r.duration_ms != null && r.ttft_ms != null && r.duration_ms > 0 && gen !== null && ( + )} +
- +
diff --git a/src/events.test.ts b/src/events.test.ts index 02a0b985..88dfc6e2 100644 --- a/src/events.test.ts +++ b/src/events.test.ts @@ -121,6 +121,44 @@ describe("从事件缝出一行", () => { expect(rows.get(1)?.costMicros).toBeUndefined(); }); + /** + * 第一个 token 一到就记在行上(在跑的那一格要写它),速度跟着结局来。**非流式的两个 + * 都没有**:响应头要等生成完才到,没有「第一个」 + */ + it("首 token 在跑的时候就记上,生成速度跟着结局来", () => { + const rows = new Map(); + applyEvent(rows, started()); + applyEvent(rows, { kind: "request_headers", id: 1, status: 200, ttfb_ms: 300 }); + applyEvent(rows, { kind: "request_first_token", id: 1, ttft_ms: 1_200 }); + expect(rows.get(1)?.state).toBe("in_flight"); + expect(rows.get(1)?.ttftMs).toBe(1_200); + applyEvent(rows, { + kind: "request_finished", + id: 1, + model: "claude-sonnet-4-5", + status: 200, + bytes: 10, + duration_ms: 4_000, + usage: { input: 10, output: 280, cache_read: 0, cache_write: 0 }, + tokens_per_sec: 100, + }); + expect(rows.get(1)?.tokensPerSec).toBe(100); + + applyEvent(rows, started({ id: 2 })); + applyEvent(rows, { kind: "request_headers", id: 2, status: 200, ttfb_ms: 3_990 }); + applyEvent(rows, { + kind: "request_finished", + id: 2, + model: "claude-sonnet-4-5", + status: 200, + bytes: 10, + duration_ms: 4_000, + usage: { input: 10, output: 280, cache_read: 0, cache_write: 0 }, + }); + expect(rows.get(2)?.ttftMs).toBeUndefined(); + expect(rows.get(2)?.tokensPerSec).toBeUndefined(); + }); + /** * 客户端先断开了(Claude Code 里按 Esc)。**这一行不能停在「进行中」**, * 也不能算成失败 —— 上游已经为它计了费,到断开为止的用量要接上。 @@ -404,8 +442,10 @@ function stored(over: Partial = {}): HistoryRow { model: "claude-sonnet-4-5", path: "/v1/messages", status: 200, - ttfb_ms: 800, + ttfb_ms: 300, + ttft_ms: 800, duration_ms: 4_000, + tokens_per_sec: 6, bytes: 1_234, input_tokens: 100, output_tokens: 20, diff --git a/src/format.ts b/src/format.ts index 143492c0..2e9997c4 100644 --- a/src/format.ts +++ b/src/format.ts @@ -10,22 +10,22 @@ import { formatText } from "./format.i18n"; import { usd } from "./types"; /** - * 首字节和总耗时合成一列。 + * 首 token 和总耗时合成一列。 * - * 非流式请求两者几乎相同(`253ms / 254ms`),两列占着宽度却只有一个 - * 信息。**只在它们真的差得开时才显示两个数** —— 那时差值本身就是结论: - * 首字节快而总耗时长 = 模型在慢慢吐;两者都长 = 卡在网络或排队。 + * 非流式请求没有首 token(整段一起到),只写总耗时。**两个数只在真的差得开时才都 + * 显示** —— 那时差值本身就是结论:首 token 快而总耗时长 = 模型在慢慢吐;首 token 就 + * 慢 = 卡在排队或读输入。 * * 阈值 50ms:低于这个差别在感知上不存在,显示出来只是噪音。 */ export function latency( - ttfbMs: number | undefined, + ttftMs: number | undefined, durationMs: number | undefined, ): string { - if (durationMs == null) return ttfbMs != null ? `${ttfbMs}ms` : "—"; - if (ttfbMs == null) return `${durationMs}ms`; - if (durationMs - ttfbMs < 50) return `${durationMs}ms`; - return `${ttfbMs}→${durationMs}ms`; + if (durationMs == null) return ttftMs != null ? `${ttftMs}ms` : "—"; + if (ttftMs == null) return `${durationMs}ms`; + if (durationMs - ttftMs < 50) return `${durationMs}ms`; + return `${ttftMs}→${durationMs}ms`; } /** diff --git a/src/generated/tw-api.ts b/src/generated/tw-api.ts index d8ed2be7..62358bc9 100644 --- a/src/generated/tw-api.ts +++ b/src/generated/tw-api.ts @@ -1,6 +1,6 @@ // Generated by tw-api (`tw_api::ts::export_all`). Do not edit by hand. -export const CONTROL_API_VERSION = 26; +export const CONTROL_API_VERSION = 27; /** * 一个账号上游登的是哪个账号。 @@ -678,7 +678,7 @@ model: string, method: string, path: string, * DeepSeek 官方收:发给别的上游之前网关会去掉它,界面要能说出「这个请求带着 * 会话日志、有多大」 */ -session_log_bytes?: number | null, at_ms: number, } | { "kind": "request_headers", id: number, status: number, ttfb_ms: number, } | { "kind": "request_finished", id: number, +session_log_bytes?: number | null, at_ms: number, } | { "kind": "request_headers", id: number, status: number, ttfb_ms: number, } | { "kind": "request_first_token", id: number, ttft_ms: number, } | { "kind": "request_finished", id: number, /** * 客户端要的模型名,和 `RequestStarted` 里的是同一个。 * @@ -694,7 +694,16 @@ model: string, status: number, bytes: number, duration_ms: number, * 上游报的用量。**没报就是 None,不是零** —— 零会让一次真实的 * 调用看起来是免费的 */ -usage?: UsageView | null, } | { "kind": "request_failed", id: number, +usage?: UsageView | null, +/** + * 生成速度:每秒输出多少 token,**从第一个 token 算到结束**。 + * + * 分母不含第一个 token 之前的排队和读输入;分子是那之后吐出来的输出。推理 + * 被隐藏的(第一个 token 之前模型一直在想、一个字都没吐),上游报了其中多少 + * 是推理就扣掉,没报就没有这个数 —— 那些推理 token 是在分母之外生成的,算进 + * 来会把速度顶高好几倍。没有第一个 token 的(非流式)、没有输出的,也没有 + */ +tokens_per_sec?: number | null, } | { "kind": "request_failed", id: number, /** * 模型名。理由见 `RequestFinished::model` */ @@ -1091,7 +1100,20 @@ export type HiddenKind = "zero_width" | "tag" | "bidi" | "homoglyph" | "private_ /** * 一条历史请求。 */ -export type HistoryRow = { id: number, at_ms: number, client: string, provider: string, model: string, path: string, status: number | null, ttfb_ms: number | null, duration_ms: number | null, bytes: number | null, input_tokens: number | null, output_tokens: number | null, cache_read_tokens: number | null, cache_write_tokens: number | null, cost_micros: number | null, +export type HistoryRow = { id: number, at_ms: number, client: string, provider: string, model: string, path: string, status: number | null, +/** + * 响应头到的时刻 + */ +ttfb_ms: number | null, +/** + * 第一个 token 到的时刻。只有流式请求有,见 [`Event::RequestFirstToken`] + */ +ttft_ms: number | null, duration_ms: number | null, +/** + * 生成速度,token/秒。只有跑完的流式请求有,见 + * `RequestFinished::tokens_per_sec` + */ +tokens_per_sec: number | null, bytes: number | null, input_tokens: number | null, output_tokens: number | null, cache_read_tokens: number | null, cache_write_tokens: number | null, cost_micros: number | null, /** * 这个成本是估的吗。**界面上要标出来** */ @@ -1199,7 +1221,7 @@ export type InFlightRequest = { id: number, /** * 关于它的事件,**照事件流上的样子、按发生的先后**:第一条是 `RequestStarted`, * 之后是到目前为止发生了的 —— 响应头、路由、格式转换、防护的记录 - * (`RequestHeaders`、`RequestRouted`、`Translated`、`SecretsFound`、 + * (`RequestHeaders`、`RequestFirstToken`、`RequestRouted`、`Translated`、`SecretsFound`、 * `HiddenTextFound`、`ContentMatched`、`OutputLimited`、`ToolCallFlagged`)。 * 说的是上游现状的(`QuotaSeen`)不在里面:那是 `/quota` 的事 */ @@ -1319,6 +1341,12 @@ export type L1Stage = { step: L1Step, peer: L1Peer, }; */ export type L1Step = "config" | "dns" | "tcp" | "tls" | "handshake"; +/** + * 第一个 token 到的时刻的分位数(`GET /latency`、`/latency/provider`),毫秒。 + * + * **只有流式请求有样本**:非流式的没有第一个 token(见 [`Event::RequestFirstToken`])。 + * `model` 在按上游分的那个端点里是上游名。 + */ export type LatencyView = { model: string, p50: number, p95: number, /** * **样本数要一起给。**「800ms」是 3 个样本还是 300 个,含义完全不同 @@ -1388,8 +1416,10 @@ export type LiveView = { */ running: Array, /** - * 最近一分钟跑完的请求平均每秒生成多少 token:**每个请求的输出除以它生成用的 - * 时间**(总耗时减去首字节),按 token 加权。这一分钟里没有跑完的是空,不是 0 + * 最近一分钟跑完的请求平均每秒生成多少 token:每个请求的速度(见 + * `RequestFinished::tokens_per_sec`)按它生成用的时间加权,也就是这些请求 + * 吐出的 token 合计除以生成用的时间合计。**只数有速度的**:非流式的不算。这一分钟里 + * 没有的是空,不是 0 */ tokens_per_sec: number | null, }; @@ -3163,6 +3193,18 @@ security: SecurityCounts, */ pricing_date: string, }; +/** + * 生成速度的中位数(`GET /token-rate`、`/token-rate/provider`),token/秒。 + * + * 样本是有速度的请求(见 `RequestFinished::tokens_per_sec`)。`model` 在按上游 + * 分的那个端点里是上游名。 + */ +export type TokenRateView = { model: string, p50: number, +/** + * 和延迟一样:「90 token/秒」是 3 个样本还是 300 个,含义完全不同 + */ +samples: number, }; + /** * 一次请求做过的格式转换。 */ @@ -3318,6 +3360,8 @@ export const ENDPOINTS = { History: { method: "GET", path: "/history", params: [], format: "json" }, Latency: { method: "GET", path: "/latency", params: [], format: "json" }, LatencyByProvider: { method: "GET", path: "/latency/provider", params: [], format: "json" }, + TokenRate: { method: "GET", path: "/token-rate", params: [], format: "json" }, + TokenRateByProvider: { method: "GET", path: "/token-rate/provider", params: [], format: "json" }, RequestDetail: { method: "GET", path: "/request/{id}", params: ["id"], format: "json" }, Fixture: { method: "GET", path: "/request/{id}/fixture", params: ["id"], format: "text" }, Sessions: { method: "GET", path: "/sessions", params: [], format: "json" }, @@ -3413,6 +3457,8 @@ export type Endpoints = { History: { req: ListQuery; res: Array }; Latency: { req: Window; res: Array }; LatencyByProvider: { req: Window; res: Array }; + TokenRate: { req: Window; res: Array }; + TokenRateByProvider: { req: Window; res: Array }; RequestDetail: { req: null; res: RequestDetail }; Fixture: { req: null; res: string }; Sessions: { req: ListQuery; res: Array }; diff --git a/src/overview/LatencySection.tsx b/src/overview/LatencySection.tsx index ca93ad04..ac1da0eb 100644 --- a/src/overview/LatencySection.tsx +++ b/src/overview/LatencySection.tsx @@ -26,7 +26,7 @@ const COL = { } as const; /** - * 延迟:首字节时间的 P50 和 P95。 + * 延迟:第一个 token 到的时刻的 P50 和 P95。只有流式请求有样本:非流式的整段一起到。 * * **左右两栏,各自纵向长。**「哪个模型慢」的下一步是换模型,「哪个上游慢」的 * 下一步是换上游 —— 两个问题各占一栏。只有一个上游时右栏没有可比的,不画。 diff --git a/src/overview/OverviewPage.tsx b/src/overview/OverviewPage.tsx index 63f87e3f..f5fe7a94 100644 --- a/src/overview/OverviewPage.tsx +++ b/src/overview/OverviewPage.tsx @@ -17,6 +17,7 @@ import { HeroStats } from "./HeroStats"; import { TrendSection } from "./TrendSection"; import { CacheSection } from "./CacheSection"; import { LatencySection } from "./LatencySection"; +import { SpeedSection } from "./SpeedSection"; import { SecuritySection } from "./SecuritySection"; import type { Metric } from "./series"; import { overviewText } from "./overview.i18n"; @@ -202,6 +203,7 @@ function Body({ + )} diff --git a/src/overview/SpeedSection.tsx b/src/overview/SpeedSection.tsx new file mode 100644 index 00000000..7af6a1b3 --- /dev/null +++ b/src/overview/SpeedSection.tsx @@ -0,0 +1,174 @@ +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, Overview, TokenRateView } from "@/types"; +import { useText } from "@/i18n"; +import { ROWS } from "./series"; +import { LinkRow, ModelMark, Scope } from "./parts"; +import { overviewText } from "./overview.i18n"; + +/** 样本少于这个数,中位数不可靠:样本数那一格标黄。和延迟一节同一条线 */ +const FEW = 10; + +/** + * 一行里数字那几列的宽度。**和延迟一节对齐**:条从同一处起,长度占掉延迟的条和它的 + * P50 那两格,速度的数字落在延迟的 P95 那一格,样本数落在样本数那一格 —— 两节上下 + * 对着看的是同一个模型的两个数。 + */ +const COL = { + bar: "w-[8.625rem]", + p50: "w-12", + samples: "w-9", +} as const; + +/** + * 生成速度:每秒输出多少 token 的中位数,按模型、按上游。 + * + * 和「延迟」同一个样子:两栏,各自纵向长;行的顺序也一样(用得多的在前)。条从零 + * 画到中位数,越长越快。样本是跑完的流式请求:非流式的整段一起到,没有速度。点一行 + * 落到流量页,和延迟一节一样。 + */ +export function SpeedSection({ + d, + ov, + scope, + scoped, +}: { + d: Dashboard; + ov: Overview | null; + scope: string; + scoped?: string; +}) { + const t = useText(overviewText); + const nav = useNav(); + // 取不到(`null`)不是样本不足:按模型那份取不到,整块写「暂时取不到」;按上游那份 + // 取不到,就只画按模型的那一栏 + const byModel = d.token_rate ?? []; + const byUpstream = d.token_rate_by_provider ?? []; + // 两栏的条按同一把尺子画,才能横着比 + const max = Math.max(1, ...byModel.map((l) => l.p50), ...byUpstream.map((l) => l.p50)) * 1.04; + const upstreams = byUpstream.length >= 2; + const providers = new Map((ov?.providers ?? []).map((p) => [p.name, p])); + return ( + + {t.speedWhat} + {scoped && ` · ${scoped}`} + + } + > + {byModel.length === 0 ? ( +

+ {d.token_rate === null ? t.speedUnavailable : t.notEnoughSamples} +

+ ) : ( +
+
+ } + onOpen={(name) => nav.open("requests", { grouped: false, filter: { model: name } })} + /> + {upstreams && ( + { + const p = providers.get(name); + return ( + + ); + }} + onOpen={(name) => nav.open("requests", { grouped: false, filter: { provider: name } })} + /> + )} +
+
+ )} +
+ ); +} + +/** 一栏速度,带一行表头。顺序和延迟一节的 `latencyRows` 一样:样本多的在前 */ +function Bars({ + head, + rows, + max, + scope, + mark, + onOpen, +}: { + head: string; + rows: TokenRateView[]; + max: number; + scope: string; + mark: (name: string) => ReactNode; + onOpen: (name: string) => void; +}) { + const t = useText(overviewText); + const sorted = [...rows].sort((a, b) => b.samples - a.samples || a.model.localeCompare(b.model)); + const shown = usePresentList(sorted.slice(0, ROWS), (l) => l.model); + return ( +
+ {/* 表头:和下面每一行同一套列宽,行尾留出箭头那一格 */} +
+ {head} + + P50 + {t.samples} + +
+ {shown.map(({ item: l, key, presence }) => ( + onOpen(l.model)} + > + {mark(l.model)} + + {l.model} + + {/* 条的右端那道竖线是中位数,和延迟一节的 P50 竖线同一个记号 */} + + + + + + + Math.round(n).toLocaleString()} scope={scope} /> + + {l.samples < FEW ? ( + + {l.samples} + + ) : ( + + {l.samples} + + )} + + ))} + {rows.length > ROWS &&

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

} +
+ ); +} diff --git a/src/overview/overview.i18n.ts b/src/overview/overview.i18n.ts index 45fcc7c8..eecec354 100644 --- a/src/overview/overview.i18n.ts +++ b/src/overview/overview.i18n.ts @@ -118,7 +118,7 @@ export const overviewText = messages( // 延迟 latency: "延迟", - latencyWhat: "首字节时间", + latencyWhat: "首 token 时间", notEnoughSamples: "所选区间内样本不足,暂无分位数据", /** 取数失败,**不是样本不足** */ latencyUnavailable: "延迟数据暂时取不到", @@ -129,6 +129,12 @@ export const overviewText = messages( /** 样本太少的那一格的悬停说明 */ fewSamples: "样本较少,分位数仅供参考", + // 生成速度:和延迟一节同一个样子 + speed: "生成速度", + speedWhat: "token/秒", + /** 取数失败,**不是样本不足** */ + speedUnavailable: "生成速度数据暂时取不到", + // 安全:各项防护的档位和这段时间各自看见了什么。数的是安全日志里的条数 security: "安全", modeOff: "关闭", @@ -262,7 +268,7 @@ export const overviewText = messages( hitByModel: "Hit rate by model", latency: "Latency", - latencyWhat: "Time to first byte", + latencyWhat: "Time to first token", notEnoughSamples: "Not enough samples in the selected range; no percentiles yet", latencyUnavailable: "Latency data is unavailable right now", byModel: "By model", @@ -270,6 +276,10 @@ export const overviewText = messages( samples: "Samples", fewSamples: "Few samples; the percentiles are only indicative", + speed: "Generation speed", + speedWhat: "Tokens/s", + speedUnavailable: "Generation speed data is unavailable right now", + security: "Security", modeOff: "Off", modeObserve: "Observe", diff --git a/src/overview/series.test.ts b/src/overview/series.test.ts index 2df18c8b..350b61a5 100644 --- a/src/overview/series.test.ts +++ b/src/overview/series.test.ts @@ -96,6 +96,8 @@ function dashboard(since: number, groups: CostBucketGroup[]): Dashboard { summary: summary(), latency: [], latency_by_provider: [], + token_rate: [], + token_rate_by_provider: [], storage: null, buckets: [...buckets.values()], buckets_by_model: groups, diff --git a/src/overview/useLive.test.ts b/src/overview/useLive.test.ts index 2885d48b..14abe040 100644 --- a/src/overview/useLive.test.ts +++ b/src/overview/useLive.test.ts @@ -51,8 +51,10 @@ function stored(over: Partial = {}): HistoryRow { model: "claude-sonnet-5", path: "/v1/messages", status: 200, - ttfb_ms: 800, + ttfb_ms: 300, + ttft_ms: 800, duration_ms: 4_000, + tokens_per_sec: 6, bytes: 1_234, input_tokens: 100, output_tokens: 20, diff --git a/src/traffic/RequestTable.tsx b/src/traffic/RequestTable.tsx index aec64e48..a1d02d2a 100644 --- a/src/traffic/RequestTable.tsx +++ b/src/traffic/RequestTable.tsx @@ -109,7 +109,7 @@ export function RequestTable({ > {/* **表头必须钉住。**这张表滚两屏之后就没有列名了,而并排的 - 两列毫秒数,不看列名根本分不出哪个是首字节哪个是总耗时 —— + 两列毫秒数,不看列名根本分不出哪个是首 token 哪个是总耗时 —— 那恰恰是排查时唯一要看的区别。 钉在页面的滚动层上,所以上面的 `scroll={false}` 不能去掉:表外 @@ -128,7 +128,7 @@ export function RequestTable({ {showClient && {t.client}} {t.model} {t.upstream} - {/* 首字节和总耗时合成一列 —— 非流式请求两者几乎相同 */} + {/* 首 token 和总耗时合成一列,生成速度在它的悬停里 —— 非流式请求没有首 token */} @@ -502,7 +502,7 @@ const Row = memo(function Row({ 扫出极值。 */} - {r.state === "in_flight" ? : latency(r.ttfbMs, r.durationMs)} + {r.state === "in_flight" ? : } @@ -527,21 +527,51 @@ const Row = memo(function Row({ }); /** - * 在跑的那一条的延迟:首字节到了就先写它,后面是已经跑了多久,每秒走一格 + * 在跑的那一条的延迟:第一个 token 到了就先写它,后面是已经跑了多久,每秒走一格 * (`1180→0:42`)。灰的,而且写成时钟的样子 —— 别让它看起来像已经结束的总耗时; - * 结局一到换成「首字节→总耗时」。 + * 结局一到换成「首 token→总耗时」。 * * 秒针只改这一格里的字(`Elapsed`),行和表都不重画。 */ function Running({ r }: { r: RequestRow }) { return ( - {r.ttfbMs != null && `${r.ttfbMs}→`} + {r.ttftMs != null && `${r.ttftMs}→`} ); } +/** + * 跑完的那一条的延迟:首 token→总耗时。 + * + * **生成速度在悬停里,不另占一列。**默认窗口下这张表已经放满了,再加一列,英文 + * 界面里最右边的费用就出了视野。悬停写全四个数:首 token、总耗时、生成用时、生成 + * 速度(core 算好的,没有就不写那一行)。非流式的没有首 token,只写总耗时、没有悬停。 + */ +function LatencyCell({ r }: { r: RequestRow }) { + const t = useText(trafficText); + const text = latency(r.ttftMs, r.durationMs); + if (r.ttftMs == null || r.durationMs == null) return <>{text}; + const ms = (n: number) => `${n.toLocaleString()}ms`; + return ( + + } + > + {text} + + ); +} + function StatusCell({ r }: { r: RequestRow }) { const t = useText(trafficText); const tone = TONE[statusTone(r.status, r.state)]; diff --git a/src/traffic/Traffic.i18n.tsx b/src/traffic/Traffic.i18n.tsx index b696e55c..de664694 100644 --- a/src/traffic/Traffic.i18n.tsx +++ b/src/traffic/Traffic.i18n.tsx @@ -78,6 +78,13 @@ export const trafficText = messages( model: "模型", upstream: "上游", latency: "延迟", + /** 延迟那一格的悬停:首 token、总耗时、生成用时,和生成速度(有的话) */ + latencyTip: (ttft: string, total: string, gen: string, speed: string | null) => [ + `首 token ${ttft}`, + `总耗时 ${total}`, + `生成用时 ${gen}`, + ...(speed != null ? [`生成速度 ${speed} token/秒`] : []), + ], tokens: "token", cost: "费用", @@ -188,6 +195,12 @@ export const trafficText = messages( model: "Model", upstream: "Upstream", latency: "Latency", + latencyTip: (ttft: string, total: string, gen: string, speed: string | null) => [ + `First token ${ttft}`, + `Total ${total}`, + `Generation ${gen}`, + ...(speed != null ? [`Speed ${speed} tokens/s`] : []), + ], tokens: "Tokens", cost: "Cost", diff --git a/src/types.ts b/src/types.ts index f94217f5..27c21f14 100644 --- a/src/types.ts +++ b/src/types.ts @@ -21,6 +21,7 @@ import type { Status, StorageStatus, Summary, + TokenRateView, TranslatedView, } from "./generated/tw-api"; import type { LocalEvent } from "./generated/lite-api"; @@ -83,8 +84,16 @@ export interface RequestRow { */ state: "in_flight" | "done" | "failed" | "cancelled"; status?: number; + /** 响应头到的时刻 */ ttfbMs?: number; + /** + * 第一个 token 到的时刻。**只有流式请求有**:非流式的整段一起到,没有「第一个」。 + * 在跑的请求一到就有(`request_first_token`) + */ + ttftMs?: number; durationMs?: number; + /** 生成速度,token/秒,core 在结局里算好的。只有跑完的流式请求有 */ + tokensPerSec?: number; bytes?: number; /** 新输入的 token。**不含缓存读写**:三者不重叠,加起来才是这一轮送进去的全部 */ inputTokens?: number; @@ -157,6 +166,11 @@ export function applyEvent(rows: Map, ev: CoreEvent): void { } break; } + case "request_first_token": { + const r = rows.get(ev.id); + if (r) r.ttftMs = ev.ttft_ms; + break; + } case "request_finished": { const r = rows.get(ev.id); if (r) { @@ -164,6 +178,7 @@ export function applyEvent(rows: Map, ev: CoreEvent): void { r.status = ev.status; r.bytes = ev.bytes; r.durationMs = ev.duration_ms; + r.tokensPerSec = ev.tokens_per_sec ?? undefined; if (ev.usage) { r.inputTokens = ev.usage.input; r.outputTokens = ev.usage.output; @@ -343,7 +358,7 @@ export function interruptInFlight(rows: Map): boolean { export interface Dashboard { summary: Summary; /** - * 首字节时间的分位,按模型分。和 `summary` 同一个时间窗。 + * 第一个 token 到的时刻的分位,按模型分。和 `summary` 同一个时间窗。 * * 这一样和下面几样**取不到是 `null`,不是空的**:空的是「没有样本、没有请求」, * 取数失败时照那样画就是编了一个零。见到 `null` 写「暂时取不到」。 @@ -351,6 +366,10 @@ export interface Dashboard { latency: LatencyView[] | null; /** 按上游分。**和按模型分是两个问题** */ latency_by_provider: LatencyView[] | null; + /** 生成速度的中位数,按模型分。同一个时间窗 */ + token_rate: TokenRateView[] | null; + /** 按上游分 */ + token_rate_by_provider: TokenRateView[] | null; storage: StorageStatus | null; /** * 按所选时间范围分格。**稀疏的** —— core 那边只产出有数据的桶, diff --git a/src/upstreams/UpstreamTable.i18n.ts b/src/upstreams/UpstreamTable.i18n.ts index 85c67e1a..99b85be6 100644 --- a/src/upstreams/UpstreamTable.i18n.ts +++ b/src/upstreams/UpstreamTable.i18n.ts @@ -12,7 +12,8 @@ export const upstreamTableText = messages( models: "模型", quota: "额度 / 计费", day: "24 小时", - ttfb: "首字节 P50", + /** 上面一行是首 token 的 P50,下面一行是生成速度的中位数 */ + timing: "首 token / 速度", actionsColumn: "操作", disabled: "已停用", disabledTip: "已停用的上游不参与转发。", @@ -51,14 +52,16 @@ export const upstreamTableText = messages( dayCost: (cost: string) => `费用 ${cost}`, ms: (n: number) => `${n.toLocaleString()} ms`, latencyTip: (p95: number, samples: number) => - `P95 ${p95.toLocaleString()} ms · ${samples.toLocaleString()} 个样本`, + `首 token P95 ${p95.toLocaleString()} ms · ${samples.toLocaleString()} 个样本`, + speedValue: (n: number) => `${n.toLocaleString()} token/秒`, + speedTip: (samples: number) => `生成速度 · ${samples.toLocaleString()} 个样本`, }, { upstream: "Upstream", models: "Models", quota: "Quota / billing", day: "24 hours", - ttfb: "TTFB P50", + timing: "TTFT / speed", actionsColumn: "Actions", disabled: "Disabled", disabledTip: "A disabled upstream receives no requests.", @@ -99,6 +102,9 @@ export const upstreamTableText = messages( dayCost: (cost: string) => `Cost ${cost}`, ms: (n: number) => `${n.toLocaleString()} ms`, latencyTip: (p95: number, samples: number) => - `P95 ${p95.toLocaleString()} ms · ${samples.toLocaleString()} ${samples === 1 ? "sample" : "samples"}`, + `First token P95 ${p95.toLocaleString()} ms · ${samples.toLocaleString()} ${samples === 1 ? "sample" : "samples"}`, + speedValue: (n: number) => `${n.toLocaleString()} tokens/s`, + speedTip: (samples: number) => + `Speed · ${samples.toLocaleString()} ${samples === 1 ? "sample" : "samples"}`, }, ); diff --git a/src/upstreams/UpstreamTable.tsx b/src/upstreams/UpstreamTable.tsx index e18b02b4..166edcb8 100644 --- a/src/upstreams/UpstreamTable.tsx +++ b/src/upstreams/UpstreamTable.tsx @@ -59,7 +59,7 @@ export interface UpstreamActions { * * 单击一行(或 Enter)打开它的编辑对话框;行尾按钮和右键打开的是同一份操作。 * - * 五列是定过的(lite#46):上游、模型、额度 / 计费、24 小时、首字节 P50。「24 小时」 + * 五列是定过的(lite#46):上游、模型、额度 / 计费、24 小时、首 token / 速度。「24 小时」 * 一格里多了一条按小时的走势:请求在一天里怎么分布、失败落在哪几个小时,一眼看得出, * 数字留给右边和悬停。窗口窄到放不下时走势先让位(页面的容器查询),数字照常在。 */ @@ -111,7 +111,7 @@ export function UpstreamTable({ {/* 订阅额度和按量计费是同一个问题的两种答案:还能用多少 */} {t.quota} {t.day} - {t.ttfb} + {t.timing} {t.actionsColumn} @@ -511,7 +511,14 @@ function DayCell({ ); } -/** 首字节 P50。P95 与样本数在悬停里:「800 ms」是 3 个样本还是 300 个,含义完全不同 */ +/** + * 首 token 和生成速度,上下两行,和「24 小时」那一格同一个写法:上面是首 token 的 P50, + * 下面淡一档的是生成速度的中位数。P95 与样本数在悬停里:「800 ms」是 3 个样本还是 300 个, + * 含义完全不同。 + * + * **速度不另占一列**:单起一列,上游名那一列要让出一百多像素,副行的地址被截得只剩开头。 + * 只有非流式请求的上游没有速度,下一行写「—」。 + */ function LatencyCell({ p, stats }: { p: ProviderView; stats: Resource }) { const t = useText(upstreamTableText); if (stats.data === undefined) { @@ -525,10 +532,22 @@ function LatencyCell({ p, stats }: { p: ProviderView; stats: Resource—; } + const rate = stats.data.token_rate?.find((r) => r.model === p.name); + const speed = rate && rate.samples > 0 ? rate : null; return ( - - {t.ms(lat.p50)} + +
{t.latencyTip(lat.p95, lat.samples)}
+ {speed &&
{t.speedTip(speed.samples)}
} +
+ } + > +
+ {t.ms(lat.p50)} + {speed ? t.speedValue(speed.p50) : "—"} +
); diff --git a/src/upstreams/api.ts b/src/upstreams/api.ts index 2a61e7de..1a262414 100644 --- a/src/upstreams/api.ts +++ b/src/upstreams/api.ts @@ -14,6 +14,7 @@ import type { CostBucketGroup, CostGroup, LatencyView, + TokenRateView, PriceQuery, PriceSheetSave, Protocol, @@ -36,6 +37,8 @@ import type { export interface UpstreamStats { costs: CostGroup[] | null; latency: LatencyView[] | null; + /** 生成速度的中位数,按上游 */ + token_rate: TokenRateView[] | null; quotas: ProviderQuota[] | null; /** 按 `bucketMs` 分格、按上游分开的请求数。**稀疏的**:没有请求的格子不在里面 */ buckets: CostBucketGroup[] | null; diff --git a/src/upstreams/data.test.ts b/src/upstreams/data.test.ts index b1897dbb..8f3ceae9 100644 --- a/src/upstreams/data.test.ts +++ b/src/upstreams/data.test.ts @@ -66,7 +66,7 @@ describe("slotsByUpstream", () => { }); describe("statsPartial", () => { - const full: UpstreamStats = { costs: [], latency: [], quotas: [], buckets: [] }; + const full: UpstreamStats = { costs: [], latency: [], token_rate: [], quotas: [], buckets: [] }; it("says nothing before the stats arrive, or when every part was read", () => { expect(statsPartial(undefined)).toBe(false); @@ -74,10 +74,11 @@ describe("statsPartial", () => { expect(statsPartial(full)).toBe(false); }); - it("speaks up when costs, the trend or latency could not be read, but not for quotas", () => { + it("speaks up when costs, the trend, latency or speed could not be read, but not for quotas", () => { expect(statsPartial({ ...full, costs: null })).toBe(true); expect(statsPartial({ ...full, buckets: null })).toBe(true); expect(statsPartial({ ...full, latency: null })).toBe(true); + expect(statsPartial({ ...full, token_rate: null })).toBe(true); expect(statsPartial({ ...full, quotas: null })).toBe(false); }); }); diff --git a/src/upstreams/data.ts b/src/upstreams/data.ts index 583746fb..d1430e19 100644 --- a/src/upstreams/data.ts +++ b/src/upstreams/data.ts @@ -84,7 +84,9 @@ export function patch(f: (s: T) => T): (s: T | undefined) => T { * 「不知道」的写法,不会读成一个数。 */ export function statsPartial(s: UpstreamStats | undefined): boolean { - return s !== undefined && (s.costs === null || s.buckets === null || s.latency === null); + return ( + s !== undefined && (s.costs === null || s.buckets === null || s.latency === null || s.token_rate === null) + ); } /** 一个小时格:请求数、其中失败的 */ diff --git a/src/useRequests.ts b/src/useRequests.ts index 3593f5c3..15e70028 100644 --- a/src/useRequests.ts +++ b/src/useRequests.ts @@ -56,12 +56,14 @@ export function mergeHistory(rows: Map, history: HistoryRow[ next.state = h.error ? "failed" : h.cancelled ? "cancelled" : "done"; if (h.status != null) next.status = h.status; next.durationMs = h.duration_ms ?? undefined; + next.tokensPerSec = h.tokens_per_sec ?? undefined; next.bytes = h.bytes ?? undefined; next.error = h.error ?? undefined; } // 上游以库里的为准:故障转移之后服务它的是尝试链的最后一跳 if (!h.local) next.provider = h.provider; next.model ??= h.model || undefined; + next.ttftMs ??= h.ttft_ms ?? undefined; if (h.input_tokens != null) next.inputTokens = h.input_tokens; if (h.output_tokens != null) next.outputTokens = h.output_tokens; if (h.cache_read_tokens != null) next.cacheReadTokens = h.cache_read_tokens; @@ -98,7 +100,9 @@ export function mergeHistory(rows: Map, history: HistoryRow[ state: h.error ? "failed" : h.cancelled ? "cancelled" : "done", status: h.status ?? undefined, ttfbMs: h.ttfb_ms ?? undefined, + ttftMs: h.ttft_ms ?? undefined, durationMs: h.duration_ms ?? undefined, + tokensPerSec: h.tokens_per_sec ?? undefined, bytes: h.bytes ?? undefined, inputTokens: h.input_tokens ?? undefined, outputTokens: h.output_tokens ?? undefined, @@ -137,6 +141,7 @@ function changed(a: RequestRow, b: RequestRow): boolean { function touches(ev: CoreEvent): number | null { switch (ev.kind) { case "request_headers": + case "request_first_token": case "request_finished": case "request_cancelled": case "request_failed":