diff --git a/src/overview/ModelRanking.tsx b/src/overview/ModelRanking.tsx index 5e1bd474..e082851d 100644 --- a/src/overview/ModelRanking.tsx +++ b/src/overview/ModelRanking.tsx @@ -5,8 +5,8 @@ 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 { rankCost, type Metric, type RankRow } from "./series"; +import { LinkRow, LinkText, MarkSpace, Meter, ModelMark } from "./parts"; import { overviewText } from "./overview.i18n"; const fmtTokens = (n: number) => compact(Math.round(n)); @@ -66,19 +66,9 @@ export function ModelRanking({ - - {/* - **用了 token 却没有费用,不写「$0」。**那可能是未定价(费用没算进来),也 - 可能是不计费(本地模型)—— 分组的格子里没有「无法计价」的条数,分不出是哪 - 一种,而「$0」只在后一种情况下是真的。 - */} - {r.cost === 0 && r.tokens > 0 ? ( - - — - - ) : ( - - )} + {/* 80px:「≥~$1234.56」要 79 */} + + t.times(Math.round(n))} scope={scope} /> @@ -88,3 +78,58 @@ export function ModelRanking({ ); } + +/** + * 一行的费用。写什么见 `rankCost`;有说明的写在悬停里。 + * + * · 金额有说明时带虚线下划线,和会话、请求行里有说明的金额同一个记号。 + * · 「无法计价」是琥珀色:它要人去补一个价,和上面费用大数下的「N 条无法计价」同色。 + * 「无用量」补不了什么,淡一档。两个词都不跟着费用口径加粗 —— 它们不是金额。 + * + * **有无法计价的请求时,这一格自己可以点**:落到流量页这个模型里没算出费用的那一批 + * —— 看到它之后要做的就是去补价,而补给谁要从那一批里看。合并的「其他」不是一个 + * 模型,只说不点。 + */ +function Cost({ r, scope }: { r: RankRow; scope: string }) { + const t = useText(overviewText); + const nav = useNav(); + const c = rankCost(r, t); + if (c.kind === "amount" && c.notes.length === 0) + return ; + const shown = + c.kind === "unpriced" ? ( + t.unpricedCell + ) : c.kind === "noUsage" ? ( + t.noUsageCell + ) : ( + c.prefix + usd(n)} scope={scope} /> + ); + const look = + c.kind === "amount" + ? "underline decoration-dotted underline-offset-2" + : c.kind === "unpriced" + ? "font-normal text-warning" + : "font-normal text-muted-foreground"; + const tip = ( + + {c.notes.map((l) => ( + {l} + ))} + + ); + return ( + + {r.unpriced > 0 && !r.merged ? ( + nav.open("requests", { grouped: false, filter: { model: r.name, unpricedOnly: true } })} + > + {shown} + {t.viewUnpriced} + + ) : ( + {shown} + )} + + ); +} diff --git a/src/overview/overview.i18n.ts b/src/overview/overview.i18n.ts index 6c9620d6..df51a29f 100644 --- a/src/overview/overview.i18n.ts +++ b/src/overview/overview.i18n.ts @@ -69,6 +69,8 @@ export const overviewText = messages( costRate: (amount: string) => `${amount}/小时`, /** 悬停提示抬头下面那一句:这一格有几次请求 */ tipRequests: (requests: number, failed: number) => `${requests} 次请求${failed ? `,${failed} 次失败` : ""}`, + /** 那一句后面接着的几项(费用口径下的「3 条无法计价」)之间的分隔 */ + listSep: ",", tipNone: "无请求", waiting: "等待请求", noRequests: "所选区间内无请求记录", @@ -81,8 +83,15 @@ export const overviewText = messages( // 模型排行 models: "模型", times: (n: number) => `${n} 次`, - /** 用了 token 却没有费用的那一格(「—」)的悬停说明 */ - noCost: "无费用记录:模型未定价或不计费", + /** 排行费用那一格(和费用口径下悬停的合计):有用量,却一条都没算出费用 */ + unpricedCell: "无法计价", + /** 同上:连用量都没有 */ + noUsageCell: "无用量", + /** 费用那一格悬停里的句子:金额之外的请求。含估算的那句和费用大数的限定语共用 `estimated` */ + rankUnpriced: (n: number) => `${n} 条请求无法计价:模型未定价,费用未计入`, + rankNoUsage: (n: number) => `${n} 条请求没有用量数据,费用未计入`, + /** 可以点的「无法计价」,读屏读出来的后半句 */ + viewUnpriced: "在流量中查看无法计价的请求", moreNotListed: (n: number) => `另有 ${n} 项未列出`, /** 可以点的一行,读屏读出来的后半句 */ viewInTraffic: "在流量中查看", @@ -199,6 +208,7 @@ export const overviewText = messages( costRate: (amount: string) => `${amount}/hour`, tipRequests: (requests: number, failed: number) => `${requests === 1 ? "1 request" : `${requests} requests`}${failed ? `, ${failed} failed` : ""}`, + listSep: ", ", tipNone: "No requests", waiting: "Waiting for requests", noRequests: "No requests recorded in the selected range", @@ -209,7 +219,17 @@ export const overviewText = messages( models: "Models", times: (n: number) => `${n}×`, - noCost: "No cost recorded: the model is unpriced or not billed", + unpricedCell: "Unpriced", + noUsageCell: "No usage", + rankUnpriced: (n: number) => + n === 1 + ? "1 request unpriced: the model has no price, so its cost is not included" + : `${n} requests unpriced: the model has no price, so their cost is not included`, + rankNoUsage: (n: number) => + n === 1 + ? "1 request has no usage data, so its cost is not included" + : `${n} requests have no usage data, so their cost is not included`, + viewUnpriced: "View unpriced requests in Traffic", moreNotListed: (n: number) => `${n} more not listed`, viewInTraffic: "View in Traffic", diff --git a/src/overview/parts.tsx b/src/overview/parts.tsx index 0cf3a730..37b72090 100644 --- a/src/overview/parts.tsx +++ b/src/overview/parts.tsx @@ -1,4 +1,4 @@ -import type { KeyboardEvent, ReactNode } from "react"; +import type { ComponentProps, KeyboardEvent, ReactNode } from "react"; import { ChevronRightIcon } from "lucide-react"; import { cn } from "@/lib/utils"; import { Badge } from "@/ui/badge"; @@ -84,22 +84,40 @@ export function LinkRow({ /** * 一段可以点的字(「6 次失败」「3 条无法计价」)。悬停出下划线,键盘同样能打开。 + * + * **别的属性原样落到这个 span 上**:套在 `Tip` 里时,悬停提示的触发器把指针、焦点的 + * 处理和 ref 交给它,吞掉的话提示永远不出来。 + * + * 点击和按键只打开它自己,**不再往上冒泡**:它放在一整行都能点的排行里时(排行里 + * 「无法计价」那一格),那一行不该跟着再打开一次。 */ export function LinkText({ onOpen, className, children, -}: { + onClick, + onKeyDown, + ...rest +}: Omit, "role" | "tabIndex"> & { onOpen: () => void; - className?: string; children: ReactNode; }) { + const activate = onActivate(onOpen); return ( { + onClick?.(e); + e.stopPropagation(); + onOpen(); + }} + onKeyDown={(e) => { + onKeyDown?.(e); + if (e.key === "Enter" || e.key === " ") e.stopPropagation(); + activate(e); + }} className={cn( "cursor-pointer rounded-sm underline-offset-2 outline-none transition-colors duration-(--motion-fast) hover:underline focus-visible:underline focus-visible:ring-2 focus-visible:ring-ring/40", className, diff --git a/src/overview/series.test.ts b/src/overview/series.test.ts index 4fa3010a..cc36b15e 100644 --- a/src/overview/series.test.ts +++ b/src/overview/series.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import type { CostBucketGroup, Dashboard, Summary } from "@/types"; +import type { CostBucket, CostBucketGroup, Dashboard, Summary } from "@/types"; import { buildTrend, cacheByModel, @@ -11,9 +11,11 @@ import { liveTicks, modelGlyph, niceCeil, + rankCost, + type RankRow, } from "./series"; import { overviewText } from "./overview.i18n"; -import { LIVE_BUCKET_MS } from "./useLive"; +import { LIVE_BUCKET_MS, type LiveSample } from "./useLive"; const t = overviewText.zh; const HOUR = 3_600_000; @@ -68,12 +70,25 @@ function group(at_ms: number, name: string, tokens: number, cost = 0, requests = }; } +/** 各格按模型加起来,和 core 的 `/summary/buckets` 对得上 */ function dashboard(since: number, groups: CostBucketGroup[]): Dashboard { - const buckets = new Map(); + const buckets = new Map(); for (const g of groups) { - const b = buckets.get(g.at_ms) ?? { requests: 0, cost: 0 }; + const b = buckets.get(g.at_ms) ?? { + at_ms: g.at_ms, + requests: 0, + failed: 0, + cost_micros_exact: 0, + cost_micros_estimated: 0, + unpriced_requests: 0, + no_usage_requests: 0, + }; b.requests += g.requests; - b.cost += g.cost_micros_exact; + b.failed += g.failed; + b.cost_micros_exact += g.cost_micros_exact; + b.cost_micros_estimated += g.cost_micros_estimated; + b.unpriced_requests += g.unpriced_requests; + b.no_usage_requests += g.no_usage_requests; buckets.set(g.at_ms, b); } return { @@ -81,21 +96,29 @@ function dashboard(since: number, groups: CostBucketGroup[]): Dashboard { 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: [...buckets.values()], buckets_by_model: groups, prev: null, since_ms: since, }; } +/** 排行里的一行,只写要测的那几项 */ +function rank(over: Partial): RankRow { + return { + name: "m", + merged: 0, + tokens: 1000, + cost: 0, + estimated: 0, + unpriced: 0, + noUsage: 0, + requests: 1, + color: "var(--chart-1)", + ...over, + }; +} + describe("纵轴上界", () => { it("粗档是 1 / 2 / 5", () => { expect(niceCeil(0)).toBe(1); @@ -275,6 +298,141 @@ describe("趋势图和模型排行", () => { }); }); +/** + * 排行里费用那一格。**「没有价格」「确实不花钱」「没有用量」是三件事**,都写成 + * 一个 `$0` 或一个「—」的话,读的人分不出哪一行该去补价。 + */ +describe("排行的费用", () => { + it("全都算出来了:写金额,没有悬停;合计是零就写 $0(不计费的上游)", () => { + expect(rankCost(rank({ cost: 1_234 }), t)).toEqual({ kind: "amount", prefix: "", notes: [] }); + expect(rankCost(rank({ cost: 0 }), t)).toEqual({ kind: "amount", prefix: "", notes: [] }); + }); + + it("有用量、一条都没算出费用:「无法计价」,不写 $0", () => { + const c = rankCost(rank({ unpriced: 5 }), t); + expect(c.kind).toBe("unpriced"); + expect(c.notes).toEqual([t.rankUnpriced(5)]); + }); + + it("连用量都没有:「无用量」", () => { + const c = rankCost(rank({ tokens: 0, noUsage: 2 }), t); + expect(c.kind).toBe("noUsage"); + expect(c.notes).toEqual([t.rankNoUsage(2)]); + }); + + it("两样都有、一分钱都没算出来:算「无法计价」—— 补价修得好的那一种优先说", () => { + const c = rankCost(rank({ unpriced: 1, noUsage: 3 }), t); + expect(c.kind).toBe("unpriced"); + expect(c.notes).toEqual([t.rankUnpriced(1), t.rankNoUsage(3)]); + }); + + it("算出了一部分:金额是下限,写「≥」,缺的那几条写在悬停里", () => { + expect(rankCost(rank({ cost: 500, unpriced: 2 }), t)).toEqual({ + kind: "amount", + prefix: "≥", + notes: [t.rankUnpriced(2)], + }); + expect(rankCost(rank({ cost: 500, noUsage: 1 }), t)).toMatchObject({ prefix: "≥", notes: [t.rankNoUsage(1)] }); + }); + + it("含估算:带「~」,估算的数写在悬停里;两样都有是「≥~」", () => { + expect(rankCost(rank({ cost: 500, estimated: 120 }), t)).toEqual({ + kind: "amount", + prefix: "~", + notes: [t.estimated("$0.0001")], + }); + expect(rankCost(rank({ cost: 500, estimated: 120, unpriced: 1 }), t)).toMatchObject({ + prefix: "≥~", + notes: [t.estimated("$0.0001"), t.rankUnpriced(1)], + }); + }); + + describe("从哪儿数出来", () => { + const since = new Date(2026, 8, 24, 0, 0).getTime(); + const now = since + 3 * HOUR; + const base = { live: false, bucketMs: HOUR, rangeMs: DAY, samples: [], fails: [], now, prevStack: [], t }; + const at = since + HOUR; + const g = (name: string, over: Partial): CostBucketGroup => ({ ...group(at, name, 1000), ...over }); + + it("历史档:每个模型自己带着无法计价、无用量的条数和估算的金额,跨格加起来", () => { + const d = dashboard(since, [ + g("priced", { cost_micros_exact: 900, cost_micros_estimated: 100 }), + g("priced", { at_ms: at + HOUR, cost_micros_exact: 50 }), + g("unpriced", { unpriced_requests: 4, requests: 4 }), + g("free", {}), + g("silent", { input_tokens: 0, no_usage_requests: 2, requests: 2 }), + ]); + const by = new Map(buildTrend({ ...base, d, by: "token" }).ranking.map((r) => [r.name, r])); + expect(by.get("priced")).toMatchObject({ cost: 1050, estimated: 100, unpriced: 0, noUsage: 0 }); + expect(by.get("unpriced")).toMatchObject({ cost: 0, unpriced: 4, noUsage: 0 }); + expect(by.get("free")).toMatchObject({ cost: 0, unpriced: 0, noUsage: 0 }); + expect(by.get("silent")).toMatchObject({ tokens: 0, noUsage: 2 }); + expect(rankCost(by.get("unpriced")!, t).kind).toBe("unpriced"); + expect(rankCost(by.get("free")!, t)).toEqual({ kind: "amount", prefix: "", notes: [] }); + expect(rankCost(by.get("silent")!, t).kind).toBe("noUsage"); + }); + + it("合并的「其他」把几项的条数加在一起:里面有无法计价的,金额就是下限", () => { + const d = dashboard( + since, + ["a", "b", "c", "d", "e"].map((m, i) => g(m, { input_tokens: (10 - i) * 1000, cost_micros_exact: 100 })).concat([ + g("f", { input_tokens: 10, cost_micros_exact: 30 }), + g("g", { input_tokens: 5, unpriced_requests: 1 }), + ]), + ); + const other = buildTrend({ ...base, d, by: "token" }).ranking.at(-1)!; + expect(other).toMatchObject({ merged: 2, cost: 30, unpriced: 1 }); + expect(rankCost(other, t).prefix).toBe("≥"); + }); + + it("实时档:价钱到了却是空的算无法计价,还没到的不算", () => { + const live = { ...base, live: true, rangeMs: 10 * 60_000, d: dashboard(since, []) }; + const s = (id: number, model: string, over: Partial): LiveSample => ({ id, at: now - 30_000, model, tokens: 100, ...over }); + const tr = buildTrend({ + ...live, + by: "cost", + samples: [ + s(1, "a", { cost: 300 }), + s(2, "a", { cost: 200, estimated: true }), + s(3, "b", { cost: null }), + // 刚落地,价钱还在路上 + s(4, "b", {}), + s(5, "c", { cost: 0 }), + ], + }); + const by = new Map(tr.ranking.map((r) => [r.name, r])); + expect(by.get("a")).toMatchObject({ cost: 500, estimated: 200, unpriced: 0, requests: 2 }); + expect(by.get("b")).toMatchObject({ cost: 0, unpriced: 1, requests: 2 }); + expect(by.get("c")).toMatchObject({ cost: 0, unpriced: 0 }); + }); + + it("费用口径的悬停:金额之外的条数跟在请求数后面,金额写成下限", () => { + const d = dashboard(since, [ + g("a", { cost_micros_exact: 5_000, requests: 3, failed: 1 }), + g("b", { unpriced_requests: 2, requests: 2 }), + g("c", { no_usage_requests: 1, requests: 1 }), + ]); + const tip = buildTrend({ ...base, d, by: "cost" }).tips[1]; + expect(tip).toEqual({ + title: fmtBucket(at, HOUR), + value: "≥$0.0050", + note: [t.tipRequests(6, 1), t.unpriced(2), t.noUsage(1)].join(t.listSep), + }); + // token 口径说的是用量,和价钱无关 + expect(buildTrend({ ...base, d, by: "token" }).tips[1]?.note).toBe(t.tipRequests(6, 1)); + }); + + it("一格里一分钱都没算出来:合计写成词,不写「≥$0」", () => { + const only = (over: Partial) => + buildTrend({ ...base, d: dashboard(since, [g("x", over)]), by: "cost" }).tips[1]?.value; + expect(only({ unpriced_requests: 1 })).toBe(t.unpricedCell); + expect(only({ input_tokens: 0, no_usage_requests: 1 })).toBe(t.noUsageCell); + // 不计费:真的是零 + expect(only({})).toBe("$0"); + }); + }); +}); + describe("各模型的缓存", () => { it("按上下文量从大到小,跨格合计,没有上下文的不列", () => { const g = (name: string, read: number, plain: number, write: number): CostBucketGroup => ({ diff --git a/src/overview/series.ts b/src/overview/series.ts index 5f54b374..9cca4ac7 100644 --- a/src/overview/series.ts +++ b/src/overview/series.ts @@ -82,13 +82,67 @@ export interface RankRow { /** 合并了几项。单个模型是 0 */ merged: number; tokens: number; - /** 微分 */ + /** 微分:实测加估算 */ cost: number; + /** 其中估算的那部分,微分 */ + estimated: number; + /** 有用量、模型却不在价目表里的请求:费用不在 `cost` 里 */ + unpriced: number; + /** 没有拿到用量的请求:费用算不出来,也不在 `cost` 里 */ + noUsage: number; requests: number; /** 图里那一层的颜色 */ color: string; } +/** + * 排行里费用那一格写什么。**一个数或一个词,说明进悬停**,和会话的费用那一格 + * (`costCell`)同一套写法: + * + * · 有用量、却一条都没算出费用:「无法计价」。**不写 $0** —— 那是在说它不花钱。 + * · 连用量都没有:「无用量」。 + * · 其余写金额。有算不出来的请求时金额只是下限,写成「≥」;含估算的带「~」。 + * 全都算出来了、合计是零时写 $0:不计费的上游(本地模型)就是这样,它说的是真的。 + * + * `notes` 是悬停里的几句话,一句一段;空的就没有悬停。 + */ +export function rankCost( + r: Pick, + t: Text, +): { kind: "amount" | "unpriced" | "noUsage"; prefix: string; notes: string[] } { + // 金额之外的请求,各说各的 + const outside = [ + ...(r.unpriced > 0 ? [t.rankUnpriced(r.unpriced)] : []), + ...(r.noUsage > 0 ? [t.rankNoUsage(r.noUsage)] : []), + ]; + if (r.cost === 0 && r.unpriced > 0) return { kind: "unpriced", prefix: "", notes: outside }; + if (r.cost === 0 && r.noUsage > 0) return { kind: "noUsage", prefix: "", notes: outside }; + const estimated = r.estimated > 0; + return { + kind: "amount", + prefix: costPrefix(outside.length > 0, estimated), + notes: [...(estimated ? [t.estimated(usd(r.estimated))] : []), ...outside], + }; +} + +/** + * 金额前面的记号:缺了算不出来的请求,金额只是下限(「≥」);**估算不能冒充实测**, + * 含估算的带「~」。 + */ +function costPrefix(incomplete: boolean, estimated: boolean): string { + return (incomplete ? "≥" : "") + (estimated ? "~" : ""); +} + +/** 一格的费用写成一个词或一个带记号的金额,和排行那一格同一套(`rankCost`) */ +function bucketCost(g: CostBucket, t: Text): string { + const cost = g.cost_micros_exact + g.cost_micros_estimated; + const c = rankCost( + { cost, estimated: g.cost_micros_estimated, unpriced: g.unpriced_requests, noUsage: g.no_usage_requests }, + t, + ); + return c.kind === "unpriced" ? t.unpricedCell : c.kind === "noUsage" ? t.noUsageCell : c.prefix + usd(cost); +} + export interface Trend { /** 图的每一格:`label` 是这一格的时刻(横轴的键,每格不同),其余键是各层的值 */ rows: Record[]; @@ -160,6 +214,9 @@ export function buildTrend({ : []; const byBucket = new Map>(); const money = new Map(); + const estimated = new Map(); + const unpriced = new Map(); + const noUsage = new Map(); const volume = new Map(); const count = new Map(); const add = (at: number, name: string, v: number) => { @@ -167,6 +224,9 @@ export function buildTrend({ slot.set(name, (slot.get(name) ?? 0) + v); byBucket.set(at, slot); }; + const bump = (m: Map, name: string, v: number) => { + if (v !== 0) m.set(name, (m.get(name) ?? 0) + v); + }; if (live) { /* **一条请求摊成一个高斯鼓包,不是一根针也不是一个方块。**核归一到总 @@ -182,6 +242,9 @@ export function buildTrend({ 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); + if (x.estimated) bump(estimated, x.model, x.cost ?? 0); + // 价钱到了却是空的:模型未定价。还没到的(`undefined`)不算 + if (x.cost === null) bump(unpriced, x.model, 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)); @@ -199,6 +262,9 @@ export function buildTrend({ 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); + bump(estimated, name, b.cost_micros_estimated); + bump(unpriced, name, b.unpriced_requests); + bump(noUsage, name, b.no_usage_requests); add(b.at_ms, name, tokensMode ? tok : cost); } } @@ -263,6 +329,9 @@ export function buildTrend({ merged: 0, tokens: volume.get(name) ?? 0, cost: money.get(name) ?? 0, + estimated: estimated.get(name) ?? 0, + unpriced: unpriced.get(name) ?? 0, + noUsage: noUsage.get(name) ?? 0, requests: count.get(name) ?? 0, color: colorOf.get(name) ?? "var(--chart-1)", })); @@ -272,6 +341,9 @@ export function buildTrend({ merged: rest.length, tokens: sum(volume), cost: sum(money), + estimated: sum(estimated), + unpriced: sum(unpriced), + noUsage: sum(noUsage), requests: sum(count), color: OTHER, }); @@ -320,10 +392,16 @@ export function buildTrend({ } : { 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, + value: tokensMode ? t.tokens(compact(Math.round(total)), total) : bucketCost(g, t), + note: + g.requests === 0 + ? t.tipNone + : [ + t.tipRequests(g.requests, g.failed), + // 费用口径下,金额之外的那几条也说出来:和上面费用那个大数的限定语同一套说法 + ...(!tokensMode && g.unpriced_requests > 0 ? [t.unpriced(g.unpriced_requests)] : []), + ...(!tokensMode && g.no_usage_requests > 0 ? [t.noUsage(g.no_usage_requests)] : []), + ].join(t.listSep), }, ); // `label` 是横轴的键:每一格各不相同(到分钟,实时档到秒),「现在」那一点靠它找位置 diff --git a/src/overview/useLive.ts b/src/overview/useLive.ts index 3e844ef3..c3fd196b 100644 --- a/src/overview/useLive.ts +++ b/src/overview/useLive.ts @@ -79,8 +79,13 @@ export interface LiveSample { at: number; model: string; tokens: number; - /** 价钱比用量晚一拍到(`request_priced`)。没到之前是 `undefined` */ - cost?: number; + /** + * 微分。价钱比用量晚一拍到(`request_priced`):没到之前是 `undefined`;到了却是 + * 空的是 `null` —— 用量是有的,模型不在价目表里(不计费的上游记的是 0) + */ + cost?: number | null; + /** 这笔费用是估算的(请求在响应结束前断开,输出只算到断开时) */ + estimated?: boolean; } /** 一次失败。**带着 id**:事件流和补回来的历史会说到同一次,要能去重 */ @@ -271,7 +276,8 @@ export function useLiveWindow(active: boolean, windowMs: number) { 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; + x.cost = ev.cost_micros ?? null; + x.estimated = ev.cost_estimated === true; break; } } @@ -296,6 +302,14 @@ export function useLiveWindow(active: boolean, windowMs: number) { try { // 挂上了再补 —— `listen` 是异步注册的 await un; + /* + **库里的时刻是 core 的时钟,图的横轴是这边的时钟。**连的是另一台机器上 + 的 core 时,两边不一定对得上:差出一分钟,补回来的这一段就整段错开一分钟, + 和事件流上画的接不上。所以先问 core 此刻几点(`/in-flight` 带着它), + 起点按它算,每一条再按两边的差挪回这边的时钟上。 + */ + const { now_ms: coreNow } = await call("InFlight", null); + const skew = coreNow - Date.now(); /* **按时间取,不按条数取。**十分钟里有多少条请求说不准:取固定的 条数,忙的时候补不满一个窗口,闲的时候又白拿一堆窗口外的。 @@ -306,15 +320,17 @@ export function useLiveWindow(active: boolean, windowMs: number) { */ const rows = await call("History", { limit: 2000, - from_ms: Date.now() - 2 * windowMs, + from_ms: coreNow - 2 * windowMs, }); if (!alive) return; const cut = Date.now() - windowMs; const seeded: LiveSample[] = []; const seededFails: LiveFail[] = []; for (const r of rows) { - // 和事件流同一个口径:落在结束的那一刻 - const at = r.at_ms + (r.duration_ms ?? 0); + // 本地应答没到上游,和别处的汇总一样不算 + if (r.local) continue; + // 和事件流同一个口径:落在结束的那一刻,换到这边的时钟上 + const at = r.at_ms + (r.duration_ms ?? 0) - skew; if (at < cut) continue; if (r.error && !failedAlready(r.id)) seededFails.push({ id: r.id, at }); if (counted(r.id)) continue; @@ -330,7 +346,9 @@ export function useLiveWindow(active: boolean, windowMs: number) { at, model: r.model || textOf(liveText).unknownModel, tokens, - ...(r.cost_micros != null ? { cost: r.cost_micros } : {}), + // 落了库的都已经算过价:有用量却是空的,就是未定价 + cost: r.cost_micros, + estimated: r.cost_estimated, }); } // **按时间排好**:`request_priced` 是从末尾倒着找那一条的
{l}