From cfd3367df879ca753b2a7ea13716ed07da188d8f Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 17:22:00 +0800 Subject: [PATCH] usage: a request's details show its service tier (JackyFill on X) The ledger has kept each call's service tier since #1784 (tier_asked, tier_sent, tier_served in the log, the CSV and the JSON), but the Requests page never showed it. A request's details now have a Service tier line: "asked X", then "sent Y" only when it differs, then "answered Z" only when the reply named a tier. A call with none shows no line. Row flag bits are untouched: the tiers are string slots, so no bit is taken. Run, on mica: new ledger-service-tier.test.cjs (3 rows: all three tiers, asked+sent without an answer, none) in chromium and webkit, en zh zh-TW ja de, 12 of 12 green; with the add("Service tier") line removed by hand it is 0 of 12; i18n-keys caught a duplicate "Service tier" key (the core table already has all four languages), which is removed; ledger-*, i18n-keys, i18n-en-no-cjk and gui-* files rerun green after (ledger-cache-hit chromium was red once in the first batch, green on rerun in the same batch's second run). Not tried: a real Codex priority call end to end (the gateway side is #1784's); the full suite runs after the tag. --- docs/reference.md | 4 +- internal/gui/assets/plugins/usage/i18n.js | 12 ++ internal/gui/assets/plugins/usage/page.js | 14 +++ .../gui/tests/ledger-service-tier.test.cjs | 114 ++++++++++++++++++ 4 files changed, 143 insertions(+), 1 deletion(-) create mode 100644 internal/gui/tests/ledger-service-tier.test.cjs diff --git a/docs/reference.md b/docs/reference.md index 5696ccafa..73d48ea5a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -445,7 +445,9 @@ vendor's reply said it ran at, empty when the reply doesn't say. The ChatGPT backend (Codex signed in with ChatGPT) says `auto` and `default` whether Fast ran or not, so from it those are left empty too. The JSON log keeps them as `tier_asked`, `tier_sent` and `tier_served`, and each -try in `/v1/magpie/route` has `tier` and `tier_served`. The last column, +try in `/v1/magpie/route` has `tier` and `tier_served`. A request's row +on the Requests page shows them as Service tier (asked, sent when it +differs, answered). The last column, `upstream_stop`, is why the upstream said its reply ended, in its own words (`stop`, `tool_calls`, `end_turn`, a Responses reply's `completed`), empty when it said none. A request's row on the Requests diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index d81065414..8678a3367 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -232,6 +232,9 @@ magpie.strings({ "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中显示,它们的调用仍计入总数和图表。点击查看。", "Vendor's first token": "厂商首字等待", "Tries that failed first": "之前失败的尝试", + "asked {tier}": "请求 {tier}", + "sent {tier}": "发出 {tier}", + "answered {tier}": "上游答复 {tier}", "Connecting and sending": "连接并发送请求", "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "立即刷新,含额度;Claude 账号的额度通过运行 Claude Code 自带的 /usage 读取", "{n} by magpie itself": "其中 {n} 次由 magpie 自身发出", @@ -491,6 +494,9 @@ magpie.strings({ "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "只是不在此列表中顯示,它們的呼叫仍計入總數和圖表。點按查看。", "Vendor's first token": "廠商首字等待", "Tries that failed first": "之前失敗的嘗試", + "asked {tier}": "請求 {tier}", + "sent {tier}": "送出 {tier}", + "answered {tier}": "上游回覆 {tier}", "Connecting and sending": "連線並傳送請求", "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "立即重新整理,含額度;Claude 帳號的額度透過執行 Claude Code 自帶的 /usage 讀取", "{n} by magpie itself": "其中 {n} 次由 magpie 自身發出", @@ -750,6 +756,9 @@ magpie.strings({ "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "この一覧に表示しないだけで、呼び出しは合計とグラフに含まれます。クリックで表示します。", "Vendor's first token": "ベンダーの最初のトークン", "Tries that failed first": "先に失敗した試行", + "asked {tier}": "要求 {tier}", + "sent {tier}": "送信 {tier}", + "answered {tier}": "応答 {tier}", "Connecting and sending": "接続と送信", "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "今すぐ更新し、利用枠も読み込み直します。Claude アカウントの利用枠は Claude Code 自身の /usage を実行して読み取ります", "{n} by magpie itself": "うち {n} 件は magpie 自身", @@ -1009,6 +1018,9 @@ magpie.strings({ "Hidden from this list only: their calls still count in the totals and the chart. Click to see them.": "Nur in dieser Liste ausgeblendet: Ihre Aufrufe zählen weiter in den Summen und im Diagramm. Klicken, um sie zu sehen.", "Vendor's first token": "Erstes Token des Anbieters", "Tries that failed first": "Zuvor fehlgeschlagene Versuche", + "asked {tier}": "angefragt: {tier}", + "sent {tier}": "gesendet: {tier}", + "answered {tier}": "Antwort: {tier}", "Connecting and sending": "Verbinden und Senden", "Refresh now, the allowances too; a Claude account's is read by running Claude Code's own /usage": "Jetzt aktualisieren, auch die Kontingente; das eines Claude-Kontos wird über das eigene /usage von Claude Code gelesen", "{n} by magpie itself": "{n} von magpie selbst", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 4d750a28b..686fa0296 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -1638,6 +1638,19 @@ function renderLedReq() { pane.replaceChildren(bar, head, ledDetail(r)); } +// the service tier of a request (OpenAI's words: priority, flex, default…): +// what the client asked for, what went out to the vendor when that differs +// (a fast pick, a plan without Ultrafast), and what the vendor's reply said +// it ran at. Each is told only when the row has it: a tier the reply never +// named is not said to have been served. +function ledTierText(r) { + const parts = []; + if (r.tier_asked) parts.push(t("asked {tier}", { tier: r.tier_asked })); + if (r.tier_sent && r.tier_sent !== r.tier_asked) parts.push(t("sent {tier}", { tier: r.tier_sent })); + if (r.tier_served) parts.push(t("answered {tier}", { tier: r.tier_served })); + return parts.join(" · "); +} + // what is known of one request: when, who sent it and from where, what // it asked for and what answered, what it cost and took, the id its // vendor gave it, the path it went to, and, if it failed, what the vendor @@ -1672,6 +1685,7 @@ function ledDetail(r) { add("Sent", r.model); if (r.served) add("Served", ledServed(r)); add("Effort", r.effort); + add("Service tier", ledTierText(r)); if (ledFailed_(r)) { add("Status", r.status ? String(r.status) : "—", "bad"); add("Error type", r.err_type, "bad"); diff --git a/internal/gui/tests/ledger-service-tier.test.cjs b/internal/gui/tests/ledger-service-tier.test.cjs new file mode 100644 index 000000000..7201ea3dc --- /dev/null +++ b/internal/gui/tests/ledger-service-tier.test.cjs @@ -0,0 +1,114 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// JackyFill on X: the request log keeps each call's service tier (what the +// client asked for, what went to the vendor, what the reply said it ran at), +// and the request's details now show it as "Service tier". A tier the reply +// never named is not told as answered; a call with none shows no line. +// In Chromium and WebKit, in every language; 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 reader = require("./reader.cjs"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const now = Date.now(); + +// a counted call, 9000 of its 10000 prompt from the cache, and a Kiro one +// whose 148000 prompt no one counted: 90%, where reading Kiro's 0 as a miss +// said 9000 / 158000, 6% +const counted = { input: 500, cache_read: 9000, cache_write: 500 }; +const kiro = { input: 148000, cache_read: 0, cache_write: 0, cache_unknown: 148000, cache_unknown_calls: 1 }; +const plus = (...xs) => xs.reduce((a, x) => { for (const [k, v] of Object.entries(x)) a[k] = (a[k] || 0) + v; return a; }, {}); +const agentRow = (name, x) => ({ name, icon: "", calls: 10, errors: 0, output: 1000, reasoning: 0, cost: 0, unpriced: 0, cache_unknown: 0, ...x }); +const agents = [agentRow("Claude Code", plus(counted, kiro)), agentRow("Kiro only", kiro)]; +const usage = { calls: 20, errors: 0, output: 2000, reasoning: 0, cost: 0, unpriced: 0, path: "/test/usage.jsonl", bucket: "day", agents, models: [], series: [], ...plus(counted, kiro, kiro) }; + +const req = (i, x) => ({ + t: new Date(now - (i + 1) * 60e3).toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", + providerAccount: "a@example.com", req: "claude-sonnet-4.5", model: "claude-sonnet-4.5", served: "claude-sonnet-4.5", + ms: 3000, status: 200, rid: "r-" + i, ep: "/v1/messages", cost: 0.01, priced: true, out: 19, ...x, +}); +const ROWS = [ + req(0, { provider: "openai", providerName: "OpenAI", in: 500, tier_asked: "priority", tier_sent: "priority", tier_served: "default" }), + req(1, { provider: "openai", providerName: "OpenAI", in: 500, tier_asked: "flex", tier_sent: "default" }), + req(2, { provider: "anthropic", providerName: "Anthropic", in: 500 }), +]; +const page = (q) => ({ period: q.get("period"), rows: ROWS, offset: 0, total: ROWS.length, calls: 2, errors: 0, output: 38, reasoning: 0, cost: 0.02, unpriced: 0, + ...plus(counted, kiro), bucket: "day", series: [], by: { provider: [], agent: [], model: [] }, agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }] }); + +function serve(lang) { + 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:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) await new Promise((r) => setTimeout(r, 20e3)); + return json({ mine: true, now: new Date(now).toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [], models: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, calls: [], groups: [] } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/requests") return json(page(url.searchParams)); + if (url.pathname === "/api/usage/requests/content") return json({ found: false, why: "read" }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json(usage); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} }); + if (url.pathname.startsWith("/api/window/")) return route.fulfill({ status: 204 }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404 }); } + }; +} + +const LANGS = ["en", "zh", "zh-TW", "ja", "de"]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a request's details show its service tier`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of LANGS) { + await t.test(lang, async () => { + const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" }); + const errors = []; + try { + const p = await context.newPage(); + p.setDefaultTimeout(5000); + p.setDefaultNavigationTimeout(60000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", serve(lang)); + await p.goto("http://magpie.test/?view=usage"); + const say = (s, v) => p.evaluate(([s, v]) => t(s, v), [s, v]); + const label = await say("Service tier"); + if (lang !== "en") assert.notEqual(label, "Service tier", "translated"); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + const rows = p.locator(".led tbody tr.led-row"); + await rows.nth(ROWS.length - 1).waitFor({ timeout: 15000 }); + const tier = async (i) => { + const d = await reader.openRequest(p, rows.nth(i)); + const v = await d.evaluate((b, l) => { + const dt = [...b.querySelectorAll("dt")].find((x) => x.textContent === l); + return dt ? dt.nextElementSibling.textContent : null; + }, label); + await reader.closeRequest(p); + return v; + }; + // asked, sent (same, so told once) and answered + assert.equal(await tier(0), [await say("asked {tier}", { tier: "priority" }), await say("answered {tier}", { tier: "default" })].join(" · ")); + // asked and sent differ, no answer: the answer is not invented + assert.equal(await tier(1), [await say("asked {tier}", { tier: "flex" }), await say("sent {tier}", { tier: "default" })].join(" · ")); + // none: no line + assert.equal(await tier(2), null); + assert.deepEqual(errors, []); + } finally { + await context.close(); + } + }); + } + }); +}