usage: the Usage and Requests pages count any days picked, from a Custom opt after All that opens a month to pick them on (#1492, nianlee-official)

The period bar had only Today, 7 days, 30 days and All. A Custom opt now
follows them. It opens the app's own menu (no native select): Yesterday,
This month, Last month and 90 days a click away, and a month of days to
pick the first day on, then the last. Days after today can't be picked;
arrows walk the days and Escape closes. Once picked, the opt names the
days ("Oct 1 – Oct 7"), and narrow windows show only its icon until then.

The backend takes the days as period "2026-10-01..2026-10-07", both
included, in the local time zone (usage.RangeOf, Period.Known/Until).
The summary, the Requests page (index and ledger fallback), Direct and the
CSV name count only calls from the first day's midnight up to the
midnight after the last. The chart is an hour each for one day, a day each
up to 60 days, and a week each from a Monday past that. A picked range is
summarised afresh each time, so ranges never pile up in the summary cache.
The credits-per-day card follows the days picked. New strings in zh,
zh-TW, ja and de.

Run:
- go test -tags nogui ./internal/usage ./internal/gui (sandbox HOME): ok.
- TestPickedDaysArePeriod with Until returning zero (no range end):
  FAIL, Summarize 5 calls / QueryPage 5 rows / LedgerOf 5 rows, want 3.
- usage-range.test.cjs, Chromium and WebKit, en and zh, at 390px: 4/4.
- Every GUI test touching period or the Usage view (87 files): Chromium
  388/388; WebKit 386/388, the two purpose-filter's Routing focus check
  (scrollTop off by 1px after a wheel), which then passed 52 of 56 lone
  runs here and 25 of 25 on origin/main; nothing in this change runs on
  the Routing page. gui-de, gui-ja, gui-zh-tw, i18n-keys: pass.
- gofmt -l; GOOS=linux and GOOS=windows go vet -tags nogui on both pkgs.
This commit is contained in:
yetone
2026-10-10 19:15:12 +08:00
parent a5114d931f
commit 6d3bc9183d
12 changed files with 576 additions and 40 deletions
+23
View File
@@ -2141,6 +2141,29 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.proto-menu .pm-words { display: grid; gap: 1px; min-width: 0; }
.proto-menu .pm-name { font-size: 12.5px; font-weight: 500; line-height: 16px; }
.proto-menu .pm-note { font-size: 11px; color: var(--muted); line-height: 15px; }
/* Usage's days of the reader's own (#1492): the periods' last opt, and the
menu it opens, a few spans and a month of days */
.range-opt { display: inline-flex; align-items: center; gap: 5px; }
.range-opt svg { flex: none; }
.pop.proto-menu.range-menu { width: 252px; max-height: none; display: block; padding: 4px 6px 8px; }
.range-menu .rm-quick { display: flex; flex-wrap: wrap; gap: 4px; padding: 0 2px 6px; border-bottom: 1px solid var(--line-2); }
.range-menu .rm-span { height: 22px; padding: 0 8px; border-radius: 6px; background: var(--pill); color: var(--fg-2); font-size: 11.5px; }
.range-menu .rm-span:hover, .range-menu .rm-span:focus-visible { color: var(--fg); }
.range-menu .rm-span.on { color: var(--fg); background: color-mix(in srgb, var(--accent) 18%, var(--pill)); }
.range-menu .rm-nav { display: flex; align-items: center; justify-content: space-between; padding: 6px 2px 4px; }
.range-menu .rm-month { font-size: 12.5px; font-weight: 600; }
.range-menu .rm-step { display: grid; place-items: center; width: 24px; height: 24px; border-radius: 6px; color: var(--muted); }
.range-menu .rm-step:hover:not(:disabled) { background: var(--pill); color: var(--fg); }
.range-menu .rm-step:disabled { opacity: .35; }
.range-menu .rm-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px 0; }
.range-menu .rm-wd { height: 20px; display: grid; place-items: center; font-size: 10.5px; color: var(--faint); }
.range-menu .rm-day { height: 28px; font-size: 12px; font-variant-numeric: tabular-nums; color: var(--fg); border-radius: 7px; outline: none; }
.range-menu .rm-day:hover:not(:disabled), .range-menu .rm-day:focus-visible { background: var(--pill); }
.range-menu .rm-day.today { font-weight: 650; color: var(--accent); }
.range-menu .rm-day.in { background: color-mix(in srgb, var(--accent) 14%, transparent); border-radius: 0; }
.range-menu .rm-day.end { background: var(--accent); color: var(--accent-fg, #fff); }
.range-menu .rm-day:disabled { color: var(--faint); opacity: .5; }
@media (max-width: 640px) { .range-opt:not(.on) > span { display: none; } }
/* a subscription's allowance, under its name */
.accts .acc.with-aq { flex-wrap: wrap; row-gap: 3px; padding-top: 7px; padding-bottom: 8px; }
.acc .aq { flex-basis: 100%; display: flex; flex-wrap: wrap; align-items: center; gap: 4px 16px; padding-left: 25px; font-size: 10.5px; color: var(--muted); min-height: 14px; }
+171 -10
View File
@@ -13044,7 +13044,7 @@ async function loadUsage(asked) {
renderUsageLoading();
if (!asked) loadQuotas();
const p = period, read = ++usageRead;
const next = await api("usage?period=" + p);
const next = await api("usage?period=" + encodeURIComponent(p));
if (read !== usageRead || view !== "usage" || usageTab !== "usage" || period !== p) return;
usage = next;
renderUsage();
@@ -13086,12 +13086,169 @@ function renderPeriod(loading) {
for (const [id, name] of PERIODS) {
const b = el("button", "opt" + (id === period ? " on" : ""), t(name));
b.disabled = !!loading;
b.onclick = () => { for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "period"); period = id; ledDay = ""; ledOffset = 0; loadUsage().catch((e) => status(e.message, "err")); };
b.onclick = () => { for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b); slide(seg, "period"); pickPeriod(id); };
seg.append(b);
}
// days of the reader's own (#1492): the last opt names them once picked,
// and opens the range menu to pick them, or others
const range = periodDays(period);
const b = el("button", "opt range-opt" + (range ? " on" : ""));
b.type = "button";
b.disabled = !!loading;
b.setAttribute("aria-haspopup", "dialog");
b.setAttribute("aria-expanded", "false");
b.setAttribute("aria-label", range ? t("Days picked: {days}", { days: rangeName(range) }) : t("Pick days"));
b.append(svg("M3 4.5h10v8.5H3zM3 7h10M5.5 3v3M10.5 3v3", 12, 1.4), el("span", "", range ? rangeName(range) : t("Custom")));
if (range) b.title = t("Days picked: {days}", { days: rangeName(range) });
b.onclick = () => {
if (b.classList.contains("open")) return closeProtoMenu();
openRangeMenu(b, range, (from, to) => {
for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b);
b.lastChild.textContent = rangeName({ from, to });
b.title = t("Days picked: {days}", { days: rangeName({ from, to }) });
b.setAttribute("aria-label", b.title);
slide(seg, "period");
pickPeriod(from + ".." + to);
});
};
seg.append(b);
slide(seg, "period");
}
function pickPeriod(id) {
period = id; ledDay = ""; ledOffset = 0;
loadUsage().catch((e) => status(e.message, "err"));
}
// A period of picked days is "2026-10-01..2026-10-07", both included, in
// this computer's time zone, as the backend reads it (usage.RangeOf).
// periodDays is its two days, or null for a preset.
function periodDays(p) {
const m = /^(\d{4}-\d{2}-\d{2})\.\.(\d{4}-\d{2}-\d{2})$/.exec(p || "");
return m ? { from: m[1], to: m[2] } : null;
}
const dayKeyOf = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const dayOfKey = (k) => new Date(k + "T12:00:00");
// rangeName says picked days short: "Oct 1 – Oct 7", the year only when it
// isn't this one, one day alone as itself
function rangeName({ from, to }) {
const year = new Date().getFullYear();
const name = (k) => dayOfKey(k).toLocaleDateString(intlLang() || "en", { month: "short", day: "numeric", ...(dayOfKey(k).getFullYear() !== year ? { year: "numeric" } : {}) });
return from === to ? name(from) : name(from) + " – " + name(to);
}
// noCallsIn is what an empty page says of the period it is on
function noCallsIn(p) {
if (periodDays(p)) return "No calls on the days picked.";
return { today: "No calls today.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[p] || "No calls yet.";
}
// openRangeMenu is the app's own menu for picking days (#1492): a few
// spans a click away, and a month to pick the first day on, then the last.
// Days after today can't be picked. choose gets the two days, in order.
function openRangeMenu(anchor, current, choose) {
closeProtoMenu();
const today = dayKeyOf(new Date());
let start = null; // the first day clicked, waiting for the last
let shown = dayOfKey(current?.to || today);
shown = new Date(shown.getFullYear(), shown.getMonth(), 1, 12);
const box = el("div", "pop proto-menu range-menu");
box.setAttribute("role", "dialog");
box.setAttribute("aria-label", t("Pick days"));
const head = el("div", "pm-head");
const quick = el("div", "rm-quick");
const span = (from, to) => ({ from: dayKeyOf(from), to: dayKeyOf(to) });
const now = new Date();
now.setHours(12, 0, 0, 0);
const back = (n) => { const d = new Date(now); d.setDate(d.getDate() - n); return d; };
const quicks = [
["Yesterday", span(back(1), back(1))],
["This month", span(new Date(now.getFullYear(), now.getMonth(), 1, 12), now)],
["Last month", span(new Date(now.getFullYear(), now.getMonth() - 1, 1, 12), new Date(now.getFullYear(), now.getMonth(), 0, 12))],
["90 days", span(back(89), now)],
];
for (const [name, r] of quicks) {
const b = el("button", "rm-span" + (current && current.from === r.from && current.to === r.to ? " on" : ""), t(name));
b.type = "button";
b.title = rangeName(r);
b.onclick = (e) => { e.stopPropagation(); closeProtoMenu(); choose(r.from, r.to); };
quick.append(b);
}
const nav = el("div", "rm-nav");
const prev = el("button", "rm-step"), next = el("button", "rm-step"), month = el("span", "rm-month");
prev.type = next.type = "button";
prev.setAttribute("aria-label", t("Previous month"));
next.setAttribute("aria-label", t("Next month"));
prev.append(svg("M10 4 6 8l4 4", 12, 1.6));
next.append(svg("m6 4 4 4-4 4", 12, 1.6));
nav.append(prev, month, next);
const grid = el("div", "rm-grid");
grid.setAttribute("role", "grid");
box.append(head, quick, nav, grid);
const draw = (focusDay) => {
head.textContent = start ? t("Now the last day") : t("Pick the first day, then the last");
month.textContent = shown.toLocaleDateString(intlLang() || "en", { year: "numeric", month: "long" });
next.disabled = dayKeyOf(new Date(shown.getFullYear(), shown.getMonth() + 1, 1, 12)) > today;
const cells = [];
// the weekdays, Monday first, as the app's weeks are
for (let i = 0; i < 7; i++) cells.push(el("span", "rm-wd", new Date(2024, 0, 1 + i, 12).toLocaleDateString(intlLang() || "en", { weekday: "narrow" })));
const first = new Date(shown);
const lead = (first.getDay() + 6) % 7;
for (let i = 0; i < lead; i++) cells.push(el("span", "rm-pad"));
const lo = start || current?.from, hi = start ? null : current?.to;
for (let d = new Date(first); d.getMonth() === shown.getMonth(); d.setDate(d.getDate() + 1)) {
const k = dayKeyOf(d);
const b = el("button", "rm-day", String(d.getDate()));
b.type = "button";
b.dataset.day = k;
b.setAttribute("aria-label", d.toLocaleDateString(intlLang() || "en", { year: "numeric", month: "long", day: "numeric" }));
if (k === today) b.classList.add("today");
if (lo && (k === lo || k === hi)) b.classList.add("end");
if (lo && hi && k > lo && k < hi) b.classList.add("in");
b.disabled = k > today;
b.onclick = (e) => {
e.stopPropagation();
if (!start) { start = k; draw(k); return; }
const [from, to] = start <= k ? [start, k] : [k, start];
closeProtoMenu();
choose(from, to);
};
cells.push(b);
}
grid.replaceChildren(...cells);
(focusDay && grid.querySelector(`[data-day="${focusDay}"]`))?.focus({ preventScroll: true });
};
const turn = (by) => (e) => { e.stopPropagation(); shown = new Date(shown.getFullYear(), shown.getMonth() + by, 1, 12); draw(); };
prev.onclick = turn(-1);
next.onclick = turn(1);
draw();
document.body.append(box);
placeMenu(box, anchor);
anchor.classList.add("open");
anchor.setAttribute("aria-expanded", "true");
const outside = (e) => { if (!box.contains(e.target) && !anchor.contains(e.target)) closeProtoMenu(); };
const scroll = (e) => { if (!box.contains(e.target)) closeProtoMenu(); };
// Escape closes; arrows walk the days, a week up or down
const keys = (e) => {
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeProtoMenu(); anchor.focus({ preventScroll: true }); return; }
const at = document.activeElement?.dataset?.day;
const by = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[e.key];
if (!at || !by || !box.contains(document.activeElement)) return;
e.preventDefault(); e.stopPropagation();
const d = dayOfKey(at);
d.setDate(d.getDate() + by);
const k = dayKeyOf(d);
if (k > today) return;
if (d.getMonth() !== shown.getMonth() || d.getFullYear() !== shown.getFullYear()) shown = new Date(d.getFullYear(), d.getMonth(), 1, 12);
draw(k);
};
document.addEventListener("mousedown", outside, true);
document.addEventListener("keydown", keys, true);
document.addEventListener("scroll", scroll, true);
addEventListener("resize", closeProtoMenu);
protoMenu = { box, anchor, outside, keys, scroll, done: null };
(grid.querySelector(".rm-day.end") || grid.querySelector(".rm-day.today") || quick.firstChild).focus({ preventScroll: true });
}
function renderUsageLoading() {
const view = $("#view-usage");
view.classList.add("loading");
@@ -13514,12 +13671,16 @@ function creditDays(sub) {
const key = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const today = new Date();
today.setHours(12, 0, 0, 0);
// the period's days, the first from when counting began for All
let n = { today: 1, "7d": 7, "30d": 30 }[period];
if (!n) n = Math.min(120, Math.max(1, Math.round((today - new Date(since + "T12:00:00")) / 864e5) + 1));
// the period's days, the first from when counting began for All, a
// picked range's own (#1492), its last 120 at most
const range = periodDays(period);
const last = range ? dayOfKey(range.to) : today;
let n = range ? Math.round((last - dayOfKey(range.from)) / 864e5) + 1 : { today: 1, "7d": 7, "30d": 30 }[period];
if (!n) n = Math.round((today - new Date(since + "T12:00:00")) / 864e5) + 1;
n = Math.min(120, Math.max(1, n));
const list = [];
for (let i = n - 1; i >= 0; i--) {
const d = new Date(today);
const d = new Date(last);
d.setDate(d.getDate() - i);
list.push({ day: key(d), date: d, used: by.get(key(d)) || 0, known: key(d) >= since });
}
@@ -13529,7 +13690,7 @@ function creditDays(sub) {
const head = el("div", "cd-head");
const name = el("span", "", t("Credits used per day"));
name.title = t("Counted from magpie's readings of the vendor's meter, since {date}: what is used while magpie isn't reading it is counted on the day it next does", { date: dayName(new Date(since + "T12:00:00")) });
head.append(name, el("b", "", n === 1 ? t("{n} today", { n: num(sum) }) : t("{n} in {days} days", { n: num(sum), days: n })));
head.append(name, el("b", "", n > 1 ? t("{n} in {days} days", { n: num(sum), days: n }) : range && range.to !== key(today) ? t("{n} on {date}", { n: num(sum), date: dayName(last) }) : t("{n} today", { n: num(sum) })));
box.append(head);
if (n > 1) {
const bars = el("div", "cd-bars");
@@ -15214,7 +15375,7 @@ function renderUsage() {
$("#usageAccountsHead").hidden = $("#usageAccounts").hidden = empty || !u.accounts?.length;
if (empty) {
stats.classList.add("empty");
const none = { today: "No calls today.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[period];
const none = noCallsIn(period);
stats.append(el("div", "none", t(none) + " " + t("Point an agent at a catalog model and use it; every call through the gateway is counted here.")));
$("#usageNote").textContent = "";
return;
@@ -16468,7 +16629,7 @@ function renderLedger() {
if (!l.total) {
wrap.classList.add("none");
const filtered = ledPurpose || ledDay || ledRoute || ledAgent || ledProvider || ledAccount || ledComputer || ledCallerKey || ledModel || ledVia || ledFailed || ledQuery.trim();
const none = { today: "No calls today.", "7d": "No calls in the last 7 days.", "30d": "No calls in the last 30 days.", all: "No calls yet." }[period];
const none = noCallsIn(period);
wrap.replaceChildren(el("div", "led-none", filtered ? t("No requests match these filters.") : t(none)));
ledFit();
ledHScroll();
@@ -21292,7 +21453,7 @@ function refreshUsage(now = false) {
else if (usage && performance.now() - quotasAsked > 60e3) { quotasAsked = performance.now(); loadQuotas(); }
if (usage) {
const p = period, read = ++usageRead;
const u = await api("usage?period=" + p);
const u = await api("usage?period=" + encodeURIComponent(p));
if (read === usageRead && view === "usage" && usageTab === "usage" && p === period) {
if (JSON.stringify(u) !== JSON.stringify(usage)) { usage = u; renderUsage(); }
// this read claimed the newest one: a pick it superseded had put the
+44
View File
@@ -4,6 +4,17 @@
// works. {name} slots are filled by t(str, vars).
const I18N = {
zh: {
"Yesterday": "昨天",
"This month": "本月",
"Last month": "上个月",
"Pick days": "选择日期",
"Previous month": "上个月",
"Next month": "下个月",
"Days picked: {days}": "所选日期:{days}",
"Now the last day": "再选最后一天",
"Pick the first day, then the last": "先选第一天,再选最后一天",
"No calls on the days picked.": "所选日期内没有调用。",
"{n} on {date}": "{date} {n}",
"You set {value}; the model's {window} comes first": "你设置的是 {value},但模型的 {window} 优先",
"Auto-compact": "自动压缩",
"Prompt cache · main conversation": "提示缓存 · 主对话",
@@ -4005,6 +4016,17 @@ const I18N = {
"Video · 7 days": "视频 · 7 天",
},
"zh-TW": {
"Yesterday": "昨天",
"This month": "本月",
"Last month": "上個月",
"Pick days": "選擇日期",
"Previous month": "上個月",
"Next month": "下個月",
"Days picked: {days}": "所選日期:{days}",
"Now the last day": "再選最後一天",
"Pick the first day, then the last": "先選第一天,再選最後一天",
"No calls on the days picked.": "所選日期內沒有呼叫。",
"{n} on {date}": "{date} {n}",
"You set {value}; the model's {window} comes first": "你設定的是 {value},但模型的 {window} 優先",
"Auto-compact": "自動壓縮",
"Prompt cache · main conversation": "提示快取 · 主對話",
@@ -7989,6 +8011,17 @@ const I18N = {
"Video · 7 days": "影片 · 7 天",
},
ja: {
"Yesterday": "昨日",
"This month": "今月",
"Last month": "先月",
"Pick days": "日付を選ぶ",
"Previous month": "前の月",
"Next month": "次の月",
"Days picked: {days}": "選んだ日付:{days}",
"Now the last day": "次に最終日を選択",
"Pick the first day, then the last": "最初の日、次に最終日を選択",
"No calls on the days picked.": "選んだ日付の呼び出しはありません。",
"{n} on {date}": "{date} {n}",
"You set {value}; the model's {window} comes first": "設定は {value} ですが、モデルの {window} が優先されます",
"Auto-compact": "自動コンパクト",
"Prompt cache · main conversation": "プロンプトキャッシュ · メイン会話",
@@ -11975,6 +12008,17 @@ const I18N = {
"Main navigation": "メインナビゲーション",
},
de: {
"Yesterday": "Gestern",
"This month": "Dieser Monat",
"Last month": "Letzter Monat",
"Pick days": "Tage wählen",
"Previous month": "Vorheriger Monat",
"Next month": "Nächster Monat",
"Days picked: {days}": "Gewählte Tage: {days}",
"Now the last day": "Jetzt den letzten Tag",
"Pick the first day, then the last": "Erst den ersten Tag, dann den letzten wählen",
"No calls on the days picked.": "An den gewählten Tagen keine Aufrufe.",
"{n} on {date}": "{n} am {date}",
"You set {value}; the model's {window} comes first": "Du hast {value} gesetzt; das Fenster des Modells ({window}) hat Vorrang",
"Auto-compact": "Auto-Kompaktierung",
"Prompt cache · main conversation": "Prompt-Cache · Hauptunterhaltung",
+143
View File
@@ -0,0 +1,143 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Usage's days of the reader's own (#1492, nianlee-official): after Today,
// 7 days, 30 days and All, a Custom opt opens the app's own menu (never a
// native <select>) with a few spans and a month of days. Picking a first day
// then a last asks the backend for "first..last", the opt then names the days,
// days after today can't be picked, a span is a click away, Escape and a click
// outside close it, and nothing scrolls the page. English and Chinese, at a
// phone's width; no backend, the API is faked here.
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(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets"));
const dayKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
const back = (n) => { const d = new Date(); d.setHours(12, 0, 0, 0); d.setDate(d.getDate() - n); return d; };
function serve(lang, asked) {
const settings = { theme: "light", lang, quotaLeft: false, currency: "usd" };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings });
if (url.pathname === "/api/settings") return json(settings);
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/usage") {
const p = url.searchParams.get("period");
asked.push(p);
return json({ period: p, calls: 0, errors: 0, input: 0, output: 0, reasoning: 0, unpriced: 0, cost: 0, bucket: "day", series: [], agents: [], models: [], path: "" });
}
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/sessions") return json({ sessions: [], dirs: [] });
if (url.pathname === "/api/sessions/stats") return json({ from: "", to: "", days: [], agents: {} });
if (url.pathname.startsWith("/api/")) 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 words = {
en: { custom: "Custom", yesterday: "Yesterday", head: "Pick the first day, then the last", next: "Now the last day", none: "No calls on the days picked." },
zh: { custom: "自定义", yesterday: "昨天", head: "先选第一天,再选最后一天", next: "再选最后一天", none: "所选日期内没有调用。" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
test(`${engine} ${lang}: Usage over days of the reader's own`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
let page;
t.after(async () => {
if (process.env.ARTIFACT_DIR && page) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-usage-range.png`) });
}
await browser.close();
});
page = await (await browser.newContext({ viewport: { width: 390, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const asked = [];
await page.route("**/*", serve(lang, asked));
await page.goto("http://magpie.test/?view=usage");
const opt = page.locator("#period .range-opt");
await opt.waitFor();
await page.waitForFunction(() => !document.querySelector("#period .opt:disabled"));
assert.equal(await opt.getAttribute("aria-haspopup"), "dialog");
const scrollY = () => page.evaluate(() => [scrollY, document.querySelector("#view-usage").scrollTop]);
const y = await scrollY();
// the menu: the app's own, never a native select, whole on the page
await opt.click();
const menu = page.locator(".range-menu");
await menu.waitFor();
assert.equal(await menu.locator(".pm-head").textContent(), w.head);
assert.equal(await page.locator("select").count(), 0);
const box = await menu.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 390, `the menu runs off a phone's width: ${JSON.stringify(box)}`);
assert.deepEqual(await menu.evaluate((m) => [getComputedStyle(m).borderLeftWidth === getComputedStyle(m).borderRightWidth]), [true]);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "the page scrolls sideways");
// a day after today can't be picked
const tomorrow = dayKey(back(-1));
const later = menu.locator(`.rm-day[data-day="${tomorrow}"]`);
if (await later.count()) assert.equal(await later.isDisabled(), true);
assert.equal(await menu.locator(".rm-step").last().isDisabled(), true, "no month after this one");
// Escape closes it
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
// first day then last, in either order: from the earlier
const first = back(9), last = back(3);
await opt.click();
await menu.waitFor();
const day = async (d) => {
for (let i = 0; i < 3 && !(await menu.locator(`.rm-day[data-day="${dayKey(d)}"]`).count()); i++) await menu.locator(".rm-step").first().click();
await menu.locator(`.rm-day[data-day="${dayKey(d)}"]`).click();
};
asked.length = 0;
await day(last);
assert.equal(await menu.locator(".pm-head").textContent(), w.next);
assert.deepEqual(asked, [], "one day clicked asks for nothing yet");
await day(first);
await menu.waitFor({ state: "detached" });
await page.waitForFunction(() => document.querySelector("#period .range-opt.on"));
const want = dayKey(first) + ".." + dayKey(last);
assert.ok(asked.includes(want), `asked for ${JSON.stringify(asked)}, want ${want}`);
assert.equal(await page.locator("#period .opt.on").count(), 1, "one opt is on");
const label = (await opt.textContent()).trim();
assert.match(label, /–/, "the opt names the days picked: " + label);
// the empty page says so of the days picked
await page.waitForFunction((none) => document.querySelector("#view-usage").textContent.includes(none), w.none);
// the menu again opens on the days picked, and a span is a click away
await opt.click();
await menu.waitFor();
assert.equal(await menu.locator(".rm-day.end").count() >= 1, true);
asked.length = 0;
await menu.locator(".rm-span", { hasText: w.yesterday }).click();
await menu.waitFor({ state: "detached" });
await page.waitForFunction(() => !document.querySelector("#period .opt:disabled"));
assert.deepEqual(asked, [dayKey(back(1)) + ".." + dayKey(back(1))]);
assert.doesNotMatch((await opt.textContent()).trim(), /–/, "one day is named alone");
// a click outside closes it, and back to a preset
await opt.click();
await menu.waitFor();
await page.mouse.click(380, 740);
await menu.waitFor({ state: "detached" });
await page.locator("#period .opt").first().click();
await page.waitForFunction(() => !document.querySelector("#period .range-opt.on"));
assert.equal((await opt.textContent()).trim(), w.custom);
assert.deepEqual(await scrollY(), y, "a click scrolled the page");
assert.deepEqual(errors, []);
});
}
}
+7 -9
View File
@@ -108,9 +108,10 @@ func callerUsageGroups(s usage.Summary) []usageGroup {
return keys
}
// periodOf is the period a ?period= names: a preset, or days picked as
// "2026-10-01..2026-10-07" (#1492); 30 days for anything else.
func periodOf(s string) usage.Period {
switch p := usage.Period(s); p {
case usage.Today, usage.Week, usage.Month, usage.All:
if p := usage.Period(s); p.Known() {
return p
}
return usage.Month
@@ -122,6 +123,9 @@ func csvStamp(p usage.Period, day string, now time.Time) string {
if _, err := time.Parse(time.DateOnly, day); err == nil {
return "magpie-requests-day-" + day
}
if p.IsRange() { // the days picked, which already say when
return "magpie-requests-" + strings.Replace(string(p), "..", "-to-", 1)
}
return "magpie-requests-" + string(p) + "-" + now.Format(time.DateOnly)
}
@@ -375,13 +379,7 @@ func requestContent(agent, session string, from, to, at time.Time) contentJSON {
func usageRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("GET /api/usage", func(rw http.ResponseWriter, r *http.Request) {
p := usage.Period(r.URL.Query().Get("period"))
switch p {
case usage.Today, usage.Week, usage.Month, usage.All:
default:
p = usage.Month
}
writeJSON(rw, usageState(p))
writeJSON(rw, usageState(periodOf(r.URL.Query().Get("period"))))
})
// the ledger: the period's calls, newest first, a page at a time
mux.HandleFunc("GET /api/usage/requests", func(rw http.ResponseWriter, r *http.Request) {
+3 -4
View File
@@ -28,9 +28,8 @@ func Summaries(p Period) (Summary, Summary) {
func direct(p Period, now time.Time, rows []Row) Summary {
s := Summary{Period: p, Since: p.Since(now), Bucket: "day", Agents: []Group{}, Models: []Group{}, ProviderKeys: []Group{}, Accounts: []Group{}, CallerKeys: []Group{}, Sessions: []Group{}, Series: []Point{}}
if p != Today && p != Week && p != Month {
s.Period = All
}
s.Period = p.shown()
until := p.Until(now)
agents, models, accounts, sessions := map[string]*Group{}, map[string]*Group{}, map[string]*Group{}, map[string]*Group{}
put := func(m map[string]*Group, k string, g Group, r Row) {
if m[k] == nil {
@@ -39,7 +38,7 @@ func direct(p Period, now time.Time, rows []Row) Summary {
m[k].addRow(r)
}
for _, r := range rows {
if r.Source != "log" || r.IsRejected() || r.Time.Before(s.Since) {
if r.Source != "log" || r.IsRejected() || r.Time.Before(s.Since) || after(until, r.Time) {
continue
}
s.Totals.addRow(r)
+27 -9
View File
@@ -159,6 +159,9 @@ func (f Filter) keeps(r Record) bool {
// Since is when the period began, as of now; zero for all.
func (p Period) Since(now time.Time) time.Time {
if first, _, ok := p.days(now.Location()); ok {
return first
}
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
switch p {
case Today:
@@ -212,7 +215,7 @@ func LedgerOfAt(p Period, f Filter, now time.Time) Ledgered {
if reader == nil {
reader = sessions.Calls
}
rows, sum, agents, providers := ledgerWithShared(since, f, Load(gatewaySince), reader(since), sharedRecords(since))
rows, sum, agents, providers := ledgerWithShared(since, p.Until(now), f, Load(gatewaySince), reader(since), sharedRecords(since))
return Ledgered{rows, sum, agents, providers}
}
@@ -322,12 +325,13 @@ func gatewayMatches(recs []Record, logs []sessions.Call) map[int]bool {
}
func ledgerWith(since time.Time, f Filter, recs []Record, logs []sessions.Call) (rows []Row, sum Totals, agents, providers []string) {
return ledgerWithShared(since, f, recs, logs, nil)
return ledgerWithShared(since, time.Time{}, f, recs, logs, nil)
}
// ledgerWithShared is ledgerWith with the calls other computers made (#542),
// priced and judged here as this computer's are.
func ledgerWithShared(since time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall) (rows []Row, sum Totals, agents, providers []string) {
// priced and judged here as this computer's are, and none from until on (a
// picked range's end, #1492; zero for none).
func ledgerWithShared(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall) (rows []Row, sum Totals, agents, providers []string) {
renamed := provider.Renamed()
// the upstream names in force now, read once for the lot: a row is
// judged by the names standing today, which is what Ledger says, and
@@ -364,7 +368,7 @@ func ledgerWithShared(since time.Time, f Filter, recs []Record, logs []sessions.
}
for i := len(recs) - 1; i >= 0; i-- {
r := recs[i]
if !since.IsZero() && r.Time.Before(since) {
if !since.IsZero() && r.Time.Before(since) || after(until, r.Time) {
continue
}
if id, ok := renamed[r.Provider]; ok {
@@ -373,7 +377,7 @@ func ledgerWithShared(since time.Time, f Filter, recs []Record, logs []sessions.
add(r, priceOf(r), "")
}
for i, c := range logs {
if (!since.IsZero() && c.Time.Before(since)) || matched[i] {
if (!since.IsZero() && c.Time.Before(since)) || after(until, c.Time) || matched[i] {
continue
}
// Session identity does not establish a billing provider; price the
@@ -386,7 +390,7 @@ func ledgerWithShared(since time.Time, f Filter, recs []Record, logs []sessions.
}
for _, c := range others {
r := c.Record
if !since.IsZero() && r.Time.Before(since) {
if !since.IsZero() && r.Time.Before(since) || after(until, r.Time) {
continue
}
if id, ok := renamed[r.Provider]; ok {
@@ -489,7 +493,21 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
bucket, pts = "day", []Point{}
var n int
if first, last, ok := p.days(now.Location()); ok {
// a picked range: an hour each of a single day, else a day each,
// a week each (from a Monday) past 60 days as All has
since, n = first, calendarDays(first, last)+1
if n == 1 {
bucket = "hour"
} else if n > 60 {
bucket = "week"
since = since.AddDate(0, 0, -((int(since.Weekday()) + 6) % 7))
n = calendarDays(since, last)/7 + 1
}
p = ""
}
switch p {
case "":
case Today:
since, bucket = day, "hour"
case Week:
@@ -513,8 +531,8 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
}
switch bucket {
case "hour":
for h := 0; day.Add(time.Duration(h) * time.Hour).Before(day.AddDate(0, 0, 1)); h++ {
t := day.Add(time.Duration(h) * time.Hour)
for h := 0; since.Add(time.Duration(h) * time.Hour).Before(since.AddDate(0, 0, 1)); h++ {
t := since.Add(time.Duration(h) * time.Hour)
pts = append(pts, Point{Label: t.Format("15"), Time: t})
}
case "day":
+77
View File
@@ -0,0 +1,77 @@
package usage
import (
"strings"
"time"
)
// A period can also be days the reader picked (#1492): from one date to
// another, both whole days and both included, in the local time zone,
// written "2026-10-01..2026-10-07". It begins at the first day's midnight and
// ends at the midnight after the last, where the presets end at now.
const rangeSep = ".."
// RangeOf is the period of the days from one date (YYYY-MM-DD) to another,
// in either order; ok is false when either is not a date.
func RangeOf(from, to string) (Period, bool) {
a, err1 := time.Parse(time.DateOnly, from)
b, err2 := time.Parse(time.DateOnly, to)
if err1 != nil || err2 != nil {
return "", false
}
if b.Before(a) {
a, b = b, a
}
return Period(a.Format(time.DateOnly) + rangeSep + b.Format(time.DateOnly)), true
}
// days is the first and last day of a picked range, at midnight in loc.
func (p Period) days(loc *time.Location) (first, last time.Time, ok bool) {
from, to, found := strings.Cut(string(p), rangeSep)
if !found {
return
}
a, err1 := time.ParseInLocation(time.DateOnly, from, loc)
b, err2 := time.ParseInLocation(time.DateOnly, to, loc)
if err1 != nil || err2 != nil || b.Before(a) {
return
}
return a, b, true
}
// IsRange is whether p is days the reader picked rather than a preset.
func (p Period) IsRange() bool {
_, _, ok := p.days(time.UTC)
return ok
}
// Known is whether p is a period the usage pages answer for: a preset or a
// picked range.
func (p Period) Known() bool {
switch p {
case Today, Week, Month, All:
return true
}
return p.IsRange()
}
// Until is when the period ends, as of now: the midnight after a picked
// range's last day, zero for a preset, which runs up to now.
func (p Period) Until(now time.Time) time.Time {
if _, last, ok := p.days(now.Location()); ok {
return last.AddDate(0, 0, 1)
}
return time.Time{}
}
// after is whether t falls past the period's end.
func after(until, t time.Time) bool { return !until.IsZero() && !t.Before(until) }
// shown is the period a summary says it is of: the preset or range asked
// for, and All for anything else.
func (p Period) shown() Period {
if p == Today || p == Week || p == Month || p.IsRange() {
return p
}
return All
}
+63
View File
@@ -0,0 +1,63 @@
package usage
import (
"testing"
"time"
)
// Days the reader picked (#1492, nianlee-official) are a period of their own:
// the Usage page, the Requests page, the ledger and Direct count the calls of
// those days and nothing after the last, under a chart of those days, an hour
// each for one day and a week each past 60 days.
func TestPickedDaysArePeriod(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 10, 10, 12, 0, 0, 0, time.Local))
day := func(m time.Month, d, h int) time.Time { return time.Date(2026, m, d, h, 0, 0, 0, time.Local) }
for _, at := range []time.Time{
day(9, 30, 23), // the day before
day(10, 1, 0), // the first day's first hour
day(10, 2, 9),
day(10, 3, 23), // the last day's last hour
day(10, 4, 0), // the day after
day(10, 9, 12),
} {
Append(Record{Time: at, Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
}
p, ok := RangeOf("2026-10-03", "2026-10-01") // either order
if !ok || p != "2026-10-01..2026-10-03" || !p.Known() {
t.Fatalf("RangeOf: %q %v", p, ok)
}
if !p.Since(now).Equal(day(10, 1, 0)) || !p.Until(now).Equal(day(10, 4, 0)) {
t.Errorf("%s: from %v until %v", p, p.Since(now), p.Until(now))
}
s := Summarize(p)
if s.Calls != 3 || s.Period != p || s.Bucket != "day" || len(s.Series) != 3 || !s.Series[0].Time.Equal(day(10, 1, 0)) {
t.Errorf("Summarize(%s): %d calls, period %q, %d %s points; want 3 calls in 3 days", p, s.Calls, s.Period, len(s.Series), s.Bucket)
}
if pg := QueryPage(p, Filter{}, 0, 10); pg.Total != 3 {
t.Errorf("QueryPage(%s): %d rows, want 3", p, pg.Total)
}
if l := LedgerOf(p, Filter{}); len(l.Rows) != 3 {
t.Errorf("LedgerOf(%s): %d rows, want 3", p, len(l.Rows))
}
if d := Direct(p); d.Period != p || !d.Since.Equal(day(10, 1, 0)) {
t.Errorf("Direct(%s): period %q since %v", p, d.Period, d.Since)
}
// one day: its hours
one, _ := RangeOf("2026-10-09", "2026-10-09")
if s := Summarize(one); s.Calls != 1 || s.Bucket != "hour" || len(s.Series) != 24 {
t.Errorf("Summarize(%s): %d calls, %d %s points; want 1 in 24 hours", one, s.Calls, len(s.Series), s.Bucket)
}
// past 60 days: weeks from a Monday, and still none after the last day
long, _ := RangeOf("2026-07-01", "2026-10-01")
if s := Summarize(long); s.Calls != 2 || s.Bucket != "week" || s.Series[0].Time.Weekday() != time.Monday {
t.Errorf("Summarize(%s): %d calls in %s points from %v; want 2 in weeks from a Monday", long, s.Calls, s.Bucket, s.Since)
}
for _, bad := range []Period{"2026-10-03..2026-10-01", "2026-13-01..2026-13-02", "x..y", "90d"} {
if bad.Known() {
t.Errorf("%q is known", bad)
}
}
}
+2 -2
View File
@@ -743,14 +743,14 @@ func buildRequestPage(p Period, f Filter, offset, limit int, gateway *rowChunk,
// days are read from it.
func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string) RequestPage {
skip := visibleLocal(chunks)
since := p.Since(now)
since, until := p.Since(now), p.Until(now)
matched := matchedBlocks(gateways, chunks, skip, since, true)
all := append(append(slices.Clone(gateways), chunks...), others...)
visit := func(fn func(rowRef, Row)) {
for _, c := range all {
for i, pr := range c.Rows {
ref := rowRef{c, i}
if pr.Time.Before(since) || skip[ref] || matched[ref] {
if pr.Time.Before(since) || after(until, pr.Time) || skip[ref] || matched[ref] {
continue
}
fn(ref, c.row(i))
+9 -3
View File
@@ -27,10 +27,16 @@ var summaries struct {
}
func indexedSummary(p Period, now time.Time) Summary {
if p != Today && p != Week && p != Month {
p = All
}
p = p.shown()
snapshot := logSnapshotFor(true)
if p.IsRange() {
// a picked range is read afresh each time, so ranges never pile up
// in the cache (#1492)
if snapshot.uncached && len(snapshot.blocks) == 0 {
snapshot = readLogSnapshot()
}
return summarizeFrom(p, now, snapshot.first, snapshot.keyProviders, func(fn func(Record)) { snapshot.visit(p.Since(now), fn) })
}
meta := usagePriceCacheKey(now)
summaries.Lock()
old, ok := summaries.entries[p]
+7 -3
View File
@@ -584,8 +584,14 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
normalizedKeys[id] = true
}
historicalKeys = normalizedKeys
// a picked range's own days alone: its chart can start on the Monday
// before its first, and it ends before now (#1492)
from, until := p.Since(now), p.Until(now)
visit := func(fn func(Record)) {
read(func(r Record) {
if r.Time.Before(from) || after(until, r.Time) {
return
}
if next, ok := renamed[r.Provider]; ok {
r.Provider = next
}
@@ -594,9 +600,7 @@ func summarizeFrom(p Period, now time.Time, first time.Time, historicalKeys map[
}
s := Summary{Period: p, Bucket: "day", Agents: []Group{}, Models: []Group{}, ProviderKeys: []Group{}, Accounts: []Group{}, CallerKeys: []Group{}, Sessions: []Group{}, Series: []Point{}}
s.Since, s.Bucket, s.Series = timeline(p, now, first)
if p != Today && p != Week && p != Month {
s.Period = All
}
s.Period = p.shown()
priceOf := pricer()
// the places each provider id went in the period, and goes now