diff --git a/docs/reference.md b/docs/reference.md index 02a789da9..3a89ba99b 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -180,6 +180,17 @@ columns, `cache_write_5m_tokens` and `cache_write_1h_tokens`, split it by how long Anthropic keeps it (a record from before the split is all 5-minute). The app shows the split on a request's Cache and the usage tiles' tooltips. +**Output speed** (tok/s on the Usage and Routing pages, `magpie usage`) is +output tokens over the time after the first token, summed per request: the +tokens of every timed request over the sum of their windows, so concurrent +subagents never add up. A reply that reasoned counts only its answer, from its +first text (`usage.DecodeOf`): hidden reasoning is written before the stream +shows anything, so counting it in a window that starts after it read +gpt-6.1-sol at hundreds of tok/s. A reply that reasoned and then wrote only +tool calls, one not streamed, and a burst (under 100 ms, or over 10,000 tok/s) +tell no speed. History is read the same way, as it keeps the reasoning and the +first text. + It lists **accounts** too: each Codex, Claude or other subscription account's tokens and cost, by the account that actually answered — the one that took over after a failover, the one `X-Magpie-Account` pinned. The account is named diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index e3fae4f7d..2a025fd1f 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -409,7 +409,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri link.Reply = replyDigest t.TitleLink = &link } - t.Output, t.TTFT, t.FirstText = out, ttft, text + t.Output, t.Reasoning, t.TTFT, t.FirstText = out, uu.Reasoning, ttft, text t.Usage = routeUsage("openai", model, uu) t.Tries[0].Served, t.Tries[0].Swapped = served, swapped(model, served) t.Served, t.Swapped = t.Tries[0].Served, t.Tries[0].Swapped diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d9851805b..edc2f7acb 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2321,7 +2321,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro t.Usage = append(t.Usage, routeUsage(call.Provider, model, call.Usage)...) } t.Tokens = call.Usage.Input + call.Usage.Output + call.Usage.CacheRead + call.Usage.CacheWrite - t.Output, t.TTFT, t.FirstText = call.Usage.Output, call.TTFT, call.FirstText + t.Output, t.Reasoning, t.TTFT, t.FirstText = call.Usage.Output, call.Usage.Reasoning, call.TTFT, call.FirstText if n := len(t.Tries); n > 0 && call.Status < 400 { t.Served, t.Swapped, t.Routed = t.Tries[n-1].Served, t.Tries[n-1].Swapped, t.Tries[n-1].Routed t.Upstream = t.Tries[n-1].Upstream diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 7d2503c1f..7f559aedc 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -59,6 +59,9 @@ type Route struct { Millis int64 `json:"ms,omitempty"` Tokens int `json:"tokens,omitempty"` Output int `json:"out,omitempty"` // of Tokens, the reply's + // Reasoning: of Output, the reply's reasoning, which its speed leaves + // out (usage.DecodeOf) + Reasoning int `json:"reasoning,omitempty"` // TTFT: ms from the request to its reply's first content (text, // reasoning or a tool call), FirstText to its first text, as Millis // counts: streamed replies only (#196) diff --git a/internal/gateway/ttft_test.go b/internal/gateway/ttft_test.go index ce07ace0c..09d24a224 100644 --- a/internal/gateway/ttft_test.go +++ b/internal/gateway/ttft_test.go @@ -60,14 +60,14 @@ var ( `data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`, `~data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{"reasoning_content":"hmm"}}]}`, `~data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{"content":"hi"}}]}`, - `~data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":20}}`, + `~data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":20,"completion_tokens_details":{"reasoning_tokens":12}}}`, `data: [DONE]`, } pacedResponses = []string{ "event: response.created\ndata: " + `{"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`, "~event: response.reasoning_summary_text.delta\ndata: " + `{"type":"response.reasoning_summary_text.delta","item_id":"rs_1","output_index":0,"summary_index":0,"delta":"hmm"}`, "~event: response.output_text.delta\ndata: " + `{"type":"response.output_text.delta","item_id":"msg_1","output_index":1,"content_index":0,"delta":"hi"}`, - "~event: response.completed\ndata: " + `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":20}}}`, + "~event: response.completed\ndata: " + `{"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":20,"output_tokens_details":{"reasoning_tokens":12}}}}`, } ) @@ -129,6 +129,10 @@ func TestUsageKeepsTimeToFirstToken(t *testing.T) { t.Errorf("usage ttft %d, first text %d, ms %d, out %d; want the reasoning after %d ms and the text after %d", u.TTFT, u.FirstText, u.Millis, u.Output, gap, 2*gap) } r := lastRoute(s) + // the reply's reasoning, which its speed leaves out (usage.DecodeOf) + if c.proto != provider.Anthropic && (u.Reasoning != 12 || r.Reasoning != 12) { + t.Errorf("reasoning: usage %d, route %d; want 12", u.Reasoning, r.Reasoning) + } if len(r.Tries) != 1 || r.TTFT != u.TTFT || r.FirstText != u.FirstText || r.Output != 20 || r.Tries[0].TTFT < gap || r.Tries[0].TTFT > u.TTFT || r.Tries[0].FirstText < 2*gap { t.Errorf("route ttft %d/%d out %d, tries %+v", r.TTFT, r.FirstText, r.Output, r.Tries) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index cec2c14cb..5669ce90b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15100,7 +15100,7 @@ function renderLedgerDash(l) { const speed = ledSpeed(l); block("Output speed", speed ? t("{n} tok/s", { n: ledNum(Math.round(speed)) }) : "—", line(ledTTFT(l) ? t("first token in {ms} on average", { ms: ledTook(ledTTFT(l)) }) : t("no streamed replies timed")), - "", t("Output tokens a second after the first, over the streamed replies")); + "", t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it")); drawLedTrend(); } @@ -15193,9 +15193,18 @@ const LED_COLS = [ ["In", "n"], ["Out", "n"], ["Cache write", "n", true], ["Cache read", "n", true], ["Cost", "n"], ["Duration", "n"], ["Speed", "n"], ["Status"], ]; -// how fast a reply wrote, in tokens a second after its first: as -// usage.DecodeWindow and routing.js's speedOf tell it, 0 when it can't -const ledRowSpeed = (r) => !ledFailed_(r) && r.out > 0 && r.ttft_ms > 0 && r.ms - r.ttft_ms >= 100 && r.out * 1000 <= 10000 * (r.ms - r.ttft_ms) ? r.out / ((r.ms - r.ttft_ms) / 1000) : 0; +// the tokens a reply was seen to write and the ms it took, as +// usage.DecodeOf and routing.js's decodeOf tell them: one that reasoned +// counts its answer from its first text, its reasoning written before +// the stream showed any (tony on Discord); null when it tells no speed +const ledDecode = (r) => { + if (ledFailed_(r) || !(r.ttft_ms > 0)) return null; + const think = r.reasoning > 0, n = think ? r.out - r.reasoning : r.out, from = think ? r.first_text_ms : r.ttft_ms; + const w = r.ms - from; + return n > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w ? { n, w } : null; +}; +// how fast a reply wrote, in tokens a second: 0 when it can't tell +const ledRowSpeed = (r) => { const d = ledDecode(r); return d ? d.n / (d.w / 1000) : 0; }; // the table as wide as the window, when leaving out what the row's details // say anyway makes it so: else it scrolls sideways (#799) @@ -15395,7 +15404,8 @@ function renderLedger() { // how fast it wrote once it began, as CC Switch's log has it (#860) const v = ledRowSpeed(r); td(v ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : "—", "n speed" + (v ? "" : " faint"), - v ? t("{n} output tokens in {ms} after the first", { n: ledNum(r.out), ms: ledTook(r.ms - r.ttft_ms) }) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) + v ? (r.reasoning > 0 ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) }) + : t("{n} output tokens in {ms} after the first", { n: ledNum(r.out), ms: ledTook(r.ms - r.ttft_ms) })) + " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) : r.ttft_ms || untimed || ledFailed_(r) ? "" : t("Not streamed: no first token to time a speed from")); const st = el("span", "st"); // a status when the gateway logged the call; a session file has none, diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index fee10c72a..ba149a83d 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2938,6 +2938,8 @@ const I18N = { "No streamed replies timed in this period": "这段时间没有可计时的流式回复", "Sent, Effort and the cache are in each row's details": "窗口较窄:发送模型、推理强度和缓存在每行的详情里", "{n} output tokens in {ms} after the first": "首字后 {ms} 输出 {n} 个 token", + "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回复只算正文部分,从首个正文起计:推理在流里出现前就已写完", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "首个正文后 {ms} 输出 {n} 个正文 token,之前的 {r} 个推理 token 不计", "Not streamed: no first token to time a speed from": "非流式:没有首字时间,算不出速度", "Cache": "缓存", "{w} written · {r} read": "写入 {w} · 读取 {r}", @@ -6439,6 +6441,8 @@ const I18N = { "No streamed replies timed in this period": "この期間に計測できたストリーミング応答はありません", "Sent, Effort and the cache are in each row's details": "ウィンドウが狭いため、送信したモデル・推論レベル・キャッシュは各行の詳細にあります", "{n} output tokens in {ms} after the first": "最初のトークン後 {ms} で {n} トークンを出力", + "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "推論した応答は、最初の本文からの回答部分のみ数えます。推論はストリームに出る前に書き終わっています", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "最初の本文後 {ms} で回答 {n} トークン(その前の推論 {r} トークンは含めず)", "Not streamed: no first token to time a speed from": "ストリーミングではないため、速度を計れる最初のトークンの時刻がありません", "Cache": "キャッシュ", "{w} written · {r} read": "書き込み {w} · 読み取り {r}", @@ -9953,6 +9957,8 @@ const I18N = { "No streamed replies timed in this period": "In diesem Zeitraum wurde keine gestreamte Antwort gemessen", "Sent, Effort and the cache are in each row's details": "Schmales Fenster: Gesendet, Effort und Cache stehen in den Details jeder Zeile", "{n} output tokens in {ms} after the first": "{n} Ausgabe-Token in {ms} nach dem ersten", + "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "Eine Antwort mit Reasoning zählt nur ihre Antwort ab dem ersten Text: Das Reasoning entstand, bevor der Stream es zeigte", + "{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out": "{n} Antwort-Token in {ms} nach dem ersten Text, ohne die {r} Reasoning-Token davor", "Not streamed: no first token to time a speed from": "Nicht gestreamt: kein erstes Token, an dem sich ein Tempo messen ließe", "Cache": "Cache", "{w} written · {r} read": "{w} geschrieben · {r} gelesen", diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 2b7cba88c..cf2b679f6 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -233,7 +233,21 @@ // 100 ms or would have it write over 10,000 tok/s, as it came in one // burst at its end (usage.DecodeWindow, #731: a whole Gemini tool call, // 8264 tokens 1 ms before the end, read 8,264,000 tok/s) - const speedOf = (out, ms, ttft) => out > 0 && ttft > 0 && ms - ttft >= 100 && out * 1000 <= 10000 * (ms - ttft) ? out / ((ms - ttft) / 1000) : 0; + // A reply that reasoned counts its answer, its output less the + // reasoning, from its first text (usage.DecodeOf, tony on Discord): + // the reasoning was written before the stream showed any, OpenAI's + // encrypted and its summary sent when done, and counting it read + // gpt-6.1-sol at 163 tok/s. The reply's reasoning is its served try's. + function decodeOf(r, ms, ttft, firstText) { + const think = reasoningOf(r), n = think > 0 ? r.out - think : r.out, from = think > 0 ? firstText : ttft; + const w = ms - from; + return n > 0 && ttft > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w ? { n, w } : null; + } + const reasoningOf = (r) => r.reasoning ?? (r.usage?.length ? r.usage[r.usage.length - 1].reasoning || 0 : 0); + const speedOf = (r, ms = r.ms, ttft = r.ttft, firstText = r.firstText) => { + const d = decodeOf(r, ms, ttft, firstText); + return d ? d.n / (d.w / 1000) : 0; + }; function promptOf(r) { let prompt = 0, read = 0; // Input excludes both cache tiers. Include writes in the denominator, @@ -269,7 +283,7 @@ // Both times start at the request, so subtracting them leaves the // reply's decode window even after a retry. Output is the reply's, // not the prompt or the output of earlier billable tries. - const speed = r.done && how !== "bad" ? speedOf(r.out, r.ms, r.ttft) : 0; + const speed = r.done && how !== "bad" ? speedOf(r) : 0; const values = { duration: ["duration", "Duration", r.done && r.ms ? took(r.ms) : "—", ""], ttft: ["ttft", "First token", r.done && r.ttft ? took(r.ttft) : "—", t("First token")], @@ -277,7 +291,7 @@ cache: ["cache-hit", "Cache", prompt ? pct(100 * read / prompt) : "—", t("Cache hit rate") + ": " + t("The share of the prompt read from the cache")], speed: ["speed", "Speed", speed ? t("{n} tok/s", { n: Math.round(speed) }) : "—", - t("Output tokens a second after the first, over the streamed replies")], + t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it")], cost: ["cost", "Cost", routeCost(r), r.priced ? costNote() : t("No known price or token counts for this request")], }; return visibleMetrics.map((key) => values[key]).filter((metric) => metric[2] !== "—"); @@ -293,7 +307,7 @@ function firstNote(r, tr) { let s = tr.ttft ? " · " + t("first token in {ms}", { ms: took(tr.ttft) }) : ""; if (tr.ttft && tr.firstText > tr.ttft) s += " · " + t("first text in {ms}", { ms: took(tr.firstText) }); - const v = speedOf(r.out, tr.ms, tr.ttft); + const v = speedOf(r, tr.ms, tr.ttft, tr.firstText); if (v) s += " · " + t("{n} tok/s", { n: Math.round(v) }); const { prompt, read } = promptOf(r); if (prompt) s += " · " + t("request cache hit rate {p}", { p: pct(100 * read / prompt) }); @@ -1628,9 +1642,8 @@ s.completed++; const { prompt, read } = promptOf(r); if (prompt) { s.prompt += prompt; s.read += read; s.cached++; } - if (outcome(r)[1] !== "bad" && speedOf(r.out, r.ms, r.ttft)) { - s.decodeMs += r.ms - r.ttft; s.decodeOut += r.out; s.timed++; - } + const d = outcome(r)[1] !== "bad" && decodeOf(r, r.ms, r.ttft, r.firstText); + if (d) { s.decodeMs += d.w; s.decodeOut += d.n; s.timed++; } } return s; }, { cost: 0, tokens: 0, priced: 0, unpriced: 0, running: 0, completed: 0, prompt: 0, read: 0, cached: 0, decodeMs: 0, decodeOut: 0, timed: 0 }); @@ -1660,7 +1673,7 @@ if (g.key && visibleMetrics.includes("cache") && total.prompt) meta.push(metricElement(["cache-hit", "Avg. cache", pct(100 * total.read / total.prompt), t("Total cache reads divided by total prompt tokens; larger prompts carry more weight") + "\n" + coverage(total.cached)])); if (g.key && visibleMetrics.includes("speed") && total.decodeMs) meta.push(metricElement(["speed", "Avg. speed", t("{n} tok/s", { n: Math.round(total.decodeOut * 1000 / total.decodeMs) }), - t("Total output tokens divided by total decode time; excludes waiting and replies without usable timing") + "\n" + coverage(total.timed)])); + t("Total output tokens divided by total decode time; excludes waiting and replies without usable timing") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + "\n" + coverage(total.timed)])); const metaSig = JSON.stringify([bits, tokenHelp, meta.map((e) => [e.textContent, e.title])]); if (x.meta.dataset.sig !== metaSig) { x.meta.replaceChildren(...meta); x.meta.dataset.sig = metaSig; } setText(x.cost, total.priced ? "≈" + fmtCost({ cost: total.cost, unpriced: 0 }) + (total.unpriced ? "+" : "") : ""); diff --git a/internal/gui/tests/reasoning-speed.test.cjs b/internal/gui/tests/reasoning-speed.test.cjs new file mode 100644 index 000000000..6f77d9633 --- /dev/null +++ b/internal/gui/tests/reasoning-speed.test.cjs @@ -0,0 +1,136 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A reply that reasoned is timed by its answer (tony on Discord: gpt-6.1-sol +// read 163 tok/s with a 14 s first token). A Codex turn of 2000 reasoning +// tokens, written before its first content at 14 s, and a 200-token answer +// over the 1.5 s after counted 2200 tokens in 1.5 s, 1,467 tok/s; it is 200 +// in 1.5 s, 133. An older route without its own reasoning count takes its +// served try's; a reply that reasoned and wrote only tool calls tells no +// speed; one that didn't reason is timed as before. The Routing page's rows, +// a session's average and the Usage page's rows and their tooltip all say +// it, in English, Chinese, Japanese and German; no backend, the API is faked. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = new Date(); +const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-"); +const seat = { id: "codex", provider: "codex", name: "Codex", who: "test@example.com", kind: "account", model: "gpt-6.1-sol" }; +const at = (i) => new Date(now.getTime() - (i + 1) * 60e3).toISOString(); +// newest first: [out, reasoning (top level), reasoning (usage only), ms, ttft, firstText] +const timing = [ + [2200, 2000, 0, 15500, 14000, 14000], // the turn: 200 in 1.5 s, 133 tok/s + [1300, 0, 1000, 9000, 6000, 6000], // an older route: 300 in 3 s, 100 tok/s + [1500, 1400, 0, 9000, 8000, 0], // reasoning, then tool calls only: none + [500, 0, 0, 7000, 2000, 2000], // no reasoning: 500 in 5 s, 100 tok/s +]; +const routes = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText], i) => ({ + id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", session: "think-chat", model: "codex/gpt-6.1-sol", provider: "codex", + order: [seat], tries: [{ id: seat.id, model: seat.model, start: at(i), done: true, status: 200, ms, ttft, firstText }], + done: true, status: 200, ms, ttft, firstText, tokens: out + 9000, out, ...(reasoning ? { reasoning } : {}), + usage: [{ provider: "codex", model: seat.model, in: 9000, out, ...(reasoning || usageReasoning ? { reasoning: reasoning || usageReasoning } : {}) }], +})); +const rows = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText], i) => ({ + route_id: 100 - i, t: at(i), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "codex", providerName: "Codex", + host: "test@example.com", req: "codex/gpt-6.1-sol", model: "gpt-6.1-sol", served: "gpt-6.1-sol", in: 9000, out, + ...(reasoning || usageReasoning ? { reasoning: reasoning || usageReasoning } : {}), ms, ttft_ms: ttft, ...(firstText ? { first_text_ms: firstText } : {}), + status: 200, ep: "/backend-api/codex/responses", cost: 0.01, priced: true, +})); +// what the server sums: 1000 answer tokens in 9.5 s +const M = { id: "gpt-6.1-sol", calls: 4, input: 36000, output: 5500, cache_read: 0, cache_write: 0, cost: 0.04, timed: 4, ttft_ms: 30000, decode_ms: 9500, decode_out: 1000 }; + +function serve(lang) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/t/c.toml", icon: "codex-color", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day, requests: routes.length }], routes: url.searchParams.get("day") ? routes : [] }); + if (url.pathname === "/api/usage/requests") { + return json({ period: url.searchParams.get("period"), rows, offset: 0, total: rows.length, ...M, unpriced: 0, errors: 0, by: { model: [M] }, bucket: "hour", series: [], agents: [{ id: "codex", name: "Codex", icon: "codex-color" }] }); + } + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], models: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + return route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const L = { + en: { s: (n) => `${n} tok/s`, speed: "Speed", note: /200 answer tokens in 1\.5 s after the first text, the 2,000 reasoning tokens before it left out/, rule: /A reply that reasoned counts only its answer/ }, + zh: { s: (n) => `${n} token/秒`, speed: "速度", note: /首个正文后 1\.5 秒 输出 200 个正文 token,之前的 2,000 个推理 token 不计/, rule: /有推理的回复只算正文部分/ }, + ja: { s: (n) => `${n} トークン/秒`, speed: "速度", note: /回答 200 トークン(その前の推論 2,000 トークンは含めず)/, rule: /推論した応答は/ }, + de: { s: (n) => `${n} Token/s`, speed: "Tempo", note: /200 Antwort-Token in .* nach dem ersten Text, ohne die 2\.000 Reasoning-Token davor/, rule: /Eine Antwort mit Reasoning/ }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(L)) { + test(`${engine} ${lang}: a reply that reasoned is timed by its answer`, async (t) => { + const w = L[lang]; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang)); + + // the Routing page: each row, and the session's average + await page.goto("http://magpie.test/?view=routing"); + await page.locator(".rt-days .rt-day").nth(1).click(); + const reqs = page.locator(".rt-req"); + await reqs.nth(timing.length - 1).waitFor(); + const speedOf = async (i) => (await reqs.nth(i).locator(".speed").count()) ? (await reqs.nth(i).locator(".speed .v").textContent()).trim() : ""; + assert.equal(await speedOf(0), w.s(133), "the turn's answer, not 1,467"); + assert.equal(await speedOf(1), w.s(100), "an older route's reasoning is its try's"); + assert.equal(await speedOf(2), "", "tool calls after reasoning tell no speed"); + assert.equal(await speedOf(3), w.s(100), "no reasoning: as before"); + assert.match(await reqs.nth(0).locator(".speed").getAttribute("title"), w.rule); + await reqs.nth(0).click(); + await page.waitForTimeout(200); + const story = await page.locator(".rt-steps").textContent(); + assert(story.includes(w.s(133)) && !/1[,.]?467/.test(story), "the story's speed: " + story); + await page.locator(".rt-group-by button").nth(1).click(); + const group = page.locator("button.rt-session").first(); + await group.waitFor(); + // 1000 answer tokens over 9.5 s of answers, not 4500 over them + assert.equal((await group.locator(".speed .v").textContent()).trim(), w.s(105)); + assert.match(await group.locator(".speed").getAttribute("title"), w.rule); + + // the Usage page's requests: each row, its tooltip, and the period's + await page.goto("http://magpie.test/"); + await page.locator('[data-view="usage"]').first().click(); + await page.locator("#usageTab .opt").nth(1).click(); + await page.locator("#ledWrap .led tbody tr").first().waitFor(); + await page.waitForTimeout(300); + const heads = await page.locator(".led thead th").evaluateAll((ths) => ths.filter((th) => th.offsetParent).map((th) => th.textContent)); + const col = heads.indexOf(w.speed); + assert(col > 0, "a Speed column: " + heads.join(", ")); + const cell = (i) => page.locator(".led tbody tr.led-row").nth(i).locator("td").filter({ visible: true }).nth(col); + assert.equal((await cell(0).textContent()).trim(), w.s(133)); + assert.match(await cell(0).getAttribute("title"), w.note); + assert.equal((await cell(1).textContent()).trim(), w.s(100)); + assert.equal((await cell(2).textContent()).trim(), "—"); + assert.equal((await cell(3).textContent()).trim(), w.s(100)); + const kpi = page.locator("#ledKpi .blk").nth(4); + assert.equal((await kpi.locator(".v").textContent()).trim(), w.s(105)); + assert.match(await kpi.getAttribute("title") || await kpi.locator("[title]").first().getAttribute("title"), w.rule); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, "no sideways scroll"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 40bc6b245..027f614bb 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -497,9 +497,9 @@ func (t *Totals) addRow(r Row) { if r.TTFT > 0 && !r.Failed() { t.Timed++ t.TTFT += r.TTFT - if w := DecodeWindow(r.Output, r.Millis, r.TTFT); w > 0 { + if n, w := r.Decode(); w > 0 { t.DecodeMs += w - t.DecodeOut += r.Output + t.DecodeOut += n } } t.Calls++ @@ -631,9 +631,9 @@ func (p *Part) add(r Row) { if r.TTFT > 0 && !r.Failed() { p.Timed++ p.TTFT += r.TTFT - if w := DecodeWindow(r.Output, r.Millis, r.TTFT); w > 0 { + if n, w := r.Decode(); w > 0 { p.DecodeMs += w - p.DecodeOut += r.Output + p.DecodeOut += n } } } diff --git a/internal/usage/usage.go b/internal/usage/usage.go index cdc4cfae1..a3750cffb 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -277,8 +277,9 @@ type Totals struct { Unpriced int `json:"unpriced"` // calls with tokens but no known price // Timed: the answered calls whose first token was timed (streamed), // TTFT the sum of their ttft_ms; DecodeMs the time from it to the end - // of those that wrote any, over which DecodeOut tokens came: their - // mean wait, and how fast they wrote (#196) + // of those that wrote any, over which DecodeOut tokens came (a + // reasoning reply's answer, Record.Decode): their mean wait, and how + // fast they wrote (#196) Timed int `json:"timed,omitempty"` TTFT int64 `json:"ttft_ms,omitempty"` DecodeMs int64 `json:"decode_ms,omitempty"` @@ -306,7 +307,7 @@ func (t Totals) Speed() float64 { } // A reply's speed is its output tokens over its decode window, the ms -// from its first content to its end (#196); a window counts only when it +// from its first content to its end (#196; one that reasoned, DecodeOf); a window counts only when it // timed the writing (#731). One that is shorter than MinDecodeMs, or over // which the tokens would have come faster than MaxDecodeSpeed a second, // didn't: the reply came in one burst at its end, written before the @@ -334,6 +335,36 @@ func DecodeWindow(out int, ms, ttft int64) int64 { return w } +// DecodeOf is what a reply's speed is told by: the tokens it was seen to +// write and the ms it took (tony on Discord: gpt-6.1-sol read 163 tok/s, +// with a 14 s first token). A reply that reasoned counts only its answer — +// its output less the reasoning, from its first text — as most vendors +// keep the reasoning out of the stream (OpenAI's is encrypted, its summary +// sent when it's done; Claude's may come with no text): its tokens were +// written before the first content, over time the window from it doesn't +// hold, and counting them read a 2,000-token think and a 200-token answer +// in 1.5 s as 1,467 tok/s. Its time goes to the wait before the answer. +// One with reasoning and no text (all tool calls) tells no speed. The +// window is DecodeWindow's: 0 for a reply that tells none. +func DecodeOf(out, reasoning int, ms, ttft, firstText int64) (tokens int, w int64) { + start := ttft + if reasoning > 0 { + out, start = out-reasoning, firstText + } + if ttft <= 0 { + return 0, 0 + } + if w = DecodeWindow(out, ms, start); w == 0 { + return 0, 0 + } + return out, w +} + +// Decode is the record's DecodeOf. +func (r Record) Decode() (tokens int, w int64) { + return DecodeOf(r.Output, r.Reasoning, r.Millis, r.TTFT, r.FirstText) +} + // FormatCost renders an effective-price cost, kept in USD everywhere it's // stored, as the CLI and TUI show it: at amountUSD's own price when // currency isn't "cny", else converted at rate (CNY per one USD, from @@ -370,9 +401,9 @@ func (t *Totals) add(r Record, price *catalog.Price) { if r.TTFT > 0 && !r.Failed() { t.Timed++ t.TTFT += r.TTFT - if w := DecodeWindow(r.Output, r.Millis, r.TTFT); w > 0 { + if n, w := r.Decode(); w > 0 { t.DecodeMs += w - t.DecodeOut += r.Output + t.DecodeOut += n } } if r.Input+r.Output == 0 { diff --git a/internal/usage/usage_test.go b/internal/usage/usage_test.go index 188728bbb..c1ea2a657 100644 --- a/internal/usage/usage_test.go +++ b/internal/usage/usage_test.go @@ -202,6 +202,70 @@ func TestBurstTellsNoSpeed(t *testing.T) { } } +// A reply that reasoned is timed by its answer (tony on Discord: gpt-6.1-sol +// read 163 tok/s with a 14 s first token). A Codex turn of 2000 hidden +// reasoning tokens before its first content at 14 s and a 200-token answer +// over the 1.5 s after counted 2200 tokens in 1.5 s, 1,467 tok/s; it's 200 +// in 1.5 s, 133. Two such subagents running at once are each their own +// window, summed, not the wall clock's. A reply that reasoned and wrote +// only tool calls has no first text and tells no speed; one that didn't +// reason, or wasn't streamed, is timed as before. The summary, ledger rows +// and the timeline's parts agree. +func TestReasoningReplyTimedByItsAnswer(t *testing.T) { + now := time.Date(2026, 10, 6, 15, 30, 0, 0, time.UTC) + at := now.Add(-time.Hour) + codex := func(out, reasoning int, ms, ttft, text int64) Record { + return Record{Time: at, Provider: "codex", Model: "gpt-6.1-sol", Output: out, Reasoning: reasoning, Millis: ms, TTFT: ttft, FirstText: text, Status: 200} + } + recs := []Record{ + codex(2200, 2000, 15500, 14000, 14000), // the turn: 200 in 1.5 s + codex(2200, 2000, 15500, 13990, 14000), // a summary 10 ms before the text: the same + codex(1300, 1000, 9000, 6000, 6000), // a subagent at once: 300 in 3 s + codex(1500, 1400, 9000, 8000, 0), // reasoning, then tool calls only: no speed + codex(900, 1000, 9000, 6000, 6000), // reasoning over output: none + {Time: at, Provider: "codex", Model: "gpt-6.1-sol", Output: 500, Millis: 7000, TTFT: 2000, Status: 200}, // no reasoning: 500 in 5 s + {Time: at, Provider: "codex", Model: "gpt-6.1-sol", Output: 900, Reasoning: 300, Millis: 7000, Status: 200}, // not streamed + } + const ms, out = 1500 + 1500 + 3000 + 5000, 200 + 200 + 300 + 500 + m := summarize(Today, now, recs).Models[0] + if m.Timed != 6 || m.DecodeMs != ms || m.DecodeOut != out || m.Speed() != 109.0909090909091 { + t.Fatalf("model: %+v, %v tok/s", m.Totals, m.Speed()) + } + var rows Totals + var lr []Row + for _, r := range recs { + rows.addRow(Row{Record: r}) + lr = append(lr, Row{Record: r}) + } + if rows.Timed != 6 || rows.DecodeMs != ms || rows.DecodeOut != out { + t.Fatalf("rows: %+v", rows) + } + _, pts := LedgerSeries(Today, lr) + var p Part + for _, pt := range pts { + if q, ok := pt.By["model"]["gpt-6.1-sol"]; ok { + p = q + } + } + if p.DecodeMs != ms || p.DecodeOut != out { + t.Fatalf("part: %+v", p) + } + for _, c := range []struct { + r Record + n int + w int64 + }{ + {recs[0], 200, 1500}, + {recs[3], 0, 0}, + {recs[5], 500, 5000}, + {recs[6], 0, 0}, + } { + if n, w := c.r.Decode(); n != c.n || w != c.w { + t.Errorf("Decode(%+v) = %d, %d; want %d, %d", c.r, n, w, c.n, c.w) + } + } +} + // FormatCost stays in dollars unless cny is asked for and a usable rate is // given; it keeps the same 0/2/3-decimal rule either currency, and a rate // that's missing or non-positive falls back to USD rather than hiding the