usage: picked days can start and end at a minute
blrbrzkj on Discord asked to see usage from one time to another, not only whole days. The range menu has a start and an end time under its month (empty is the whole day; 9:30, 0930 and 09:30 all read 09:30). Picked with the days, the period is "2026-10-01T09:30..2026-10-01T18:00"; Enter applies new times to the days already picked. A time that isn't one, or an end not after the start on one day, is marked and asks for nothing. The opt says "Oct 1 09:30 – 18:00". The backend reads either end as a date or a date with its minute (usage.RangeOf, bounds); an untimed end is its next midnight. A timed range of 48 hours or less is drawn by the hour from the first's hour. CSV names drop the colons. Run (mote): node --test usage-range-times (new, chromium + webkit, en + zh), usage-range, i18n-keys, credit-days: 26/26 ok. go test ./internal/usage ./internal/gui ok (TestCoreScriptBudget fits, the periodDays comment cut to pay for its regex); gofmt clean; go vet native, GOOS=windows (usage, gui), GOOS=linux (usage) ok. Broken by hand: a timed end read as its day's midnight turns TestPickedMinutesArePeriod red. The page's own typedTime first clashed with app.js's hhmm and stopped the Usage page mounting; the GUI run caught it. Not tried: the real app with a real ledger; ja/de/zh-TW screens. Reported-by: blrbrzkj (Discord)
This commit is contained in:
@@ -3087,6 +3087,13 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
.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; }
|
||||
/* the minutes the first day begins at and the last ends at */
|
||||
.range-menu .rm-times { display: flex; align-items: center; gap: 6px; margin-top: 6px; padding: 7px 2px 0; border-top: 1px solid var(--line-2); color: var(--muted); }
|
||||
.range-menu .rm-times svg { flex: none; }
|
||||
.range-menu .rm-time { width: 52px; height: 24px; padding: 0 6px; border: 1px solid var(--line-2); border-radius: 6px; background: transparent; color: var(--fg); font: inherit; font-size: 12px; font-variant-numeric: tabular-nums; text-align: center; }
|
||||
.range-menu .rm-time:focus { outline: none; border-color: var(--accent); }
|
||||
.range-menu .rm-time[aria-invalid="true"] { border-color: var(--red); }
|
||||
.range-menu .rm-dash { color: var(--faint); }
|
||||
@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; }
|
||||
|
||||
@@ -15909,12 +15909,11 @@ function keepRefreshedQuotas(next, began) {
|
||||
return out.concat([...kept.values()]);
|
||||
}
|
||||
|
||||
// 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.
|
||||
// Picked days, "2026-10-01..2026-10-07T18:00", both in, in this computer's
|
||||
// zone (usage.RangeOf): periodDays is their days and minutes, or null.
|
||||
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 m = /^([\d-]{10})(?:T([\d:]{5}))?\.\.([\d-]{10})(?:T([\d:]{5}))?$/.exec(p || "");
|
||||
return m ? { from: m[1], to: m[3], fromAt: m[2] || "", toAt: m[4] || "" } : null;
|
||||
}
|
||||
const dayOfKey = (k) => new Date(k + "T12:00:00");
|
||||
// a count as a short number: 133M, and 1.33 亿, 68.1 万 in Chinese with
|
||||
|
||||
@@ -63,6 +63,8 @@ magpie.strings({
|
||||
"This month": "本月",
|
||||
"Last month": "上个月",
|
||||
"Pick days": "选择日期",
|
||||
"Start time": "开始时间",
|
||||
"End time": "结束时间",
|
||||
"Previous month": "上个月",
|
||||
"Next month": "下个月",
|
||||
"Days picked: {days}": "所选日期:{days}",
|
||||
@@ -307,6 +309,8 @@ magpie.strings({
|
||||
"This month": "本月",
|
||||
"Last month": "上個月",
|
||||
"Pick days": "選擇日期",
|
||||
"Start time": "開始時間",
|
||||
"End time": "結束時間",
|
||||
"Previous month": "上個月",
|
||||
"Next month": "下個月",
|
||||
"Days picked: {days}": "所選日期:{days}",
|
||||
@@ -551,6 +555,8 @@ magpie.strings({
|
||||
"This month": "今月",
|
||||
"Last month": "先月",
|
||||
"Pick days": "日付を選ぶ",
|
||||
"Start time": "開始時刻",
|
||||
"End time": "終了時刻",
|
||||
"Previous month": "前の月",
|
||||
"Next month": "次の月",
|
||||
"Days picked: {days}": "選んだ日付:{days}",
|
||||
@@ -795,6 +801,8 @@ magpie.strings({
|
||||
"This month": "Dieser Monat",
|
||||
"Last month": "Letzter Monat",
|
||||
"Pick days": "Tage wählen",
|
||||
"Start time": "Startzeit",
|
||||
"End time": "Endzeit",
|
||||
"Previous month": "Vorheriger Monat",
|
||||
"Next month": "Nächster Monat",
|
||||
"Days picked: {days}": "Gewählte Tage: {days}",
|
||||
|
||||
@@ -245,9 +245,10 @@ function renderPeriod(loading) {
|
||||
if (b.classList.contains("open")) return closeProtoMenu();
|
||||
// on a phone the strip is hidden behind the head's menu, which opens it
|
||||
openRangeMenu(b.offsetParent ? b : $("#usageRangeMenu"), range, (from, to) => {
|
||||
const picked = periodDays(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.lastChild.textContent = rangeName(picked);
|
||||
b.title = t("Days picked: {days}", { days: rangeName(picked) });
|
||||
b.setAttribute("aria-label", b.title);
|
||||
slide(seg, "period");
|
||||
pickPeriod(from + ".." + to);
|
||||
@@ -298,11 +299,23 @@ function pickPeriod(id) {
|
||||
|
||||
const dayKeyOf = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
// 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 }) {
|
||||
// isn't this one, one day alone as itself, and the minutes an end names
|
||||
// after its day: "Oct 1 09:30 – 18:00" within one day
|
||||
function rangeName({ from, to, fromAt = "", toAt = "" }) {
|
||||
const year = new Date().getFullYear();
|
||||
const name = (k) => dayOfKey(k).toLocaleDateString(intlLang(), { month: "short", day: "numeric", ...(dayOfKey(k).getFullYear() !== year ? { year: "numeric" } : {}) });
|
||||
return from === to ? name(from) : name(from) + " – " + name(to);
|
||||
if (!fromAt && !toAt) return from === to ? name(from) : name(from) + " – " + name(to);
|
||||
const end = from === to ? toAt || "24:00" : name(to) + (toAt ? " " + toAt : "");
|
||||
return name(from) + " " + (fromAt || "00:00") + " – " + end;
|
||||
}
|
||||
// typedTime reads a time typed into the range menu, "9:30", "0930" or "09:30",
|
||||
// as "09:30"; "" when empty, null when it isn't one. The end's "24:00" is
|
||||
// its day's end, which is no minute of its own.
|
||||
function typedTime(v, end) {
|
||||
v = v.trim();
|
||||
if (!v || (end && /^24:?00$/.test(v))) return "";
|
||||
const m = /^([01]?\d|2[0-3]):?([0-5]\d)$/.exec(v);
|
||||
return m ? m[1].padStart(2, "0") + ":" + m[2] : null;
|
||||
}
|
||||
// noCallsIn is what an empty page says of the period it is on
|
||||
function noCallsIn(p) {
|
||||
@@ -351,7 +364,37 @@ function openRangeMenu(anchor, current, choose) {
|
||||
nav.append(prev, month, next);
|
||||
const grid = el("div", "rm-grid");
|
||||
grid.setAttribute("role", "grid");
|
||||
box.append(head, quick, nav, grid);
|
||||
// the minutes the first day begins at and the last ends at, a whole day
|
||||
// each when left empty; Enter applies them to the days already picked
|
||||
const times = el("div", "rm-times");
|
||||
const timeIn = (v, hint, label) => {
|
||||
const i = el("input", "rm-time");
|
||||
Object.assign(i, { type: "text", inputMode: "numeric", maxLength: 5, placeholder: hint, value: v || "", spellcheck: false, autocomplete: "off" });
|
||||
i.setAttribute("aria-label", t(label));
|
||||
i.oninput = () => i.removeAttribute("aria-invalid");
|
||||
i.onkeydown = (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
const r = start ? null : current;
|
||||
if (r) withTimes(r.from, r.to);
|
||||
};
|
||||
return i;
|
||||
};
|
||||
const fromT = timeIn(current?.fromAt, "00:00", "Start time"), toT = timeIn(current?.toAt, "24:00", "End time");
|
||||
times.append(svg("M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 0 0 0-11zM8 5v3.2l2 1.3", 12, 1.4), fromT, el("span", "rm-dash", "–"), toT);
|
||||
// the two days with the minutes typed, chosen; false when a time isn't
|
||||
// one or the range would end before it begins
|
||||
const withTimes = (fromDay, toDay) => {
|
||||
const a = typedTime(fromT.value, false), z = typedTime(toT.value, true);
|
||||
if (a == null) fromT.setAttribute("aria-invalid", "true");
|
||||
if (z == null) toT.setAttribute("aria-invalid", "true");
|
||||
if (a == null || z == null) return false;
|
||||
if (fromDay === toDay && z && (a || "00:00") >= z) { toT.setAttribute("aria-invalid", "true"); return false; }
|
||||
closeProtoMenu();
|
||||
choose(fromDay + (a ? "T" + a : ""), toDay + (z ? "T" + z : ""));
|
||||
return true;
|
||||
};
|
||||
box.append(head, quick, nav, grid, times);
|
||||
const draw = (focusDay) => {
|
||||
head.textContent = start ? t("Now the last day") : t("Pick the first day, then the last");
|
||||
month.textContent = shown.toLocaleDateString(intlLang(), { year: "numeric", month: "long" });
|
||||
@@ -377,8 +420,7 @@ function openRangeMenu(anchor, current, choose) {
|
||||
e.stopPropagation();
|
||||
if (!start) { start = k; draw(k); return; }
|
||||
const [from, to] = start <= k ? [start, k] : [k, start];
|
||||
closeProtoMenu();
|
||||
choose(from, to);
|
||||
if (!withTimes(from, to)) { start = null; draw(); }
|
||||
};
|
||||
cells.push(b);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Usage's days down to the minute (blrbrzkj on Discord): the range menu has a
|
||||
// start and an end time under its month. Typed before the days are picked,
|
||||
// they go with them: the backend is asked for "dayT09:30..dayT18:00", and the
|
||||
// opt names the day with its minutes. A time that isn't one, or an end before
|
||||
// the start on one day, is marked and asks for nothing. The menu opens again
|
||||
// on the minutes picked. 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: "" }); }
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
test(`${engine} ${lang}: Usage over minutes 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-times.png`) });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page = await (await browser.newContext({ viewport: { width: 390, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
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");
|
||||
const head = page.locator("#usageRangeMenu");
|
||||
await head.waitFor();
|
||||
await page.waitForFunction(() => !document.querySelector("#period .opt:disabled"));
|
||||
const openDays = async () => {
|
||||
await head.click();
|
||||
const items = page.locator(".proto-menu .pm-item");
|
||||
await items.first().waitFor();
|
||||
await items.nth((await items.count()) - 1).click();
|
||||
};
|
||||
const menu = page.locator(".range-menu");
|
||||
const fromT = menu.locator(".rm-time").first(), toT = menu.locator(".rm-time").last();
|
||||
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();
|
||||
};
|
||||
const picked = back(3), k = dayKey(picked);
|
||||
|
||||
await openDays();
|
||||
await menu.waitFor();
|
||||
assert.equal(await menu.locator(".rm-time").count(), 2, "a start and an end time");
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "the page scrolls sideways");
|
||||
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)}`);
|
||||
|
||||
// a time that isn't one is marked, and nothing is asked
|
||||
asked.length = 0;
|
||||
await fromT.fill("25:00");
|
||||
await day(picked);
|
||||
await day(picked);
|
||||
assert.equal(await fromT.getAttribute("aria-invalid"), "true");
|
||||
assert.equal(await menu.isVisible(), true, "the menu stays");
|
||||
assert.deepEqual(asked, []);
|
||||
|
||||
// an end before the start on one day is marked too
|
||||
await fromT.fill("18:00");
|
||||
assert.equal(await fromT.getAttribute("aria-invalid"), null, "typing clears the mark");
|
||||
await toT.fill("9:30");
|
||||
await day(picked);
|
||||
await day(picked);
|
||||
assert.equal(await toT.getAttribute("aria-invalid"), "true");
|
||||
assert.deepEqual(asked, []);
|
||||
|
||||
// 09:30 to 18:00 of one day
|
||||
await fromT.fill("0930");
|
||||
await toT.fill("18:00");
|
||||
await day(picked);
|
||||
await day(picked);
|
||||
await menu.waitFor({ state: "detached" });
|
||||
await page.waitForFunction(() => document.querySelector("#period .range-opt.on") && !document.querySelector("#period .opt:disabled"));
|
||||
const want = `${k}T09:30..${k}T18:00`;
|
||||
assert.ok(asked.includes(want), `asked for ${JSON.stringify(asked)}, want ${want}`);
|
||||
const label = (await opt.textContent()).trim();
|
||||
assert.match(label, /09:30 – 18:00$/, "the opt names the minutes: " + label);
|
||||
assert.equal((await head.textContent()).trim(), label, "the menu names them too");
|
||||
|
||||
// the menu opens on them again; Enter applies new ones to the days picked
|
||||
await openDays();
|
||||
await menu.waitFor();
|
||||
assert.equal(await fromT.inputValue(), "09:30");
|
||||
assert.equal(await toT.inputValue(), "18:00");
|
||||
asked.length = 0;
|
||||
await toT.fill("");
|
||||
await fromT.fill("12:00");
|
||||
await fromT.press("Enter");
|
||||
await menu.waitFor({ state: "detached" });
|
||||
await page.waitForFunction(() => !document.querySelector("#period .opt:disabled"));
|
||||
assert.deepEqual(asked, [`${k}T12:00..${k}`]);
|
||||
assert.match((await opt.textContent()).trim(), /12:00 – 24:00$/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,9 @@ func csvStamp(p usage.Period, day string, now time.Time) string {
|
||||
return "magpie-requests-day-" + day
|
||||
}
|
||||
if p.IsRange() { // the days picked, which already say when
|
||||
return "magpie-requests-" + strings.Replace(string(p), "..", "-to-", 1)
|
||||
// a minute an end names ("T09:30") without the colon Windows
|
||||
// doesn't take in a file name
|
||||
return "magpie-requests-" + strings.ReplaceAll(strings.Replace(string(p), "..", "-to-", 1), ":", "")
|
||||
}
|
||||
// a rolling window ("last:24h0m0s") without the colon, which Windows
|
||||
// doesn't take in a file name (#2075)
|
||||
|
||||
@@ -331,6 +331,11 @@ func TestCSVStamp(t *testing.T) {
|
||||
if got := csvStamp(p, "", now); strings.ContainsAny(got, `:/\\`) {
|
||||
t.Errorf("rolling window: %s", got)
|
||||
}
|
||||
// nor has a range whose ends name their minutes
|
||||
r, _ := usage.RangeOf("2026-09-29T09:30", "2026-09-30T18:00")
|
||||
if got := csvStamp(r, "", now); got != "magpie-requests-2026-09-29T0930-to-2026-09-30T1800" {
|
||||
t.Errorf("range of minutes: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// midnightUsageClock sets usage.Clock to read a tenth of a second before
|
||||
|
||||
@@ -233,8 +233,8 @@ func (f Filter) keepsRecord(r *Record, codexIdentity bool, subagent, parentAgent
|
||||
|
||||
// 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
|
||||
if since, _, ok := p.bounds(now.Location()); ok {
|
||||
return since
|
||||
}
|
||||
// a rolling window ends now, so it began that long ago (#2075)
|
||||
if d := p.Last(); d > 0 {
|
||||
@@ -752,7 +752,7 @@ func WriteCSV(w io.Writer, rows []Row) error {
|
||||
func timeline(p Period, now, first time.Time) (since time.Time, bucket string, pts []Point) {
|
||||
day := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||
bucket, pts = "day", []Point{}
|
||||
var n int
|
||||
var n, hours int
|
||||
// a rolling window ends now: an hour each of two days or less, else a
|
||||
// day each from when it began (#2075)
|
||||
if d := p.Last(); d > 0 {
|
||||
@@ -772,11 +772,22 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
|
||||
}
|
||||
return since, bucket, pts
|
||||
}
|
||||
if first, last, ok := p.days(now.Location()); ok {
|
||||
if first, until, ok := p.bounds(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
|
||||
// a week each (from a Monday) past 60 days as All has. One that
|
||||
// names its minutes is an hour each from the hour it begins in,
|
||||
// up to two days of them, else a day each from its first day.
|
||||
last := until.Add(-time.Nanosecond)
|
||||
since, n = first, calendarDays(first, last)+1
|
||||
if n == 1 {
|
||||
if p.timed() {
|
||||
hour := time.Date(first.Year(), first.Month(), first.Day(), first.Hour(), 0, 0, 0, first.Location())
|
||||
if h := int((until.Sub(hour) + time.Hour - 1) / time.Hour); h <= 48 {
|
||||
since, bucket, hours = hour, "hour", h
|
||||
} else {
|
||||
since = time.Date(first.Year(), first.Month(), first.Day(), 0, 0, 0, 0, first.Location())
|
||||
}
|
||||
}
|
||||
if n == 1 && !p.timed() {
|
||||
bucket = "hour"
|
||||
} else if n > 60 {
|
||||
bucket = "week"
|
||||
@@ -810,7 +821,11 @@ func timeline(p Period, now, first time.Time) (since time.Time, bucket string, p
|
||||
}
|
||||
switch bucket {
|
||||
case "hour":
|
||||
for h := 0; since.Add(time.Duration(h) * time.Hour).Before(since.AddDate(0, 0, 1)); h++ {
|
||||
end := since.AddDate(0, 0, 1)
|
||||
if hours > 0 {
|
||||
end = since.Add(time.Duration(hours) * time.Hour)
|
||||
}
|
||||
for h := 0; since.Add(time.Duration(h) * time.Hour).Before(end); h++ {
|
||||
t := since.Add(time.Duration(h) * time.Hour)
|
||||
pts = append(pts, Point{Label: t.Format("15"), Time: t})
|
||||
}
|
||||
|
||||
@@ -9,20 +9,50 @@ import (
|
||||
// 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.
|
||||
//
|
||||
// Either end can also name a minute of its day (blrbrzkj on Discord):
|
||||
// "2026-10-01T09:30..2026-10-01T18:00" begins at 09:30 and ends at 18:00,
|
||||
// that minute itself not included. An end without one stays a whole day.
|
||||
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.
|
||||
// rangeMinute is the layout of an end that names its minute.
|
||||
const rangeMinute = "2006-01-02T15:04"
|
||||
|
||||
// rangeEnd reads one end of a picked range in loc: when it begins and
|
||||
// whether it named its minute.
|
||||
func rangeEnd(s string, loc *time.Location) (at time.Time, timed bool, ok bool) {
|
||||
if t, err := time.ParseInLocation(time.DateOnly, s, loc); err == nil {
|
||||
return t, false, true
|
||||
}
|
||||
if t, err := time.ParseInLocation(rangeMinute, s, loc); err == nil {
|
||||
return t, true, true
|
||||
}
|
||||
return time.Time{}, false, false
|
||||
}
|
||||
|
||||
// RangeOf is the period from one date (YYYY-MM-DD), or one minute of a date
|
||||
// (YYYY-MM-DDTHH:MM), to another, in either order; ok is false when either
|
||||
// is neither, or when the two are the same minute.
|
||||
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 {
|
||||
a, ta, ok1 := rangeEnd(from, time.UTC)
|
||||
b, tb, ok2 := rangeEnd(to, time.UTC)
|
||||
if !ok1 || !ok2 {
|
||||
return "", false
|
||||
}
|
||||
if b.Before(a) {
|
||||
a, b = b, a
|
||||
a, b, ta, tb = b, a, tb, ta
|
||||
}
|
||||
return Period(a.Format(time.DateOnly) + rangeSep + b.Format(time.DateOnly)), true
|
||||
name := func(t time.Time, timed bool) string {
|
||||
if timed {
|
||||
return t.Format(rangeMinute)
|
||||
}
|
||||
return t.Format(time.DateOnly)
|
||||
}
|
||||
p := Period(name(a, ta) + rangeSep + name(b, tb))
|
||||
if !p.IsRange() {
|
||||
return "", false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
// A period can also be hours or days long, ending now (#2075): a rolling
|
||||
@@ -55,23 +85,38 @@ func (p Period) Last() time.Duration {
|
||||
return d
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// bounds is when a picked range begins and the moment after it ends, in
|
||||
// loc: midnight for an end that is a whole day, its minute for one that
|
||||
// names it. ok is false for anything else, and for a range that ends
|
||||
// before it begins or where it begins.
|
||||
func (p Period) bounds(loc *time.Location) (since, until 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) {
|
||||
a, _, ok1 := rangeEnd(from, loc)
|
||||
b, timed, ok2 := rangeEnd(to, loc)
|
||||
if !ok1 || !ok2 {
|
||||
return
|
||||
}
|
||||
if !timed {
|
||||
b = b.AddDate(0, 0, 1)
|
||||
}
|
||||
if !a.Before(b) {
|
||||
return
|
||||
}
|
||||
return a, b, true
|
||||
}
|
||||
|
||||
// timed is whether either end of a picked range names its minute.
|
||||
func (p Period) timed() bool {
|
||||
from, to, _ := strings.Cut(string(p), rangeSep)
|
||||
return strings.Contains(from, "T") || strings.Contains(to, "T")
|
||||
}
|
||||
|
||||
// IsRange is whether p is days the reader picked rather than a preset.
|
||||
func (p Period) IsRange() bool {
|
||||
_, _, ok := p.days(time.UTC)
|
||||
_, _, ok := p.bounds(time.UTC)
|
||||
return ok
|
||||
}
|
||||
|
||||
@@ -86,10 +131,11 @@ func (p Period) Known() bool {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// range's last day, or the minute its end names, 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)
|
||||
if _, until, ok := p.bounds(now.Location()); ok {
|
||||
return until
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
@@ -61,3 +61,63 @@ func TestPickedDaysArePeriod(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Either end of a picked range can name its minute (blrbrzkj on Discord):
|
||||
// the calls from that minute up to, not including, the end's, under an
|
||||
// hour each of the time for two days or less, a day each past that.
|
||||
func TestPickedMinutesArePeriod(t *testing.T) {
|
||||
pageHome(t)
|
||||
now := holdClock(t, time.Date(2026, 10, 10, 12, 0, 0, 0, time.Local))
|
||||
at := func(d, h, m int) time.Time { return time.Date(2026, 10, d, h, m, 0, 0, time.Local) }
|
||||
for _, ts := range []time.Time{
|
||||
at(1, 9, 29), // a minute before the start
|
||||
at(1, 9, 30), // the start
|
||||
at(1, 12, 0),
|
||||
at(2, 17, 59), // the last minute
|
||||
at(2, 18, 0), // the end, not included
|
||||
at(3, 9, 0),
|
||||
} {
|
||||
Append(Record{Time: ts, Agent: "claude", Provider: "openai", Model: "m", Input: 10, Status: 200})
|
||||
}
|
||||
p, ok := RangeOf("2026-10-02T18:00", "2026-10-01T09:30") // either order
|
||||
if !ok || p != "2026-10-01T09:30..2026-10-02T18:00" || !p.Known() || !p.IsRange() {
|
||||
t.Fatalf("RangeOf: %q %v", p, ok)
|
||||
}
|
||||
if !p.Since(now).Equal(at(1, 9, 30)) || !p.Until(now).Equal(at(2, 18, 0)) {
|
||||
t.Errorf("%s: from %v until %v", p, p.Since(now), p.Until(now))
|
||||
}
|
||||
s := Summarize(p)
|
||||
// 09:00 on the 1st to 18:00 on the 2nd: 33 hours
|
||||
if s.Calls != 3 || s.Period != p || s.Bucket != "hour" || len(s.Series) != 33 || !s.Series[0].Time.Equal(at(1, 9, 0)) {
|
||||
t.Errorf("Summarize(%s): %d calls, period %q, %d %s points from %v; want 3 calls in 33 hours from 09:00", p, s.Calls, s.Period, len(s.Series), s.Bucket, s.Series[0].Time)
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
// a minute to the end of a whole day: that day's last call counts
|
||||
mixed, ok := RangeOf("2026-10-02T12:00", "2026-10-03")
|
||||
if !ok || !mixed.Until(now).Equal(at(4, 0, 0)) {
|
||||
t.Errorf("RangeOf mixed: %q %v until %v", mixed, ok, mixed.Until(now))
|
||||
}
|
||||
if s := Summarize(mixed); s.Calls != 3 || s.Bucket != "hour" || len(s.Series) != 36 {
|
||||
t.Errorf("Summarize(%s): %d calls, %d %s points; want 3 in 36 hours", mixed, s.Calls, len(s.Series), s.Bucket)
|
||||
}
|
||||
// more than two days of minutes: a day each from the first day
|
||||
wide, _ := RangeOf("2026-10-01T09:30", "2026-10-09T08:00")
|
||||
if s := Summarize(wide); s.Calls != 5 || s.Bucket != "day" || len(s.Series) != 9 || !s.Series[0].Time.Equal(at(1, 0, 0)) {
|
||||
t.Errorf("Summarize(%s): %d calls, %d %s points; want 5 in 9 days", wide, s.Calls, len(s.Series), s.Bucket)
|
||||
}
|
||||
|
||||
for _, bad := range []string{"2026-10-01T09:30..2026-10-01T09:30", "2026-10-01T10:00..2026-10-01T09:00", "2026-10-01T25:00..2026-10-02", "2026-10-01 09:30..2026-10-02"} {
|
||||
if Period(bad).Known() {
|
||||
t.Errorf("%q is known", bad)
|
||||
}
|
||||
}
|
||||
if _, ok := RangeOf("2026-10-01T09:30", "2026-10-01T09:30"); ok {
|
||||
t.Error("RangeOf took a range of no time")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user