diff --git a/packages/day-card/day-card.test.mjs b/packages/day-card/day-card.test.mjs index c9f2d4f..1199ea1 100644 --- a/packages/day-card/day-card.test.mjs +++ b/packages/day-card/day-card.test.mjs @@ -334,3 +334,25 @@ test("the blur and dim sliders stay put while a slider is dragged (#957)", () => for (const id of [...B.list.map((b) => b.id), "custom"]) expect([id, typeof B.meta(id).photo]).toEqual([id, "boolean"]) expect(read("app.js")).toContain('pop.classList.toggle("photo", B.meta(bg.bg).photo === true)') }) + +test("a day or a span in the past still lists every later day in the menu, not today right above it (shangyuan0818 on X)", () => { + // usage:day's days stop at the date read (usageapi.SpanOf), so a week + // ending 11-04, read on 11-09, knows nothing of 11-06 to 11-09 + const past = { ...day, from: "2026-10-29", date: "2026-11-04", days: day.days.filter((d) => d.date <= "2026-11-04") } + const latest = day.days + const dates = (list) => list.map((d) => d.date) + expect(dates(V.menuDays(past.days, past.today, latest))).toEqual(["2026-11-09", "2026-11-08", "2026-11-07", "2026-11-06", "2026-11-01"]) + // today with no calls yet is still first, and no day is listed twice + const quiet = latest.slice(0, -1) + expect(dates(V.menuDays(past.days, "2026-11-09", quiet))).toEqual(["2026-11-09", "2026-11-08", "2026-11-07", "2026-11-06", "2026-11-01"]) + // the latest read's numbers win for a day both know + expect(V.menuDays([{ date: "2026-11-01", tokens: 5 }], "2026-11-09", [{ date: "2026-11-01", tokens: 9 }]).at(-1).tokens).toBe(9) + // with no read of today's days the menu doesn't pretend: it lists the + // days it has, and no today above a gap + expect(dates(V.menuDays(past.days, past.today, null))).toEqual(["2026-11-01"]) + // the day read stays in the menu however long the list + const many = Array.from({ length: 300 }, (_, i) => ({ date: V.shift("2026-11-09", -i), tokens: 1 })).reverse() + const old = V.shift("2026-11-09", -200) + expect(V.menuDays(many.filter((d) => d.date <= old), "2026-11-09", many).some((d) => d.date === old)).toBe(true) + expect(read("app.js")).toContain("V.menuDays(") +}) diff --git a/packages/day-card/day-menu.gui.mjs b/packages/day-card/day-menu.gui.mjs new file mode 100644 index 0000000..4635e6d --- /dev/null +++ b/packages/day-card/day-menu.gui.mjs @@ -0,0 +1,74 @@ +// The day menu lists every day with calls up to today, whatever day or span +// is shown (shangyuan0818 on X): a day or a week in the past used to list +// today and then the past day, as if the days between had no calls. +// usage:day's days stop at the date read, so the page reads today's days +// for the menu. Drives the real page in Chromium and WebKit, in a day, a +// week and a month, against a stub bridge that answers as magpie does. +// Run: NODE_PATH= node day-menu.gui.mjs +import { readFileSync, existsSync } from "node:fs" +import { join } from "node:path" +import { createRequire } from "node:module" + +const require = createRequire(import.meta.url) +const { chromium, webkit } = require("playwright") +const page_dir = join(import.meta.dirname, "page") +const ALL = [["2026-10-20", 500], ["2026-11-01", 1000], ["2026-11-06", 2000], ["2026-11-07", 3000], ["2026-11-08", 4000], ["2026-11-09", 5000]] +const bridge = ` +const ALL = ${JSON.stringify(ALL)}; +window.magpie = { + ready: Promise.resolve({ lang: "en", dark: false }), + onTheme() {}, + // as usageapi.SpanOf: the days with calls up to date, never after it + read: async (name, p) => { + const today = "2026-11-09", date = p.date || today; + const days = ALL.filter(([d]) => d <= date).map(([d, t]) => ({ date: d, calls: 1, tokens: t, cost: 1 })); + return { date, today, from: p.from, calls: 1, errors: 0, input: 10, output: 10, cacheRead: 0, cacheWrite: 0, reasoning: 0, cost: 1, unpriced: 0, cacheUnknown: 0, agents: [], days, icons: {}, currency: "usd", rate: 7 }; + }, + options: { get: async () => null, set: async () => {} }, + image: { copy: async () => {}, save: async () => ({}) }, +};` +const every = ["2026-11-09", "2026-11-08", "2026-11-07", "2026-11-06", "2026-11-01", "2026-10-20"] +await (async () => { + let bad = 0 + const ok = (c, m) => { console.log((c ? "ok " : "FAIL ") + m); if (!c) bad++ } + for (const [name, type] of [["chromium", chromium], ["webkit", webkit]]) { + const browser = await type.launch() + for (const span of ["day", "week", "month"]) { + const p = await browser.newPage() + const errs = [] + p.on("pageerror", (e) => errs.push(String(e))) + await p.route("**/*", (r) => { + const u = new URL(r.request().url()) + if (u.pathname.endsWith("/_magpie/bridge.js")) return r.fulfill({ contentType: "text/javascript", body: bridge }) + const f = join(page_dir, u.pathname.replace(/^\/day\//, "")) + if (!existsSync(f)) return r.fulfill({ status: 404, body: "" }) + const ct = f.endsWith(".js") ? "text/javascript" : f.endsWith(".css") ? "text/css" : "text/html" + r.fulfill({ contentType: ct, body: readFileSync(f) }) + }) + await p.goto("http://day.test/day/index.html") + await p.waitForFunction(() => document.getElementById("date-text").textContent !== "…") + const listed = async () => { + await p.click("#date") + await p.waitForSelector("#menu:not([hidden]) li") + return p.$$eval("#menu li", (l) => l.map((x) => [x.dataset.date, x.getAttribute("aria-selected") === "true"])) + } + const tag = `${name} ${span}` + let l = await listed() + ok(JSON.stringify(l.map((x) => x[0])) === JSON.stringify(every), `${tag} today: every day (${l.map((x) => x[0]).join(" ")})`) + await p.click('#menu li[data-date="2026-11-01"]') + if (span !== "day") await p.click(`#spans [data-span="${span}"]`) + await p.waitForFunction(() => /1/.test(document.getElementById("date-text").textContent) && !/Nov 9/.test(document.getElementById("date-text").textContent)) + l = await listed() + ok(JSON.stringify(l.map((x) => x[0])) === JSON.stringify(every), `${tag} to 11-01: every day, not today then 11-01 (${l.map((x) => x[0]).join(" ")})`) + ok(l.filter((x) => x[1]).map((x) => x[0]).join() === "2026-11-01", `${tag} to 11-01: 11-01 is the one picked`) + await p.click('#menu li[data-date="2026-11-07"]') + await p.waitForFunction(() => /7/.test(document.getElementById("date-text").textContent)) + ok(/Nov 7/.test(await p.textContent("#date-text")), `${tag}: a later day from the menu loads (${await p.textContent("#date-text")})`) + ok(errs.length === 0, `${tag}: no page errors ${errs.join(";")}`) + await p.close() + } + await browser.close() + } + console.log(bad ? `${bad} failed` : "all ok") + process.exit(bad ? 1 : 0) +})() diff --git a/packages/day-card/package.json b/packages/day-card/package.json index ad521b7..b98b727 100644 --- a/packages/day-card/package.json +++ b/packages/day-card/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/page-day-card", - "version": "0.3.4", + "version": "0.3.5", "description": "A page in magpie's window that draws a day, week, month or all of your AI usage as a card: tokens, cost, each agent and its models, your streak and your average day. Copy it as a picture or save it as a PNG", "files": ["page", "README.md", "NOTICE"], "keywords": ["magpie", "magpie-page", "usage", "tokens", "cost", "card"], diff --git a/packages/day-card/page/app.js b/packages/day-card/page/app.js index d7ff789..60a3553 100644 --- a/packages/day-card/page/app.js +++ b/packages/day-card/page/app.js @@ -476,11 +476,19 @@ // ---- the day menu: the days that had calls, newest first ---- const menu = $("menu"); - function openMenu() { + let menuOpening = 0; + async function openMenu() { const d = state.day; if (!d) return; - const days = (d.days || []).slice().reverse().slice(0, 120); - if (!days.some((x) => x.date === d.today)) days.unshift({ date: d.today, tokens: 0 }); + // a day or span in the past knows only the days up to it: the days + // after it come from a read of today's + let latest = d.days; + if (d.date !== d.today) { + const n = ++menuOpening; + try { latest = (await magpie.read("usage:day", { date: "", tz: zone })).days; } catch { latest = null; } + if (n !== menuOpening || state.day !== d) return; + } + const days = V.menuDays(d.days, d.today, latest); menu.replaceChildren(...days.map((x) => { const li = document.createElement("li"); li.setAttribute("role", "option"); @@ -501,6 +509,7 @@ menu.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: "nearest" }); } function closeMenu() { + menuOpening++; if (menu.hidden) return; $("date").setAttribute("aria-expanded", "false"); menu.classList.add("closing"); diff --git a/packages/day-card/page/view.js b/packages/day-card/page/view.js index 9b360da..a047b7b 100644 --- a/packages/day-card/page/view.js +++ b/packages/day-card/page/view.js @@ -207,6 +207,24 @@ return to > today ? today : to; } + // the day menu: the days that had calls, newest first, and today on top. + // usage:day's days stop at the date it read, so a day or span in the past + // takes the days after it from latest, a read of today's days; without + // that the menu lists only the days it has, never today above a gap + function menuDays(days, today, latest) { + const by = new Map(); + for (const x of days || []) by.set(x.date, x); + if (latest) { + for (const x of latest) by.set(x.date, x); + if (!by.has(today)) by.set(today, { date: today, tokens: 0 }); + } + const list = [...by.values()].sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0)); + // the newest 120, and as far back as the day read + const read = (days || []).length ? days[days.length - 1].date : ""; + const keep = Math.max(120, list.filter((x) => x.date >= read).length); + return list.slice(0, keep); + } + // when the card was drawn: "NOV 9, 2026 AT 23:04", by this computer's clock function issued(now, lang) { const p = (n) => String(n).padStart(2, "0"); @@ -327,5 +345,5 @@ // the file a saved card is named const fileName = (date, span, from) => (span === "all" ? `magpie all ${date}` : span && span !== "day" && from ? `magpie ${from} to ${date}` : `magpie ${date}`); - globalThis.DayView = { TEXT, langOf, text, count, money, tokensOf, hitRate, percent, shift, dateLabel, receiptDate, receiptRange, SPANS, spanFrom, stepDate, issued, streak, average, versus, card, fileName }; + globalThis.DayView = { TEXT, langOf, text, count, money, tokensOf, hitRate, percent, shift, dateLabel, receiptDate, receiptRange, SPANS, spanFrom, stepDate, menuDays, issued, streak, average, versus, card, fileName }; })();