diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 657f3d417..7a4205add 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -877,6 +877,25 @@ body.window .field.solo { grid-column: auto; } .led-strip .blk:nth-child(n + 3) { border-top: 1px solid var(--line-2); } .led-strip .blk:last-child:nth-child(odd) { grid-column: 1 / -1; } } +/* the heatmap (#1369): 53 weeks of days, Monday on top, the cells growing a + little to take a wide card and scrolling sideways in it when narrow */ +.led-heat { position: relative; margin-bottom: 10px; padding: 10px 14px 10px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; } +.led-heat[hidden] { display: none; } +.heat-title { display: flex; flex-direction: column; gap: 1px; min-width: 0; } +.heat-title b { font-size: 12.5px; font-weight: 600; } +.heat-title span { font-size: 11px; color: var(--muted); } +.heat-scroll { overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; padding-bottom: 4px; } +.heat-grid { display: grid; grid-template-columns: auto repeat(53, minmax(10px, 1fr)); grid-template-rows: auto repeat(7, auto); gap: 3px; min-width: min-content; max-width: calc(3em + 53 * 21px); font-size: 10px; color: var(--muted); } +.heat-grid i { aspect-ratio: 1; border-radius: 3px; min-width: 0; } +.heat-grid i:hover { outline: 1px solid var(--fg-2); outline-offset: -1px; } +/* the days of the week stay at the card's edge as the weeks scroll under them */ +.heat-grid .wd { position: sticky; left: 0; z-index: 1; align-self: stretch; display: flex; align-items: center; padding-right: 6px; line-height: 1; white-space: nowrap; background: var(--card); box-shadow: 3px 0 0 var(--card); } +.heat-grid .mo { min-width: 0; white-space: nowrap; overflow: hidden; line-height: 1.2; padding-bottom: 2px; } +.heat-foot { display: flex; justify-content: flex-end; margin-top: 4px; } +.heat-tip { position: absolute; z-index: 3; display: flex; flex-direction: column; gap: 2px; padding: 6px 9px; background: var(--pop-bg); border-radius: 8px; box-shadow: var(--shadow); font-size: 11.5px; white-space: nowrap; pointer-events: none; font-variant-numeric: tabular-nums; } +.heat-tip[hidden] { display: none; } +.heat-tip b { font-weight: 600; } +.heat-tip span { color: var(--muted); } /* over the requests: their sum, and at its right the request archive's switch */ .led-head { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; margin: 0 2px 7px; min-width: 0; } .led-head .led-sum { margin: 0; min-width: 0; } diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 2ca7eafdf..933350527 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -15068,6 +15068,7 @@ function ledParams(extra) { // quiet: a refresh while it's looked at, redrawn only on a change async function loadLedger(quiet) { if (!ledger && !quiet) renderLedgerLoading(); + loadLedHeat().catch(() => {}); const want = ledParams({ offset: ledOffset, limit: LED_PAGE }); const l = await api("usage/requests?" + want); if (want !== ledParams({ offset: ledOffset, limit: LED_PAGE })) return; // another page or filter was picked meanwhile @@ -15756,6 +15757,174 @@ function drawLedTrend() { loadLedger().catch((e) => status(e.message, "err")); }, false); } +// ---------- the heatmap (#1369) ---------- +// +// The last 53 weeks a day each, Monday on top, as a calendar of +// contributions lays them out: each day as dark as it is busy among the +// others, by tokens, requests or cost. It is of the requests the filters +// above keep, whatever the period (the server's /api/usage/heatmap, read +// from the same index as the page), its days in the gateway's time zone. A +// narrow window scrolls it sideways inside its card, the newest week in +// sight; the pointer on a day says its date and what it had. +let ledHeat = null, ledHeatWant = "", ledHeatMetric = "tokens"; +try { + const m = localStorage.getItem("magpie.ledHeatMetric"); + if (["tokens", "calls", "cost"].includes(m)) ledHeatMetric = m; +} catch {} +const LED_HEAT = [["tokens", "Tokens"], ["calls", "Requests"], ["cost", "Cost"]]; +function ledHeatParams() { + const q = new URLSearchParams(ledParams()); + q.delete("period"); + q.delete("day"); + return q.toString(); +} +async function loadLedHeat() { + const want = ledHeatParams(); + ledHeatWant = want; + const h = await api("usage/heatmap?" + want); + if (want !== ledHeatWant) return; // another filter was picked meanwhile + if (ledHeat && ledHeat.want === want && JSON.stringify(ledHeat.data) === JSON.stringify(h)) return; + ledHeat = { want, data: h }; + if (view === "usage" && usageTab === "requests") drawLedHeat(); +} +const ledHeatDate = (s) => { const [y, m, d] = String(s).split("-").map(Number); return new Date(y, m - 1, d); }; +function ledHeatTip(x) { + const loc = intlLang() || "en"; + const tip = el("div"); + tip.append(el("b", "", x.day.toLocaleDateString(loc, { year: "numeric", month: "short", day: "numeric", weekday: "short" }))); + if (!x.calls) { + tip.append(el("span", "", t("No requests"))); + return tip; + } + const parts = [t("{n} tokens", { n: fmtN(x.tokens) }), t(x.calls === 1 ? "{n} request" : "{n} requests", { n: ledNum(x.calls) })]; + const c = fmtCost(x); + if (c) parts.push("≈" + c); + const order = { tokens: 0, calls: 1, cost: 2 }[ledHeatMetric]; + if (order && parts[order]) parts.unshift(...parts.splice(order, 1)); // the metric shown first + tip.append(el("span", "", parts.join(" · "))); + return tip; +} +function drawLedHeat() { + const box = $("#ledHeat"), h = ledHeat?.data; + const at = new Map((h?.days || []).map((d) => [d.date, d])); + box.hidden = !h?.from || !h?.to || ![...at.values()].some((d) => d.calls > 0); + if (box.hidden) return; + const first = ledHeatDate(h.from), last = ledHeatDate(h.to); + const days = []; + for (const d = new Date(first); d <= last; d.setDate(d.getDate() + 1)) { + const x = at.get(sessISO(d)) || { calls: 0, tokens: 0, cost: 0 }; + days.push({ ...x, day: new Date(d) }); + } + const value = (x) => ledHeatMetric === "cost" ? x.cost : ledHeatMetric === "calls" ? x.calls : x.tokens; + const lv = sessLevels(days.map(value)); + const seg = $("#ledHeatMetric"); + seg.replaceChildren(); + for (const [id, name] of LED_HEAT) { + const b = el("button", "opt" + (id === ledHeatMetric ? " on" : ""), t(name)); + b.type = "button"; + b.onclick = () => { + if (id === ledHeatMetric) return; + ledHeatMetric = id; + try { localStorage.setItem("magpie.ledHeatMetric", id); } catch {} + drawLedHeat(); + }; + seg.append(b); + } + slide(seg, "ledHeatMetric"); + const scroll = $("#ledHeatScroll"); + // the same days in the same language keep their cells, coloured again, so + // a refresh moves nothing and the scroll stays where the reader left it + const shape = [h.from, h.to, locale].join("|"); + let grid = scroll.querySelector(".heat-grid"); + if (!grid || grid.dataset.shape !== shape) { + grid = el("div", "heat-grid"); + grid.dataset.shape = shape; + grid.setAttribute("role", "img"); + const names = sessWeekdays(); + // every row has its place at the edge, named every other day + for (let i = 0; i < 7; i++) { + const l = el("span", "wd", i % 2 ? "" : names[i]); + l.style.gridArea = `${i + 2} / 1`; + grid.append(l); + } + const loc = intlLang() || "en"; + const weeks = Math.ceil(days.length / 7), labels = []; + let month = -1; + days.forEach((x, i) => { + const w = Math.floor(i / 7), wd = i % 7; + if (wd === 0 && x.day.getMonth() !== month) { + month = x.day.getMonth(); + // a month mostly gone in the first week is left unnamed, so as not + // to crowd out the next one's name, and so is one begun in the last + // week, with no room for its name + if ((!labels.length || w - labels.at(-1).w >= 3) && !(w === 0 && x.day.getDate() > 14) && w < weeks - 1) { + const m = el("span", "mo", x.day.toLocaleDateString(loc, { month: "short" })); + labels.push({ m, w }); + grid.append(m); + } + } + const c = el("i"); + c.dataset.date = sessISO(x.day); + c.style.gridArea = `${wd + 2} / ${w + 2}`; + grid.append(c); + }); + // a month's name spans its weeks up to the next name, cut there, so a + // long one never widens the grid past its last week + labels.forEach(({ m, w }, i) => { m.style.gridArea = `1 / ${w + 2} / 2 / ${(labels[i + 1]?.w ?? weeks) + 2}`; }); + grid.onpointerover = (e) => { if (e.target.dataset?.date) ledHeatShow(e.target); }; + grid.onpointerleave = () => { $("#ledHeatTip").hidden = true; }; + scroll.replaceChildren(grid); + if (!scroll.onscroll) { + // the newest week in sight, by the card's own scroll, never the page's: + // kept there as the card is laid out or resized, until the reader + // scrolls it back, and again once they scroll to the end + scroll.onscroll = () => { + $("#ledHeatTip").hidden = true; + // its own scroll to the end, seen after the card narrowed, is not the reader's + if (scroll.clientWidth && scroll.scrollLeft !== ledHeatSetAt) ledHeatAtEnd = scroll.scrollLeft >= scroll.scrollWidth - scroll.clientWidth - 2; + }; + } + ledHeatSized.disconnect(); + ledHeatSized.observe(scroll); + ledHeatSized.observe(grid); + ledHeatKeepEnd(); + } + grid.setAttribute("aria-label", t("Usage heatmap")); + const cells = grid.querySelectorAll("i"); + days.forEach((x, i) => { + const c = cells[i]; + c.className = "l" + lv(value(x)); + c.day = x; + }); + const legend = box.querySelector(".heat-foot"); + legend.replaceChildren(sessLegend()); + const tip = $("#ledHeatTip"); + if (!tip.hidden && tip.cell?.isConnected) ledHeatShow(tip.cell); + else tip.hidden = true; +} +let ledHeatAtEnd = true, ledHeatSetAt = -1; +const ledHeatSized = new ResizeObserver(() => ledHeatKeepEnd()); +function ledHeatKeepEnd() { + const scroll = $("#ledHeatScroll"); + if (!ledHeatAtEnd || !scroll.clientWidth || scroll.scrollWidth <= scroll.clientWidth) return; + scroll.scrollLeft = scroll.scrollWidth; + ledHeatSetAt = scroll.scrollLeft; +} +// the tip over a day, above it, kept inside the card +function ledHeatShow(cell) { + const box = $("#ledHeat"), tip = $("#ledHeatTip"); + if (!cell.day) return; + tip.replaceChildren(...ledHeatTip(cell.day).children); // the date over the figures + tip.cell = cell; + tip.hidden = false; + const b = box.getBoundingClientRect(), c = cell.getBoundingClientRect(); + const w = tip.offsetWidth, hgt = tip.offsetHeight; + const left = Math.max(6, Math.min(b.width - w - 6, c.left - b.left + c.width / 2 - w / 2)); + let top = c.top - b.top - hgt - 6; + if (top < 4) top = c.bottom - b.top + 6; + tip.style.left = left + "px"; + tip.style.top = top + "px"; +} // the table's scrollbar, kept in view at the window's foot (#799): as wide // as the table can go sideways, and moving it as the table moves it function ledHScroll() { @@ -15986,6 +16155,7 @@ function renderLedger() { loadLedger().catch((e) => status(e.message, "err")); }; renderLedgerDash(l); + drawLedHeat(); const wrap = $("#ledWrap"); const pager = $("#ledPager"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 8beab6047..35e826e2c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2272,6 +2272,9 @@ const I18N = { "Activity": "活跃度", "nothing": "无", "Less": "少", + "Usage heatmap": "用量热力图", + "Daily usage over the last 53 weeks": "最近 53 周的每日用量", + "No requests": "无请求", "More": "多", "{n} session": "{n} 个会话", "{n} sessions": "{n} 个会话", @@ -6082,6 +6085,9 @@ const I18N = { "Activity": "活躍度", "nothing": "無", "Less": "少", + "Usage heatmap": "用量熱力圖", + "Daily usage over the last 53 weeks": "最近 53 週的每日用量", + "No requests": "無請求", "More": "多", "{n} session": "{n} 個會話", "{n} sessions": "{n} 個會話", @@ -9856,6 +9862,9 @@ const I18N = { "Activity": "アクティビティ", "nothing": "なし", "Less": "少", + "Usage heatmap": "使用量ヒートマップ", + "Daily usage over the last 53 weeks": "直近 53 週間の日ごとの使用量", + "No requests": "リクエストなし", "More": "多", "{n} session": "{n} 件のセッション", "{n} sessions": "{n} 件のセッション", @@ -13649,6 +13658,9 @@ const I18N = { "Activity": "Aktivität", "nothing": "nichts", "Less": "Weniger", + "Usage heatmap": "Nutzungs-Heatmap", + "Daily usage over the last 53 weeks": "Tägliche Nutzung der letzten 53 Wochen", + "No requests": "Keine Anfragen", "More": "Mehr", "{n} session": "{n} Sitzung", "{n} sessions": "{n} Sitzungen", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index 2efefafaa..39830b8ce 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -186,6 +186,16 @@ +

diff --git a/internal/gui/tests/usage-heatmap.test.cjs b/internal/gui/tests/usage-heatmap.test.cjs new file mode 100644 index 000000000..c612012ca --- /dev/null +++ b/internal/gui/tests/usage-heatmap.test.cjs @@ -0,0 +1,213 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Requests tab's heatmap (#1369): the last 53 weeks a day each, Monday +// on top, month names over the weeks and the days of the week beside them, by +// tokens, requests or cost, with a five-shade Less…More legend. It is of the +// requests the filters keep, whatever the period or day picked; the pointer on +// a day says its date and what it had; a switch moves nothing on the page; a +// narrow window scrolls it sideways inside its card with the newest week in +// sight. Every language, both widths, light and dark; 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"); + +// the pointer onto an element where it is: a locator's hover would scroll +// the card to it first, as a reader's pointer doesn't +async function pointTo(p, loc) { + const b = await loc.boundingBox(); + await p.mouse.move(b.x + b.width / 2, b.y + b.height / 2, { steps: 2 }); +} +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const iso = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; +const today = new Date(); +today.setHours(0, 0, 0, 0); +const from = new Date(today); +from.setDate(from.getDate() - ((today.getDay() + 6) % 7) - 7 * 52); +const SPAN = Math.round((today - from) / 864e5) + 1; // 7 × 52 + this week's days so far +// a day of every fifth quiet; the busiest by tokens is today, by requests ten days ago +const DAYS = []; +for (let i = 0; i < SPAN; i++) { + const d = new Date(from); + d.setDate(d.getDate() + i); + if (i % 5 === 0 && i !== SPAN - 1) continue; + const calls = i === SPAN - 11 ? 500 : (i % 13) + 1; + DAYS.push({ date: iso(d), calls, tokens: i === SPAN - 1 ? 9e9 : calls * 1e5 * (1 + (i % 7)), cost: calls * 0.5 }); +} +const ROW = { t: new Date().toISOString(), agent: "claude", agentName: "Claude Code", icon: "claudecode-color", provider: "anthropic", providerName: "Claude", model: "claude-sonnet-5", req: "sonnet", in: 2, out: 600, cache_write: 900, cache_read: 390000, ms: 2380, status: 200, cost: 0.087, priced: true }; +const share = (id, name) => ({ id, name, icon: "generic", calls: 1, errors: 0, input: 2, output: 600, cache_write: 900, cache_read: 390000, cost: 0.087 }); +const PAGE = { + period: "30d", rows: [ROW], offset: 0, total: 1, calls: 1, errors: 0, input: 2, output: 600, cache_write: 900, cache_read: 390000, reasoning: 0, cost: 0.087, unpriced: 0, + bucket: "day", series: [], by: { provider: [share("anthropic", "Claude")], agent: [share("claude", "Claude Code")], model: [share("claude-sonnet-5", "claude-sonnet-5")] }, + agents: [{ id: "claude", name: "Claude Code", icon: "claudecode-color" }], providers: [{ id: "anthropic", name: "Claude", icon: "generic" }], +}; + +function server(lang, theme, variant, asked) { + 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 } }); + if (url.pathname === "/api/usage/requests") return json(PAGE); + if (url.pathname === "/api/usage/heatmap") { + asked.push(url.searchParams); + return json({ from: iso(from), to: iso(today), days: variant === "none" ? [] : DAYS }); + } + 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: [], path: "~/.config/magpie/usage.jsonl" }); + if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const L = { + en: { title: "Usage heatmap", sub: "Daily usage over the last 53 weeks", metric: ["Tokens", "Requests", "Cost"], less: "Less", more: "More", tokens: "tokens", none: "No requests", loc: "en" }, + zh: { title: "用量热力图", sub: "最近 53 周的每日用量", metric: ["Token", "请求", "费用"], less: "少", more: "多", tokens: "token", none: "无请求", loc: "zh-CN" }, + "zh-TW": { title: "用量熱力圖", sub: "最近 53 週的每日用量", metric: ["Token", "請求", "費用"], less: "少", more: "多", tokens: "token", none: "無請求", loc: "zh-TW" }, + ja: { title: "使用量ヒートマップ", sub: "直近 53 週間の日ごとの使用量", metric: ["トークン", "リクエスト", "費用"], less: "少", more: "多", tokens: "トークン", none: "リクエストなし", loc: "ja-JP" }, + de: { title: "Nutzungs-Heatmap", sub: "Tägliche Nutzung der letzten 53 Wochen", metric: ["Token", "Anfragen", "Kosten"], less: "Weniger", more: "Mehr", tokens: "Token", none: "Keine Anfragen", loc: "de-DE" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Requests tab's heatmap", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch()); + t.after(() => browser.close()); + const shots = process.env.ARTIFACT_DIR; + if (shots) await fs.mkdir(shots, { recursive: true }); + const open = async (lang, { width, theme = "light", variant = "" }) => { + const errors = [], asked = []; + const context = await browser.newContext({ viewport: { width, height: 820 }, reducedMotion: "reduce" }); + const p = await context.newPage(); + p.setDefaultTimeout(5000); + p.on("pageerror", (e) => errors.push(e.message)); + await p.route("**/*", server(lang, theme, variant, asked)); + await p.goto("http://magpie.test/"); + await p.locator('[data-view="usage"]').first().click(); + await p.locator("#usageTab .opt").nth(1).click(); + await p.locator("#ledRank .rk").first().waitFor(); + return { p, errors, asked, context }; + }; + + for (const lang of Object.keys(L)) for (const width of [420, 1100]) { + const w = L[lang]; + await t.test(`${lang} at ${width}`, async () => { + const { p, errors, asked, context } = await open(lang, { width }); + const heat = p.locator("#ledHeat"); + await heat.locator(".heat-grid i").first().waitFor(); + assert.equal(await heat.locator(".heat-title b").textContent(), w.title); + assert.equal(await heat.locator(".heat-title span").textContent(), w.sub); + assert.deepEqual(await heat.locator("#ledHeatMetric .opt").allTextContents(), w.metric); + assert.equal(await heat.locator("#ledHeatMetric .opt.on").textContent(), w.metric[0]); + // a cell a day, from the Monday 52 weeks before this week's to today + const cells = heat.locator(".heat-grid i"); + assert.equal(await cells.count(), SPAN); + assert.equal(await cells.first().getAttribute("data-date"), iso(from)); + assert.equal(await cells.last().getAttribute("data-date"), iso(today)); + // Monday on top, in the days' own column: the first cell's row is the first week's + const rows = await cells.evaluateAll((cs) => cs.slice(0, 7).map((c) => Math.round(c.getBoundingClientRect().top))); + assert(rows.every((y, i) => !i || y > rows[i - 1]), "a week's days go down: " + rows); + // the days of the week and the months, in the language + const wd = (await heat.locator(".heat-grid .wd").allTextContents()).filter(Boolean); + const want = await p.evaluate((loc) => [0, 2, 4, 6].map((i) => new Date(2024, 0, 1 + i).toLocaleDateString(loc, { weekday: "short" })), w.loc); + assert.deepEqual(wd, want); + const months = await heat.locator(".heat-grid .mo").allTextContents(); + assert(months.length >= 11 && months.length <= 13, "months: " + months); + const mon = await p.evaluate((loc) => new Date().toLocaleDateString(loc, { month: "short" }), w.loc); + assert(months.includes(mon) || today.getDate() < 8, "this month named: " + months); + // five shades, Less to More; today busiest, a quiet day the lightest + assert.equal(await heat.locator(".sess-legend i").count(), 5); + assert.deepEqual(await heat.locator(".sess-legend span").allTextContents(), [w.less, w.more]); + assert.equal(await cells.last().getAttribute("class"), "l4"); + assert.equal(await cells.first().getAttribute("class"), "l0"); + const shades = await heat.locator(".sess-legend i").evaluateAll((is) => is.map((i) => getComputedStyle(i).backgroundColor)); + assert.equal(new Set(shades).size, 5, "five shades: " + shades); + + // the newest week is in sight, inside the card; only the card scrolls sideways + const sc = await p.evaluate(() => { + const s = document.querySelector("#ledHeatScroll"), r = s.getBoundingClientRect(), last = [...s.querySelectorAll(".heat-grid i")].at(-1).getBoundingClientRect(); + const card = document.querySelector("#ledHeat").getBoundingClientRect(); + return { over: s.scrollWidth > s.clientWidth + 1, left: s.scrollLeft, sw: s.scrollWidth, cw: s.clientWidth, lr: [last.left, last.right, r.left, r.right], inView: last.right <= r.right + 1 && last.left >= r.left - 1, inCard: r.left >= card.left && r.right <= card.right, + page: document.documentElement.scrollWidth <= window.innerWidth + 1, view: document.querySelector("#view-usage").scrollWidth <= document.querySelector("#view-usage").clientWidth + 1 }; + }); + assert(sc.inView, "the newest day in sight: " + JSON.stringify(sc)); + assert(sc.inCard && sc.page && sc.view, "no sideways scroll outside the card: " + JSON.stringify(sc)); + if (width === 420) assert(sc.over && sc.left > 0, "a narrow card scrolls, at its end: " + JSON.stringify(sc)); + else assert(!sc.over, "a wide card holds every week"); + + // the pointer on a day: its date and what it had, inside the card + const busy = DAYS.find((d) => d.date === iso(new Date(today.getTime() - 10 * 864e5))); + const cell = heat.locator(`.heat-grid i[data-date="${busy.date}"]`); + // the reader wheels the page to the card (magpie puts back a scroll by + // code), and the pointer then rests on a day + await p.mouse.move(width / 2, 300); + for (let i = 0; i < 20; i++) { + const b = await heat.boundingBox(); + if (b.y >= 60 && b.y + b.height <= 800) break; + await p.mouse.wheel(0, b.y < 60 ? -120 : 120); + await p.waitForTimeout(60); + } + await pointTo(p, cell); + const tip = heat.locator("#ledHeatTip"); + await tip.waitFor(); + const text = await tip.textContent(); + // the browser's own words for the day: its ICU is not Node's + const day = await p.evaluate(([at, loc]) => new Date(at).toLocaleDateString(loc, { year: "numeric", month: "short", day: "numeric", weekday: "short" }), [today.getTime() - 10 * 864e5, w.loc]); + assert(text.startsWith(day), `tip: ${text} (want ${day})`); + // the date on a line of its own, over the figures + const [d1, d2] = await tip.locator(":scope > *").evaluateAll((es) => es.map((e) => e.getBoundingClientRect().top)); + assert(d2 > d1 + 4, "the figures under the date"); + assert(text.includes(w.tokens) && text.includes("500"), "tip: " + text); + const tb = await tip.boundingBox(), cb = await heat.boundingBox(); + assert(tb.x >= cb.x - 1 && tb.x + tb.width <= cb.x + cb.width + 1, "the tip is inside the card"); + // a quiet day in the newest weeks, in sight without scrolling the card + const quiet = iso(new Date(from.getFullYear(), from.getMonth(), from.getDate() + 5 * Math.floor((SPAN - 2) / 5))); + await pointTo(p, heat.locator(`.heat-grid i[data-date="${quiet}"]`)); + assert((await tip.textContent()).endsWith(w.none), "a quiet day: " + (await tip.textContent())); + await p.mouse.move(2, 2); + await tip.waitFor({ state: "hidden" }); + assert(await p.evaluate(() => { const s = document.querySelector("#ledHeatScroll"); return s.scrollLeft >= s.scrollWidth - s.clientWidth - 2; }), "the card still at its newest week"); + + // Requests: ten days ago is busiest; the switch moves nothing and is kept + const at = await p.evaluate(() => [window.scrollY, document.querySelector("#view-usage").scrollTop, document.querySelector("#ledHeatScroll").scrollLeft]); + await heat.locator("#ledHeatMetric .opt").nth(1).click(); + assert.equal(await heat.locator("#ledHeatMetric .opt.on").textContent(), w.metric[1]); + assert.equal(await cell.getAttribute("class"), "l4"); + assert.notEqual(await cells.last().getAttribute("class"), "l4"); + assert.deepEqual(await p.evaluate(() => [window.scrollY, document.querySelector("#view-usage").scrollTop, document.querySelector("#ledHeatScroll").scrollLeft]), at, "a click scrolled"); + assert.equal(await p.evaluate(() => localStorage.getItem("magpie.ledHeatMetric")), "calls"); + + // the filters: no period or day; a model picked in the ranking asks again with it + assert(asked.length >= 1 && !asked.at(-1).has("period") && !asked.at(-1).has("day"), "asked: " + asked.at(-1)); + await p.locator("#ledRank .rk").first().click(); + for (let i = 0; i < 60 && asked.at(-1).get("model") !== "claude-sonnet-5"; i++) await p.waitForTimeout(40); + assert.equal(asked.at(-1).get("model"), "claude-sonnet-5"); + if (shots) await p.screenshot({ path: path.join(shots, `heatmap-${engine}-${lang}-${width}.png`), fullPage: false }); + assert.deepEqual(errors, []); + await context.close(); + }); + } + + await t.test("dark, and none", async () => { + const { p, errors, context } = await open("en", { width: 1100, theme: "dark" }); + await p.locator("#ledHeat .heat-grid i").first().waitFor(); + // a frame for the reduced-motion transitions the shades start with + await p.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + const [l0, l4, card] = await p.evaluate(() => [".heat-grid i.l0", ".heat-grid i.l4", "#ledHeat"].map((s) => getComputedStyle(document.querySelector(s)).backgroundColor)); + assert(l0 !== l4 && l0 !== card, `dark shades: ${l0} ${l4} on ${card}`); + if (shots) await p.locator("#ledHeat").screenshot({ path: path.join(shots, `heatmap-${engine}-dark.png`) }); + assert.deepEqual(errors, []); + await context.close(); + const none = await open("en", { width: 1100, variant: "none" }); + await none.p.waitForTimeout(300); + assert(await none.p.locator("#ledHeat").isHidden(), "nothing to show: no heatmap"); + assert.deepEqual(none.errors, []); + await none.context.close(); + }); + }); +} diff --git a/internal/gui/usage.go b/internal/gui/usage.go index a5fa3eadb..6533c6315 100644 --- a/internal/gui/usage.go +++ b/internal/gui/usage.go @@ -390,6 +390,11 @@ func usageRoutes(mux *http.ServeMux, w Windows) { limit, _ := strconv.Atoi(q.Get("limit")) writeJSON(rw, ledgerPage(periodOf(q.Get("period")), ledgerFilter(q), offset, limit)) }) + // the heatmap (#1369): the last 53 weeks a day each, of the requests the + // page's filters keep, read from the same index as the page + mux.HandleFunc("GET /api/usage/heatmap", func(rw http.ResponseWriter, r *http.Request) { + writeJSON(rw, usage.HeatmapOf(ledgerFilter(r.URL.Query()))) + }) // what was said in one request, read from the agent's session file when the // row is opened, between two times (the call's own, or a gateway request's // span): magpie keeps no copy diff --git a/internal/gui/usage_test.go b/internal/gui/usage_test.go index 4385e0aef..b1383809a 100644 --- a/internal/gui/usage_test.go +++ b/internal/gui/usage_test.go @@ -378,3 +378,32 @@ func TestUsageCSVAtMidnight(t *testing.T) { t.Errorf("export: %d %s, want %s with 1 row", w.Code, w.Body, want) } } + +// GET /api/usage/heatmap (#1369): the last 53 weeks a day each, of the +// requests the page's filters keep (here the provider), every day's though a +// day is picked on the page. +func TestUsageHeatmapRoute(t *testing.T) { + sandboxHome(t) + now := holdUsageClock(t, time.Date(2026, 10, 9, 12, 0, 0, 0, time.Local)) + for i, at := range []time.Time{now.AddDate(0, 0, -380), now.AddDate(0, 0, -100), now.AddDate(0, 0, -1), now.Add(-time.Hour)} { + usage.Append(usage.Record{Time: at, Agent: "codex", Provider: "relay", Model: "m", Input: 10 + i, Output: 1, Status: 200}) + } + usage.Append(usage.Record{Time: now.Add(-time.Hour), Agent: "claude", Provider: "anthropic", Model: "m", Input: 500, Status: 200}) + mux := http.NewServeMux() + usageRoutes(mux, folderOnly{}) + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/usage/heatmap?provider=relay&day=2026-10-09&period=today", nil)) + var h usage.Heatmap + if err := json.Unmarshal(w.Body.Bytes(), &h); w.Code != 200 || err != nil { + t.Fatalf("heatmap: %d %s", w.Code, w.Body) + } + if h.From != "2025-10-06" || h.To != "2026-10-09" || len(h.Days) != 3 { + t.Fatalf("heatmap: %s", w.Body) + } + if d := h.Days[0]; d.Date != now.AddDate(0, 0, -100).Format(time.DateOnly) || d.Calls != 1 || d.Tokens != 12 { + t.Fatalf("100 days ago: %+v", d) + } + if d := h.Days[2]; d.Date != "2026-10-09" || d.Calls != 1 || d.Tokens != 14 { + t.Fatalf("today: %+v", d) + } +} diff --git a/internal/usage/heatmap.go b/internal/usage/heatmap.go new file mode 100644 index 000000000..7dea421fe --- /dev/null +++ b/internal/usage/heatmap.go @@ -0,0 +1,99 @@ +package usage + +// The heatmap (#1369): the last 53 weeks a day each, as a calendar of +// contributions lays them out, Monday on top. It is the request page's own +// index read over that span — QueryPage's cached chunks, priced once — and +// not another pass over the logs, so a page asking for it again reads only +// what changed. It counts what the Requests tab's chart counts: the rows its +// filters keep, but for the day picked, and not the calls the gateway turned +// away itself. + +import ( + "slices" + "time" +) + +// HeatmapWeeks is how many weeks the heatmap shows, this one the last. +const HeatmapWeeks = 53 + +// heatmapPeriod is the span the heatmap is read over: QueryPage's period for +// it, from the Monday HeatmapWeeks-1 weeks before this week's. Not one the +// page's period switch offers. +const heatmapPeriod Period = "heatmap" + +// heatmapSince is the Monday the heatmap starts on, as of now. +func heatmapSince(now time.Time) time.Time { + day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + return day.AddDate(0, 0, -(int(day.Weekday())+6)%7-7*(HeatmapWeeks-1)) +} + +// Day is one day's calls, by the local calendar day they fell on. +type Day struct { + Date string `json:"date"` // YYYY-MM-DD + Calls int `json:"calls"` + Tokens int `json:"tokens"` // in, out and through the cache, as the chart counts them + Cost float64 `json:"cost"` // of the priced calls, USD + // Unpriced: calls with tokens but no known price, not in Cost + Unpriced int `json:"unpriced,omitempty"` +} + +// Heatmap is the days from From to To (today), both YYYY-MM-DD in the local +// time zone: only those with calls are listed, oldest first. +type Heatmap struct { + From string `json:"from"` + To string `json:"to"` + Days []Day `json:"days"` +} + +// HeatmapOf is the last HeatmapWeeks weeks of the calls the filter keeps, a +// day each. The filter's Day is not one of its dimensions here: the heatmap +// is every day's. +func HeatmapOf(f Filter) Heatmap { + f.Day = "" + if h := QueryPage(heatmapPeriod, f, 0, 1).Heat; h != nil { + return *h + } + return Heatmap{Days: []Day{}} +} + +// heatmapOf sums the rows visit gives it by their local day, from since to +// now's day; a row outside those days is left out. +func heatmapOf(since, now time.Time, visit func(add func(Row))) *Heatmap { + h := &Heatmap{From: since.Format(time.DateOnly), To: now.In(time.Local).Format(time.DateOnly), Days: []Day{}} + at := map[string]*Day{} + visit(func(r Row) { + if r.IsRejected() || r.Time.Before(since) { + return + } + d := r.Time.In(time.Local).Format(time.DateOnly) + if d > h.To { + return + } + x := at[d] + if x == nil { + x = &Day{Date: d} + at[d] = x + } + x.Calls++ + x.Tokens += r.Input + r.Output + r.CacheRead + r.CacheWrite + switch { + case r.Priced: + x.Cost += r.Cost + case r.Input+r.Output > 0: + x.Unpriced++ + } + }) + for _, x := range at { + h.Days = append(h.Days, *x) + } + slices.SortFunc(h.Days, func(a, b Day) int { + if a.Date < b.Date { + return -1 + } + if a.Date > b.Date { + return 1 + } + return 0 + }) + return h +} diff --git a/internal/usage/heatmap_test.go b/internal/usage/heatmap_test.go new file mode 100644 index 000000000..da91a5182 --- /dev/null +++ b/internal/usage/heatmap_test.go @@ -0,0 +1,95 @@ +package usage + +import ( + "math" + "reflect" + "testing" + "time" +) + +// The heatmap (#1369) is the last 53 weeks from a Monday, a day each by the +// local calendar: the rows the chart's filter keeps, the day picked set +// aside, without the gateway's own rejections, the days before its first +// Monday or after today. The streaming page and the ledger's agree. +func TestHeatmapDays(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 10, 9, 15, 0, 0, 0, time.Local)) // a Friday + from := time.Date(2025, 10, 6, 0, 0, 0, 0, time.Local) // the Monday 52 weeks before this week's + if got := heatmapSince(now); !got.Equal(from) || got.Weekday() != time.Monday { + t.Fatalf("heatmap starts %v, want %v", got, from) + } + today := time.Date(2026, 10, 9, 0, 0, 0, 0, time.Local) + gateway := &rowChunk{} + all := Ledgered{Agents: []string{"codex"}, Providers: []string{"a", "b"}} + for i, r := range []Record{ + {Time: from.Add(-time.Nanosecond), Provider: "a", Input: 1000}, // the Sunday before: not shown + {Time: from, Provider: "a", Input: 10, Output: 5, CacheRead: 100}, // the first day + {Time: from.Add(23 * time.Hour).UTC(), Provider: "b", Input: 20}, // the same local day, stamped in UTC + {Time: today.Add(-time.Nanosecond), Provider: "a", Input: 30, Status: 500}, // yesterday, failed: still a call + {Time: today.Add(time.Hour), Provider: "a", Input: 40}, + {Time: today.Add(2 * time.Hour), Provider: "a", Input: 999, Rejected: true}, + {Time: today.Add(time.Hour), Provider: "a", Input: 7, Output: 1}, // no known price + } { + r.Agent, r.Model = "codex", "m" + row := Row{Record: r, Cost: float64(r.Input) / 100, Priced: i != 6} + gateway.add(row, "", int64(i), false) + all.Rows = append(all.Rows, row) + if !r.IsRejected() { + all.Sum.addRow(row) + } + } + for name, query := range map[string]func(Filter) RequestPage{ + "compact": func(f Filter) RequestPage { return buildRequestPage(heatmapPeriod, f, 0, 1, gateway, nil) }, + "ledger": func(f Filter) RequestPage { return pageFromLedger(heatmapPeriod, f, 0, 1, all) }, + } { + t.Run(name, func(t *testing.T) { + h := query(Filter{}).Heat + if h == nil { + t.Fatal("no heatmap") + } + if h.From != "2025-10-06" || h.To != "2026-10-09" { + t.Fatalf("span: %s to %s", h.From, h.To) + } + want := []Day{ + {Date: "2025-10-06", Calls: 2, Tokens: 135, Cost: 0.3}, + {Date: "2026-10-08", Calls: 1, Tokens: 30, Cost: 0.3}, + {Date: "2026-10-09", Calls: 2, Tokens: 48, Cost: 0.4, Unpriced: 1}, + } + for i := range h.Days { + h.Days[i].Cost = math.Round(h.Days[i].Cost*1e9) / 1e9 + } + if !reflect.DeepEqual(h.Days, want) { + t.Fatalf("days:\n got %+v\nwant %+v", h.Days, want) + } + // a provider picked: only its rows; a day picked: still every day + if h := query(Filter{Provider: "b", Day: "2026-10-09"}).Heat; len(h.Days) != 1 || h.Days[0].Date != "2025-10-06" || h.Days[0].Tokens != 20 { + t.Fatalf("provider b's days: %+v", h.Days) + } + if p := query(Filter{}); p.Heat == nil { + t.Fatal("heatmap dropped") + } + }) + } + if p := buildRequestPage(Month, Filter{}, 0, 1, gateway, nil); p.Heat != nil { + t.Fatal("a page of another period has no heatmap") + } +} + +// HeatmapOf reads the log itself: a call appended today is today's, and the +// filter given narrows it. +func TestHeatmapOf(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 10, 9, 15, 0, 0, 0, time.Local)) + for i, at := range []time.Time{now.AddDate(0, 0, -400), now.AddDate(0, -3, 0), now.Add(-time.Hour), now.Add(-time.Minute)} { + Append(Record{Time: at, Agent: "claude", Provider: "openai", Model: "m", Input: 10 + i, Status: 200}) + } + Append(Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 100, Status: 200}) + h := HeatmapOf(Filter{Agent: "claude", Day: "2026-10-09"}) + want := []Day{{Date: now.AddDate(0, -3, 0).Format(time.DateOnly), Calls: 1, Tokens: 11}, {Date: "2026-10-09", Calls: 2, Tokens: 25}} + for i := range h.Days { + h.Days[i].Cost = 0 + } + if h.From != "2025-10-06" || h.To != "2026-10-09" || !reflect.DeepEqual(h.Days, want) { + t.Fatalf("heatmap: %+v", h) + } +} diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index 7614234af..03d9c4fd6 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -167,6 +167,8 @@ func (p Period) Since(now time.Time) time.Time { return day.AddDate(0, 0, -6) case Month: return day.AddDate(0, 0, -29) + case heatmapPeriod: + return heatmapSince(now) } return time.Time{} } diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 3eb887bd9..c80dc266e 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -52,6 +52,9 @@ type RequestPage struct { // other computer's calls were brought here by sync (#542) Computers []Share Names map[string]string + // Heat is the rows by day, as the chart's filter keeps them: only for + // the heatmap's own period (HeatmapOf) + Heat *Heatmap } type packedRow struct { @@ -951,6 +954,15 @@ func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, ga pt.By[d][k] = part } }) + if p == heatmapPeriod { + out.Heat = heatmapOf(since, now, func(add func(Row)) { + visit(func(_ rowRef, r Row) { + if chartFilter.keepsRow(r) { + add(r) + } + }) + }) + } // Match LedgerSeries's top-24 selection on the filtered data, not facets. for _, d := range Dimensions { kept := map[string]bool{} @@ -1018,6 +1030,13 @@ func pageFromLedgerAt(p Period, f Filter, offset, limit int, all Ledgered, now t out.ChartBy = map[string][]Share{} } out.Bucket, out.Series = ledgerSeriesAt(p, chartRows, now) + if p == heatmapPeriod { + out.Heat = heatmapOf(p.Since(now), now, func(add func(Row)) { + for _, r := range chartRows { + add(r) + } + }) + } for _, d := range Dimensions { g := f if d == "provider" {