diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 6c1ce4775..0f1ba175b 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -16475,7 +16475,7 @@ function creditDays(daily, named) { // 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]; + let n = range ? Math.round((last - dayOfKey(range.from)) / 864e5) + 1 : { today: 1, "last:24h": 2, "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 = []; diff --git a/internal/gui/assets/plugins/usage/i18n.js b/internal/gui/assets/plugins/usage/i18n.js index cb392e754..bc8fd8f2b 100644 --- a/internal/gui/assets/plugins/usage/i18n.js +++ b/internal/gui/assets/plugins/usage/i18n.js @@ -197,6 +197,7 @@ magpie.strings({ "Not counted: {models}, with no known price": "未计入:{models},没有已知价格", "No calls today.": "今天没有调用。", "No calls in the last 7 days.": "最近 7 天没有调用。", + "No calls in the last 24 hours.": "最近 24 小时没有调用。", "No calls in the last 30 days.": "最近 30 天没有调用。", "No calls yet.": "还没有调用。", "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "让某个 Agent 使用目录中的模型;每次经过网关的调用都会计入这里。", @@ -440,6 +441,7 @@ magpie.strings({ "Not counted: {models}, with no known price": "未計入:{models},沒有已知價格", "No calls today.": "今天沒有呼叫。", "No calls in the last 7 days.": "最近 7 天沒有呼叫。", + "No calls in the last 24 hours.": "最近 24 小時沒有呼叫。", "No calls in the last 30 days.": "最近 30 天沒有呼叫。", "No calls yet.": "還沒有呼叫。", "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "讓某個 Agent 使用目錄中的模型;每次經過閘道的呼叫都會計入這裡。", @@ -683,6 +685,7 @@ magpie.strings({ "Not counted: {models}, with no known price": "計上されていません:{models}(価格不明)", "No calls today.": "今日の呼び出しはありません。", "No calls in the last 7 days.": "過去 7 日間の呼び出しはありません。", + "No calls in the last 24 hours.": "過去 24 時間の呼び出しはありません。", "No calls in the last 30 days.": "過去 30 日間の呼び出しはありません。", "No calls yet.": "呼び出しはまだありません。", "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "エージェントにカタログのモデルを指定して使うと、ゲートウェイ経由のすべての呼び出しがここに集計されます。", @@ -926,6 +929,7 @@ magpie.strings({ "Not counted: {models}, with no known price": "Nicht gezählt: {models}, ohne bekannten Preis", "No calls today.": "Heute keine Aufrufe.", "No calls in the last 7 days.": "Keine Aufrufe in den letzten 7 Tagen.", + "No calls in the last 24 hours.": "Keine Aufrufe in den letzten 24 Stunden.", "No calls in the last 30 days.": "Keine Aufrufe in den letzten 30 Tagen.", "No calls yet.": "Noch keine Aufrufe.", "Point an agent at a catalog model and use it; every call through the gateway is counted here.": "Richten Sie einen Agenten auf ein Katalogmodell aus und nutzen Sie ihn; jeder Aufruf über den Zugangspunkt wird hier gezählt.", diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 84739e201..900191f2e 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -151,7 +151,12 @@ function archivePanel(name, id, redraw) { return box; } -const PERIODS = [["today", "Today"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; +// "24 hours" is the day up to now rather than since midnight (mahiro233 on +// Discord), the server's rolling window (#2075). The reader's pick of these +// is kept for the next time the page opens; picked days are not, as they +// go stale. +const PERIODS = [["today", "Today"], ["last:24h", "24 hours"], ["7d", "7 days"], ["30d", "30 days"], ["all", "All"]]; +try { const v = localStorage.getItem("magpie.usagePeriod"); if (PERIODS.some(([id]) => id === v)) period = v; } catch {} // The reader's time zone, which magpie reads the period's days, the chart's // hours and a picked day in: magpie web may be read from another zone than @@ -287,6 +292,7 @@ function renderPeriod(loading) { function pickPeriod(id) { period = id; ledDay = ""; ledOffset = 0; + if (PERIODS.some(([p]) => p === id)) try { localStorage.setItem("magpie.usagePeriod", id); } catch {} loadUsage().catch((e) => status(e.message, "err")); } @@ -301,7 +307,7 @@ function rangeName({ from, 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."; + return { today: "No calls today.", "last:24h": "No calls in the last 24 hours.", "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 diff --git a/internal/gui/tests/usage-24h.test.cjs b/internal/gui/tests/usage-24h.test.cjs new file mode 100644 index 000000000..b5e5c95b3 --- /dev/null +++ b/internal/gui/tests/usage-24h.test.cjs @@ -0,0 +1,102 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Usage's "24 hours" (mahiro233 on Discord): the day up to now, asked of the +// backend as the rolling window "last:24h", not since midnight as Today is. +// The reader's pick of a period is kept: the page opens on it again, until a +// way in (the menu bar's total) names another. Picked days are not kept. +// English and Chinese, both engines; 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: { day: "24 hours", none: "No calls in the last 24 hours.", week: "7 days" }, + zh: { day: "24 小时", none: "最近 24 小时没有调用。", week: "7 天" }, +}; + +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 the last 24 hours, kept`, 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-24h.png`) }); + } + await browser.close(); + }); + page = await (await browser.newContext({ viewport: { width: 900, 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)); + const on = () => page.locator("#period .opt.on").textContent(); + const settle = () => page.waitForFunction(() => document.querySelector("#period .opt") && !document.querySelector("#period .opt:disabled")); + + await page.goto("http://magpie.test/?view=usage"); + await settle(); + assert.equal(asked[0], "today", "a first visit opens on Today"); + const opts = await page.locator("#period .opt:not(.range-opt)").allTextContents(); + assert.equal(opts[1].trim(), w.day, "24 hours sits after Today"); + + await page.locator("#period .opt", { hasText: new RegExp("^" + w.day + "$") }).click(); + await page.waitForFunction(() => document.querySelector("#view-usage .none")); + assert.equal(asked.at(-1), "last:24h"); + assert.ok((await page.locator("#view-usage .none").textContent()).startsWith(w.none)); + + // opened again: on the pick + asked.length = 0; + await page.reload(); + await settle(); + assert.equal(asked[0], "last:24h", "the page opens on the kept pick"); + assert.equal((await on()).trim(), w.day); + + // the menu bar's total names its own period, which isn't kept + asked.length = 0; + await page.goto("http://magpie.test/?view=usage&period=7d"); + await settle(); + assert.equal(asked[0], "7d"); + asked.length = 0; + await page.goto("http://magpie.test/?view=usage"); + await settle(); + assert.equal(asked[0], "last:24h", "a way in leaves the pick as it was"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/usage-ledger-chart.test.cjs b/internal/gui/tests/usage-ledger-chart.test.cjs index 81512e596..f2e6a15ea 100644 --- a/internal/gui/tests/usage-ledger-chart.test.cjs +++ b/internal/gui/tests/usage-ledger-chart.test.cjs @@ -283,7 +283,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", for (const lang of ["en", "zh"]) await t.test(lang + ": a day filters details while keeping the whole chart", async () => { const { p, asked, exported, errors } = await open(lang, lang === "zh" ? "dark" : "light", { variant: "daily" }); - await p.locator("#period .opt").nth(1).click(); + await p.locator("#period .opt").nth(2).click(); const days = p.locator("#ledChart .led-day"); await days.nth(6).waitFor(); const initial = await p.locator("#ledChart rect.col").evaluateAll((rs) => rs.map((r) => [r.dataset.day, r.dataset.k, r.getAttribute("height"), r.dataset.color])); diff --git a/internal/gui/tests/usage-ledger-open-settled.test.cjs b/internal/gui/tests/usage-ledger-open-settled.test.cjs index fd6293ddd..78d2ec9b1 100644 --- a/internal/gui/tests/usage-ledger-open-settled.test.cjs +++ b/internal/gui/tests/usage-ledger-open-settled.test.cjs @@ -65,7 +65,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await p.locator('[data-view="usage"]').first().click(); await p.locator(":is(#usageTab .opt, .nav-s):visible").nth(1).click(); await p.locator("#ledWrap .led tbody tr").first().waitFor(); - await p.locator("#period .opt").nth(1).click(); + await p.locator("#period .opt").nth(2).click(); await p.waitForFunction(() => document.querySelectorAll("#ledWrap .led tbody tr.led-row").length === 100); await p.waitForTimeout(600); const fitted = await p.locator("#ledWrap table.led").getAttribute("class"); diff --git a/internal/gui/tests/usage-ledger.test.cjs b/internal/gui/tests/usage-ledger.test.cjs index e26962d35..afc29dc6d 100644 --- a/internal/gui/tests/usage-ledger.test.cjs +++ b/internal/gui/tests/usage-ledger.test.cjs @@ -182,12 +182,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", }); await route.fulfill({ json: data }); }); - await tab.locator("#period .opt").nth(2).click(); + await tab.locator("#period .opt").nth(3).click(); await lastAsked(tab, asked, q => q.get("period") === "30d"); await tab.locator(key === "agent" ? "#ledAgent" : "#ledProvider").click(); await tab.locator(".sess-menu .pm-item", { hasText: name }).click(); await lastAsked(tab, asked, q => q.get(key) === removed); - await tab.locator("#period .opt").nth(1).click(); + await tab.locator("#period .opt").nth(2).click(); await lastAsked(tab, asked, q => q.get("period") === "7d" && !q.has(key) && q.get("offset") === "0"); assert.equal(await tab.locator(key === "agent" ? "#ledAgent" : "#ledProvider").textContent(), all); assert.equal(await tab.locator(".led-row").count(), Math.min(100, ROWS.filter(r => r[key] !== removed).length)); diff --git a/internal/gui/tests/usage-phone-head.test.cjs b/internal/gui/tests/usage-phone-head.test.cjs index 359b19e5c..5ceac6408 100644 --- a/internal/gui/tests/usage-phone-head.test.cjs +++ b/internal/gui/tests/usage-phone-head.test.cjs @@ -144,10 +144,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator("#usageRangeMenu").click(); const items = page.locator(".proto-menu .pm-item"); assert.ok(await items.count() >= 4, "every period is in the menu"); - await items.nth(1).click(); - await page.waitForFunction(() => document.querySelectorAll("#period .opt")[1].classList.contains("on")); + await items.nth(2).click(); + await page.waitForFunction(() => document.querySelectorAll("#period .opt")[2].classList.contains("on")); assert.equal(await page.locator(".proto-menu").count(), 0, "a pick shuts the menu"); - const seven = await page.locator("#period .opt").nth(1).textContent(); + const seven = await page.locator("#period .opt").nth(2).textContent(); await page.waitForFunction((s) => document.querySelector("#usageRangeMenu").textContent.trim() === s.trim(), seven); // Sessions has its own range: the menu follows the tab diff --git a/internal/gui/tests/usage-refresh-flight.test.cjs b/internal/gui/tests/usage-refresh-flight.test.cjs index 75164b25b..3465c59a0 100644 --- a/internal/gui/tests/usage-refresh-flight.test.cjs +++ b/internal/gui/tests/usage-refresh-flight.test.cjs @@ -213,7 +213,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium"] // numbers over 30 days' await p.locator("#usageReload").click(); // today's refresh, held await gate.waitFor("usage", 2); - await p.locator("#period .opt").nth(2).click(); // 30 days + await p.locator("#period .opt").nth(3).click(); // 30 days await gate.waitFor("usage", 3); gate.release("usage", -1); // 30 days' answer first await p.waitForTimeout(300);