page-usage-tree 0.1.1: refresh warning only on a real failure, hit rate and model-detail fixes (#960)
page-usage-tree 0.1.1 (CHENZUDE): - A failed refresh is kept on the cache entry the page reads, so "Refresh failed; showing the previous data" shows when a refresh threw (on 0.1.0 it was written to an entry already replaced and never shown). Only a loader that threw counts: an older disk cache marked stale does not, and a retry from a failed entry stays failed until a loader succeeds. The page takes the server's X-Usage-Tree-Refresh on every answer, quiet follow-ups included, so the warning clears once the gateway recovers. - Hit rate uses magpie's hitPct rounding (0.9996 shows 99.96%, not 100%). - A failed per-account model-detail read keeps the account totals and says model details are incomplete (zh, en). Disk cache v8. - Not in the PR body: a /bridge.js shim served by the service (talks only to parent: hello, options.get/set, theme and visibility), request timeout 10s -> 30s, narrow breakpoint 620px -> 700px, model split on narrow screens, "permissions": [] added (same as absent), zh warnings joined with ";". Run at the reviewed head 74363201570d9f69866ac0e4afff7a2b898e6dab: - WSL (magpie-desktop), fresh HOME: bun test packages/page-usage-tree 62 pass 1 skip (parity needs a live magpie); node --test 68 pass 1 skip; bun scripts/check.mjs ok. - Windows (xiaomi-gpu), fresh HOME and USERPROFILE: bun test packages/page-usage-tree exit 0; bun scripts/check.mjs ok. CI green. - Playwright 1.62 Chromium and WebKit on WSL, sandbox server with fake data, 1280 and 420px, en and zh: a first open from a stale disk cache never shows the refresh warning; a failed manual refresh shows it, it stays while the gateway is down, and clears on the quiet follow-ups after recovery while the model-detail warning stays; no page errors, no horizontal scroll. The same probe on e3da32bed fails 3 checks (false warning on open, warning never clears, zh joined by a space). - Broken by hand: counting data.stale as failed, a retry entry forgetting the failure, and a quiet load never clearing each turn a test red. Not covered by a test: dropping warningStateChanged (render also runs renderWarnings) and the zh join between two data warnings. - Host/Origin/token handling on /api/tree unchanged from main; /bridge.js is static and behind the Host check. dist had only 0.1.0.
This commit is contained in:
@@ -25,9 +25,9 @@ magpie plugin add @magpie-community/page-usage-tree
|
||||
## Architecture
|
||||
|
||||
- `page/index.html` and `page/boot.js` are the launcher Magpie sandboxes. They
|
||||
read the theme, language, page options and theme tokens, then navigate the
|
||||
frame to the local service. They never probe it first: a plugin page's CSP
|
||||
uses `connect-src 'none'`.
|
||||
read the theme, language, theme tokens and this plugin's own options, then
|
||||
navigate the frame to the local service. They never probe the service first:
|
||||
a plugin page's CSP uses `connect-src 'none'`.
|
||||
- `ui/app.html`, `ui/app.js`, `ui/view.js`, `ui/i18n.js` and `ui/style.css` are
|
||||
the page, served by the local service. It uses Magpie's own `--magpie-*`
|
||||
colours, font and control shapes.
|
||||
@@ -52,10 +52,17 @@ magpie plugin add @magpie-community/page-usage-tree
|
||||
## Currency and units
|
||||
|
||||
The gateway reports cost in USD, Magpie's default. The page shows `$` unless
|
||||
the page options explicitly set `currency: "cny"` and a `usdCny` rate; only
|
||||
then does it convert for display. Token counts use `K`, `M` and `B`; Chinese
|
||||
`万` and `亿` are used only when the language is Chinese and
|
||||
`chineseUnits` is on.
|
||||
Magpie's page bridge supplies its own display settings (for example
|
||||
`currency`, `chineseUnits` and an exchange rate), or this plugin's options
|
||||
explicitly set `currency: "cny"` and a `usdCny` rate. Only then does it
|
||||
convert for display. Token counts use `K`, `M` and `B`; Chinese `万` and `亿`
|
||||
are used only when the language is Chinese and `chineseUnits` is on.
|
||||
|
||||
The current Magpie page bridge exposes language and theme, but not the global
|
||||
Settings preferences. Until those fields are supplied by the bridge, the
|
||||
plugin's own options remain the supported fallback. Theme and visibility
|
||||
callbacks re-read those options once; no Magpie settings file is read, no
|
||||
configuration read is declared, and nothing is polled.
|
||||
|
||||
## Token measure
|
||||
|
||||
@@ -63,6 +70,14 @@ then does it convert for display. Token counts use `K`, `M` and `B`; Chinese
|
||||
writes are part of the token measure used by the summary, row values, token
|
||||
shares and token sorting. Turning it off leaves the input + output total
|
||||
visible while keeping cache in the detail line. The page remembers the choice.
|
||||
The detail line also shows Magpie's cache hit rate: cache reads over the counted
|
||||
prompt, with calls whose vendor reports no cache left out of the denominator.
|
||||
As in Magpie's own usage view, a row with no cache reads omits the rate; a row
|
||||
with cache-uncounted calls says how many calls were left out. A mixed row shows
|
||||
both notes. Hit-rate percentages use Magpie's rounding rule, so a rate below
|
||||
100% is never displayed as a misleading `100%`. If an account's per-model
|
||||
request read fails, the page keeps its account totals and says that model
|
||||
details are temporarily incomplete.
|
||||
|
||||
## Security
|
||||
|
||||
|
||||
@@ -52,10 +52,31 @@ function cacheFile(period) {
|
||||
|
||||
// A read written by an older build can lack a field this page needs, so it
|
||||
// is a miss rather than served as current.
|
||||
const CACHE_VERSION = 6;
|
||||
const CACHE_VERSION = 8;
|
||||
|
||||
export function cacheUsable(data) {
|
||||
return Boolean(data && Array.isArray(data.providers) && Array.isArray(data.accounts));
|
||||
if (!data || !Array.isArray(data.providers) || !Array.isArray(data.accounts)) return false;
|
||||
const fields = [
|
||||
"cacheRead",
|
||||
"cacheWrite",
|
||||
"cacheUnknown",
|
||||
"cacheUnknownCalls",
|
||||
];
|
||||
const hasFields = (part) => part && typeof part === "object" && fields.every(
|
||||
(field) => typeof part[field] === "number" && Number.isFinite(part[field]),
|
||||
);
|
||||
const parts = [data.summary, ...data.providers, ...data.accounts];
|
||||
for (const account of data.accounts) parts.push(...(Array.isArray(account?.models) ? account.models : []));
|
||||
for (const provider of data.providers) {
|
||||
for (const account of Array.isArray(provider?.accounts) ? provider.accounts : []) {
|
||||
parts.push(...(Array.isArray(account?.models) ? account.models : []));
|
||||
}
|
||||
}
|
||||
for (const part of parts) {
|
||||
if (!part || typeof part !== "object") return false;
|
||||
if (!hasFields(part)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function readCached(period) {
|
||||
@@ -99,6 +120,7 @@ function writeCached(period, data) {
|
||||
// group from borrowing another provider's models.
|
||||
async function requestsForAccounts(usage, period, options) {
|
||||
const out = {};
|
||||
let failures = 0;
|
||||
const accounts = Array.isArray(usage?.accounts) ? usage.accounts : [];
|
||||
await Promise.all(
|
||||
accounts.map(async (item) => {
|
||||
@@ -111,11 +133,12 @@ async function requestsForAccounts(usage, period, options) {
|
||||
} catch {
|
||||
// The account totals still come from the usage answer; only its
|
||||
// model rows are missing.
|
||||
failures += 1;
|
||||
out[key] = null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return out;
|
||||
return { requests: out, failures };
|
||||
}
|
||||
|
||||
async function readGateway(period, options) {
|
||||
@@ -125,15 +148,18 @@ async function readGateway(period, options) {
|
||||
// that is usually none of them.
|
||||
const preview = aggregateGatewayUsage(usage, {}, { period });
|
||||
const missing = preview.accounts.filter((account) => account.calls > 0 && !account.models.length);
|
||||
const requestsByAccount = missing.length
|
||||
const detailRead = missing.length
|
||||
? await requestsForAccounts(
|
||||
{ ...usage, accounts: usage.accounts.filter((item) =>
|
||||
missing.some((account) => account.provider === item.provider && account.account === item.account)) },
|
||||
period,
|
||||
options,
|
||||
)
|
||||
: {};
|
||||
return aggregateGatewayUsage(usage, requestsByAccount, { period });
|
||||
: { requests: {}, failures: 0 };
|
||||
return aggregateGatewayUsage(usage, detailRead.requests, {
|
||||
period,
|
||||
missingModelAccounts: detailRead.failures,
|
||||
});
|
||||
}
|
||||
|
||||
const refreshing = new Set();
|
||||
|
||||
@@ -11,6 +11,80 @@ const UI_DIR = fileURLToPath(new URL("../ui/", import.meta.url));
|
||||
const CACHE_MS = 25_000;
|
||||
export const PLUGIN_NAME = "magpie-usage-tree";
|
||||
|
||||
// The service page runs inside Magpie's plugin frame. Its own bridge lives
|
||||
// in the launcher document; this small registered bridge serves subsequent
|
||||
// plugin-option and visibility calls from the same parent window.
|
||||
const BRIDGE_SHIM = `(() => {
|
||||
const waiting = new Map();
|
||||
let next = 0;
|
||||
const themed = [];
|
||||
const watched = [];
|
||||
function call(method, params) {
|
||||
// Opening the service directly has no Magpie parent to answer. Leave the
|
||||
// optional bridge inert instead of posting a request to the page itself.
|
||||
if (parent === window) return Promise.resolve(undefined);
|
||||
const id = ++next;
|
||||
return new Promise((resolve, reject) => {
|
||||
waiting.set(id, { resolve, reject });
|
||||
parent.postMessage({ magpie: 1, id, method, params }, "*");
|
||||
});
|
||||
}
|
||||
function paint(theme) {
|
||||
if (!theme) return;
|
||||
const root = document.documentElement;
|
||||
root.dataset.theme = theme.dark ? "dark" : "light";
|
||||
root.style.colorScheme = theme.dark ? "dark" : "light";
|
||||
if (theme.lang) root.lang = theme.lang;
|
||||
for (const [key, value] of Object.entries(theme.tokens || {})) {
|
||||
if (typeof value === "string") root.style.setProperty("--magpie-" + key, value);
|
||||
}
|
||||
}
|
||||
addEventListener("message", (event) => {
|
||||
const message = event.data;
|
||||
if (!message || message.magpie !== 1 || event.source !== parent) return;
|
||||
if (message.event === "theme") {
|
||||
api.theme = message.data;
|
||||
paint(message.data);
|
||||
for (const fn of themed) {
|
||||
try { fn(message.data); } catch { /* a page listener cannot break the bridge */ }
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.event === "visibility") {
|
||||
for (const fn of watched) fn(!!message.data?.visible);
|
||||
return;
|
||||
}
|
||||
const wait = waiting.get(message.id);
|
||||
if (!wait) return;
|
||||
waiting.delete(message.id);
|
||||
if (message.error) wait.reject(new Error(message.error));
|
||||
else wait.resolve(message.result);
|
||||
});
|
||||
const api = {
|
||||
theme: null,
|
||||
context: {},
|
||||
service: "",
|
||||
onTheme(fn) { themed.push(fn); },
|
||||
options: {
|
||||
get: () => call("options.get"),
|
||||
set: (options) => call("options.set", { options }),
|
||||
},
|
||||
onVisibility(fn) { watched.push(fn); },
|
||||
};
|
||||
api.ready = call("hello").then((hello = {}) => {
|
||||
const { context, service, ...theme } = hello;
|
||||
api.theme = theme;
|
||||
api.context = context || {};
|
||||
api.service = "";
|
||||
if (service) {
|
||||
try { api.service = new URL(service, location.href).href; } catch { /* none */ }
|
||||
}
|
||||
paint(theme);
|
||||
return theme;
|
||||
});
|
||||
window.magpie = api;
|
||||
})();`;
|
||||
|
||||
// The build's own version, so an older service on the port is told apart
|
||||
// from this one.
|
||||
export function version() {
|
||||
@@ -101,6 +175,7 @@ function allowNullOrigin(req, res) {
|
||||
res.setHeader("Access-Control-Allow-Origin", "null");
|
||||
res.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
|
||||
res.setHeader("Access-Control-Allow-Headers", "x-usage-tree-token");
|
||||
res.setHeader("Access-Control-Expose-Headers", "x-usage-tree-cache, x-usage-tree-refresh");
|
||||
res.setHeader("Vary", "Origin");
|
||||
}
|
||||
}
|
||||
@@ -185,6 +260,12 @@ export async function startServer(options = {}) {
|
||||
const cache = new Map();
|
||||
let boundPort = requestedPort;
|
||||
|
||||
function refreshFailedFor(period) {
|
||||
// A stale answer can simply be an older disk cache. Only a loader that
|
||||
// actually threw makes this a failed refresh.
|
||||
return cache.get(period)?.refreshFailed === true;
|
||||
}
|
||||
|
||||
async function dataFor(period, options = {}) {
|
||||
const wanted = PERIODS.has(period) ? period : "7d";
|
||||
const hit = cache.get(wanted);
|
||||
@@ -199,19 +280,28 @@ export async function startServer(options = {}) {
|
||||
return {
|
||||
data: { ...hit.data, stale },
|
||||
cache: stale ? "stale" : "fresh",
|
||||
refreshFailed: refreshFailedFor(wanted),
|
||||
};
|
||||
}
|
||||
// A read is already running behind the page: what was read last is
|
||||
// still the best answer to give now.
|
||||
if (hit?.pending) {
|
||||
if (hit.data && !options.fresh) {
|
||||
return { data: { ...hit.data, stale: true }, cache: "stale" };
|
||||
return {
|
||||
data: { ...hit.data, stale: true },
|
||||
cache: "stale",
|
||||
refreshFailed: refreshFailedFor(wanted),
|
||||
};
|
||||
}
|
||||
return { data: await hit.pending, cache: "shared" };
|
||||
return { data: await hit.pending, cache: "shared", refreshFailed: refreshFailedFor(wanted) };
|
||||
}
|
||||
|
||||
const loaded = await refreshInBackground(wanted, { wait: true, fresh: options.fresh });
|
||||
return { data: loaded, cache: loaded?.stale ? "stale" : "miss" };
|
||||
return {
|
||||
data: loaded,
|
||||
cache: loaded?.stale ? "stale" : "miss",
|
||||
refreshFailed: refreshFailedFor(wanted),
|
||||
};
|
||||
}
|
||||
|
||||
function refreshInBackground(wanted, options = {}) {
|
||||
@@ -219,20 +309,36 @@ export async function startServer(options = {}) {
|
||||
if (hit?.pending) {
|
||||
return options.wait ? hit.pending : Promise.resolve(hit.data);
|
||||
}
|
||||
// A retry started from a failed entry must keep that failure visible
|
||||
// until a loader actually succeeds; otherwise a quiet read would report
|
||||
// success while another failed refresh is still in flight.
|
||||
const entry = {
|
||||
at: hit?.at || 0,
|
||||
data: hit?.data,
|
||||
pending: null,
|
||||
refreshFailed: hit?.refreshFailed === true,
|
||||
};
|
||||
|
||||
const pending = loader(wanted, { fresh: Boolean(options.fresh) })
|
||||
.then((data) => {
|
||||
cache.set(wanted, { at: Date.now(), data, ttl: CACHE_MS });
|
||||
cache.set(wanted, {
|
||||
at: Date.now(),
|
||||
data,
|
||||
ttl: CACHE_MS,
|
||||
refreshFailed: false,
|
||||
});
|
||||
return data;
|
||||
})
|
||||
.catch((error) => {
|
||||
if (hit?.data) {
|
||||
hit.error = error;
|
||||
if (entry.data) {
|
||||
entry.refreshFailed = true;
|
||||
entry.error = error;
|
||||
// Keep the last good answer, but never let the page mistake it for
|
||||
// a successful fresh read. Marking it stale also keeps the next
|
||||
// request retrying instead of accepting the cache as current.
|
||||
hit.data = { ...hit.data, stale: true };
|
||||
return hit.data;
|
||||
entry.data = { ...entry.data, stale: true };
|
||||
if (cache.get(wanted) === entry) cache.set(wanted, entry);
|
||||
return entry.data;
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
@@ -241,10 +347,11 @@ export async function startServer(options = {}) {
|
||||
if (current?.pending === pending) current.pending = null;
|
||||
});
|
||||
|
||||
cache.set(wanted, { at: hit?.at || 0, data: hit?.data, pending });
|
||||
entry.pending = pending;
|
||||
cache.set(wanted, entry);
|
||||
if (!options.wait) {
|
||||
void pending.catch(() => {});
|
||||
return Promise.resolve(hit?.data);
|
||||
return Promise.resolve(entry.data);
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
@@ -279,6 +386,7 @@ export async function startServer(options = {}) {
|
||||
) {
|
||||
allowNullOrigin(req, res);
|
||||
res.writeHead(204, {
|
||||
"Access-Control-Expose-Headers": "x-usage-tree-cache, x-usage-tree-refresh",
|
||||
"Cache-Control": "no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
@@ -292,15 +400,16 @@ export async function startServer(options = {}) {
|
||||
return;
|
||||
}
|
||||
const template = await readFile(join(UI_DIR, "app.html"), "utf8");
|
||||
const hasUnits = url.searchParams.has("chineseUnits");
|
||||
const boot = {
|
||||
tokens: parseTokens(url.searchParams.get("tokens")),
|
||||
...displaySettings({
|
||||
theme: url.searchParams.get("theme") === "dark" ? "dark" : "light",
|
||||
lang: url.searchParams.get("lang") || "",
|
||||
currency: url.searchParams.get("currency") || options.currency || "",
|
||||
chineseUnits:
|
||||
url.searchParams.get("chineseUnits") === "1" ||
|
||||
(options.chineseUnits === true && !url.searchParams.has("chineseUnits")),
|
||||
chineseUnits: hasUnits
|
||||
? url.searchParams.get("chineseUnits") === "1"
|
||||
: options.chineseUnits === true,
|
||||
usdCny: url.searchParams.get("usdCny") || options.usdCny || 0,
|
||||
}),
|
||||
};
|
||||
@@ -313,6 +422,7 @@ export async function startServer(options = {}) {
|
||||
.replaceAll("__USAGE_TREE_CURRENCY__", escHTML(boot.currency))
|
||||
.replaceAll("__USAGE_TREE_USD_CNY__", escHTML(String(boot.usdCny)))
|
||||
.replaceAll("__USAGE_TREE_CHINESE_UNITS__", String(boot.chineseUnits))
|
||||
.replaceAll("__USAGE_TREE_SETTINGS__", url.searchParams.get("settings") === "1" ? "1" : "0")
|
||||
.replaceAll(
|
||||
"__USAGE_TREE_TITLE__",
|
||||
escHTML(lang.toLowerCase().startsWith("zh") ? "账号用量" : "Account usage"),
|
||||
@@ -329,6 +439,18 @@ export async function startServer(options = {}) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A small same-page bridge keeps plugin-option and visibility messages
|
||||
// working after the launcher navigates to the service.
|
||||
if (url.pathname === "/bridge.js") {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/javascript; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
});
|
||||
res.end(req.method === "HEAD" ? undefined : BRIDGE_SHIM);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/tree") {
|
||||
allowNullOrigin(req, res);
|
||||
if (!allowedOrigin(req.headers.origin, boundPort)) {
|
||||
@@ -346,6 +468,7 @@ export async function startServer(options = {}) {
|
||||
}
|
||||
const loaded = await dataFor(period, { fresh: url.searchParams.get("fresh") === "1" });
|
||||
res.setHeader("X-Usage-Tree-Cache", loaded.cache);
|
||||
res.setHeader("X-Usage-Tree-Refresh", loaded.refreshFailed ? "failed" : "ok");
|
||||
json(res, 200, loaded.data);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,6 +53,8 @@ function blankStats() {
|
||||
output: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
reasoning: 0,
|
||||
cost: 0,
|
||||
unpriced: 0,
|
||||
@@ -83,6 +85,8 @@ function gatewayStats(item) {
|
||||
["output", "output"],
|
||||
["cacheRead", "cache_read"],
|
||||
["cacheWrite", "cache_write"],
|
||||
["cacheUnknown", "cache_unknown"],
|
||||
["cacheUnknownCalls", "cache_unknown_calls"],
|
||||
["reasoning", "reasoning"],
|
||||
["cost", "cost"],
|
||||
["unpriced", "unpriced"],
|
||||
@@ -108,6 +112,8 @@ function addTotals(total, item) {
|
||||
"output",
|
||||
"cacheRead",
|
||||
"cacheWrite",
|
||||
"cacheUnknown",
|
||||
"cacheUnknownCalls",
|
||||
"reasoning",
|
||||
"cost",
|
||||
"unpriced",
|
||||
@@ -220,6 +226,7 @@ function modelRows(requests, account) {
|
||||
// GET /v1/magpie/usage/requests?account=...
|
||||
export function aggregateGatewayUsage(usage, requestsByAccount = {}, options = {}) {
|
||||
const period = PERIODS.has(options.period) ? options.period : "today";
|
||||
const missingModelAccounts = Math.max(0, Number(options.missingModelAccounts) || 0);
|
||||
const accountItems = Array.isArray(usage?.accounts) ? usage.accounts : [];
|
||||
const accounts = [];
|
||||
let apiKeyGroups = 0;
|
||||
@@ -328,7 +335,10 @@ export function aggregateGatewayUsage(usage, requestsByAccount = {}, options = {
|
||||
summary,
|
||||
providers,
|
||||
accounts,
|
||||
warnings: summary.calls ? [] : [{ code: "no-usage" }],
|
||||
warnings: [
|
||||
...(summary.calls ? [] : [{ code: "no-usage" }]),
|
||||
...(missingModelAccounts ? [{ code: "model-details", count: missingModelAccounts }] : []),
|
||||
],
|
||||
source: "Magpie gateway usage",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-usage-tree",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"description": "在 Magpie 窗口中按供应商 -> 账号 -> 模型查看用量,逐级展开调用、错误、Token 与费用。A page in Magpie's window: usage as provider -> account -> model, each level expandable, with calls, errors, tokens and cost from Magpie's local usage API.",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
@@ -60,6 +60,7 @@
|
||||
},
|
||||
"icon": "page/icon.svg"
|
||||
},
|
||||
"permissions": [],
|
||||
"options": {
|
||||
"port": 3494,
|
||||
"currency": "usd",
|
||||
|
||||
@@ -25,8 +25,30 @@
|
||||
chineseUnits: false,
|
||||
usdCny: 0,
|
||||
};
|
||||
let officialDisplay = false;
|
||||
|
||||
function followDisplay(value) {
|
||||
function hasOfficialDisplay(value) {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
return (
|
||||
value.currency === "cny" ||
|
||||
value.currency === "usd" ||
|
||||
typeof value.chineseUnits === "boolean" ||
|
||||
(Number.isFinite(Number(value.usdCny)) && Number(value.usdCny) > 0) ||
|
||||
(Number.isFinite(Number(value.fx?.rate)) && Number(value.fx.rate) > 0)
|
||||
);
|
||||
}
|
||||
|
||||
function followDisplay(value, official = false) {
|
||||
// A future bridge can carry Magpie's own display settings. Until it does,
|
||||
// this plugin's options are the only supported fallback.
|
||||
if (official && !hasOfficialDisplay(value)) return;
|
||||
if (official && !officialDisplay) {
|
||||
display.currency = "usd";
|
||||
display.chineseUnits = false;
|
||||
display.usdCny = 0;
|
||||
}
|
||||
if (official) officialDisplay = true;
|
||||
if (officialDisplay && !official) return;
|
||||
if (!value || typeof value !== "object") return;
|
||||
if (value.currency === "cny" || value.currency === "usd") {
|
||||
display.currency = value.currency;
|
||||
@@ -36,6 +58,8 @@
|
||||
}
|
||||
const rate = Number(value.usdCny);
|
||||
if (Number.isFinite(rate) && rate > 0) display.usdCny = rate;
|
||||
const nestedRate = Number(value.fx?.rate);
|
||||
if (Number.isFinite(nestedRate) && nestedRate > 0) display.usdCny = nestedRate;
|
||||
}
|
||||
|
||||
function followLanguage(value) {
|
||||
@@ -54,7 +78,7 @@
|
||||
theme = current.dark ? "dark" : "light";
|
||||
lang = String(current.lang || lang).toLowerCase().startsWith("zh") ? "zh" : "en";
|
||||
tokens = current.tokens || null;
|
||||
followDisplay(current);
|
||||
followDisplay(current, true);
|
||||
}
|
||||
} catch {
|
||||
// The page still works without the bridge.
|
||||
@@ -79,6 +103,7 @@
|
||||
followLanguage(lang);
|
||||
window.magpie?.onTheme?.((next) => {
|
||||
if (!next) return;
|
||||
followDisplay(next, true);
|
||||
if (typeof next.dark === "boolean") theme = next.dark ? "dark" : "light";
|
||||
if (typeof next.lang === "string") {
|
||||
const before = lang;
|
||||
@@ -97,6 +122,7 @@
|
||||
query.set("currency", display.currency);
|
||||
query.set("chineseUnits", display.chineseUnits ? "1" : "0");
|
||||
if (display.usdCny > 0) query.set("usdCny", String(display.usdCny));
|
||||
query.set("settings", "1");
|
||||
if (tokens && typeof tokens === "object") {
|
||||
try {
|
||||
const slim = {};
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createServer } from "node:http";
|
||||
import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { loadUsageData } from "../lib/data.mjs";
|
||||
import { cacheUsable, loadUsageData } from "../lib/data.mjs";
|
||||
|
||||
test("a stale disk cache says so while it refreshes behind the page", async (t) => {
|
||||
const root = mkdtempSync(join(tmpdir(), "usage-tree-cache-"));
|
||||
@@ -14,12 +14,18 @@ test("a stale disk cache says so while it refreshes behind the page", async (t)
|
||||
writeFileSync(
|
||||
join(root, "usage-tree", "today.json"),
|
||||
JSON.stringify({
|
||||
v: 6,
|
||||
v: 8,
|
||||
at: Date.now() - 60_000,
|
||||
data: {
|
||||
period: "today",
|
||||
generatedAt: "old",
|
||||
summary: { calls: 1 },
|
||||
summary: {
|
||||
calls: 1,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
},
|
||||
providers: [],
|
||||
accounts: [],
|
||||
warnings: [],
|
||||
@@ -75,3 +81,146 @@ test("a stale disk cache says so while it refreshes behind the page", async (t)
|
||||
assert.equal(statSync(join(root, "usage-tree", "today.json")).mode & 0o777, 0o600);
|
||||
}
|
||||
});
|
||||
|
||||
test("a v6 cache without hit-rate fields is not served as current", async (t) => {
|
||||
const root = mkdtempSync(join(tmpdir(), "usage-tree-old-cache-"));
|
||||
const previousCache = process.env.MAGPIE_CACHE_DIR;
|
||||
process.env.MAGPIE_CACHE_DIR = root;
|
||||
mkdirSync(join(root, "usage-tree"), { recursive: true });
|
||||
writeFileSync(
|
||||
join(root, "usage-tree", "today.json"),
|
||||
JSON.stringify({
|
||||
v: 6,
|
||||
at: Date.now(),
|
||||
data: {
|
||||
period: "today",
|
||||
generatedAt: "old",
|
||||
summary: { calls: 1, cache: 0 },
|
||||
providers: [],
|
||||
accounts: [],
|
||||
warnings: [],
|
||||
},
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const gateway = createServer((req, res) => {
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.end(JSON.stringify({
|
||||
period: "today",
|
||||
calls: 2,
|
||||
errors: 0,
|
||||
input: 2,
|
||||
output: 0,
|
||||
cache_read: 0,
|
||||
cache_write: 0,
|
||||
cost: 0,
|
||||
unpriced: 0,
|
||||
accounts: [],
|
||||
models: [],
|
||||
}));
|
||||
});
|
||||
await new Promise((resolve) => gateway.listen(0, "127.0.0.1", resolve));
|
||||
const base = `http://127.0.0.1:${gateway.address().port}`;
|
||||
|
||||
t.after(async () => {
|
||||
await new Promise((resolve) => gateway.close(resolve));
|
||||
if (previousCache === undefined) delete process.env.MAGPIE_CACHE_DIR;
|
||||
else process.env.MAGPIE_CACHE_DIR = previousCache;
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const result = await loadUsageData("today", { gateway: base });
|
||||
assert.notEqual(result.summary.calls, 1);
|
||||
assert.equal(result.summary.calls, 2);
|
||||
assert.equal(result.summary.cacheUnknown, 0);
|
||||
assert.equal(result.summary.cacheUnknownCalls, 0);
|
||||
});
|
||||
|
||||
test("a failed per-account request read warns without discarding the usage answer", async (t) => {
|
||||
const root = mkdtempSync(join(tmpdir(), "usage-tree-detail-warning-"));
|
||||
const previousCache = process.env.MAGPIE_CACHE_DIR;
|
||||
process.env.MAGPIE_CACHE_DIR = root;
|
||||
t.after(() => {
|
||||
if (previousCache === undefined) delete process.env.MAGPIE_CACHE_DIR;
|
||||
else process.env.MAGPIE_CACHE_DIR = previousCache;
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const gateway = createServer((req, res) => {
|
||||
res.setHeader("content-type", "application/json");
|
||||
if (req.url.startsWith("/v1/magpie/usage/requests")) {
|
||||
res.writeHead(503).end(JSON.stringify({ error: "requests unavailable" }));
|
||||
return;
|
||||
}
|
||||
if (req.url.startsWith("/v1/magpie/usage")) {
|
||||
res.end(JSON.stringify({
|
||||
period: "today",
|
||||
calls: 2,
|
||||
errors: 0,
|
||||
input: 2,
|
||||
output: 0,
|
||||
cache_read: 0,
|
||||
cache_write: 0,
|
||||
cost: 0,
|
||||
unpriced: 0,
|
||||
accounts: [{
|
||||
provider: "codex",
|
||||
account: "alice@example.com",
|
||||
calls: 2,
|
||||
errors: 0,
|
||||
input: 2,
|
||||
output: 0,
|
||||
cache_read: 0,
|
||||
cache_write: 0,
|
||||
cost: 0,
|
||||
unpriced: 0,
|
||||
}],
|
||||
models: [],
|
||||
}));
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
await new Promise((resolve) => gateway.listen(0, "127.0.0.1", resolve));
|
||||
const base = `http://127.0.0.1:${gateway.address().port}`;
|
||||
t.after(async () => {
|
||||
await new Promise((resolve) => gateway.close(resolve));
|
||||
});
|
||||
|
||||
const result = await loadUsageData("today", { gateway: base, fresh: true });
|
||||
assert.equal(result.summary.calls, 2);
|
||||
assert.equal(result.accounts.length, 1);
|
||||
assert.deepEqual(result.warnings, [{ code: "model-details", count: 1 }]);
|
||||
});
|
||||
|
||||
test("cached trees must carry every cache hit-rate field", () => {
|
||||
const fields = {
|
||||
cacheRead: 1,
|
||||
cacheWrite: 2,
|
||||
cacheUnknown: 3,
|
||||
cacheUnknownCalls: 4,
|
||||
};
|
||||
assert.equal(cacheUsable({ summary: fields, providers: [], accounts: [] }), true);
|
||||
assert.equal(cacheUsable({ summary: { cacheRead: 0 }, providers: [], accounts: [] }), false);
|
||||
assert.equal(cacheUsable({
|
||||
summary: fields,
|
||||
providers: [{ ...fields }],
|
||||
accounts: [{ cacheRead: 0 }],
|
||||
}), false);
|
||||
assert.equal(cacheUsable({
|
||||
summary: fields,
|
||||
providers: [],
|
||||
accounts: [{ ...fields, models: [{ cacheRead: 0 }] }],
|
||||
}), false);
|
||||
assert.equal(cacheUsable({
|
||||
summary: fields,
|
||||
providers: [{ ...fields, accounts: [{ ...fields, models: [fields] }] }],
|
||||
accounts: [],
|
||||
}), true);
|
||||
assert.equal(cacheUsable({
|
||||
summary: fields,
|
||||
providers: [{ ...fields, accounts: [{ ...fields, models: [{ cacheRead: 0 }] }] }],
|
||||
accounts: [],
|
||||
}), false);
|
||||
});
|
||||
|
||||
@@ -24,6 +24,9 @@ const summary = {
|
||||
input: 1200000,
|
||||
output: 300000,
|
||||
cache: 900000,
|
||||
cacheRead: 900000,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
tokens: 1500000,
|
||||
cost: 42.5,
|
||||
unpriced: 2,
|
||||
@@ -89,6 +92,10 @@ test("the page reads nothing of magpie and reaches no network", () => {
|
||||
);
|
||||
}
|
||||
assert.deepEqual([...reads], []);
|
||||
for (const file of readdirSync(uiDir).filter((f) => f.endsWith(".js"))) {
|
||||
const source = read(uiDir, file);
|
||||
assert.doesNotMatch(source, /\.read\(\s*"usage:day"|\bread\(\s*"usage:day"/);
|
||||
}
|
||||
});
|
||||
|
||||
test("plugin metadata speaks Chinese and English", () => {
|
||||
@@ -132,14 +139,32 @@ test("the launcher only navigates to the local service", () => {
|
||||
|
||||
test("the launcher forwards currency and unit options", () => {
|
||||
const boot = read(pageDir, "boot.js");
|
||||
assert.doesNotMatch(boot, /usage:day|magpie\?\.read\(/);
|
||||
assert.match(boot, /query\.set\("currency", display\.currency\)/);
|
||||
assert.match(boot, /query\.set\("chineseUnits", display\.chineseUnits \? "1" : "0"\)/);
|
||||
assert.match(boot, /followDisplay\(options\)/);
|
||||
assert.match(boot, /query\.set\("settings", "1"\)/);
|
||||
assert.equal(pkg.magpie.options.currency, "usd");
|
||||
assert.equal(pkg.magpie.options.chineseUnits, false);
|
||||
assert.equal(pkg.magpie.options.usdCny, 0);
|
||||
});
|
||||
|
||||
test("the launcher does not invent official display settings from a theme-only hello", () => {
|
||||
const source = read(pageDir, "boot.js");
|
||||
const start = source.indexOf(" let officialDisplay = false;");
|
||||
const end = source.indexOf(" function followLanguage", start);
|
||||
const helpers = source.slice(start, end);
|
||||
const run = new Function("display", `${helpers}; return followDisplay;`);
|
||||
const display = { currency: "cny", chineseUnits: true, usdCny: 7.2 };
|
||||
const followDisplay = run(display);
|
||||
followDisplay({ dark: true, lang: "zh" }, true);
|
||||
assert.deepEqual(display, { currency: "cny", chineseUnits: true, usdCny: 7.2 });
|
||||
followDisplay({ currency: "cny", chineseUnits: false, usdCny: 7.3 }, true);
|
||||
assert.deepEqual(display, { currency: "cny", chineseUnits: false, usdCny: 7.3 });
|
||||
followDisplay({ currency: "usd", chineseUnits: true, usdCny: 8 }, false);
|
||||
assert.deepEqual(display, { currency: "cny", chineseUnits: false, usdCny: 7.3 });
|
||||
});
|
||||
|
||||
test("the summary says accounts, calls, tokens and cost", () => {
|
||||
V.setChineseUnits(true);
|
||||
V.setLang("zh");
|
||||
@@ -163,6 +188,48 @@ test("cache can be included or excluded from token totals", () => {
|
||||
assert.equal(V.tiles(summary, "zh", "usd", 6.6696, false)[2].value, "150万");
|
||||
});
|
||||
|
||||
test("cache hit text follows Magpie's own cache-aware denominator", () => {
|
||||
assert.equal(V.cacheHitRate({ input: 120, cacheRead: 180, cacheWrite: 20 }), 0.5625);
|
||||
assert.equal(V.cacheHitRate({ input: 200, cacheRead: 0, cacheWrite: 0, cacheUnknown: 200 }), null);
|
||||
assert.equal(V.cacheHitRate({ input: 200, cacheRead: 0, cacheWrite: 0 }), null);
|
||||
assert.equal(V.cacheHitRate({ input: 200, cacheRead: 0 }), null);
|
||||
assert.equal(V.cacheHitRate({ input: 0, cacheRead: 0 }), null);
|
||||
assert.equal(V.cacheHitText(summary, "zh"), "缓存命中率 43%");
|
||||
assert.equal(V.cacheHitText(summary, "en"), "Cache hit 43%");
|
||||
assert.equal(
|
||||
V.cacheHitText({ input: 200, cacheRead: 0, cacheWrite: 0, cacheUnknown: 200, cacheUnknownCalls: 1 }, "zh"),
|
||||
"1 次未统计缓存",
|
||||
);
|
||||
assert.equal(
|
||||
V.cacheHitText({ input: 120, cacheRead: 180, cacheWrite: 20, cacheUnknownCalls: 2 }, "zh"),
|
||||
"缓存命中率 56% · 2 次未统计缓存",
|
||||
);
|
||||
assert.equal(
|
||||
V.cacheHitText({ input: 120, cacheRead: 180, cacheWrite: 20, cacheUnknownCalls: 2 }, "en"),
|
||||
"Cache hit 56% · 2 cache-uncounted calls",
|
||||
);
|
||||
assert.equal(V.cacheHitText({ input: 0, cacheRead: 0, cacheWrite: 0 }, "en"), "");
|
||||
assert.equal(V.cacheHitSuffix({ input: 0, cacheRead: 0 }, "en"), "");
|
||||
assert.match(V.tiles(summary, "zh", "usd", 0)[2].sub, / · 缓存命中率 43%$/);
|
||||
assert.match(V.tiles(summary, "en", "usd", 0)[2].sub, / · Cache hit 43%$/);
|
||||
});
|
||||
|
||||
test("cache hit percentages use Magpie's rounding", () => {
|
||||
assert.equal(V.hitPercent(0), "0%");
|
||||
assert.equal(V.hitPercent(1), "100%");
|
||||
assert.equal(V.hitPercent(0.43), "43%");
|
||||
assert.equal(V.hitPercent(0.996), "99.6%");
|
||||
assert.equal(V.hitPercent(0.99999), "99.99%");
|
||||
assert.equal(V.hitPercent(1e-7), "0.01%");
|
||||
assert.equal(V.hitPercent(0.056), "6%");
|
||||
assert.equal(V.hitPercent(0.001), "0.1%");
|
||||
assert.equal(V.hitPercent(0.0001), "0.01%");
|
||||
assert.equal(
|
||||
V.cacheHitText({ input: 4, cacheRead: 996, cacheWrite: 0 }, "zh"),
|
||||
"缓存命中率 99.6%",
|
||||
);
|
||||
});
|
||||
|
||||
test("an account shows the name the user gave it", () => {
|
||||
const rows = V.accounts(accounts, "tokens", "zh");
|
||||
assert.equal(rows[0].name, "10月学生Plus");
|
||||
@@ -277,6 +344,18 @@ test("the model table has one column per value and follows the cache switch", ()
|
||||
assert.doesNotMatch(head, /el\("span", "", "Token"\)/);
|
||||
assert.equal(scope.UsageI18n.get("zh").token, "Token");
|
||||
assert.equal(scope.UsageI18n.get("en").token, "Token");
|
||||
assert.match(read(uiDir, "app.js"), /V\.cacheHitSuffix\(model, lang\)/);
|
||||
});
|
||||
|
||||
test("the cache hit detail wraps at intermediate and phone widths", () => {
|
||||
const css = read(uiDir, "style.css");
|
||||
const base = css.slice(0, css.indexOf("@media (max-width: 900px)"));
|
||||
const narrow = css.slice(css.indexOf("@media (max-width: 700px)"));
|
||||
assert.match(base, /\.summary-sub \{[\s\S]*?overflow-wrap: anywhere;[\s\S]*?white-space: normal;/);
|
||||
assert.match(base, /\.model-split \{[\s\S]*?overflow-wrap: anywhere;[\s\S]*?white-space: normal;/);
|
||||
assert.match(narrow, /\.model-row \.model-split \{[\s\S]*?display: block;/);
|
||||
assert.doesNotMatch(narrow, /grid-column: 1 \/ -1;/);
|
||||
assert.doesNotMatch(narrow, /\.model-row \.model-provider,\s*\.model-row \.model-split,/);
|
||||
});
|
||||
|
||||
test("model calls sit under the right-aligned calls header", () => {
|
||||
@@ -288,14 +367,20 @@ test("model calls sit under the right-aligned calls header", () => {
|
||||
|
||||
test("the 900 px grid keeps every visible cell in its own column", () => {
|
||||
const css = read(uiDir, "style.css");
|
||||
const block = css.slice(css.indexOf("@media (max-width: 900px)"), css.indexOf("@media (max-width: 620px)"));
|
||||
const block = css.slice(css.indexOf("@media (max-width: 900px)"), css.indexOf("@media (max-width: 700px)"));
|
||||
const columns = "minmax\\(150px, 1fr\\) 60px 74px minmax\\(80px, 0\\.7fr\\) 44px 74px 20px";
|
||||
assert.match(block, new RegExp(`\\.account-main \\{\\s+grid-template-columns: ${columns};`));
|
||||
assert.match(block, new RegExp(`\\.provider-main \\{\\s+grid-template-columns: ${columns};`));
|
||||
assert.match(
|
||||
block,
|
||||
/\.model-head,\s*\.model-row \{\s+grid-template-columns: minmax\(150px, 1fr\) 92px 74px minmax\(80px, 0\.7fr\) 46px 74px;/,
|
||||
);
|
||||
assert.match(block, /\.provider-main \.errors-cell/);
|
||||
assert.match(block, /grid-template-columns: minmax\(150px, 1fr\) 92px 74px minmax\(80px, 0\.7fr\) 46px 74px;/);
|
||||
});
|
||||
|
||||
test("the narrow summary wraps its token split instead of cutting it", () => {
|
||||
const css = read(uiDir, "style.css");
|
||||
const block = css.slice(css.indexOf("@media (max-width: 620px)"));
|
||||
const block = css.slice(css.indexOf("@media (max-width: 700px)"));
|
||||
assert.match(block, /\.summary-sub \{[\s\S]*?white-space: normal;/);
|
||||
});
|
||||
|
||||
@@ -337,7 +422,7 @@ test("the token-cache switch is native-looking, persistent and default-on", () =
|
||||
assert.match(source, /store\.get\("usage-tree\.include-cache"\) !== "0"/);
|
||||
assert.match(source, /store\.set\("usage-tree\.include-cache", state\.includeCache \? "1" : "0"\)/);
|
||||
assert.match(source, /V\.tokenTotal\(item, state\.includeCache\)/);
|
||||
assert.match(source, /summary\.cache[\s\S]*?provider\.cache[\s\S]*?account\.cache[\s\S]*?model\.cache/);
|
||||
assert.match(source, /item\.cache,\s*item\.allTokens,/);
|
||||
const providerSort = source.slice(
|
||||
source.indexOf("function visibleProviders"),
|
||||
source.indexOf("function providersOf", source.indexOf("function visibleProviders")),
|
||||
@@ -348,7 +433,7 @@ test("the token-cache switch is native-looking, persistent and default-on", () =
|
||||
|
||||
test("the page follows magpie's language without a reload", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /function applyDisplay\(display\)/);
|
||||
assert.match(source, /function applyDisplay\(display, source = "options"\)/);
|
||||
assert.match(source, /W = globalThis\.UsageI18n\.get\(lang\)/);
|
||||
// Nothing is polled: the theme message carries the language.
|
||||
assert.doesNotMatch(source, /setInterval/);
|
||||
@@ -359,26 +444,192 @@ test("the page follows magpie's language without a reload", () => {
|
||||
assert.match(source, /getAttribute\("content"\) \|\| "en"/);
|
||||
});
|
||||
|
||||
test("official display preferences win over plugin options when the bridge provides them", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /let officialDisplay = false;/);
|
||||
assert.match(source, /const hasOfficialDisplay =[\s\S]*?display\.currency === "cny"/);
|
||||
assert.match(source, /if \(hasOfficialDisplay\) applyDisplay\(display, "magpie"\)/);
|
||||
assert.match(source, /if \(officialDisplay\) return;/);
|
||||
assert.match(source, /else if \(officialDisplay && source !== "magpie"\) \{\s*return false;\s*\}/);
|
||||
assert.match(source, /Number\(display\.fx\?\.rate\)/);
|
||||
const boot = read(pageDir, "boot.js");
|
||||
assert.match(boot, /function hasOfficialDisplay\(value\)/);
|
||||
assert.match(boot, /followDisplay\(current, true\)/);
|
||||
assert.match(boot, /followDisplay\(next, true\)/);
|
||||
assert.match(boot, /followDisplay\(options\);/);
|
||||
});
|
||||
|
||||
test("warnings can explain incomplete model details in both languages", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /item\.code === "model-details"[\s\S]*?W\.modelDetails/);
|
||||
assert.match(scope.UsageI18n.get("zh").modelDetails(2), /2 个账号的模型明细/);
|
||||
assert.match(scope.UsageI18n.get("en").modelDetails(1), /1 account is/);
|
||||
assert.match(scope.UsageI18n.get("en").modelDetails(2), /2 accounts are/);
|
||||
});
|
||||
|
||||
test("plugin options are re-read on callbacks, never polled", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /onVisibility\?\.\(\(visible\) =>/);
|
||||
assert.doesNotMatch(source, /usage:day|bridge\.read\(/);
|
||||
assert.match(source, /await bridge\.options\.get\(\)/);
|
||||
assert.match(source, /if \(!options \|\| typeof options !== "object"\) return;/);
|
||||
assert.match(source, /if \(options\.currency === "cny" \|\| options\.currency === "usd"\)/);
|
||||
assert.match(source, /meta\("settings"\) === "1"/);
|
||||
assert.match(source, /message\.event !== "theme"[\s\S]*?syncDisplaySettings\(window\.magpie\)/);
|
||||
assert.doesNotMatch(source, /setInterval|setTimeout\(\s*\(\)\s*=>\s*void syncDisplaySettings/);
|
||||
assert.match(read(pageDir, "boot.js"), /query\.set\("settings", "1"\)/);
|
||||
});
|
||||
|
||||
test("slow usage reads get more than one gateway request to finish", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /const REQUEST_TIMEOUT_MS = 30_000;/);
|
||||
assert.match(source, /const SERVICE_TIMEOUT_MS = REQUEST_TIMEOUT_MS \+ 1_000;/);
|
||||
assert.match(source, /AbortSignal\.timeout\(REQUEST_TIMEOUT_MS\)/);
|
||||
assert.match(source, /\}, SERVICE_TIMEOUT_MS\);/);
|
||||
assert.match(source, /error\?\.name === "TimeoutError"[\s\S]*?state\.error = W\.serviceTimeout/);
|
||||
assert.match(source, /addEventListener\("pagehide", \(\) => clearTimeout\(serviceTimer\)/);
|
||||
});
|
||||
|
||||
test("only the newest settings read can repaint display settings", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /let displaySettingsRequest = 0;/);
|
||||
assert.match(source, /const requestId = \+\+displaySettingsRequest;/);
|
||||
assert.match(source, /await bridge\.options\.get\(\);\s*if \(requestId !== displaySettingsRequest\) return;/);
|
||||
});
|
||||
|
||||
test("a newer load owns the refresh UI after an older request settles", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /function isCurrentLoad\(requestId, requestedPeriod\)/);
|
||||
assert.match(source, /requestId === state\.requestId && requestedPeriod === state\.period/);
|
||||
assert.match(source, /if \(state\.controller === controller\) state\.controller = null;/);
|
||||
assert.match(source, /if \(!isCurrentLoad\(requestId, requestedPeriod\)\) return;/);
|
||||
});
|
||||
|
||||
test("a retry can repaint and fingerprints cover displayed metrics", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /function renderError\(\) \{\s+state\.rendered = false;/);
|
||||
for (const field of [
|
||||
"summary.errors",
|
||||
"summary.unpriced",
|
||||
"summary.input",
|
||||
"summary.output",
|
||||
"item.calls",
|
||||
"item.errors",
|
||||
"item.unpriced",
|
||||
"item.input",
|
||||
"item.output",
|
||||
"item.tokens",
|
||||
"item.cache",
|
||||
"item.allTokens",
|
||||
"item.cacheRead",
|
||||
"item.cacheWrite",
|
||||
"item.cacheUnknown",
|
||||
"item.cacheUnknownCalls",
|
||||
"account.lastAt",
|
||||
"model.errors",
|
||||
"model.hostNotes",
|
||||
]) {
|
||||
assert.match(source, new RegExp(field.replace(".", "\\.")), field);
|
||||
}
|
||||
assert.match(source, /const delay = attempt === 1 \? 1200 : attempt === 2 \? 2500 : 5000;/);
|
||||
});
|
||||
|
||||
test("a quiet refresh repaints when only the cache hit composition changes", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
const start = source.indexOf("function fingerprint(data) {");
|
||||
const open = source.indexOf("{", start);
|
||||
let depth = 0;
|
||||
let end = -1;
|
||||
for (let index = open; index < source.length; index += 1) {
|
||||
if (source[index] === "{") depth += 1;
|
||||
if (source[index] === "}") depth -= 1;
|
||||
if (depth === 0) {
|
||||
end = index + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert.ok(end > start, "fingerprint body was found");
|
||||
const fingerprint = new Function(`${source.slice(start, end)}; return fingerprint;`)();
|
||||
const sample = () => {
|
||||
const stats = {
|
||||
period: "today",
|
||||
calls: 1,
|
||||
input: 200,
|
||||
output: 10,
|
||||
tokens: 210,
|
||||
cache: 200,
|
||||
allTokens: 410,
|
||||
cacheRead: 200,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
cost: 1,
|
||||
};
|
||||
return {
|
||||
period: "today",
|
||||
summary: { ...stats, accounts: 1, providers: 1, models: 1 },
|
||||
providers: [{
|
||||
id: "p",
|
||||
providerName: "P",
|
||||
...stats,
|
||||
accounts: [{
|
||||
id: "a",
|
||||
account: "a",
|
||||
alias: "",
|
||||
providerName: "P",
|
||||
...stats,
|
||||
lastAt: "",
|
||||
models: [{
|
||||
id: "m",
|
||||
model: "m",
|
||||
provider: "p",
|
||||
providerName: "P",
|
||||
...stats,
|
||||
hostNotes: [],
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
};
|
||||
};
|
||||
|
||||
const before = fingerprint(sample());
|
||||
for (const path of [
|
||||
["summary"],
|
||||
["providers", 0],
|
||||
["providers", 0, "accounts", 0],
|
||||
["providers", 0, "accounts", 0, "models", 0],
|
||||
]) {
|
||||
const changed = sample();
|
||||
let item = changed;
|
||||
for (const key of path) item = item[key];
|
||||
item.cacheRead = 150;
|
||||
item.cacheWrite = 50;
|
||||
item.cacheUnknownCalls = 1;
|
||||
assert.notEqual(fingerprint(changed), before, `fingerprint changed at ${path.join(".")}`);
|
||||
}
|
||||
const legacy = () => ({
|
||||
period: "today",
|
||||
summary: sample().summary,
|
||||
accounts: [{
|
||||
...sample().providers[0].accounts[0],
|
||||
cacheRead: 200,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
}],
|
||||
});
|
||||
const changedLegacy = legacy();
|
||||
changedLegacy.accounts[0].cacheRead = 150;
|
||||
changedLegacy.accounts[0].cacheWrite = 50;
|
||||
assert.notEqual(fingerprint(legacy()), fingerprint(changedLegacy));
|
||||
});
|
||||
|
||||
test("a failed follow-up keeps the period already on screen", () => {
|
||||
const source = read(uiDir, "app.js");
|
||||
assert.match(source, /state\.data\?\.period === requestedPeriod/);
|
||||
assert.match(source, /warning\.textContent = W\.refreshFailed/);
|
||||
assert.match(source, /let refreshFailed = false;/);
|
||||
assert.match(source, /function showRefreshWarning\(\)/);
|
||||
assert.match(source, /function clearRefreshWarning\(\)/);
|
||||
assert.match(source, /showRefreshWarning\(\);/);
|
||||
assert.match(source, /renderWarnings\(state\.data\?\.warnings \|\| \[\]\)/);
|
||||
assert.match(source, /renderWarnings\(body\.warnings \|\| \[\]\)/);
|
||||
assert.match(source, /x-usage-tree-refresh/);
|
||||
assert.match(source, /if \(!options\.quiet\) clearRefreshWarning\(\)/);
|
||||
assert.match(scope.UsageI18n.get("en").refreshFailed, /previous data/);
|
||||
});
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ import http from "node:http";
|
||||
import https from "node:https";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { aggregateGatewayUsage } from "../lib/usage.mjs";
|
||||
import { loadUsageData } from "../lib/data.mjs";
|
||||
import { gatewayCandidates } from "../lib/gateway.mjs";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
@@ -149,7 +151,9 @@ function gatewayReachable(gateway) {
|
||||
|
||||
// The gateway's account rows must be the rows `magpie usage 7d` prints,
|
||||
// except API-key calls: magpie's Accounts table leaves those out by design.
|
||||
test("matches magpie's own usage tables", async (t) => {
|
||||
// A live 7d ledger plus the per-account requests read can exceed Bun's
|
||||
// default 5 s test timeout; the read remains bounded by its HTTP timeouts.
|
||||
test("matches magpie's own usage tables", { timeout: 15_000 }, async (t) => {
|
||||
const binary = magpieBinary();
|
||||
const gateway = gatewayCandidates()[0];
|
||||
if (!binary) {
|
||||
@@ -170,8 +174,21 @@ test("matches magpie's own usage tables", async (t) => {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
});
|
||||
// Use the same read as the page. Some accounts need the per-account
|
||||
// requests answer to complete their model table; the top-level usage
|
||||
// snapshot alone can leave those calls out.
|
||||
const root = mkdtempSync(join(tmpdir(), "usage-tree-parity-"));
|
||||
const previousCache = process.env.MAGPIE_CACHE_DIR;
|
||||
process.env.MAGPIE_CACHE_DIR = root;
|
||||
t.after(() => {
|
||||
if (previousCache === undefined) delete process.env.MAGPIE_CACHE_DIR;
|
||||
else process.env.MAGPIE_CACHE_DIR = previousCache;
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
const mine = await loadUsageData("7d", { gateway, fresh: true });
|
||||
// Take the closing snapshot after the page read, so a concurrent call
|
||||
// recorded while it was reading stays inside the inclusive range.
|
||||
const after = await usageSnapshot(gateway);
|
||||
const mine = aggregateGatewayUsage(after, {}, { period: "7d" });
|
||||
const cli = parseCLIUsage(stdout);
|
||||
|
||||
// The gateway answer on the page must agree with Magpie's own top-level
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const dir = join(import.meta.dirname, "..");
|
||||
const uiDir = join(dir, "ui");
|
||||
const read = (file) => readFileSync(join(uiDir, file), "utf8");
|
||||
|
||||
const base = {
|
||||
period: "today",
|
||||
generatedAt: "2026-11-11T00:00:00.000Z",
|
||||
source: "synthetic gateway",
|
||||
summary: {
|
||||
accounts: 0,
|
||||
providers: 0,
|
||||
models: 0,
|
||||
calls: 0,
|
||||
errors: 0,
|
||||
unpriced: 0,
|
||||
input: 0,
|
||||
output: 0,
|
||||
tokens: 0,
|
||||
cache: 0,
|
||||
allTokens: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
cost: 0,
|
||||
},
|
||||
providers: [],
|
||||
accounts: [],
|
||||
warnings: [],
|
||||
};
|
||||
|
||||
const tick = async () => {
|
||||
for (let index = 0; index < 8; index += 1) await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
};
|
||||
|
||||
// The real app.js runs here against a tiny DOM and a real fetch sequence.
|
||||
// This exercises the initial load, a failed manual refresh and the quiet
|
||||
// follow-up that clears the warning when the gateway recovers.
|
||||
async function runRefreshFlow(lang) {
|
||||
const runtime = {};
|
||||
new Function("globalThis", read("i18n.js"))(runtime);
|
||||
new Function("globalThis", read("view.js"))(runtime);
|
||||
|
||||
const meta = new Map([
|
||||
["usage-tree-token", "test-token"],
|
||||
["usage-tree-theme", "light"],
|
||||
["usage-tree-lang", lang],
|
||||
["usage-tree-tokens", "{}"],
|
||||
["usage-tree-currency", "usd"],
|
||||
["usage-tree-usd-cny", ""],
|
||||
["usage-tree-chinese-units", "false"],
|
||||
["usage-tree-settings", "0"],
|
||||
]);
|
||||
|
||||
function element(tag = "div") {
|
||||
const listeners = new Map();
|
||||
const classes = new Set();
|
||||
const attributes = new Map();
|
||||
return {
|
||||
tagName: String(tag).toUpperCase(),
|
||||
className: "",
|
||||
textContent: "",
|
||||
title: "",
|
||||
hidden: false,
|
||||
disabled: false,
|
||||
type: "",
|
||||
placeholder: "",
|
||||
innerHTML: "",
|
||||
children: [],
|
||||
style: { setProperty() {} },
|
||||
dataset: {},
|
||||
listeners,
|
||||
classList: {
|
||||
add(...items) { for (const item of items) classes.add(item); },
|
||||
remove(...items) { for (const item of items) classes.delete(item); },
|
||||
toggle(item, force) {
|
||||
const on = force === undefined ? !classes.has(item) : Boolean(force);
|
||||
if (on) classes.add(item);
|
||||
else classes.delete(item);
|
||||
return on;
|
||||
},
|
||||
contains(item) { return classes.has(item); },
|
||||
},
|
||||
append(...children) { this.children.push(...children); },
|
||||
replaceChildren(...children) { this.children = [...children]; },
|
||||
setAttribute(name, value) { attributes.set(name, String(value)); },
|
||||
getAttribute(name) { return attributes.has(name) ? attributes.get(name) : null; },
|
||||
addEventListener(type, fn) {
|
||||
if (!listeners.has(type)) listeners.set(type, []);
|
||||
listeners.get(type).push(fn);
|
||||
},
|
||||
querySelectorAll() { return []; },
|
||||
closest() { return null; },
|
||||
click() {
|
||||
for (const fn of listeners.get("click") || []) fn({ target: this });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const elements = new Map();
|
||||
for (const id of [
|
||||
"summary", "accounts", "state-card", "warning", "refresh", "progress",
|
||||
"expand-all", "search", "period", "token-cache", "sort", "source-note", "updated",
|
||||
]) elements.set(id, element());
|
||||
|
||||
const document = {
|
||||
documentElement: { lang: "", dataset: {}, style: { setProperty() {} } },
|
||||
title: "",
|
||||
hidden: false,
|
||||
querySelector(selector) {
|
||||
const name = /meta\[name="([^"]+)"\]/.exec(selector)?.[1];
|
||||
return meta.has(name) ? { getAttribute: () => meta.get(name) } : null;
|
||||
},
|
||||
querySelectorAll() { return []; },
|
||||
getElementById(id) {
|
||||
if (!elements.has(id)) elements.set(id, element());
|
||||
return elements.get(id);
|
||||
},
|
||||
createElement(tag) { return element(tag); },
|
||||
createTextNode(value) { return { textContent: String(value) }; },
|
||||
};
|
||||
const window = { addEventListener() {}, parent: {}, magpie: undefined };
|
||||
const location = { href: `http://127.0.0.1:3494/?lang=${lang}`, search: `?lang=${lang}` };
|
||||
|
||||
let timerId = 0;
|
||||
const timers = new Map();
|
||||
const fakeSetTimeout = (fn, delay) => {
|
||||
const id = ++timerId;
|
||||
timers.set(id, { fn, delay });
|
||||
return id;
|
||||
};
|
||||
const fakeClearTimeout = (id) => { timers.delete(Number(id)); };
|
||||
const pagehide = [];
|
||||
const globalAddEventListener = (type, fn) => {
|
||||
if (type === "pagehide") pagehide.push(fn);
|
||||
};
|
||||
|
||||
class FakeAbortController {
|
||||
signal = { aborted: false };
|
||||
abort() { this.signal.aborted = true; }
|
||||
}
|
||||
const FakeAbortSignal = {
|
||||
any(signals) { return signals[0]; },
|
||||
timeout() { return { aborted: false }; },
|
||||
};
|
||||
|
||||
const stale = { ...base, stale: true, warnings: [] };
|
||||
const warnings = [{ code: "no-usage" }, { code: "model-details", count: 2 }];
|
||||
const failed = { ...base, stale: true, warnings };
|
||||
const replies = [
|
||||
{ header: "ok", body: stale },
|
||||
{ header: "failed", body: failed },
|
||||
{ header: "failed", body: failed },
|
||||
{ header: "ok", body: failed },
|
||||
];
|
||||
const requests = [];
|
||||
let replyIndex = 0;
|
||||
const fakeFetch = async (url, options) => {
|
||||
requests.push({ url: String(url), options });
|
||||
const reply = replies[Math.min(replyIndex++, replies.length - 1)];
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: {
|
||||
get(name) {
|
||||
return name.toLowerCase() === "x-usage-tree-refresh" ? reply.header : null;
|
||||
},
|
||||
},
|
||||
json: async () => reply.body,
|
||||
};
|
||||
};
|
||||
|
||||
new Function(
|
||||
"globalThis", "document", "window", "location", "fetch",
|
||||
"setTimeout", "clearTimeout", "addEventListener",
|
||||
"AbortController", "AbortSignal",
|
||||
read("app.js"),
|
||||
)(
|
||||
runtime, document, window, location, fakeFetch,
|
||||
fakeSetTimeout, fakeClearTimeout, globalAddEventListener,
|
||||
FakeAbortController, FakeAbortSignal,
|
||||
);
|
||||
|
||||
await tick();
|
||||
const warning = elements.get("warning");
|
||||
const first = { hidden: warning.hidden, text: warning.textContent };
|
||||
elements.get("refresh").click();
|
||||
await tick();
|
||||
const afterFailure = { hidden: warning.hidden, text: warning.textContent };
|
||||
|
||||
const quiet = [...timers.entries()]
|
||||
.filter(([, timer]) => String(timer.fn).includes("quiet: true"))
|
||||
.sort((a, b) => b[0] - a[0])[0];
|
||||
assert.ok(quiet, "a stale answer schedules a quiet follow-up");
|
||||
quiet[1].fn();
|
||||
await tick();
|
||||
const whileStillFailed = { hidden: warning.hidden, text: warning.textContent };
|
||||
const recovery = [...timers.entries()]
|
||||
.filter(([, timer]) => String(timer.fn).includes("quiet: true"))
|
||||
.sort((a, b) => b[0] - a[0])[0];
|
||||
assert.ok(recovery, "a failed quiet answer schedules another retry");
|
||||
recovery[1].fn();
|
||||
await tick();
|
||||
const afterRecovery = { hidden: warning.hidden, text: warning.textContent };
|
||||
for (const fn of pagehide) fn();
|
||||
return { first, afterFailure, whileStillFailed, afterRecovery, requests, warnings: runtime.UsageI18n.get(lang) };
|
||||
}
|
||||
|
||||
test("an older disk cache does not warn, and a quiet recovery clears a real warning", async () => {
|
||||
const zh = await runRefreshFlow("zh");
|
||||
assert.equal(zh.first.hidden, true);
|
||||
assert.equal(zh.first.text, "");
|
||||
assert.equal(zh.afterFailure.hidden, false);
|
||||
assert.match(zh.afterFailure.text, /;刷新失败/);
|
||||
assert.doesNotMatch(zh.afterFailure.text, /。;/);
|
||||
assert.match(zh.whileStillFailed.text, /刷新失败/);
|
||||
assert.equal(zh.afterRecovery.hidden, false);
|
||||
assert.match(zh.afterRecovery.text, /这个周期还没有用量/);
|
||||
assert.match(zh.afterRecovery.text, /2 个账号的模型明细/);
|
||||
assert.doesNotMatch(zh.afterRecovery.text, /刷新失败/);
|
||||
assert.equal(zh.requests.length, 4);
|
||||
assert.match(zh.requests[1].url, /fresh=1/);
|
||||
assert.doesNotMatch(zh.requests[2].url, /fresh=1/);
|
||||
assert.doesNotMatch(zh.requests[3].url, /fresh=1/);
|
||||
|
||||
const en = await runRefreshFlow("en");
|
||||
assert.equal(en.first.hidden, true);
|
||||
assert.equal(en.first.text, "");
|
||||
assert.match(en.afterFailure.text, /Refresh failed/);
|
||||
assert.match(en.whileStillFailed.text, /Refresh failed/);
|
||||
assert.equal(en.afterRecovery.hidden, false);
|
||||
assert.match(en.afterRecovery.text, /No usage in this period yet/);
|
||||
assert.match(en.afterRecovery.text, /2 accounts are/);
|
||||
assert.doesNotMatch(en.afterRecovery.text, /Refresh failed/);
|
||||
});
|
||||
@@ -30,6 +30,17 @@ test("the page's service routes", { concurrency: false }, async (t) => {
|
||||
assert.match(htmlBody, /meta name="usage-tree-token"/);
|
||||
assert.match(htmlBody, /<main class="view">/);
|
||||
assert.match(htmlBody, /usage-tree-currency" content="usd"/);
|
||||
assert.match(htmlBody, /usage-tree-settings" content="0"/);
|
||||
assert.match(htmlBody, /<script src="bridge\.js">/);
|
||||
|
||||
const bridge = await fetch(`http://127.0.0.1:${info.port}/bridge.js`);
|
||||
assert.equal(bridge.status, 200);
|
||||
const bridgeBody = await bridge.text();
|
||||
assert.doesNotMatch(bridgeBody, /read: \(name, params\)|call\("read"/);
|
||||
assert.match(bridgeBody, /call\("hello"\)/);
|
||||
assert.match(bridgeBody, /onTheme\(fn\)/);
|
||||
assert.match(bridgeBody, /if \(parent === window\) return Promise\.resolve\(undefined\)/);
|
||||
assert.match(bridgeBody, /call\("hello"\)\.then\(\(hello = \{\}\) => \{/);
|
||||
|
||||
const configured = await fetch(
|
||||
`http://127.0.0.1:${info.port}/?lang=zh&theme=dark¤cy=cny&chineseUnits=1&usdCny=7.2`,
|
||||
@@ -39,6 +50,10 @@ test("the page's service routes", { concurrency: false }, async (t) => {
|
||||
assert.match(configuredBody, /usage-tree-currency" content="cny"/);
|
||||
assert.match(configuredBody, /usage-tree-chinese-units" content="true"/);
|
||||
assert.match(configuredBody, /usage-tree-usd-cny" content="7.2"/);
|
||||
assert.match(configuredBody, /usage-tree-settings" content="0"/);
|
||||
|
||||
const settingsEnabled = await fetch(`http://127.0.0.1:${info.port}/?settings=1`);
|
||||
assert.match(await settingsEnabled.text(), /usage-tree-settings" content="1"/);
|
||||
|
||||
const denied = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`);
|
||||
assert.equal(denied.status, 401);
|
||||
@@ -105,6 +120,100 @@ test("the page's service routes", { concurrency: false }, async (t) => {
|
||||
assert.equal(fresh.headers.get("x-usage-tree-cache"), "stale");
|
||||
assert.equal(body.stale, true);
|
||||
assert.equal(body.revision, 1);
|
||||
|
||||
// A quiet follow-up must still see the stale mark and retry. Previously
|
||||
// the failure was written to an object the cache had already replaced.
|
||||
const followUp = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, {
|
||||
headers: { "x-usage-tree-token": token },
|
||||
});
|
||||
const followUpBody = await followUp.json();
|
||||
assert.equal(followUp.headers.get("x-usage-tree-cache"), "stale");
|
||||
assert.equal(followUpBody.stale, true);
|
||||
assert.equal(followUp.headers.get("x-usage-tree-refresh"), "failed");
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
assert.ok(calls >= 3, "the next stale read starts another refresh");
|
||||
});
|
||||
|
||||
await t.test("an older disk cache is stale without being a failed refresh", async (t) => {
|
||||
let calls = 0;
|
||||
const info = await startServer({
|
||||
port: 0,
|
||||
load: async () => {
|
||||
calls += 1;
|
||||
return calls === 1
|
||||
? { ...data, cached: true, stale: true }
|
||||
: { ...data, revision: calls };
|
||||
},
|
||||
});
|
||||
t.after(async () => {
|
||||
await info.close();
|
||||
});
|
||||
|
||||
const html = await (await fetch(`http://127.0.0.1:${info.port}/`)).text();
|
||||
const token = html.match(/name="usage-tree-token" content="([^"]+)"/)?.[1];
|
||||
assert.ok(token);
|
||||
const headers = { "x-usage-tree-token": token };
|
||||
|
||||
const first = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, { headers });
|
||||
const firstBody = await first.json();
|
||||
assert.equal(first.headers.get("x-usage-tree-refresh"), "ok");
|
||||
assert.equal(firstBody.stale, true);
|
||||
assert.equal(firstBody.cached, true);
|
||||
|
||||
// The first stale read starts a real refresh behind the page. Once it
|
||||
// succeeds, the service stops reporting a failure and serves good data.
|
||||
await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, { headers });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const recovered = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, { headers });
|
||||
const recoveredBody = await recovered.json();
|
||||
assert.equal(recovered.headers.get("x-usage-tree-refresh"), "ok");
|
||||
assert.notEqual(recoveredBody.stale, true);
|
||||
assert.ok(calls >= 2);
|
||||
});
|
||||
|
||||
await t.test("a failed refresh stays failed until the loader really recovers", async (t) => {
|
||||
let calls = 0;
|
||||
const info = await startServer({
|
||||
port: 0,
|
||||
load: async (_period, options) => {
|
||||
calls += 1;
|
||||
if (options.fresh && calls <= 3) throw new Error("gateway down");
|
||||
return { ...data, revision: calls };
|
||||
},
|
||||
});
|
||||
t.after(async () => {
|
||||
await info.close();
|
||||
});
|
||||
|
||||
const html = await (await fetch(`http://127.0.0.1:${info.port}/`)).text();
|
||||
const token = html.match(/name="usage-tree-token" content="([^"]+)"/)?.[1];
|
||||
assert.ok(token);
|
||||
const headers = { "x-usage-tree-token": token };
|
||||
const tree = (query = "") => fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d${query}`, { headers });
|
||||
|
||||
const initial = await tree();
|
||||
await initial.json();
|
||||
assert.equal(initial.headers.get("x-usage-tree-refresh"), "ok");
|
||||
|
||||
const firstFailure = await tree("&fresh=1");
|
||||
const firstFailureBody = await firstFailure.json();
|
||||
assert.equal(firstFailure.headers.get("x-usage-tree-refresh"), "failed");
|
||||
assert.equal(firstFailureBody.stale, true);
|
||||
assert.equal(firstFailureBody.revision, 1);
|
||||
|
||||
// A follow-up while the gateway is still down must not accidentally
|
||||
// clear the failure, even though a new retry now owns the cache entry.
|
||||
const secondFailure = await tree("&fresh=1");
|
||||
const secondFailureBody = await secondFailure.json();
|
||||
assert.equal(secondFailure.headers.get("x-usage-tree-refresh"), "failed");
|
||||
assert.equal(secondFailureBody.stale, true);
|
||||
assert.equal(secondFailureBody.revision, 1);
|
||||
|
||||
const recovered = await tree("&fresh=1");
|
||||
const recoveredBody = await recovered.json();
|
||||
assert.equal(recovered.headers.get("x-usage-tree-refresh"), "ok");
|
||||
assert.notEqual(recoveredBody.stale, true);
|
||||
assert.equal(recoveredBody.revision, 4);
|
||||
});
|
||||
|
||||
await t.test("rejects a non-loopback host", async (t) => {
|
||||
|
||||
@@ -11,6 +11,8 @@ const usage = {
|
||||
output: 100,
|
||||
cache_read: 500,
|
||||
cache_write: 0,
|
||||
cache_unknown: 200,
|
||||
cache_unknown_calls: 1,
|
||||
reasoning: 10,
|
||||
cost: 0.5,
|
||||
unpriced: 2,
|
||||
@@ -26,6 +28,8 @@ const usage = {
|
||||
input: 800,
|
||||
output: 50,
|
||||
cache_read: 500,
|
||||
cache_unknown: 200,
|
||||
cache_unknown_calls: 1,
|
||||
cost: 0.5,
|
||||
unpriced: 0,
|
||||
},
|
||||
@@ -88,6 +92,8 @@ test("builds provider, account and model from the gateway's own totals", () => {
|
||||
assert.equal(data.summary.errors, 1);
|
||||
assert.equal(data.summary.tokens, 1100);
|
||||
assert.equal(data.summary.cache, 500);
|
||||
assert.equal(data.summary.cacheUnknown, 200);
|
||||
assert.equal(data.summary.cacheUnknownCalls, 1);
|
||||
assert.equal(data.summary.cost, 0.5);
|
||||
assert.equal(data.summary.unpriced, 2);
|
||||
assert.equal(data.summary.accounts, 2);
|
||||
@@ -100,6 +106,7 @@ test("builds provider, account and model from the gateway's own totals", () => {
|
||||
const alice = data.accounts.find((account) => account.account === "alice@example.com");
|
||||
assert.equal(alice.alias, "10月学生Plus");
|
||||
assert.equal(alice.calls, 3);
|
||||
assert.equal(alice.cacheUnknown, 200);
|
||||
assert.equal(alice.models.length, 1);
|
||||
assert.equal(alice.models[0].model, "gpt-a");
|
||||
assert.equal(alice.models[0].errors, 1);
|
||||
@@ -215,8 +222,30 @@ test("an empty gateway answer is an empty tree with a note", () => {
|
||||
assert.deepEqual(data.warnings, [{ code: "no-usage" }]);
|
||||
});
|
||||
|
||||
test("a failed per-account model read is reported without losing account totals", () => {
|
||||
const data = aggregateGatewayUsage(usage, requests, {
|
||||
period: "today",
|
||||
missingModelAccounts: 2,
|
||||
});
|
||||
assert.equal(data.summary.calls, 5);
|
||||
assert.equal(data.accounts.length, 2);
|
||||
assert.deepEqual(data.warnings, [{ code: "model-details", count: 2 }]);
|
||||
});
|
||||
|
||||
test("a read from before the three-level shape is not served as current", () => {
|
||||
const fields = {
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
};
|
||||
assert.equal(cacheUsable({ summary: {}, accounts: [{ id: "a" }] }), false);
|
||||
assert.equal(cacheUsable({ summary: {}, providers: [], accounts: [] }), true);
|
||||
assert.equal(cacheUsable({ summary: fields, providers: [], accounts: [] }), true);
|
||||
assert.equal(cacheUsable({ summary: {}, providers: [], accounts: [] }), false);
|
||||
assert.equal(cacheUsable({
|
||||
summary: fields,
|
||||
providers: [{ ...fields, accounts: [{ ...fields, models: [{ cacheRead: 0 }] }] }],
|
||||
accounts: [],
|
||||
}), false);
|
||||
assert.equal(cacheUsable(null), false);
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<meta name="usage-tree-currency" content="__USAGE_TREE_CURRENCY__">
|
||||
<meta name="usage-tree-usd-cny" content="__USAGE_TREE_USD_CNY__">
|
||||
<meta name="usage-tree-chinese-units" content="__USAGE_TREE_CHINESE_UNITS__">
|
||||
<meta name="usage-tree-settings" content="__USAGE_TREE_SETTINGS__">
|
||||
<title>__USAGE_TREE_TITLE__</title>
|
||||
<link rel="icon" href="icon.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
@@ -85,6 +86,7 @@
|
||||
</footer>
|
||||
</main>
|
||||
|
||||
<script src="bridge.js"></script>
|
||||
<script src="i18n.js"></script>
|
||||
<script src="view.js"></script>
|
||||
<script src="app.js"></script>
|
||||
|
||||
@@ -30,10 +30,18 @@
|
||||
const theme = meta("theme") || "light";
|
||||
let lang = metaLang();
|
||||
let currency = meta("currency") === "cny" ? "cny" : "usd";
|
||||
let usdCny = Number(meta("usd-cny")) || 0;
|
||||
let chineseUnits = meta("chinese-units") === "true";
|
||||
const rateMeta = meta("usd-cny");
|
||||
const unitsMeta = meta("chinese-units");
|
||||
let usdCny = rateMeta === "" ? 0 : Number(rateMeta) || 0;
|
||||
let chineseUnits = unitsMeta === "" ? false : unitsMeta === "true";
|
||||
V.setLang(lang);
|
||||
const settingsBridge = meta("settings") === "1";
|
||||
V.setChineseUnits(chineseUnits && lang === "zh");
|
||||
const REQUEST_TIMEOUT_MS = 30_000;
|
||||
const SERVICE_TIMEOUT_MS = REQUEST_TIMEOUT_MS + 1_000;
|
||||
let displaySettingsRequest = 0;
|
||||
let officialDisplay = false;
|
||||
let refreshFailed = false;
|
||||
const saved = {
|
||||
period: store.get("usage-tree.period") || "today",
|
||||
sort: store.get("usage-tree.sort") || "tokens",
|
||||
@@ -95,6 +103,20 @@
|
||||
// once, without a reload.
|
||||
function applyThemeEvent(data) {
|
||||
if (!data) return;
|
||||
const display = {
|
||||
...data,
|
||||
...(data.context && typeof data.context === "object" ? data.context : {}),
|
||||
};
|
||||
const hasOfficialDisplay =
|
||||
display.currency === "cny" ||
|
||||
display.currency === "usd" ||
|
||||
typeof display.chineseUnits === "boolean" ||
|
||||
(Number.isFinite(Number(display.usdCny)) && Number(display.usdCny) > 0) ||
|
||||
(Number.isFinite(Number(display.fx?.rate)) && Number(display.fx.rate) > 0);
|
||||
// Today's bridge sends language and theme only. If a future bridge also
|
||||
// sends Magpie's display preferences, those win over plugin options.
|
||||
if (hasOfficialDisplay) applyDisplay(display, "magpie");
|
||||
else if (typeof display.lang === "string") applyDisplay({ lang: display.lang });
|
||||
if (data.tokens && typeof data.tokens === "object") {
|
||||
for (const [key, value] of Object.entries(data.tokens)) {
|
||||
if (typeof value === "string") {
|
||||
@@ -105,7 +127,33 @@
|
||||
if (typeof data.dark === "boolean") {
|
||||
document.documentElement.dataset.theme = data.dark ? "dark" : "light";
|
||||
}
|
||||
if (typeof data.lang === "string") applyDisplay({ lang: data.lang });
|
||||
}
|
||||
|
||||
async function syncDisplaySettings(bridge = window.magpie) {
|
||||
if (!bridge?.options?.get) return;
|
||||
const requestId = ++displaySettingsRequest;
|
||||
try {
|
||||
const options = await bridge.options.get();
|
||||
if (requestId !== displaySettingsRequest) return;
|
||||
if (officialDisplay) return;
|
||||
// An absent option keeps the launcher's value; only a real option can
|
||||
// replace it. Opening the service directly has no bridge answer.
|
||||
if (!options || typeof options !== "object") return;
|
||||
const display = {};
|
||||
if (options.currency === "cny" || options.currency === "usd") display.currency = options.currency;
|
||||
if (typeof options.chineseUnits === "boolean") display.chineseUnits = options.chineseUnits;
|
||||
if (options.usdCny !== undefined && options.usdCny !== "" && options.usdCny !== null) {
|
||||
display.usdCny = options.usdCny;
|
||||
}
|
||||
applyDisplay(display, "options");
|
||||
} catch {
|
||||
// Keep the values the launcher supplied.
|
||||
}
|
||||
}
|
||||
|
||||
function paintSettings() {
|
||||
const root = document.documentElement;
|
||||
root.dataset.chineseUnits = (chineseUnits && lang === "zh") ? "on" : "off";
|
||||
}
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
@@ -114,15 +162,36 @@
|
||||
// Only the window that frames this page may change its language.
|
||||
if (event.source !== window.parent || event.source === window) return;
|
||||
applyThemeEvent(message.data);
|
||||
// The theme message carries the language and the window colours. This
|
||||
// page's own presentation options are read once from the launcher URL;
|
||||
// nothing is polled.
|
||||
// Magpie pushes a theme message after a Settings change. Re-read this
|
||||
// plugin's own options on the callback; there is still no timer.
|
||||
if (settingsBridge) void syncDisplaySettings(window.magpie);
|
||||
});
|
||||
|
||||
// Returning to the page is a visibility event: re-read plugin options once.
|
||||
window.magpie?.onVisibility?.((visible) => {
|
||||
if (visible && settingsBridge) void syncDisplaySettings(window.magpie);
|
||||
});
|
||||
|
||||
// What the window sends lands here: the page redraws in place, without a
|
||||
// reload.
|
||||
function applyDisplay(display) {
|
||||
function applyDisplay(display, source = "options") {
|
||||
if (!display) return false;
|
||||
const hasOfficialFields =
|
||||
display.currency === "cny" ||
|
||||
display.currency === "usd" ||
|
||||
typeof display.chineseUnits === "boolean" ||
|
||||
(Number.isFinite(Number(display.usdCny)) && Number(display.usdCny) > 0) ||
|
||||
(Number.isFinite(Number(display.fx?.rate)) && Number(display.fx.rate) > 0);
|
||||
if (source === "magpie" && (officialDisplay || hasOfficialFields)) {
|
||||
if (!officialDisplay) {
|
||||
currency = "usd";
|
||||
chineseUnits = false;
|
||||
usdCny = 0;
|
||||
officialDisplay = true;
|
||||
}
|
||||
} else if (officialDisplay && source !== "magpie") {
|
||||
return false;
|
||||
}
|
||||
let changed = false;
|
||||
|
||||
const wanted = String(display.lang || "").toLowerCase();
|
||||
@@ -138,20 +207,25 @@
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (typeof display.currency === "string") {
|
||||
const nextCurrency = display.currency === "cny" ? "cny" : "usd";
|
||||
if (display.currency === "cny" || display.currency === "usd") {
|
||||
const nextCurrency = display.currency;
|
||||
if (nextCurrency !== currency) {
|
||||
currency = nextCurrency;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (Number.isFinite(Number(display.usdCny))) {
|
||||
if (display.usdCny !== undefined && display.usdCny !== "" && display.usdCny !== null) {
|
||||
const nextRate = Number(display.usdCny);
|
||||
if (nextRate !== usdCny) {
|
||||
if (Number.isFinite(nextRate) && nextRate >= 0 && nextRate !== usdCny) {
|
||||
usdCny = nextRate;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
const fxRate = Number(display.fx?.rate);
|
||||
if (Number.isFinite(fxRate) && fxRate > 0 && fxRate !== usdCny) {
|
||||
usdCny = fxRate;
|
||||
changed = true;
|
||||
}
|
||||
if (typeof display.chineseUnits === "boolean") {
|
||||
const nextUnits = display.chineseUnits === true;
|
||||
if (nextUnits !== chineseUnits) {
|
||||
@@ -167,6 +241,7 @@
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
paintSettings();
|
||||
applyI18n();
|
||||
if (state.data) render();
|
||||
else applyTheme();
|
||||
@@ -176,6 +251,7 @@
|
||||
|
||||
applyI18n();
|
||||
applyTheme();
|
||||
paintSettings();
|
||||
buildSummarySkeleton();
|
||||
bind();
|
||||
load();
|
||||
@@ -287,6 +363,7 @@
|
||||
clearTimeout(state.spinTimer);
|
||||
clearTimeout(state.staleTimer);
|
||||
state.controller = new AbortController();
|
||||
const controller = state.controller;
|
||||
state.loading = true;
|
||||
state.error = "";
|
||||
const spinStarted = Date.now();
|
||||
@@ -296,7 +373,7 @@
|
||||
progress.hidden = false;
|
||||
progress.setAttribute("aria-hidden", "false");
|
||||
}
|
||||
warning.hidden = true;
|
||||
if (!options.quiet) clearRefreshWarning();
|
||||
if (!state.data) {
|
||||
stateCard.hidden = true;
|
||||
accounts.hidden = true;
|
||||
@@ -310,15 +387,18 @@
|
||||
headers: { "x-usage-tree-token": token },
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.any([
|
||||
state.controller.signal,
|
||||
AbortSignal.timeout(10000),
|
||||
controller.signal,
|
||||
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
]),
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(body.error || `HTTP ${res.status}`);
|
||||
if (requestId !== state.requestId || requestedPeriod !== state.period) return;
|
||||
if (!isCurrentLoad(requestId, requestedPeriod)) return;
|
||||
const serverFailed = res.headers.get("x-usage-tree-refresh") === "failed";
|
||||
const warningStateChanged = serverFailed !== refreshFailed;
|
||||
refreshFailed = serverFailed;
|
||||
const next = fingerprint(body);
|
||||
const changed = next !== state.fingerprint || !state.rendered;
|
||||
const changed = next !== state.fingerprint || !state.rendered || warningStateChanged;
|
||||
state.data = body;
|
||||
state.fingerprint = next;
|
||||
state.loadedAt = Date.now();
|
||||
@@ -345,26 +425,39 @@
|
||||
render();
|
||||
} else {
|
||||
renderFoot();
|
||||
renderWarnings(body.warnings || []);
|
||||
}
|
||||
} catch (error) {
|
||||
if (requestId !== state.requestId || error?.name === "AbortError") return;
|
||||
if (!isCurrentLoad(requestId, requestedPeriod) || error?.name === "AbortError") return;
|
||||
if (error?.name === "TimeoutError") {
|
||||
state.error = W.serviceTimeout;
|
||||
if (state.data?.period === requestedPeriod) {
|
||||
showRefreshWarning();
|
||||
renderFoot();
|
||||
return;
|
||||
}
|
||||
renderError();
|
||||
return;
|
||||
}
|
||||
state.error = `${error?.name || "Error"}: ${error?.message || W.readFailed}`;
|
||||
if (state.data?.period === requestedPeriod) {
|
||||
warning.hidden = false;
|
||||
warning.textContent = W.refreshFailed;
|
||||
showRefreshWarning();
|
||||
renderFoot();
|
||||
return;
|
||||
}
|
||||
renderError();
|
||||
} finally {
|
||||
if (requestId !== state.requestId) return;
|
||||
if (!isCurrentLoad(requestId, requestedPeriod)) {
|
||||
if (state.controller === controller) state.controller = null;
|
||||
return;
|
||||
}
|
||||
// A cached answer is over in tens of ms: hold the spin for a beat so
|
||||
// a press reads as a refresh. A slow read keeps it until it is done.
|
||||
const elapsed = Date.now() - spinStarted;
|
||||
const settle = () => {
|
||||
if (requestId !== state.requestId) return;
|
||||
if (!isCurrentLoad(requestId, requestedPeriod)) return;
|
||||
state.loading = false;
|
||||
state.controller = null;
|
||||
if (state.controller === controller) state.controller = null;
|
||||
refresh.classList.remove("busy");
|
||||
refresh.disabled = false;
|
||||
progress.hidden = true;
|
||||
@@ -380,8 +473,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (!state.data && state.loading) {
|
||||
// A newer request owns the loading UI even if an older request finishes
|
||||
// after the period has already changed.
|
||||
function isCurrentLoad(requestId, requestedPeriod) {
|
||||
return requestId === state.requestId && requestedPeriod === state.period;
|
||||
}
|
||||
|
||||
const serviceTimer = setTimeout(() => {
|
||||
if (!state.data && state.loading && !state.error) {
|
||||
clearTimeout(state.spinTimer);
|
||||
state.error = W.serviceTimeout;
|
||||
renderError();
|
||||
@@ -391,57 +490,50 @@
|
||||
progress.hidden = true;
|
||||
progress.setAttribute("aria-hidden", "true");
|
||||
}
|
||||
}, 10500);
|
||||
}, SERVICE_TIMEOUT_MS);
|
||||
addEventListener("pagehide", () => clearTimeout(serviceTimer), { once: true });
|
||||
|
||||
// What the page reads: if a read came back the same, nothing is redrawn.
|
||||
function fingerprint(data) {
|
||||
const summary = data?.summary || {};
|
||||
const cost = (value) => Number(value || 0).toFixed(6);
|
||||
const partsFor = (item, extra = []) => [
|
||||
item.calls,
|
||||
item.errors,
|
||||
item.unpriced,
|
||||
item.input,
|
||||
item.output,
|
||||
item.tokens,
|
||||
item.cache,
|
||||
item.allTokens,
|
||||
item.cacheRead,
|
||||
item.cacheWrite,
|
||||
item.cacheUnknown,
|
||||
item.cacheUnknownCalls,
|
||||
cost(item.cost),
|
||||
...extra,
|
||||
];
|
||||
const parts = [
|
||||
data?.period,
|
||||
data?.stale === true,
|
||||
JSON.stringify(data?.warnings || []),
|
||||
summary.accounts,
|
||||
summary.providers,
|
||||
summary.models,
|
||||
summary.calls,
|
||||
summary.errors,
|
||||
summary.unpriced,
|
||||
summary.input,
|
||||
summary.output,
|
||||
summary.tokens,
|
||||
summary.cache,
|
||||
summary.allTokens,
|
||||
cost(summary.cost),
|
||||
...partsFor(summary),
|
||||
];
|
||||
for (const provider of data?.providers || []) {
|
||||
parts.push(
|
||||
provider.id,
|
||||
provider.providerName,
|
||||
provider.calls,
|
||||
provider.errors,
|
||||
provider.unpriced,
|
||||
provider.input,
|
||||
provider.output,
|
||||
provider.tokens,
|
||||
provider.cache,
|
||||
provider.allTokens,
|
||||
cost(provider.cost),
|
||||
);
|
||||
const providers = Array.isArray(data?.providers) && data.providers.length
|
||||
? data.providers
|
||||
: Array.isArray(data?.accounts) ? [{ accounts: data.accounts }] : [];
|
||||
for (const provider of providers) {
|
||||
parts.push(provider.id, provider.providerName, ...partsFor(provider.id ? provider : {}));
|
||||
for (const account of provider.accounts || []) {
|
||||
parts.push(
|
||||
account.id,
|
||||
account.account,
|
||||
account.alias,
|
||||
account.providerName,
|
||||
account.calls,
|
||||
account.errors,
|
||||
account.unpriced,
|
||||
account.input,
|
||||
account.output,
|
||||
account.tokens,
|
||||
account.cache,
|
||||
account.allTokens,
|
||||
cost(account.cost),
|
||||
account.lastAt,
|
||||
...partsFor(account, [account.lastAt]),
|
||||
);
|
||||
for (const model of account.models || []) {
|
||||
parts.push(
|
||||
@@ -449,16 +541,7 @@
|
||||
model.model,
|
||||
model.provider,
|
||||
model.providerName,
|
||||
model.calls,
|
||||
model.errors,
|
||||
model.unpriced,
|
||||
model.input,
|
||||
model.output,
|
||||
model.tokens,
|
||||
model.cache,
|
||||
model.allTokens,
|
||||
cost(model.cost),
|
||||
JSON.stringify(model.hostNotes || []),
|
||||
...partsFor(model, [JSON.stringify(model.hostNotes || [])]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -526,19 +609,40 @@
|
||||
}
|
||||
|
||||
function renderWarnings(warnings) {
|
||||
if (!warnings.length) {
|
||||
warning.hidden = true;
|
||||
return;
|
||||
}
|
||||
warning.hidden = false;
|
||||
warning.textContent = warnings
|
||||
const list = Array.isArray(warnings) ? warnings : [];
|
||||
const parts = list
|
||||
.map((item) => {
|
||||
if (typeof item === "string") return item;
|
||||
if (item.code === "no-usage") return W.noUsage;
|
||||
if (item.code === "model-details") return W.modelDetails(Math.max(1, Number(item.count) || 1));
|
||||
return "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
.filter(Boolean);
|
||||
// Chinese warnings are full sentences; join them with semicolons rather
|
||||
// than leaving "。;" or a bare space before the refresh note.
|
||||
const details = lang === "zh"
|
||||
? parts.map((item) => item.replace(/[\u3002\uFF1B]\s*$/u, "").trim()).filter(Boolean).join("\uFF1B")
|
||||
: parts.join(" ");
|
||||
if (!details) {
|
||||
warning.hidden = !refreshFailed;
|
||||
warning.textContent = refreshFailed ? W.refreshFailed : "";
|
||||
return;
|
||||
}
|
||||
warning.hidden = false;
|
||||
warning.textContent = refreshFailed
|
||||
? `${details}${lang === "zh" ? "\uFF1B" : " "}${W.refreshFailed}`
|
||||
: lang === "zh" ? `${details}\u3002` : details;
|
||||
}
|
||||
|
||||
function showRefreshWarning() {
|
||||
refreshFailed = true;
|
||||
warning.hidden = false;
|
||||
renderWarnings(state.data?.warnings || []);
|
||||
}
|
||||
|
||||
function clearRefreshWarning() {
|
||||
refreshFailed = false;
|
||||
warning.hidden = true;
|
||||
}
|
||||
|
||||
function renderError() {
|
||||
@@ -591,6 +695,10 @@
|
||||
tokens: 0,
|
||||
cache: 0,
|
||||
allTokens: 0,
|
||||
cacheRead: 0,
|
||||
cacheWrite: 0,
|
||||
cacheUnknown: 0,
|
||||
cacheUnknownCalls: 0,
|
||||
cost: 0,
|
||||
errors: 0,
|
||||
unpriced: 0,
|
||||
@@ -601,6 +709,10 @@
|
||||
provider.calls += account.calls || 0;
|
||||
provider.tokens += account.tokens || 0;
|
||||
provider.cache += account.cache || 0;
|
||||
provider.cacheRead += account.cacheRead || 0;
|
||||
provider.cacheWrite += account.cacheWrite || 0;
|
||||
provider.cacheUnknown += account.cacheUnknown || 0;
|
||||
provider.cacheUnknownCalls += account.cacheUnknownCalls || 0;
|
||||
provider.allTokens +=
|
||||
Number(account.allTokens) || (Number(account.tokens) || 0) + (Number(account.cache) || 0);
|
||||
provider.cost += account.cost || 0;
|
||||
@@ -824,7 +936,7 @@
|
||||
);
|
||||
const share = shareCell(model, totalForSort(account.models), account.models);
|
||||
const split = el("div", "model-split",
|
||||
`${W.input} ${compact(model.input)} · ${W.output} ${compact(model.output)} · ${W.cache} ${compact(model.cache)}`);
|
||||
`${W.input} ${compact(model.input)} · ${W.output} ${compact(model.output)} · ${W.cache} ${compact(model.cache)}${V.cacheHitSuffix(model, lang)}`);
|
||||
who.append(split);
|
||||
|
||||
const cost = metric(
|
||||
|
||||
@@ -50,6 +50,8 @@
|
||||
input: "入",
|
||||
output: "出",
|
||||
cache: "缓存",
|
||||
cacheHit: "缓存命中率",
|
||||
cacheUnknown: (calls) => `${calls} 次未统计缓存`,
|
||||
share: { tokens: "Token 占比", cost: "费用占比", calls: "调用占比", name: "Token 占比" },
|
||||
unpricedOnly: "未定价",
|
||||
unpricedCalls: (n) => `${n} 次未定价`,
|
||||
@@ -66,7 +68,8 @@
|
||||
providerModels: (p, m) => `${p} 个供应商 · ${m} 个模型`,
|
||||
hostNotes: (items) => `含 ${items}`,
|
||||
noUsage: "这个周期还没有用量:Magpie 网关记录第一次调用后会显示在这里。",
|
||||
serviceTimeout: "数据请求超过 10 秒。请检查 Magpie 网关是否可访问。",
|
||||
modelDetails: (count) => `${count} 个账号的模型明细暂时无法读取,账号汇总仍完整。`,
|
||||
serviceTimeout: "数据请求超过 30 秒。请检查 Magpie 网关是否可访问。",
|
||||
localService: (port) => `本地用量服务没有在运行(127.0.0.1:${port})`,
|
||||
},
|
||||
en: {
|
||||
@@ -119,6 +122,8 @@
|
||||
input: "In",
|
||||
output: "Out",
|
||||
cache: "Cache",
|
||||
cacheHit: "Cache hit",
|
||||
cacheUnknown: (calls) => `${calls} cache-uncounted call${calls === 1 ? "" : "s"}`,
|
||||
share: { tokens: "Token share", cost: "Cost share", calls: "Call share", name: "Token share" },
|
||||
unpricedOnly: "Not priced",
|
||||
unpricedCalls: (n) => `${n} unpriced`,
|
||||
@@ -137,7 +142,8 @@
|
||||
`${p} ${p === 1 ? "provider" : "providers"} · ${m} ${m === 1 ? "model" : "models"}`,
|
||||
hostNotes: (items) => `Includes ${items}`,
|
||||
noUsage: "No usage in this period yet: Magpie shows it after the gateway records its first call.",
|
||||
serviceTimeout: "The data request took more than 10 seconds. Check the Magpie gateway.",
|
||||
modelDetails: (count) => `Model details for ${count} ${count === 1 ? "account is" : "accounts are"} temporarily unavailable; account totals are complete.`,
|
||||
serviceTimeout: "The data request took more than 30 seconds. Check the Magpie gateway.",
|
||||
localService: (port) => `The local usage service is not running (127.0.0.1:${port})`,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -343,8 +343,10 @@ input, select {
|
||||
margin-top: 3px;
|
||||
color: var(--magpie-muted);
|
||||
font-size: 11px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
/* The hit rate is part of this sentence, not an optional tail. */
|
||||
overflow-wrap: anywhere;
|
||||
text-overflow: clip;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.summary-card.loading {
|
||||
@@ -713,8 +715,10 @@ input, select {
|
||||
overflow: hidden;
|
||||
color: var(--magpie-faint);
|
||||
font-size: 10px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
overflow-wrap: anywhere;
|
||||
text-overflow: clip;
|
||||
white-space: normal;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.bar {
|
||||
@@ -923,7 +927,9 @@ input, select {
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
/* The fixed columns need about 680px. Switch to the compact tree before
|
||||
the expanding model rows can push their values out of the viewport. */
|
||||
@media (max-width: 700px) {
|
||||
.cols {
|
||||
grid-template-columns: minmax(0, 1fr) 48px 82px 18px;
|
||||
gap: 8px;
|
||||
@@ -1012,11 +1018,15 @@ input, select {
|
||||
}
|
||||
|
||||
.model-row .model-provider,
|
||||
.model-row .model-split,
|
||||
.model-row .metric-detail {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.model-row .model-split {
|
||||
display: block;
|
||||
padding-bottom: 2px;
|
||||
}
|
||||
|
||||
/* A 420 px tile is too narrow for one line of "In ... · Out ... ·
|
||||
Cache ...". Wrap it instead of cutting the last value off. */
|
||||
.summary-sub {
|
||||
|
||||
@@ -36,6 +36,20 @@
|
||||
return `${n.toFixed(2)}%`;
|
||||
}
|
||||
|
||||
// Match Magpie's own hitPct: a rounded 0% or 100% is never shown for a
|
||||
// rate that is merely close to either end.
|
||||
function hitPercent(value) {
|
||||
const h = Math.max(0, Math.min(1, Number(value) || 0));
|
||||
let digits = 0;
|
||||
let shown = (100 * h).toFixed(digits);
|
||||
while (digits < 2 && h > 0 && h < 1 && (+shown >= 100 || +shown <= 0)) {
|
||||
shown = (100 * h).toFixed(++digits);
|
||||
}
|
||||
if (h < 1 && +shown >= 100) shown = "99.99";
|
||||
if (h > 0 && +shown <= 0) shown = "0.01";
|
||||
return `${shown}%`;
|
||||
}
|
||||
|
||||
// errorRate is errors of the calls that could have failed, so a row with
|
||||
// no calls reads as no rate rather than as 0%.
|
||||
function errorRate(errors, calls) {
|
||||
@@ -45,6 +59,35 @@
|
||||
return percent(bad / total);
|
||||
}
|
||||
|
||||
// Magpie's own cache hit rate: cache reads over the counted prompt, with
|
||||
// vendor calls that report no cache left out of the denominator.
|
||||
function cacheHitRate(item) {
|
||||
const input = Math.max(0, Number(item?.input) || 0);
|
||||
const read = Math.max(0, Number(item?.cacheRead) || 0);
|
||||
const write = Math.max(0, Number(item?.cacheWrite) || 0);
|
||||
const unknown = Math.max(0, Number(item?.cacheUnknown) || 0);
|
||||
const prompt = input + read + write - unknown;
|
||||
if (!read || prompt <= 0) return null;
|
||||
return Math.min(1, read / prompt);
|
||||
}
|
||||
|
||||
function cacheHitText(item, lang) {
|
||||
const w = text(lang);
|
||||
const rate = cacheHitRate(item);
|
||||
const unknownCalls = Math.max(0, Number(item?.cacheUnknownCalls) || 0);
|
||||
const texts = [];
|
||||
// A row can mix providers: count the hit rate only where cache reads are
|
||||
// known, and still say how many calls were left out of that denominator.
|
||||
if (rate !== null) texts.push(`${w.cacheHit} ${hitPercent(rate)}`);
|
||||
if (unknownCalls > 0) texts.push(w.cacheUnknown(Math.round(unknownCalls)));
|
||||
return texts.join(" · ");
|
||||
}
|
||||
|
||||
function cacheHitSuffix(item, lang) {
|
||||
const value = cacheHitText(item, lang);
|
||||
return value ? ` · ${value}` : "";
|
||||
}
|
||||
|
||||
function has(value, query) {
|
||||
return String(value || "").toLowerCase().includes(query);
|
||||
}
|
||||
@@ -161,7 +204,7 @@
|
||||
key: "tokens",
|
||||
label: tokenLabel,
|
||||
value: count(tokenTotal(summary, includeCache)),
|
||||
sub: `${w.input} ${count(summary.input)} · ${w.output} ${count(summary.output)} · ${w.cache} ${count(summary.cache)}`,
|
||||
sub: `${w.input} ${count(summary.input)} · ${w.output} ${count(summary.output)} · ${w.cache} ${count(summary.cache)}${cacheHitSuffix(summary, lang)}`,
|
||||
},
|
||||
{
|
||||
key: "cost",
|
||||
@@ -227,7 +270,11 @@
|
||||
text,
|
||||
count,
|
||||
percent,
|
||||
hitPercent,
|
||||
errorRate,
|
||||
cacheHitRate,
|
||||
cacheHitText,
|
||||
cacheHitSuffix,
|
||||
accountSelfMatches,
|
||||
modelMatches,
|
||||
accountMatches,
|
||||
|
||||
Reference in New Issue
Block a user