diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 80a191892..bdb21d251 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -1216,6 +1216,14 @@ body.window .field.solo { grid-column: auto; } /* a mark faster than its point's own leaves the column: the leader line ties it back, so it reads as this column's and not as a stray dash */ .led-chart line.stem { stroke-dasharray: 2 2; transition: opacity .12s; } +/* the chart as lines (molvqingtai on Discord): the pair of icons beside + the metrics, and each series' line, dots and the band under a stacked one */ +.led-style .opt { display: inline-flex; align-items: center; padding: 0 6px; } +.led-style .opt svg { display: block; } +.led-chart g.ln { fill: none; stroke-linecap: round; stroke-linejoin: round; transition: opacity .12s; } +.led-chart g.ln .line { stroke-width: 1.6; } +.led-chart g.ln .line.all { stroke-width: 1.2; stroke-dasharray: 3 3; } +.led-chart g.ln .band { stroke: none; fill-opacity: .14; } .led-chart .led-day { cursor: pointer; outline: none; } .led-chart .led-day:focus-visible { stroke: var(--accent); stroke-width: 1; } .led-chart .tip { position: absolute; top: 2px; z-index: 2; min-width: 172px; max-width: 260px; padding: 8px 10px 7px; background: var(--pop-bg); border-radius: 9px; box-shadow: var(--shadow); font-size: 11.5px; pointer-events: none; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index f2c1119fc..e6c89d510 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -18496,8 +18496,7 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) { } const topV = ledAxis(max); const selectable = l.bucket === "day" && !!box.chooseDay; - const g = sv("svg", { viewBox: `0 0 ${W} ${H}`, role: selectable ? "group" : "img" }); - g.setAttribute("aria-label", t("Usage trend")); + const g = sv("svg", { viewBox: `0 0 ${W} ${H}`, role: selectable ? "group" : "img", "aria-label": t("Usage trend") }); // the side's labels, measured as drawn: the plot starts where the widest // ends ("8000 万", "¥1250" are wider than "80M"), so none reaches past the // card's padding @@ -18537,9 +18536,7 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) { let y0 = 0; const draw = (key, color, v) => { if (!(v > 0)) return; - const r = sv("rect", { x, width: bw, y: Y(y0 + v), height: Math.max(0.5, Y(y0) - Y(y0 + v)), rx: 1, class: "col", "data-k": key, "data-day": p.time.slice(0, 10), "data-color": color }, { fill: color }); - g.append(r); - segs.push(r); + segs.push(g.appendChild(sv("rect", { x, width: bw, y: Y(y0 + v), height: Math.max(0.5, Y(y0) - Y(y0 + v)), rx: 1, class: "col", "data-k": key, "data-day": p.time.slice(0, 10), "data-color": color }, { fill: color }))); y0 += v; }; const by = p.by?.[split] || {}; @@ -18559,16 +18556,12 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) { // be drawn back down into the column if (v > totals[i]) { const top = Y(totals[i]); - const stem = sv("line", { + segs.push(g.appendChild(sv("line", { x1: x + bw / 2, x2: x + bw / 2, y1: top, y2: Math.min(Y(v) + 1.5, top), class: "col stem", "data-k": c.id, "data-day": p.time.slice(0, 10), "data-color": c.color, - }, { stroke: c.color, strokeWidth: 1, strokeOpacity: ".45" }); - g.append(stem); - segs.push(stem); + }, { stroke: c.color, strokeWidth: 1, strokeOpacity: ".45" }))); } - const r = sv("rect", { x, width: bw, y: Y(v) - 1.5, height: 3, rx: 1.5, class: "col mark", "data-k": c.id, "data-day": p.time.slice(0, 10), "data-color": c.color }, { fill: c.color }); - g.append(r); - segs.push(r); + segs.push(g.appendChild(sv("rect", { x, width: bw, y: Y(v) - 1.5, height: 3, rx: 1.5, class: "col mark", "data-k": c.id, "data-day": p.time.slice(0, 10), "data-color": c.color }, { fill: c.color }))); } return; } @@ -18576,6 +18569,8 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) { for (const c of top) { const v = ledPart(metric, by[c.id] || {}); stacked += v; draw(c.id, c.color, v); } draw("\0other", "var(--faint)", Math.max(0, totals[i] - stacked)); }); + // the Usage page's lines take the columns' place (ledLines) + box.drawn?.(g, Y, M.l + slot / 2, slot, segs); if (selectable) pts.forEach((p, i) => { const day = p.time.slice(0, 10); const hit = sv("rect", { class: "led-day", x: M.l + slot * i, y: M.t, width: slot, height: ph, fill: "transparent", role: "button", tabindex: 0, "aria-label": ledWhen(p, l.bucket), "aria-pressed": day === l.day, "data-day": day }); @@ -18632,9 +18627,8 @@ function drawLedColumns(box, l, split, metric, compact, chooseDay, focusDay) { const dimDay = l.day && r.dataset.day !== l.day; const color = dimDay ? "var(--faint)" : r.dataset.color; r.style.opacity = dimDay || key != null && r.dataset.k !== key ? ".22" : ""; - // a mark's leader line is a line, which is stroked, not filled - if (r.tagName === "line") r.style.stroke = color; - else r.style.fill = color; + // a leader line or a line chart's series is stroked, not filled + r.style[r.tagName == "rect" ? "fill" : "stroke"] = color; } }; box.emphasize(null); diff --git a/internal/gui/assets/plugins/usage/client.js b/internal/gui/assets/plugins/usage/client.js index 6708d5005..28d1e32d9 100644 --- a/internal/gui/assets/plugins/usage/client.js +++ b/internal/gui/assets/plugins/usage/client.js @@ -72,6 +72,7 @@ magpie.plugin("usage", (ctx) => {
+
Split by
diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index 4c6455899..2d3197cd6 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -2,6 +2,9 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Bar chart": "柱状图", + "Line chart": "折线图", + "Chart style": "图表样式", "(prompt not recorded)": "(未记录提示词)", "Gateway session": "网关会话", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "只经网关看到:agent 没有留下 magpie 能读的会话文件。在「会话」里开启「记录网关对话」可保留它的提示词。", @@ -200,6 +203,9 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 协议发往上游,与 agent 所用协议相同", }, "zh-TW": { + "Bar chart": "長條圖", + "Line chart": "折線圖", + "Chart style": "圖表樣式", "(prompt not recorded)": "(未記錄提示詞)", "Gateway session": "閘道會話", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "只經閘道看到:agent 沒有留下 magpie 能讀的會話檔案。在「會話」裡開啟「記錄閘道對話」可保留它的提示詞。", @@ -398,6 +404,9 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "以 {to} 協議發往上游,與 agent 所用協議相同", }, ja: { + "Bar chart": "棒グラフ", + "Line chart": "折れ線グラフ", + "Chart style": "グラフの種類", "(prompt not recorded)": "(プロンプト未記録)", "Gateway session": "ゲートウェイのセッション", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "ゲートウェイ経由でのみ確認:エージェントは magpie が読めるセッションファイルを残していません。「セッション」で「ゲートウェイの会話を記録」をオンにするとプロンプトが残ります。", @@ -596,6 +605,9 @@ magpie.strings({ "Sent upstream as {to}, as the agent spoke it": "エージェントと同じ {to} で上流へ送信", }, de: { + "Bar chart": "Balkendiagramm", + "Line chart": "Liniendiagramm", + "Chart style": "Diagrammart", "(prompt not recorded)": "(Prompt nicht aufgezeichnet)", "Gateway session": "Gateway-Sitzung", "Seen only through the gateway: the agent kept no session file magpie can read. Turn on Record gateway conversations in Sessions to keep its prompts.": "Nur über das Gateway gesehen: Der Agent hat keine Sitzungsdatei hinterlassen, die magpie lesen kann. Schalte unter Sitzungen „Gateway-Gespräche aufzeichnen“ ein, um seine Prompts zu behalten.", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 83426e3b4..e068fbe53 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -639,6 +639,10 @@ try { const m = localStorage.getItem("magpie.ledMetric"); if (["tokens", "cost", "calls", "speed"].includes(m)) ledMetric = m; } catch {} +// Columns or lines (molvqingtai on Discord), kept per viewer as the metric +// is; anything but "line", or a read that fails, is columns. +let ledLine = false; +try { ledLine = localStorage.getItem("magpie.ledChart") === "line"; } catch {} // The filters a click set for the reader rather than one they picked in a // filter's menu: someone in the chart's ranking or a day of its columns @@ -1130,6 +1134,91 @@ function renderLedgerDash(l) { drawLedTrend(); } +// the chart's two looks, as a pair of icons beside the metrics: columns +// (the default) or lines +const LED_STYLES = [["bars", "Bar chart", "M3.5 13V8.5M8 13V3.5M12.5 13V6.5"], ["line", "Line chart", "M2.5 11.5 6 7.5l3 2.5 4.5-6"]]; +function ledStyle(host) { + const cur = ledLine ? "line" : "bars"; + host.setAttribute("role", "group"); + host.setAttribute("aria-label", t("Chart style")); + host.replaceChildren(); + for (const [id, name, d] of LED_STYLES) { + const b = el("button", "opt" + (id === cur ? " on" : "")); + b.type = "button"; + b.dataset.style = id; + b.title = t(name); + b.setAttribute("aria-label", t(name)); + b.setAttribute("aria-pressed", id === cur ? "true" : "false"); + b.append(svg(d, 14, 1.7)); + b.onclick = () => { + if (id === cur) return; + ledLine = id === "line"; + try { localStorage.setItem("magpie.ledChart", id); } catch {} + drawLedTrend(); + }; + host.append(b); + } + slide(host, "ledStyle"); +} + +// The chart as lines (drawLedColumns' box.drawn): the columns drawn on its +// axis are taken away and each one told apart becomes a line through its +// points. Tokens, cost and requests stay stacked, each line where its part +// of the column ended, with its band softly filled under it, so the top +// line is the total as the column's top was; speeds don't add up, so each +// model's line is at its own speed, broken where it had none, over the +// point's own speed dashed. The tooltip, the hover, a day's pick and the +// ranking's emphasis are drawLedColumns' own, over the same slots. +function ledLines(g, Y, x0, slot, segs) { + const l = ledger, pts = l?.series || [], metric = ledMetric, split = ledSplit; + for (const r of segs) r.remove(); + segs.length = 0; + if (!l) return; + const speed = metric === "speed"; + const { top } = ledCategories(l.chartBy ? { by: l.chartBy } : l, split, metric); + const X = (i) => x0 + slot * i, dot = slot >= 12 ? 4.5 : 3; + const xy = (i, v) => X(i).toFixed(1) + " " + Y(v).toFixed(1); + // stacked, each one goes under those before it, so a band never covers + // the line under it + let head = null; + const totals = pts.map((p) => ledValue(metric, p)); + // one series: its line, the dots at its points and the band under it + const series = (key, color, vals, base, dashed) => { + const s = sv("g", { class: "col ln", "data-k": key, "data-day": l.day || "", "data-color": color }, { stroke: color }); + let line = "", dots = "", up = "", down = "", run = false; + vals.forEach((v, i) => { + if (v == null) return void (run = false); + line += (run ? "L" : "M") + xy(i, v); + if (!dashed && (v > (base?.[i] || 0) || speed)) dots += "M" + xy(i, v) + "h0"; + run = true; + }); + if (!line) return; + if (base) { + vals.forEach((v, i) => { up += (i ? "L" : "M") + xy(i, v); }); + for (let i = vals.length - 1; i >= 0; i--) down += "L" + xy(i, base[i]); + s.append(sv("path", { d: up + down + "Z", class: "band" }, { fill: color })); + } + s.append(sv("path", { d: line, class: "line" + (dashed ? " all" : "") })); + if (dots) s.append(sv("path", { d: dots, class: "dots" }, { strokeWidth: dot })); + head = g.insertBefore(s, speed ? null : head); + segs.push(s); + }; + if (speed) { + series("\0all", "var(--muted)", totals.map((v) => (v > 0 ? v : null)), null, true); + for (const c of top) series(c.id, c.color, pts.map((p) => ledSpeed(p.by?.[split]?.[c.id]) || null)); + return; + } + // from the bottom up: each one's part on what is under it, "Other" last + let under = pts.map(() => 0); + const parts = top.map((c) => [c.id, c.color, pts.map((p) => ledPart(metric, p.by?.[split]?.[c.id] || {}))]); + parts.push(["\0other", "var(--faint)", pts.map((p, i) => Math.max(0, totals[i] - parts.reduce((a, x) => a + x[2][i], 0)))]); + for (const [key, color, vs] of parts) { + const over = under.map((u, i) => u + vs[i]); + if (vs.some((v) => v > 0)) series(key, color, over, under); + under = over; + } +} + function drawLedTrend() { const l = ledger; if (!l || $("#ledDash").hidden) return; @@ -1144,10 +1233,12 @@ function drawLedTrend() { slide(host, key); }; pill($("#ledMetric"), "ledMetric", LED_TREND, ledMetric, (id) => { ledMetric = id; try { localStorage.setItem("magpie.ledMetric", id); } catch {} drawLedTrend(); }); + ledStyle($("#ledStyle")); const keyed = (l.callerKeys || []).length > 0; if (ledSplit === "callerKey" && !keyed) ledSplit = "model"; pill($("#ledSplit"), "ledSplit", LED_SPLITS.filter(([id]) => id !== "callerKey" || keyed), ledSplit, (id) => { ledSplit = id; drawLedTrend(); }); const chart = $("#ledChart"), rank = $("#ledRank"); + chart.drawn = ledLine ? ledLines : null; drawLedColumns(chart, l, ledSplit, ledMetric, false, (day) => { ledDay = ledDay === day ? "" : day; ledLent.add("day"); diff --git a/internal/gui/tests/usage-chart-line.test.cjs b/internal/gui/tests/usage-chart-line.test.cjs new file mode 100644 index 000000000..9f6fa5f21 --- /dev/null +++ b/internal/gui/tests/usage-chart-line.test.cjs @@ -0,0 +1,250 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Requests tab's chart can be columns or lines (molvqingtai on Discord): +// a pair of icons beside the metrics switches it, columns by default, and the +// choice is kept per viewer, so a reload finds lines still picked and drawn. +// Lines cover every metric: tokens, cost and requests stacked as the columns +// are (the top line the total), speeds each at their own with the point's +// own dashed. The tooltip and the ranking's emphasis work over them, the +// empty period says so, a click moves nothing, a kept value that isn't +// "line" or a read that throws is columns. Every language, light and dark, +// wide and narrow; 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 midnight = new Date(); +midnight.setHours(0, 0, 0, 0); + +// two models over a day by the hour, with timed replies for the speeds +const MODELS = [ + { id: "claude-sonnet-5", hours: [6, 20], per: { calls: 3, tokens: 900000, cost: 0.9, decode_out: 3000, decode_ms: 40000 } }, + { id: "gpt-6-luna", hours: [10, 23], per: { calls: 5, tokens: 300000, cost: 0.2, decode_out: 5000, decode_ms: 25000 } }, +]; +const toks = (n) => ({ input: n * 0.01, output: n * 0.005, cache_write: n * 0.05, cache_read: n * 0.935 }); +const SERIES = Array.from({ length: 24 }, (_, h) => { + const model = {}, p = { calls: 0, tokens: 0, cost: 0, decode_out: 0, decode_ms: 0, decode_n: 0 }; + for (const m of MODELS) { + if (h < m.hours[0] || h > m.hours[1]) continue; + model[m.id] = { ...m.per, decode_n: m.per.calls }; + for (const k in p) p[k] += model[m.id][k]; + } + return { label: String(h).padStart(2, "0"), time: new Date(midnight.getTime() + h * 3600e3).toISOString(), errors: 0, ...p, ...toks(p.tokens), by: { model, provider: {}, agent: {} } }; +}); +const sum = (k, of = SERIES) => of.reduce((a, p) => a + (p[k] || 0), 0); +const shareOf = (m) => { + const pts = SERIES.map((p) => p.by.model[m.id]).filter(Boolean); + return { id: m.id, name: m.id, icon: "", calls: sum("calls", pts), errors: 0, ...toks(sum("tokens", pts)), cost: sum("cost", pts), decode_out: sum("decode_out", pts), decode_ms: sum("decode_ms", pts), decode_n: sum("decode_n", pts) }; +}; + +function ledgerPage(empty) { + // empty: requests listed, but none of them counted in the chart's hours + const series = empty ? SERIES.map((p) => ({ ...p, calls: 0, tokens: 0, cost: 0, decode_out: 0, decode_ms: 0, decode_n: 0, ...toks(0), by: { model: {}, provider: {}, agent: {} } })) : SERIES; + return { + period: "today", rows: [], offset: 0, total: 1, bucket: "hour", series, + calls: sum("calls", series), errors: 0, ...toks(sum("tokens", series)), reasoning: 0, cost: sum("cost", series), unpriced: 0, + decode_out: sum("decode_out", series), decode_ms: sum("decode_ms", series), decode_n: sum("decode_n", series), + by: { model: empty ? [] : MODELS.map(shareOf), provider: [], agent: [] }, agents: [], providers: [], + }; +} + +function serve(lang, theme, empty) { + 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:"${theme}",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({ agents: [], profiles: [], settings: { lang, theme }, fx: { rate: 7.2, at: new Date().toISOString() } }); + if (url.pathname === "/api/usage/requests") return json(ledgerPage(empty)); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/usage") return json({ calls: 1, errors: 0, input: 1, output: 1, cache_read: 0, cache_write: 0, reasoning: 0, unpriced: 0, cost: 1, bucket: "day", series: [], agents: [], models: [] }); + 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 === "/api/plugins") return json({ plugins: [] }); + 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)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const L = { + en: { bar: "Bar chart", line: "Line chart", group: "Chart style" }, + zh: { bar: "柱状图", line: "折线图", group: "图表样式" }, + "zh-TW": { bar: "長條圖", line: "折線圖", group: "圖表樣式" }, + ja: { bar: "棒グラフ", line: "折れ線グラフ", group: "グラフの種類" }, + de: { bar: "Balkendiagramm", line: "Liniendiagramm", group: "Diagrammart" }, +}; + +// what the chart is drawn as, and the switch's state +const drawn = (p) => p.evaluate(() => { + const c = document.querySelector("#ledChart"); + const lines = [...c.querySelectorAll("g.ln")]; + return { + cols: c.querySelectorAll("rect.col, line.stem").length, + lines: lines.map((x) => x.dataset.k), + dashed: c.querySelectorAll("g.ln .line.all").length, + bands: c.querySelectorAll("g.ln .band").length, + none: c.querySelector(".none")?.textContent || "", + pressed: [...document.querySelectorAll("#ledStyle .opt")].map((b) => b.getAttribute("aria-pressed")), + on: document.querySelector("#ledStyle .opt.on")?.dataset.style || "", + }; +}); + +// the top of a stacked line chart, at the hour every model has a part in: +// the highest line ends where the column's top did, the total's height +const topAt = (p, h) => p.evaluate((h) => { + const at = [...document.querySelectorAll("#ledChart g.ln .line")].map((x) => x.getAttribute("d").split(/[ML]/).filter(Boolean).map((s) => s.split(" ").map(Number))[h]); + return at.reduce((a, b) => (b[1] < a[1] ? b : a)); +}, h); +// the top of the column whose middle is at x +const colTop = (p, x) => p.evaluate((x) => Math.min(...[...document.querySelectorAll("#ledChart rect.col")] + .filter((r) => Math.abs(+r.getAttribute("x") + +r.getAttribute("width") / 2 - x) < 1).map((r) => +r.getAttribute("y"))), x); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Requests tab's chart switches between columns and lines, and keeps the choice", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const shots = process.env.ARTIFACT_DIR; + if (shots) await fs.mkdir(shots, { recursive: true }); + + const open = async (ctx, lang, theme, empty) => { + const p = await ctx.newPage(); + const errors = []; + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", serve(lang, theme, empty)); + await p.goto("http://magpie.test/"); + await p.locator('[data-view="usage"]').first().click(); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await p.locator("#ledStyle .opt").first().waitFor(); + await p.locator(empty ? "#ledChart .none" : "#ledChart svg").waitFor(); + return { p, errors }; + }; + + for (const [lang, w] of Object.entries(L)) { + for (const theme of ["light", "dark"]) { + for (const width of [1180, 420]) { + await t.test(`${lang} ${theme} ${width}`, async () => { + // tall enough that the chart and its ranking are in sight without + // a scroll, which the page's own scroll guard would take back + const ctx = await browser.newContext({ viewport: { width, height: width < 600 ? 1300 : 900 }, reducedMotion: "reduce" }); + try { + let { p, errors } = await open(ctx, lang, theme); + // columns until the reader picks lines + let d = await drawn(p); + assert.equal(d.on, "bars", "columns by default"); + assert.deepEqual(d.pressed, ["true", "false"]); + assert(d.cols > 0 && d.lines.length === 0, "columns drawn: " + JSON.stringify(d)); + // said in the reader's language, beside the metrics + const names = await p.locator("#ledStyle .opt").evaluateAll((bs) => bs.map((b) => [b.title, b.getAttribute("aria-label")])); + assert.deepEqual(names, [[w.bar, w.bar], [w.line, w.line]]); + assert.equal(await p.locator("#ledStyle").getAttribute("aria-label"), w.group); + const row = await p.evaluate(() => { + const m = document.querySelector("#ledMetric").getBoundingClientRect(), s = document.querySelector("#ledStyle").getBoundingClientRect(); + const card = document.querySelector(".led-trend").getBoundingClientRect(); + return { gap: s.left - m.right, same: Math.abs(s.top - m.top) < 1 || s.top >= m.bottom, inside: s.left >= card.left && s.right <= card.right + 0.5, sideways: document.documentElement.scrollWidth > innerWidth + 1, border: getComputedStyle(document.querySelector("#ledStyle .opt")).borderLeftWidth }; + }); + assert(row.inside && row.same && !row.sideways, "the switch sits in the chart's header: " + JSON.stringify(row)); + assert.equal(row.border, "0px"); + if (shots && width === 1180) await p.locator(".led-trend").screenshot({ path: path.join(shots, `chart-bars-${engine}-${lang}-${theme}.png`) }); + + // a click moves nothing + await p.evaluate(() => scrollTo(0, 40)); + const y0 = await p.evaluate(() => scrollY); + await p.locator("#ledStyle .opt").nth(1).click(); + await p.locator("#ledChart g.ln").first().waitFor(); + assert.equal(await p.evaluate(() => scrollY), y0, "the click scrolled the page"); + + // reloaded, lines are still picked and drawn + await p.reload(); + await p.locator('[data-view="usage"]').first().click(); + await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); + await p.locator("#ledChart svg").waitFor(); + d = await drawn(p); + assert.equal(d.on, "line", "lines kept across a reload"); + assert.deepEqual(d.pressed, ["false", "true"]); + assert.equal(d.cols, 0, "no columns left under the lines"); + assert.deepEqual(d.lines.sort(), MODELS.map((m) => m.id).sort(), "a line for each model"); + assert.equal(d.bands, 2, "stacked: a band under each"); + + // stacked: the highest line at 15:00 is where the total's + // column top was, for tokens, cost and requests + for (let i = 0; i < 3; i++) { + await p.locator("#ledMetric .opt").nth(i).click(); + await p.locator("#ledChart g.ln").first().waitFor(); + const top = await topAt(p, 15); + await p.locator("#ledStyle .opt").nth(0).click(); + await p.locator("#ledChart rect.col").first().waitFor(); + const col = await colTop(p, top[0]); + assert(Math.abs(top[1] - col) < 1, `metric ${i}: the top line at ${top[1]}, the column\'s top at ${col}`); + await p.locator("#ledStyle .opt").nth(1).click(); + await p.locator("#ledChart g.ln").first().waitFor(); + } + + // speeds: each model's own line, over the point's own dashed + await p.locator("#ledMetric .opt").nth(3).click(); + await p.locator("#ledChart g.ln").first().waitFor(); + d = await drawn(p); + assert.equal(d.dashed, 1, "the point's own speed, dashed"); + assert.equal(d.bands, 0, "speeds aren't stacked"); + assert.equal(d.lines.length, 3); + // a model's line breaks where it had no speed: luna starts at 10:00 + const luna = await p.locator('#ledChart g.ln[data-k="gpt-6-luna"] .line').getAttribute("d"); + assert.equal(luna.split("M").length - 1, 1, "one run: " + luna); + assert.equal(luna.split(/[ML]/).filter(Boolean).length, 14, "10:00 to 23:00"); + + // the tooltip over the lines, and the ranking's emphasis + await p.locator("#ledMetric .opt").nth(0).click(); + await p.locator("#ledChart g.ln").first().waitFor(); + await p.evaluate(() => scrollTo(0, 0)); + const box = await p.locator("#ledChart svg").boundingBox(); + await p.mouse.move(box.x + box.width * 0.62, box.y + box.height / 2); + await p.locator("#ledChart .tip").waitFor(); + const tip = await p.locator("#ledChart .tip").textContent(); + assert(tip.includes("claude-sonnet-5") && tip.includes("gpt-6-luna"), "tooltip: " + tip); + await p.locator("#ledRank .rk").first().hover(); + const faded = await p.evaluate(() => [...document.querySelectorAll("#ledChart g.ln")].map((x) => [x.dataset.k, x.style.opacity])); + assert.equal(faded.filter(([, o]) => o === "0.22" || o === ".22").length, 1, "the other line fades: " + JSON.stringify(faded)); + await p.mouse.move(1, 1); + if (shots && width === 1180) await p.locator(".led-trend").screenshot({ path: path.join(shots, `chart-line-${engine}-${lang}-${theme}.png`) }); + assert.deepEqual(errors, []); + await p.close(); + + // nothing in the period: the empty line, no lines, no error + ({ p, errors } = await open(ctx, lang, theme, true)); + d = await drawn(p); + assert.equal(d.on, "line"); + assert.equal(d.lines.length, 0); + assert(d.none, "the empty period is said"); + assert.deepEqual(errors, []); + await p.close(); + } finally { + await ctx.close(); + } + }); + } + } + } + + await t.test("a kept value that isn't line, or a read that throws, is columns", async () => { + for (const init of [ + () => localStorage.setItem("magpie.ledChart", "pie"), + () => { const get = Storage.prototype.getItem; Storage.prototype.getItem = function (k) { if (k === "magpie.ledChart") throw new Error("denied"); return get.call(this, k); }; }, + ]) { + const ctx = await browser.newContext({ viewport: { width: 1180, height: 760 }, reducedMotion: "reduce" }); + await ctx.addInitScript(init); + const { p, errors } = await open(ctx, "en", "light"); + const d = await drawn(p); + assert.equal(d.on, "bars"); + assert(d.cols > 0 && d.lines.length === 0); + assert.deepEqual(errors, []); + await ctx.close(); + } + }); + }); +}