diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 302ca5d03..bf449b629 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -11318,8 +11318,9 @@ function closeProtoMenu() { // openProtoMenu picks one of opts, or several when value is a list: each // ticked or unticked in turn with the menu kept open, choose given the // ticked ones, in the menu's order, once it closes (and only if they -// changed); "" is none of them and closes it, "\x00" a note to read. -function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key speaks", cls = "", align = "left") { +// changed). With live, choose runs after each tick instead; "" is none +// of them and closes it, "\x00" a note to read. +function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key speaks", cls = "", align = "left", live = false) { closeProtoMenu(); const multi = Array.isArray(value); let picked = multi ? [...value] : null; @@ -11345,9 +11346,13 @@ function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key sp e.stopPropagation(); if (!multi) { closeProtoMenu(); choose(o.v); return; } if (o.v === "\x00") return; - if (!o.v) { picked = []; closeProtoMenu(); return; } + if (!o.v) { picked = []; closeProtoMenu(); if (live) choose([]); return; } picked = picked.includes(o.v) ? picked.filter((v) => v !== o.v) : [...picked, o.v]; items.forEach((it, i) => tick(it, opts[i])); + if (live) { + choose(opts.map((o) => o.v).filter((v) => picked.includes(v))); + b.focus({ preventScroll: true }); + } }; b.onmouseenter = () => b.focus({ preventScroll: true }); box.append(b); @@ -11386,7 +11391,7 @@ function openProtoMenu(anchor, opts, value, choose, head = "Protocol this key sp document.addEventListener("keydown", keys, true); document.addEventListener("scroll", scroll, true); addEventListener("resize", closeProtoMenu); - const done = multi ? () => { + const done = multi && !live ? () => { if (picked.length === value.length && picked.every((v) => value.includes(v))) return; choose(opts.map((o) => o.v).filter((v) => picked.includes(v))); } : null; diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 704ea9c94..6a50c0820 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1814,6 +1814,19 @@ const I18N = { "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Agent 会话文件中没有此请求:文件可能已删除、移走或尚未写入", "The session file couldn't be read": "会话文件读取失败", "Cache hit rate": "缓存命中率", + "Metrics": "指标", + "Token breakdown": "Token 明细", + "Input (uncached)": "输入(未缓存)", + "No token breakdown was recorded": "没有记录 Token 明细", + "Includes token usage from billable retries; the row totals show the final attempts": "包含计费重试的用量;列表总量为最终尝试的用量", + "Breakdown available for {n} of {total} requests": "{total} 个请求中有 {n} 个记录了明细", + "Avg. cache": "平均缓存", + "Avg. speed": "平均速率", + "Metrics to show": "选择显示的指标", + "request cache hit rate {p}": "请求缓存命中率 {p}", + "Based on {n} of {total} completed requests": "基于 {total} 个已完成请求中的 {n} 个", + "Total cache reads divided by total prompt tokens; larger prompts carry more weight": "缓存读取总量除以输入 token 总量;输入越大的请求权重越高", + "Total output tokens divided by total decode time; excludes waiting and replies without usable timing": "输出 token 总量除以输出耗时总和;不计等待时间及缺少有效计时的回复", "Usage trend": "使用趋势", "Split by": "拆分维度", "5 s": "5 秒", @@ -2819,15 +2832,15 @@ const I18N = { "Output speed": "输出速度", "first token in {ms} on average": "首字平均 {ms}", "no streamed replies timed": "没有可计时的流式回复", - "Output tokens a second after the first, over the streamed replies": "流式回复从首字起每秒输出的 token 数", + "Output tokens a second after the first, over the streamed replies": "流式回复从首响起每秒输出的 token 数", "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", "Not streamed: no first token to time a speed from": "非流式:没有首字时间,算不出速度", "Cache": "缓存", "{w} written · {r} read": "写入 {w} · 读取 {r}", - "first token in {ms}": "{ms} 后出首个 token", - "first text in {ms}": "{ms} 后出首字", + "first token in {ms}": "{ms} 后首响", + "first text in {ms}": "{ms} 后出现正文", "{n} tok/s": "{n} token/秒", "requested {sent} · served {served}": "请求 {sent} · 实际 {served}", "served {served}": "实际 {served}", @@ -5221,6 +5234,19 @@ const I18N = { "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "このリクエストはエージェントのセッションファイルにありません。削除・移動されたか、まだ書き込まれていない可能性があります", "The session file couldn't be read": "セッションファイルを読み取れませんでした", "Cache hit rate": "キャッシュヒット率", + "Metrics": "指標", + "Token breakdown": "トークン内訳", + "Input (uncached)": "入力(非キャッシュ)", + "No token breakdown was recorded": "トークン内訳は記録されていません", + "Includes token usage from billable retries; the row totals show the final attempts": "課金対象の再試行の使用量を含みます。リストの合計は最後の試行の使用量です", + "Breakdown available for {n} of {total} requests": "{total} 件中 {n} 件に内訳が記録されています", + "Avg. cache": "平均キャッシュ", + "Avg. speed": "平均速度", + "Metrics to show": "表示する指標", + "request cache hit rate {p}": "リクエストのキャッシュヒット率 {p}", + "Based on {n} of {total} completed requests": "完了した {total} 件中 {n} 件に基づく", + "Total cache reads divided by total prompt tokens; larger prompts carry more weight": "キャッシュ読み取り合計を入力トークン合計で割った値。入力が多いリクエストほど重みが大きくなります", + "Total output tokens divided by total decode time; excludes waiting and replies without usable timing": "出力トークン合計を生成時間の合計で割った値。待ち時間と有効な計測のない応答は除きます", "Usage trend": "使用量の推移", "Split by": "分割", "5 s": "5 秒", @@ -8608,6 +8634,19 @@ const I18N = { "This request isn't in the agent's session files: they may be deleted, moved, or not written yet": "Diese Anfrage ist nicht in den Sitzungsdateien des Agenten: Die Dateien wurden eventuell gelöscht, verschoben oder noch nicht geschrieben", "The session file couldn't be read": "Die Sitzungsdatei konnte nicht gelesen werden", "Cache hit rate": "Cache-Trefferquote", + "Metrics": "Kennzahlen", + "Token breakdown": "Token-Aufschlüsselung", + "Input (uncached)": "Eingabe (nicht gecacht)", + "No token breakdown was recorded": "Keine Token-Aufschlüsselung aufgezeichnet", + "Includes token usage from billable retries; the row totals show the final attempts": "Enthält die Nutzung abrechenbarer Wiederholungen; die Listensummen zeigen die letzten Versuche", + "Breakdown available for {n} of {total} requests": "Aufschlüsselung für {n} von {total} Anfragen verfügbar", + "Avg. cache": "Ø Cache", + "Avg. speed": "Ø Tempo", + "Metrics to show": "Angezeigte Kennzahlen", + "request cache hit rate {p}": "Cache-Trefferquote der Anfrage {p}", + "Based on {n} of {total} completed requests": "Basierend auf {n} von {total} abgeschlossenen Anfragen", + "Total cache reads divided by total prompt tokens; larger prompts carry more weight": "Gesamte Cache-Lese-Token geteilt durch gesamte Eingabe-Token; größere Eingaben erhalten mehr Gewicht", + "Total output tokens divided by total decode time; excludes waiting and replies without usable timing": "Gesamte Ausgabe-Token geteilt durch gesamte Generierungszeit; ohne Wartezeit und Antworten ohne brauchbare Zeitmessung", "Usage trend": "Nutzungsverlauf", "Split by": "Aufteilen nach", "5 s": "5 s", diff --git a/internal/gui/assets/routing.css b/internal/gui/assets/routing.css index 4884c7130..72f3dd84e 100644 --- a/internal/gui/assets/routing.css +++ b/internal/gui/assets/routing.css @@ -153,7 +153,7 @@ their own, they take what the requests give the row, and no less than a few accounts' */ @container rt-more (min-width: 860px) { - .rt-cols { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .rt-cols { grid-template-columns: minmax(0, 1fr) clamp(280px, 32%, 400px); } .rt-cols:not(.solo) .rt-col:last-child { display: flex; flex-direction: column; } .rt-cols:not(.solo) .rt-acts { flex: 1 1 auto; height: 0; min-height: 216px; overflow-y: auto; overscroll-behavior: contain; } } @@ -200,14 +200,23 @@ /* short of room, where it went gives way down to the provider's name, then this does */ .rt-req .to:has(.upstream) .said { min-width: min(10em, 45%); } .rt-req .to .upstream, .pr-to .upstream { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; font-size: 10.5px; line-height: 16px; color: var(--muted); white-space: nowrap; } -.rt-req .meta { color: var(--muted); font-variant-numeric: tabular-nums; white-space: nowrap; text-align: right; } -.rt-req .meta .cost { display: inline-block; margin-left: 10px; color: var(--fg-2); } +.rt-req .meta { display: flex; align-items: baseline; justify-content: flex-end; flex-wrap: wrap; gap: 2px 0; color: var(--muted); font-variant-numeric: tabular-nums; } +.rt-metric { display: inline-flex; align-items: baseline; gap: 4px; white-space: nowrap; min-width: 0; } +.rt-metric .k { color: var(--muted); } +.rt-metric .v { font-variant-numeric: tabular-nums; } +.rt-req .tokens, .rt-session .rt-token-total { cursor: help; } +.rt-req .meta .retry-count { white-space: nowrap; } +.rt-req .meta > * + .rt-metric::before { content: "·"; margin: 0 2px; } +.rt-req .meta .cost-metric { margin-left: 10px; color: var(--fg-2); } +.rt-req .meta .cost-metric::before { display: none; } +.rt-req .meta[hidden] { display: none; } .rt-session { grid-column: 1 / -1; display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; min-width: 0; padding: 9px 8px; margin-top: 4px; font: inherit; font-size: 12px; text-align: left; color: var(--fg-2); background: var(--card-2); border: 1px solid var(--line); border-radius: 8px; } button.rt-session { cursor: pointer; } .rt-session .arrow { flex: none; width: 10px; color: var(--muted); } .rt-session .nm { flex: 1 1 160px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; } -.rt-session .summary { color: var(--muted); font-variant-numeric: tabular-nums; } -.rt-session .cost { flex: none; margin-left: auto; font-variant-numeric: tabular-nums; } +.rt-session .summary { display: flex; align-items: baseline; flex-wrap: wrap; gap: 4px 10px; color: var(--muted); font-variant-numeric: tabular-nums; } +.rt-session > .cost { flex: none; margin-left: auto; font-variant-numeric: tabular-nums; } +.rt-session > .cost[hidden] { display: none; } .rt-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; } .rt-filters > .rt-days { flex: 1; min-width: 0; } .rt-group-by { flex: none; } @@ -219,6 +228,13 @@ button.rt-session { cursor: pointer; } .rt-purpose span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .rt-purpose svg { flex: none; opacity: .7; transition: transform .15s var(--ease); } .rt-purpose.open svg { transform: rotate(180deg); } +.rt-metric-pick { display: inline-flex; align-items: center; gap: 3px; height: 24px; margin-left: 6px; } +.rt-metric-pick.open svg { transform: rotate(180deg); } +.pop.proto-menu.rt-metric-menu { width: 190px; max-width: calc(100vw - 16px); background: var(--card); } +.rt-metric-menu .pm-item { align-items: center; } +.rt-metric-menu .pm-tick { height: 13px; width: 13px; border: 1px solid var(--line); border-radius: 3px; } +.rt-metric-menu .on .pm-tick { border-color: var(--muted); } +.rt-metric-menu .pm-note { display: none; } .rt-purpose-tools.set .rt-purpose { color: var(--fg-2); } .rt-purpose-clear { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 24px; padding: 0; } .pop.proto-menu.rt-purpose-menu { width: 190px; max-width: calc(100vw - 16px); background: var(--card); } @@ -229,20 +245,14 @@ button.rt-session { cursor: pointer; } #view-routing .rt-req-head .note { flex: 1 1 100%; order: 1; margin: 2px 0 0; } .rt-purpose { max-width: 150px; } } -/* one line wants room for the time, the model, where it went at what - reasoning, and the numbers; in less, where it went and the numbers share - a line under the model, and in less still each has a line of its own */ -@container (max-width: 640px) { - .rt-reqs { grid-template-columns: auto minmax(0, 1fr) auto; } - .rt-req { row-gap: 2px; } - .rt-req .asked { grid-column: 2 / -1; } - .rt-req .to { grid-column: 2; } - .rt-req .meta { grid-column: 3; } -} -@container (max-width: 460px) { +/* Keep the compact row on wide lists. In a narrow column the destination + and the metrics go under the model; individual metrics stay whole. */ +@container (max-width: 760px) { .rt-reqs { grid-template-columns: auto minmax(0, 1fr); } - .rt-req .asked, .rt-req .to, .rt-req .meta { grid-column: 2; } - .rt-req .meta { text-align: left; white-space: normal; } + .rt-req { row-gap: 2px; } + .rt-req .asked { grid-column: 2; grid-row: 1; } + .rt-req .to { grid-column: 2; grid-row: 2; } + .rt-req .meta { grid-column: 2; grid-row: 3; justify-content: flex-start; } } .rt-acts { padding: 4px 0; } .rt-cols.solo { grid-template-columns: minmax(0, 1fr); } @@ -264,6 +274,7 @@ button.rt-session { cursor: pointer; } .rt-act .tally { display: flex; flex-wrap: wrap; gap: 2px 12px; color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; } .rt-act .tally .bad { color: var(--red); } .rt-act .mdls { display: flex; flex-wrap: wrap; gap: 4px; } +.rt-act .mdls code { min-width: 0; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .rt-act .fix { display: flex; flex-wrap: wrap; gap: 2px 12px; font-size: 11px; } .rt-act .bar { height: 3px; border-radius: 2px; background: var(--card-2); overflow: hidden; } .rt-act .bar i { display: block; height: 100%; border-radius: 2px; background: var(--muted); } @@ -566,10 +577,7 @@ button.rt-session { cursor: pointer; } .pr-to .swap { flex: none; max-width: 45%; overflow: hidden; text-overflow: ellipsis; font-size: 10.5px; line-height: 16px; padding: 0 5px; border-radius: 5px; color: var(--amber); background: var(--amber-soft); white-space: nowrap; } .pr-req .meta { justify-self: end; color: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; white-space: nowrap; text-align: right; } @media (prefers-reduced-motion: reduce) { .pr-req.wait .pr-to > i, .ps-dst.wait > i, .ps-hub.busy, .ps-dot.wait { animation: none; } } -/* Safari before 16 (macOS 12's, #220) has neither container queries nor - subgrid: there the narrow layouts above go by the window's width (the - tray panel is narrower than any of them), and a request's row sets out - its own columns */ +/* Before Safari 16 the narrow layouts go by the window's width. */ @supports not (container-type: inline-size) { @media (max-width: 560px) { .rt-stage { grid-template-columns: 1fr 1fr; column-gap: 28px; row-gap: 26px; padding: 16px 0; } @@ -589,7 +597,8 @@ button.rt-session { cursor: pointer; } @media (max-width: 700px) { .rt-reqs { grid-template-columns: auto minmax(0, 1fr); } .rt-req { grid-template-columns: auto minmax(0, 1fr); row-gap: 2px; } - .rt-req .to { grid-column: 2; } - .rt-req .meta { grid-column: 2; text-align: left; white-space: normal; } + .rt-req .asked { grid-column: 2; grid-row: 1; } + .rt-req .to { grid-column: 2; grid-row: 2; } + .rt-req .meta { grid-column: 2; grid-row: 3; justify-content: flex-start; } } } diff --git a/internal/gui/assets/routing.js b/internal/gui/assets/routing.js index 55a31f3f6..d7ab7ae60 100644 --- a/internal/gui/assets/routing.js +++ b/internal/gui/assets/routing.js @@ -125,6 +125,28 @@ purposeClear.id = "rtPurposeClear"; purposeClear.append(svg(CROSS, 11, 1.6)); purposeTools.append(purposePick, purposeClear); + const metricOptions = [["duration", "Duration"], ["ttft", "First token"], ["tokens", "Tokens"], + ["cache", "Cache hit rate"], ["speed", "Output speed"], ["cost", "Cost"]]; + let visibleMetrics = metricOptions.map(([key]) => key); + try { + const saved = JSON.parse(localStorage.getItem("magpie.routingMetrics")); + if (Array.isArray(saved)) visibleMetrics = metricOptions.map(([key]) => key).filter((key) => saved.includes(key)); + } catch {} + const metricPick = el("button", "text rt-metric-pick"), metricLabel = el("span"); + metricPick.type = "button"; + metricPick.id = "rtMetrics"; + metricPick.setAttribute("aria-haspopup", "menu"); + metricPick.setAttribute("aria-expanded", "false"); + metricPick.append(metricLabel, svg(CHEV, 11, 1.6)); + metricPick.onclick = (e) => { + e.stopPropagation(); + if (metricPick.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(metricPick, metricOptions.map(([v, name]) => ({ v, name, note: "" })), visibleMetrics, (keys) => { + visibleMetrics = keys; + try { localStorage.setItem("magpie.routingMetrics", JSON.stringify(keys)); } catch {} + steady(renderHist); + }, "Metrics to show", "rt-metric-menu", "right", true); + }; let purpose = ""; purposeClear.onclick = () => { closeProtoMenu(); @@ -174,12 +196,69 @@ // 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; + function promptOf(r) { + let prompt = 0, read = 0; + // Input excludes both cache tiers. Include writes in the denominator, + // and every billable try, as the request's cost does. Older history + // without the tiers cannot tell a hit rate, even when it has tokens. + for (const u of r.usage || []) { + read += u.cache_read || 0; + prompt += (u.in || 0) + (u.cache_read || 0) + (u.cache_write || 0); + } + return { prompt, read }; + } + function tokenBreakdown(rs) { + let input = 0, output = 0, read = 0, write = 0, recorded = 0; + for (const r of rs) { + if (!r.usage?.length) continue; + recorded++; + for (const u of r.usage) { + input += u.in || 0; output += u.out || 0; + read += u.cache_read || 0; write += u.cache_write || 0; + } + } + if (!recorded) return t("No token breakdown was recorded"); + // The recorded tiers are disjoint: cached input is not counted again + // as uncached input, nor is reasoning counted again outside output. + const lines = [t("Token breakdown"), ...[["Input (uncached)", input], ["Output", output], ["Cache read", read], ["Cache write", write]] + .map(([label, n]) => t(label) + ": " + ledNum(n))]; + if (rs.some((r) => r.tries.length > 1)) lines.push(t("Includes token usage from billable retries; the row totals show the final attempts")); + if (recorded < rs.length) lines.push(t("Breakdown available for {n} of {total} requests", { n: recorded, total: rs.length })); + return lines.join("\n"); + } + function requestMetrics(r, how) { + const { prompt, read } = r.done ? promptOf(r) : { prompt: 0, read: 0 }; + // 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 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")], + tokens: ["tokens", "Tokens", r.tokens ? tokens(r.tokens) : "—", tokenBreakdown([r])], + 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")], + 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] !== "—"); + } + function metricElement([cls, label, value, help], compact = false) { + const metric = el("span", "rt-metric " + (cls === "cost" ? "cost-metric" : cls)); + if (!compact || cls === "ttft" || cls === "cache-hit") metric.append(el("span", "k", t(label))); + metric.append(el("span", "v" + (cls === "cost" ? " cost" : ""), value)); + if (compact && cls === "tokens") metric.append(el("span", "k", t("{n} tokens", { n: "" }).trim())); + metric.title = help || t(label); + return metric; + } function firstNote(r, tr) { - if (!tr.ttft) return ""; - let s = " · " + t("first token in {ms}", { ms: took(tr.ttft) }); - if (tr.firstText > tr.ttft) s += " · " + t("first text in {ms}", { ms: took(tr.firstText) }); + 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); 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) }); return s; } const tokens = (n) => n >= 1e6 ? (n / 1e6).toFixed(1) + "M" : n >= 1e3 ? (n / 1e3).toFixed(1) + "k" : String(Math.round(n)); @@ -1410,7 +1489,7 @@ // button made again each time is one WebKit may drop a click on const reqLabel = el("span", "label"), replayAll = el("button", "text"); replayAll.onclick = () => replay(listed(), pinned); - reqHead.append(reqLabel, el("span", "grow"), reqNote, purposeTools, replayAll); + reqHead.append(reqLabel, el("span", "grow"), reqNote, purposeTools, metricPick, replayAll); // each request's row, kept while what it says is the same: the list // is redrawn on every trace update, and made again whole each time it // was most of what a busy gateway cost the page (#308) @@ -1495,8 +1574,16 @@ if (r.priced) { s.cost += r.cost || 0; s.priced++; } if (!r.priced || r.unpriced) s.unpriced++; if (!r.done) s.running++; + else { + 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++; + } + } return s; - }, { cost: 0, tokens: 0, priced: 0, unpriced: 0, running: 0 }); + }, { cost: 0, tokens: 0, priced: 0, unpriced: 0, running: 0, completed: 0, prompt: 0, read: 0, cached: 0, decodeMs: 0, decodeOut: 0, timed: 0 }); setText(x.arrow, g.key ? open ? "▾" : "▸" : ""); // Background workers have their own IDs. Label groups made entirely // for one purpose without renaming a chat that also made helper calls. @@ -1508,10 +1595,26 @@ : suggestions ? kindWhy(g.r) + "\n" : g.rows.some((r) => r.parentMatched) ? t("Title requests were automatically matched using the prompt and the applied chat title.") + "\n" : ""; x.name.title = g.key ? (name ? name + "\n" : "") + purpose + t("Session id") + ": " + groupSession(g.r) : t("These requests did not provide a session ID; they are not treated as one conversation."); - const bits = [t(g.rows.length === 1 ? "{n} request" : "{n} requests", { n: g.rows.length }), t("{n} tokens", { n: tokens(total.tokens) })]; + const bits = [t(g.rows.length === 1 ? "{n} request" : "{n} requests", { n: g.rows.length })]; + if (visibleMetrics.includes("tokens") && total.tokens) bits.push(t("{n} tokens", { n: tokens(total.tokens) })); if (total.running) bits.push(t("{n} in progress", { n: total.running })); - setText(x.meta, bits.join(" · ")); - setText(x.cost, total.priced ? "≈" + fmtCost({ cost: total.cost, unpriced: 0 }) + (total.unpriced ? "+" : "") : "—"); + const count = el("span", "session-count", bits[0]), tokenHelp = visibleMetrics.includes("tokens") && total.tokens ? tokenBreakdown(g.rows) : ""; + if (tokenHelp) { + const amount = el("span", "rt-token-total", bits[1]); + amount.title = tokenHelp; + count.append(" · ", amount); + } + if (total.running) count.append(" · " + bits[bits.length - 1]); + const meta = [count]; + const coverage = (n) => t("Based on {n} of {total} completed requests", { n, total: total.completed }); + 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)])); + 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 ? "+" : "") : ""); + x.cost.hidden = !visibleMetrics.includes("cost") || !total.priced; x.cost.title = costNote(); if (g.key) x.b.setAttribute("aria-expanded", String(open)); els.push(x.b); @@ -1536,6 +1639,8 @@ setText(purposeLabel, label); purposePick.setAttribute("aria-label", label); purposePick.title = t("Filter routing by purpose") + (purpose ? "\n" + label : ""); + setText(metricLabel, t("Metrics")); + metricPick.title = t("Metrics to show"); purposePick.onclick = (e) => { e.stopPropagation(); if (purposePick.classList.contains("open")) return closeProtoMenu(); @@ -1587,17 +1692,15 @@ const ag = agentOf(r.agent); const meta = []; if (r.tries.length > 1) meta.push(t("{n} tries", { n: r.tries.length })); - if (r.done && r.ms) meta.push(took(r.ms)); - if (r.done && r.ttft) meta.push(t("TTFT {ms}", { ms: took(r.ttft) })); - if (r.tokens) meta.push(t("{n} tokens", { n: tokens(r.tokens) })); + const metrics = requestMetrics(r, how); // all the row says, and its titles const title = reqTitle(r, how, tr); const sig = JSON.stringify([lang, said, how, title, r.time, r.agent, agentName(r.agent), ag?.icon, r.model, r.provider, r.kind, r.effort, - tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, routeCost(r)]); + tr?.effort, tr?.picked, tr?.fixed, tr?.fast, tr?.swapped && tr.done && tryOk(tr) ? [tr.model, tr.served] : 0, tr?.routed && tr.done && tryOk(tr) ? tr.served : 0, tr?.done && tryOk(tr) ? tr.upstream : 0, meta, metrics, routeCost(r)]); ids.add(r.id); let x = reqRows.get(r.id); if (!x || x.sig !== sig) { - const row = x = { sig, b: reqRow(r, said, how, tr, ag, meta, title) }; + const row = x = { sig, b: reqRow(r, said, how, tr, ag, meta, metrics, title) }; row.b.onclick = () => pick(row.r); // the request as it is when clicked reqRows.set(r.id, x); } @@ -1619,7 +1722,7 @@ } renderActs(rs); } - function reqRow(r, said, how, tr, ag, meta, title) { + function reqRow(r, said, how, tr, ag, meta, metrics, title) { const b = el("button", "rt-req " + how); const when = el("span", "at", new Date(r.time).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })); const asked = el("span", "asked"); @@ -1656,8 +1759,9 @@ else if (tr?.routed && tr.done && tryOk(tr)) to.append(routedTag(tr)); if (tr?.upstream && tr.done && tryOk(tr)) to.append(upstreamTag(tr)); const info = el("span", "meta"); - info.append(el("span", "", meta.join(" · ")), el("span", "cost", routeCost(r))); - info.lastChild.title = r.priced ? costNote() : t("No known price or token counts for this request"); + if (meta.length) info.append(el("span", "retry-count", meta.join(" · "))); + info.append(...metrics.map((m) => metricElement(m, true))); + info.hidden = !metrics.length && !meta.length; b.append(when, asked, to, info); b.title = title; diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index c1de098ab..bc674ed5b 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -1804,6 +1804,40 @@ compare the same completed API state rather than a loading-order difference. node --test internal/gui/tests/mobile-web.test.cjs internal/gui/tests/old-webkit.test.cjs ``` +## Routing request metrics + +`routing-request-metrics.test.cjs` checks request-row cache hit rates (cache +reads divided by uncached input, cache reads and cache writes across billable +tries) and output speeds (reply output over the time after its first token). +It covers known zero hits, missing historical tiers, unstreamed and burst +replies, retries, unfinished and failed requests, the cache-rate description +in the story, weighted session cache rates and decode speeds (with coverage +in tooltips), folds, history, live updates, narrow layouts and persisted +metric choices. Missing values are omitted from request rows and session +headings; known zero cache rates and costs remain visible. The first-token +label matches the metric picker and the Chinese routing story. +Request and session token totals have tooltips with exact uncached input, +output, cache-read and cache-write counts. Billable retries are included and +explained; missing historical tiers and partial session coverage are explicit. +The six choices apply immediately while the menu stays open, with focus +kept on the checkbox. Mouse and keyboard changes work in both directions, +including when none are selected. +It runs in English and Chinese on Chromium and WebKit. Set `ARTIFACT_DIR` +to keep screenshots. APIs are isolated fixtures. + +```sh +node --test internal/gui/tests/routing-request-metrics.test.cjs +``` + +`routing-columns.test.cjs` checks that side-by-side requests get more room +than accounts, whose column stays between 280 and 400 CSS pixels. It checks +aligned list bottoms, account model labels, and no horizontal overflow at +940, 1100, 1440 and 1920 pixels, then the full-width stack at 700 pixels. + +```sh +node --test internal/gui/tests/routing-columns.test.cjs +``` + ## Automatic Codex title grouping `routing-sessions.test.cjs` checks automatic grouping after a Codex title write, diff --git a/internal/gui/tests/routing-burst-speed.test.cjs b/internal/gui/tests/routing-burst-speed.test.cjs index cf956415b..4c222de6d 100644 --- a/internal/gui/tests/routing-burst-speed.test.cjs +++ b/internal/gui/tests/routing-burst-speed.test.cjs @@ -51,7 +51,7 @@ function serve(lang) { const want = { en: { first: /first token in 24 s/, speed: /tok\/s/, normal: /· 100 tok\/s/, slow: /· 50 tok\/s/ }, - zh: { first: /24 秒 后出首个 token/, speed: /token\/秒/, normal: /· 100 token\/秒/, slow: /· 50 token\/秒/ }, + zh: { first: /24 秒 后首响/, speed: /token\/秒/, normal: /· 100 token\/秒/, slow: /· 50 token\/秒/ }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -71,6 +71,14 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const story = async (i) => { const row = page.locator(".rt-req").nth(i); + // Taller metric rows need the list scrolled first, with real input + // so the page's script-scroll protection keeps the same position. + const rb = await row.boundingBox(), lb = await page.locator(".rt-reqs").boundingBox(); + if (rb.y + rb.height > lb.y + lb.height) { + await page.locator(".rt-reqs").hover(); + await page.mouse.wheel(0, rb.y + rb.height - lb.y - lb.height + 6); + await page.waitForTimeout(200); + } const was = await row.evaluate((e) => e.getBoundingClientRect().top); const scrolled = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]); await row.click(); diff --git a/internal/gui/tests/routing-columns.test.cjs b/internal/gui/tests/routing-columns.test.cjs index 9279dc99d..2d3a8b87e 100644 --- a/internal/gui/tests/routing-columns.test.cjs +++ b/internal/gui/tests/routing-columns.test.cjs @@ -84,6 +84,19 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert(acts.left >= reqs.right, "side by side"); assert(Math.abs(acts.bottom - reqs.bottom) <= 1, `the lists end on one line: ${reqs.bottom} / ${acts.bottom}`); assert(acts.scroll, "the rest of the accounts scroll"); + for (const width of [940, 1100, 1440, 1920]) { + await page.setViewportSize({ width, height: 1400 }); + await page.waitForTimeout(200); + const requests = await box(".rt-col:first-child"), accounts = await box(".rt-col:last-child"); + const rw = requests.right - requests.left, aw = accounts.right - accounts.left; + assert(rw > aw * 1.6, `${width}px: requests should have more room than accounts (${rw} / ${aw})`); + assert(aw >= 280 && aw <= 400.5, `${width}px: account column stays readable and capped (${aw})`); + const rightList = await box(".rt-acts"), leftList = await box(".rt-reqs"); + assert(Math.abs(rightList.bottom - leftList.bottom) <= 1, `${width}px: list bottoms stay aligned`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `${width}px: no horizontal overflow`); + const clipped = await page.locator(".rt-act .mdls code").evaluateAll((es) => es.some((e) => e.getBoundingClientRect().right > e.closest(".rt-act").getBoundingClientRect().right + 1)); + assert.equal(clipped, false, `${width}px: models stay inside the narrower account column`); + } // the Codex account's three models on their own line, none in the tally const codex = page.locator(".rt-act", { hasText: "ann@example.com" }); diff --git a/internal/gui/tests/routing-effort-change.test.cjs b/internal/gui/tests/routing-effort-change.test.cjs index 5219508c7..e731a5526 100644 --- a/internal/gui/tests/routing-effort-change.test.cjs +++ b/internal/gui/tests/routing-effort-change.test.cjs @@ -48,6 +48,7 @@ const efText = (x) => x.asked !== x.sent ? `${x.asked} → ${x.sent}` : x.sent; // each row is a grid of its own, sized by its own numbers, and the // narrower layouts follow the window. The styles are served as it reads them const safari15 = (css) => css + .replace(/@supports not \(container-type: inline-size\)/g, "@supports (display: grid)") .replace(/@supports not \(grid-template-columns: subgrid\)/g, "@supports (display: grid)") .replace(/grid-template-columns: subgrid/g, "grid-template-columns: x-subgrid") .replace(/@container[^{]*\{/g, "@media (max-width: 0px) {"); @@ -145,8 +146,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } } // the numbers stay whole - const meta = await page.locator(".rt-req").nth(1).locator(".meta > span").first().textContent(); - assert.match(meta, lang === "zh" ? /^15 秒 · 首字 14 秒 · 6\.9k token$/ : /^15 s · TTFT 14 s · 6\.9k tokens$/, `${width}px`); + const meta = page.locator(".rt-req").nth(1).locator(".meta"); + assert.equal(await meta.locator(".duration .v").textContent(), lang === "zh" ? "15 秒" : "15 s", `${width}px`); + assert.equal(await meta.locator(".ttft .v").textContent(), lang === "zh" ? "14 秒" : "14 s", `${width}px`); + assert.equal(await meta.locator(".tokens .v").textContent(), "6.9k", `${width}px`); // where it went and the level asked for give way first: the level // sent is whole in every row, at every width const cut = await page.locator(".rt-req .ef").evaluateAll((es) => es.map((e) => { diff --git a/internal/gui/tests/routing-effort-row.test.cjs b/internal/gui/tests/routing-effort-row.test.cjs index 0bee1bfa5..ba5262460 100644 --- a/internal/gui/tests/routing-effort-row.test.cjs +++ b/internal/gui/tests/routing-effort-row.test.cjs @@ -115,9 +115,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", } } // the answered rows keep all their numbers - const meta = await page.locator(".rt-req").nth(1).locator(".meta > span").first().textContent(); - assert.match(meta, lang === "zh" ? /秒 · 首字 4\.6 秒 · 142\.4k token$/ : /s · TTFT 4\.6 s · 142\.4k tokens$/); - assert.equal(await page.locator(".rt-req").nth(1).locator(".meta .cost").textContent(), "—"); + const meta = page.locator(".rt-req").nth(1).locator(".meta"); + assert.equal(await meta.locator(".ttft .v").textContent(), lang === "zh" ? "4.6 秒" : "4.6 s"); + assert.equal(await meta.locator(".tokens .v").textContent(), "142.4k"); + assert.equal(await page.locator(".rt-req").nth(1).locator(".meta .cost").count(), 0, "unknown cost is omitted"); // no stripe down a row's side assert.equal(await page.locator(".rt-req").first().evaluate((e) => getComputedStyle(e).borderLeftColor === getComputedStyle(e).borderTopColor), true); assert.deepEqual(errors, []); diff --git a/internal/gui/tests/routing-request-metrics.test.cjs b/internal/gui/tests/routing-request-metrics.test.cjs new file mode 100644 index 000000000..a274a2a92 --- /dev/null +++ b/internal/gui/tests/routing-request-metrics.test.cjs @@ -0,0 +1,222 @@ +// Request rows use the recorded prompt tiers and the reply's decode window, +// in live and historical lists, grouped or flat. No user state is accessed. +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 tier = (input, read = 0, write = 0, out = 400) => ({ provider: seat.provider, model: seat.model, in: input, out, cache_read: read, cache_write: write }); +function req(id, usage, extra = {}) { + const time = new Date(now.getTime() - (20 - id) * 60e3).toISOString(); + return { id, seq: id, time, agent: "codex", session: "metrics-chat", model: "codex/gpt-6.1-sol", provider: "codex", + order: [seat], tries: [{ id: seat.id, model: seat.model, effort: "xhigh", start: time, done: true, status: 200, ms: 11000, ttft: 7000 }], + done: true, status: 200, ms: 11000, ttft: 7000, tokens: 5400, out: 400, usage, priced: true, cost: 0.01, ...extra }; +} +const fixtures = [ + // The prompt is 5000 tokens: cache writes belong in its denominator. + req(12, [tier(1000, 3000, 1000)]), + req(11, [tier(1000)], { out: 2000, ms: 17000, cost: 0 }), // known zero hits and cost; 200 tok/s + req(10, [tier(0, 5000)]), // every input token cached + req(9, undefined), // older history has no tiers + req(8, [tier(0, 0, 0)]), // output only: no prompt ratio + req(7, [tier(1000, 3000, 1000)], { ttft: 0 }), // unstreamed: no speed + req(6, [tier(1000, 3000, 1000)], { out: 8264, ms: 24360, ttft: 24359 }), + req(5, [tier(1000, 3000, 1000)], { out: 8264, ms: 1500, ttft: 1000 }), + // One refused try cost tokens too. The final reply is 400 tokens over + // four seconds, after a ten-second retry delay, not 1000 over 21 seconds. + req(4, [tier(1000, 0, 1000, 600), tier(1000, 6000, 1000)], { + ms: 21000, ttft: 17000, + tries: [{ id: seat.id, model: seat.model, start: now.toISOString(), done: true, status: 200, fail: "refused", ms: 10000 }, + { id: seat.id, model: seat.model, effort: "xhigh", start: now.toISOString(), done: true, status: 200, ms: 11000, ttft: 7000 }], + }), + req(3, [tier(1000, 3000, 1000)], { done: false }), + req(2, [tier(1000, 3000, 1000)], { out: 0 }), + req(1, [tier(1000, 3000, 1000)], { tries: [{ id: seat.id, start: now.toISOString(), done: true, status: 200, fail: "other", ms: 11000, ttft: 7000 }] }), + req(0, undefined, { session: "unknown-metrics", tokens: 0, out: 0, ms: 0, ttft: 0, priced: false, cost: 0 }), +]; + +function serve(lang, feed) { + 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:"dark",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", fields: [] }], profiles: [], settings: { lang, theme: "dark" } }); + if (url.pathname === "/api/gateway/trace") { + const routes = url.searchParams.has("wait") ? await new Promise((resolve) => { feed.next = resolve; }) : fixtures; + return json({ mine: true, now: now.toISOString(), seq: feed.seq || 12, totals: { requests: fixtures.length, rerouted: 1, errors: 1 }, routes }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day, requests: fixtures.length }], routes: url.searchParams.get("day") ? fixtures : [] }); + if (url.pathname === "/api/gateway/session-titles") return json({ "metrics-chat": "Request metrics" }); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true, window: true } }); + 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 }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + test(`${engine} ${lang}: request cache rates and output speeds survive grouping, history and live updates`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" }); + page.setDefaultTimeout(5000); + const feed = {}, errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, feed)); + t.after(async () => { feed.next?.([]); await browser.close(); }); + await page.goto("http://magpie.test/?view=routing"); + const rows = page.locator(".rt-req"); + await rows.nth(fixtures.length - 1).waitFor(); + const check = async () => { + assert.equal(await rows.nth(0).locator(".cache-hit .v").textContent(), "60%"); + assert.match(await rows.nth(0).locator(".cache-hit").getAttribute("title"), lang === "zh" ? /缓存命中率.*提示词/ : /Cache hit rate.*prompt/); + assert.match(await rows.nth(0).locator(".speed .v").textContent(), lang === "zh" ? /^100 token\/秒$/ : /^100 tok\/s$/); + assert.match(await rows.nth(1).locator(".cache-hit .v").textContent(), /0%$/); + assert.match(await rows.nth(2).locator(".cache-hit .v").textContent(), /100%$/); + assert.equal(await rows.nth(1).locator(".cost").textContent(), "≈$0.000", "known zero cost remains visible"); + assert.equal(await rows.nth(3).locator(".cache-hit").count(), 0, "legacy totals cannot establish a cache rate"); + assert.equal(await rows.nth(4).locator(".cache-hit").count(), 0, "output is not part of the prompt"); + for (const i of [5, 6, 7, 9, 10, 11]) assert.equal(await rows.nth(i).locator(".speed").count(), 0, `row ${i} has no measured output speed`); + assert.match(await rows.nth(8).locator(".cache-hit").textContent(), /60%$/, "sum the billable prompt tiers across retries"); + assert.match(await rows.nth(8).locator(".speed .v").textContent(), /^100 /, "retry wait and earlier output do not change decode speed"); + assert.equal(await rows.nth(9).locator(".cache-hit").count(), 0, "a request still underway has no final rate"); + assert.equal(await rows.nth(12).locator(".meta").isVisible(), false, "a row with no available metrics has no empty band"); + assert.equal(await rows.locator(".rt-metric").filter({ hasText: "—" }).count(), 0, "unavailable metrics leave no dash placeholders"); + assert.equal(await rows.nth(0).locator(".ttft .k").textContent(), lang === "zh" ? "首响" : "First token"); + const labels = lang === "zh" ? ["Token 明细", "输入(未缓存)", "输出", "缓存读取", "缓存写入"] + : ["Token breakdown", "Input (uncached)", "Output", "Cache read", "Cache write"]; + assert.equal(await rows.nth(0).locator(".tokens").getAttribute("title"), + [labels[0], labels[1] + ": 1,000", labels[2] + ": 400", labels[3] + ": 3,000", labels[4] + ": 1,000"].join("\n"), + "the tooltip shows exact, disjoint input, output and cache tiers"); + assert.match(await rows.nth(1).locator(".tokens").getAttribute("title"), new RegExp(labels[3] + ": 0"), "recorded zero cache tiers are shown"); + assert.equal(await rows.nth(3).locator(".tokens").getAttribute("title"), lang === "zh" ? "没有记录 Token 明细" : "No token breakdown was recorded", "missing historical tiers are not invented"); + const retry = await rows.nth(8).locator(".tokens").getAttribute("title"); + assert(retry.includes(labels[1] + ": 2,000") && retry.includes(labels[2] + ": 1,000") && retry.includes(labels[3] + ": 6,000") && retry.includes(labels[4] + ": 2,000"), + "billable retry tiers are included in the breakdown, including earlier output"); + assert.match(retry, lang === "zh" ? /计费重试.*最终尝试/ : /billable retries.*final attempts/, "retry totals are explained"); + }; + await check(); + await page.locator(".rt-group-by button").nth(1).click(); + const group = page.locator("button.rt-session").filter({ hasText: /metrics-chat|Request metrics/ }); + await group.waitFor(); + await check(); + const unknown = page.locator("button.rt-session").filter({ hasText: "unknown-metrics" }); + assert.equal(await unknown.locator(".rt-metric").count(), 0, "a session with no measured cache or speed omits both"); + assert.equal(await unknown.locator(".cost").isVisible(), false, "a session with unknown cost omits it"); + assert.doesNotMatch(await unknown.locator(".summary").textContent(), /token|—/, "a session without token counts has no fake zero or dash"); + assert.equal(await group.locator(".cache-hit .v").textContent(), "63%", "cache average is weighted by prompt tokens, not by request count"); + assert.match(await group.locator(".speed .v").textContent(), /^133 /, "speed is output divided by summed decode windows, not the mean of individual speeds"); + assert.match(await group.locator(".cache-hit").getAttribute("title"), /9.*11|11.*9/, "unknown and unfinished requests are excluded and coverage is disclosed"); + assert.match(await group.locator(".rt-token-total").getAttribute("title"), /11.*12|12.*11/, "session token breakdown discloses missing records"); + await group.click(); + assert.equal(await group.getAttribute("aria-expanded"), "false"); + assert.equal(await group.locator(".cache-hit .v").textContent(), "63%", "closed sessions retain their metrics"); + await group.click(); + await rows.nth(0).click(); + assert.match(await page.locator(".rt-steps").textContent(), lang === "zh" ? /请求缓存命中率 60%/ : /request cache hit rate 60%/); + if (lang === "zh") { + assert.match(await page.locator(".rt-steps").textContent(), /后首响/); + assert.doesNotMatch(await page.locator(".rt-steps").textContent(), /首字/); + } + for (const width of [1280, 1000, 700, 480, 360]) { + await page.setViewportSize({ width, height: 900 }); + await page.waitForTimeout(100); + const boxes = await rows.nth(0).evaluate((row) => { + const box = (e) => { const r = e.getBoundingClientRect(); return { left: r.left, right: r.right, top: r.top, bottom: r.bottom }; }; + return { row: box(row), meta: box(row.querySelector(".meta")), to: box(row.querySelector(".to")), + metrics: [...row.querySelectorAll(".cache-hit, .speed, .cost")].map((e) => ({ ...box(e), clipped: e.scrollWidth > e.clientWidth + 1 })) }; + }); + for (const b of boxes.metrics) { + assert(!b.clipped, `metric clipped at ${width}px`); + assert(b.left >= boxes.row.left && b.right <= boxes.row.right, `metric outside row at ${width}px: ${JSON.stringify(boxes)}`); + } + assert(boxes.meta.left >= boxes.to.right - 1 || boxes.meta.top >= boxes.to.bottom - 1, `metadata overlaps destination at ${width}px`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `horizontal page overflow at ${width}px`); + if (width === 480) { + await page.locator("#rtMetrics").click(); + const menu = page.locator(".rt-metric-menu"); + const cost = menu.getByRole("menuitemcheckbox", { name: lang === "zh" ? "费用" : "Cost", exact: true }); + await cost.click(); + assert.equal(await rows.nth(0).locator(".cost").count(), 0, "narrow layout updates before closing the menu"); + assert.equal(await menu.isVisible(), true); + await cost.click(); + assert.equal(await rows.nth(0).locator(".cost").count(), 1); + assert.equal(await menu.isVisible(), true); + await page.keyboard.press("Escape"); + } + if (process.env.ARTIFACT_DIR && [1280, 480].includes(width)) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.locator(".rt-filters").evaluate((e) => e.scrollIntoView({ block: "start" })); + await page.locator(".rt-reqs").screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-request-metrics.png`) }); + } + } + await page.setViewportSize({ width: 1280, height: 900 }); + await page.locator(".rt-days .rt-day").nth(1).click(); + await check(); + await page.locator(".rt-days .rt-day").nth(0).click(); + await check(); + // The row signature must notice rates changing even when total tokens, + // cost, duration and first-token timing remain unchanged. + await page.waitForFunction((count) => document.querySelectorAll(".rt-req").length === count, fixtures.length); + for (let i = 0; i < 50 && !feed.next; i++) await page.waitForTimeout(20); + assert(feed.next, "live poll started"); + feed.seq = 13; + feed.next([req(12, [tier(1920, 2080, 1200, 200)], { seq: 13, out: 200 })]); + await page.waitForFunction(() => document.querySelector(".rt-req .cache-hit")?.textContent.endsWith("40%")); + assert.match(await rows.nth(0).locator(".speed .v").textContent(), /^50 /); + const updated = await rows.nth(0).locator(".tokens").getAttribute("title"); + assert.match(updated, /1,920/); + assert.match(updated, /2,080/); + assert.match(updated, /1,200/); + assert.match(await group.locator(".rt-token-total").getAttribute("title"), lang === "zh" ? /输出: 4,800/ : /Output: 4,800/, "session tooltip updates even when list token totals do not change"); + await page.locator("#rtMetrics").click(); + const menu = page.locator(".rt-metric-menu"); + assert.equal(await menu.locator('[role="menuitemcheckbox"]').count(), 6); + // Keep only cache and speed. Each click updates the list immediately, + // with the menu open and focus on the checkbox for continued selection. + const labels = lang === "zh" ? ["耗时", "首响", "Token", "费用"] : ["Duration", "First token", "Tokens", "Cost"]; + for (const [i, label] of labels.entries()) { + const option = menu.getByRole("menuitemcheckbox", { name: label, exact: true }); + await option.click(); + assert.equal(await rows.nth(0).locator(".rt-metric").count(), 5 - i, "hiding a metric is immediate"); + assert.equal(await option.getAttribute("aria-checked"), "false"); + assert.equal(await menu.isVisible(), true, "menu remains open while the list updates"); + assert.equal(await option.evaluate((e) => document.activeElement === e), true, "checkbox retains focus"); + } + const duration = menu.getByRole("menuitemcheckbox", { name: labels[0], exact: true }); + await duration.focus(); + await page.keyboard.press("Space"); + assert.equal(await rows.nth(0).locator(".duration").count(), 1, "showing a metric by keyboard is immediate"); + assert.equal(await menu.isVisible(), true); + await page.keyboard.press("Space"); + assert.equal(await rows.nth(0).locator(".duration").count(), 0); + assert.equal(await group.locator(".cost").isVisible(), false, "session cost hides before closing the menu"); + assert.doesNotMatch(await group.locator(".session-count").textContent(), /token/); + await page.keyboard.press("Escape"); + assert.equal(await page.locator("#rtMetrics").getAttribute("aria-expanded"), "false"); + assert.equal(await rows.nth(0).locator(".rt-metric").count(), 2); + assert.equal(await group.locator(".cost").isVisible(), false); + assert.doesNotMatch(await group.locator(".session-count").textContent(), /token/); + await page.reload(); + await rows.nth(fixtures.length - 1).waitFor(); + assert.equal(await rows.nth(0).locator(".rt-metric").count(), 2, "metric choices survive a reload"); + await page.locator("#rtMetrics").click(); + assert.equal(await menu.locator('[aria-checked="true"]').count(), 2); + await menu.getByRole("menuitemcheckbox", { name: lang === "zh" ? "缓存命中率" : "Cache hit rate", exact: true }).click(); + await menu.getByRole("menuitemcheckbox", { name: lang === "zh" ? "输出速度" : "Output speed", exact: true }).click(); + assert.equal(await rows.nth(0).locator(".meta").isVisible(), false, "hiding the last metric is immediate"); + assert.equal(await menu.isVisible(), true); + await page.keyboard.press("Escape"); + assert.equal(await rows.nth(0).locator(".meta").isVisible(), false, "every metric can be hidden"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/routing-sessions.test.cjs b/internal/gui/tests/routing-sessions.test.cjs index d211eb502..3693d8d36 100644 --- a/internal/gui/tests/routing-sessions.test.cjs +++ b/internal/gui/tests/routing-sessions.test.cjs @@ -65,7 +65,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await group.locator(".summary").textContent(), lang === "zh" ? /3 个请求.*6.0k/ : /3 requests.*6.0k/); assert.equal(await group.locator(".cost").textContent(), "≈$0.030+", "partial totals must be marked"); assert.equal(await page.locator("button.rt-session").filter({ hasText: "Claude Code" }).locator(".cost").textContent(), "≈$0.000", "zero price is known"); - assert.equal(await page.locator("div.rt-session .cost").textContent(), "—", "legacy requests are unknown"); + assert.equal(await page.locator("div.rt-session .cost").isVisible(), false, "unknown cost is omitted for legacy requests"); assert.equal(await page.locator(".rt-req").count(), 6); await group.click(); @@ -327,7 +327,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await group("Codex · partial").locator(".summary").textContent(), lang === "zh" ? /^1 个请求/ : /^1 request ·/); assert.equal(await group("Codex · mixed").locator(".cost").textContent(), "≈$0.000+", "a free request plus an unknown request is a partial zero estimate"); assert.match(await group("Codex · mixed").locator(".summary").textContent(), lang === "zh" ? /^2 个请求/ : /^2 requests ·/); - assert.equal(await group("Claude Code · unknown").locator(".cost").textContent(), "—", "all unknown stays unknown"); + assert.equal(await group("Claude Code · unknown").locator(".cost").isVisible(), false, "all unknown costs are omitted"); await page.evaluate(() => { currency = "cny"; fx = { rate: 7, at: null, stale: false }; renderCosts(); }); assert.equal(await group("Codex · mixed").locator(".cost").textContent(), "≈¥0.000+"); assert.equal(await page.locator(".rt-req").filter({ hasText: "model-a" }).locator(".cost").textContent(), "≈¥0.000+");