page-usage-tree 0.1.0: usage as provider → account → model (CHENZUDE, #575)

New page plugin @magpie-community/page-usage-tree 0.1.0 by CHENZUDE: magpie's usage as a provider -> account -> model tree, served by a small server that reads the gateway's /v1/magpie/usage and /usage/requests.

The last round (f9e0907) gives the model row's calls cell the calls-cell class, so CALLS values sit under their right-aligned header, adds a test for it, and comments why the server's retry budget is 16 x 100ms.

What was run at f9e09079 (mote, macOS, sandbox HOME):
- In the package: node --test 50 pass; bun test 47 tests, 0 fail.
- f9e09079 merged onto main 8765cf8f: bun scripts/check.mjs ok; whole-repo bun test 6149 pass, 20 skip, 0 fail.
- Playwright against a fake gateway: CALLS header and value right edges 616/616 (1280px), 423/423 (900), 341/341 (760, 621) in Chromium and WebKit. Chromium 1280-620px, WebKit 900/760, both engines at 420px in en and zh: no clipped cell, no sideways scroll, no <select>, no page errors.
- Broken by hand: the old `model.errors ? "bad" : ""` puts values at 544 and 273 and turns "model calls sit under the right-aligned calls header" red (27 pass, 1 fail).

Not tried: a real magpie with real accounts, the desktop app, Windows and Linux.
This commit is contained in:
CHENZUDE
2026-11-05 17:11:25 +08:00
committed by GitHub
parent 29a36b1ecf
commit 808f7a184d
29 changed files with 5403 additions and 0 deletions
+1
View File
@@ -168,6 +168,7 @@ These add a page to magpie's window, in the app and in `magpie web`, under Plugi
| [powercontext](packages/powercontext) | Connection settings for an independently deployed PowerContext service | None |
| [nowledge-mem](packages/nowledge-mem) | Connection settings, recall and capture switches, a real connection test, and the scope of what is sent | None |
| [agent-office](packages/agent-office) | What are my agents doing: a real WebGL 3D office with six scenes, an isometric/2D office, grouped workbench, Today usage and recent conversations | no `magpie.read`; its host part reads local session files of Claude Code, Codex, Copilot CLI, Kimi Code, dsh, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build, including prompts, replies and tool commands (`text:false` keeps statuses and tool names only) |
| [page-usage-tree](packages/page-usage-tree) | Account usage: usage as provider -> account -> model, each level expandable, with per-account calls, errors and cost; adds the account layer Usage glance's `usage:summary` does not contain | none (its local service calls Magpie's local usage API) |
| [fingerprint](packages/fingerprint) | Numeric response fingerprints to investigate suspected model substitution across providers, with shared challenges, candidate rankings, local evidence and JSON export | none (its local service calls magpie’s gateway; sampling uses provider quota) |
| [chat](packages/chat) | Chat with magpie's models, your MCP servers, instructions and skills, by Magic_zero ([Magiczerowxy](https://github.com/Magiczerowxy)). Has a host part: a local service the page goes to | none (its service calls magpie's gateway) |
| [window-warmup](packages/window-warmup) | Window warmup: send one fixed short message ("hi", max_tokens 16) to a provider, account and model you pick, right after its quota window resets, daily at set times or every few hours, so the next subscription window opens early, by [YangHonghang](https://github.com/YangHonghang). Has a host part: a local service on 127.0.0.1 the page goes to | none; its service calls magpie's gateway and reads magpie's providers.json (keys only as sha256 fingerprints, plus key names and account models) and model cache. Each send uses the chosen account's quota |
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 magpie-usage-tree contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+109
View File
@@ -0,0 +1,109 @@
## 中文说明
在 Magpie 窗口中按 **供应商 -> 账号 -> 模型** 查看用量,逐级展开调用、错误、
Token、缓存和费用。它补充「用量速览」没有的账号层:数据由插件自己的本地服务
向 Magpie 网关查询,页面不直接读取 Magpie 的配置文件。
# @magpie-community/page-usage-tree
## English
A page in Magpie's window that shows usage as a three-level tree:
**provider -> account -> model**. Each level expands into the next, with
calls, errors, tokens, cache and cost at every level.
Usage Glance (`@magpie-community/page-usage`) shows totals and per-model usage
from `usage:summary`. This page adds the provider -> account -> model tree,
including calls, errors and cost for each account. `usage:summary` deliberately
contains no per-account data, so this page asks Magpie's local gateway for the
usage it already counted.
```sh
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'`.
- `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.
- `index.mjs` is the OpenCode v1 host part. The service runs inside Magpie's
plugin host, so it stops when Magpie stops the plugin.
- `magpie.page.service` lets the same page work through `magpie web`.
- `lib/gateway.mjs` asks the gateway for `GET /v1/magpie/usage?period=...` and
`GET /v1/magpie/usage/requests?period=...&account=...`. The gateway applies
Magpie's own accounting and pricing before this page groups the answer.
- No CLI is started, no `providers.json`, `settings.json`, `fxrate.json` or
`usage.jsonl` is read, and there is no ledger fallback.
- Each period's aggregate is cached under
`~/.cache/magpie/usage-tree/<period>.json`. A page shows the last read at
once and the service reads again behind it. Refresh (`fresh=1`) reads past
the cache. The page opens on today.
- Calls and errors are Magpie's: a try handed on to another account is not a
call of its own, and API-key calls are a clearly marked group, not an
account. Session-file rows are included because the gateway counted them.
- The page speaks Chinese and English. Every other language falls back to
English, and the launcher follows the window's language too.
## 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.
## Token measure
`Tokens include cache` is on by default. It controls whether cache reads and
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.
## Security
- Listens on `127.0.0.1` only.
- Uses a random token for every `/api/tree` and `/api/settings` request.
- Checks `Host` and `Origin`; the local sandbox's opaque origin is allowed for
the page API. CORS preflight is answered for both page APIs.
- Reads nothing from Magpie's configuration files. It only calls the local
gateway.
- Aggregation stays local; no data is uploaded.
- If another copy of this plugin owns the port, `/healthz` says which version
it is. The same build is reused. A different build, or another service, is
reported as an occupied port and is never killed: the listener may be the
plugin host that serves every plugin.
## Options
```json
{
"port": 3494,
"currency": "usd",
"chineseUnits": false,
"usdCny": 0
}
```
`currency: "cny"` also needs `usdCny` for a meaningful conversion. Without a
rate the page keeps showing USD rather than inventing one.
## Run and test
```sh
node serve.mjs --port 3494
node --test --test-force-exit test/*.test.mjs
```
`test/parity.test.mjs` compares the gateway aggregation with
`magpie usage 7d` when a CLI and gateway are available. API-key groups are
excluded from the account-count comparison because Magpie's accounts table
does not list them.
`test/lifecycle.test.mjs` checks that the same build reuses a running service,
that another build is reported and left running, and that a host on its way
out releases the port.
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" fill="none">
<rect width="128" height="128" rx="28" fill="#3a3f4b"/>
<g stroke="#e9e7f2" stroke-width="9.6" stroke-linecap="round" stroke-linejoin="round">
<rect x="42.4" y="13.6" width="43.2" height="26.4" rx="10.4"/>
<path d="M64 40v16"/>
<path d="M30.4 82.4V72.8a10.4 10.4 0 0 1 10.4-10.4h46.4a10.4 10.4 0 0 1 10.4 10.4v9.6"/>
<rect x="14.4" y="82.4" width="30.4" height="22.4" rx="9.6"/>
<rect x="48.8" y="82.4" width="30.4" height="22.4" rx="9.6"/>
<rect x="83.2" y="82.4" width="30.4" height="22.4" rx="9.6"/>
<path d="M18.4 114.4h91.2"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 678 B

+25
View File
@@ -0,0 +1,25 @@
// The host part of the plugin: magpie's Bun host loads it and asks it for
// the page's service. The service runs inside that host, so it stops when
// magpie stops the plugin.
import { startServer } from "./lib/server.mjs";
let started = null;
export default {
id: "magpie-usage-tree",
server: async (_input, options) => {
if (!started) {
started = startServer({
port: Number(options?.port) || 3494,
currency: options?.currency,
chineseUnits: options?.chineseUnits,
usdCny: options?.usdCny,
}).catch((error) => {
started = null;
throw error;
});
}
await started;
return {};
},
};
+171
View File
@@ -0,0 +1,171 @@
import { randomUUID } from "node:crypto";
import {
chmodSync,
mkdirSync,
readFileSync,
renameSync,
unlinkSync,
writeFileSync,
} from "node:fs";
import { homedir } from "node:os";
import { dirname, isAbsolute, join } from "node:path";
import { accountKey, aggregateGatewayUsage, PERIODS } from "./usage.mjs";
import {
gatewayAccountRequests,
gatewayUsage,
} from "./gateway.mjs";
export function cacheDir() {
if (process.env.MAGPIE_CACHE_DIR) return process.env.MAGPIE_CACHE_DIR;
if (isAbsolute(process.env.XDG_CACHE_HOME || "")) {
return join(process.env.XDG_CACHE_HOME, "magpie");
}
return join(homedir(), ".cache", "magpie");
}
// The page takes only what the gateway can tell it. Currency and number
// units are presentation choices passed by the launcher from this page's
// options; the gateway's costs are USD, which is magpie's default.
export function displaySettings(overrides = {}) {
return {
currency: overrides.currency === "cny" ? "cny" : "usd",
chineseUnits: overrides.chineseUnits === true,
lang: typeof overrides.lang === "string" && overrides.lang ? overrides.lang : "en",
usdCny: Number.isFinite(Number(overrides.usdCny)) && Number(overrides.usdCny) > 0
? Number(overrides.usdCny)
: 0,
theme: overrides.theme === "dark" || overrides.theme === "light" ? overrides.theme : "",
};
}
// Cost comes from the gateway in USD. The page only converts it for display,
// using the options Magpie's page bridge hands to the launcher. No settings
// or exchange-rate file is read here.
function normalizePeriod(period) {
return PERIODS.has(period) ? period : "today";
}
function cacheFile(period) {
return join(cacheDir(), "usage-tree", `${period}.json`);
}
// 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;
export function cacheUsable(data) {
return Boolean(data && Array.isArray(data.providers) && Array.isArray(data.accounts));
}
function readCached(period) {
try {
const raw = JSON.parse(readFileSync(cacheFile(period), "utf8"));
if (!raw?.data || raw.v !== CACHE_VERSION || !cacheUsable(raw.data)) return null;
return { data: raw.data, at: Number(raw.at) || 0 };
} catch {
return null;
}
}
function writeCached(period, data) {
let temporary = "";
try {
const file = cacheFile(period);
const directory = dirname(file);
mkdirSync(directory, { recursive: true, mode: 0o700 });
try {
chmodSync(directory, 0o700);
} catch {
// Windows ignores POSIX modes; the write itself is still useful.
}
const { stale, cached, ...keep } = data;
temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
writeFileSync(
temporary,
JSON.stringify({ v: CACHE_VERSION, at: Date.now(), data: keep }),
{ encoding: "utf8", mode: 0o600 },
);
renameSync(temporary, file);
} catch {
// A cache that cannot be written only costs the next read its wait.
} finally {
if (temporary) try { unlinkSync(temporary); } catch {}
}
}
// magpie's requests API can narrow by provider as well as account. A
// subscription id is unique in practice, but passing both keeps an API-key
// group from borrowing another provider's models.
async function requestsForAccounts(usage, period, options) {
const out = {};
const accounts = Array.isArray(usage?.accounts) ? usage.accounts : [];
await Promise.all(
accounts.map(async (item) => {
const account = String(item?.account || "");
if (!account) return;
const provider = String(item?.provider || "");
const key = accountKey(provider, account);
try {
out[key] = await gatewayAccountRequests(period, account, provider, options);
} catch {
// The account totals still come from the usage answer; only its
// model rows are missing.
out[key] = null;
}
}),
);
return out;
}
async function readGateway(period, options) {
const usage = await gatewayUsage(period, options);
// The usage answer carries the model table already. Only accounts whose
// models it cannot place need their own requests read; on a large ledger
// 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
? 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 });
}
const refreshing = new Set();
export async function loadUsageData(period, options = {}) {
const wanted = normalizePeriod(period);
if (!options.fresh) {
const hit = readCached(wanted);
if (hit) {
const stale = Date.now() - hit.at >= 25_000;
if (stale) void refreshBehind(wanted, options);
return { ...hit.data, cached: true, stale };
}
}
return refresh(wanted, options);
}
function refreshBehind(period, options) {
if (refreshing.has(period)) return;
refreshing.add(period);
refresh(period, { ...options, fresh: true })
.catch(() => {})
.finally(() => refreshing.delete(period));
}
async function refresh(period, options = {}) {
const result = await readGateway(period, options);
result.source = "Magpie gateway usage";
writeCached(period, result);
return result;
}
export { PERIODS };
+148
View File
@@ -0,0 +1,148 @@
// The gateway answers this page's data through magpie's own usage API.
// Nothing here reads magpie's files: MAGPIE_ADDR is what the plugin host
// gives its plugins, and the gateway is the service that counted the calls.
import http from "node:http";
import https from "node:https";
const DEFAULT_GATEWAY = "http://127.0.0.1:3425";
function normalizeGateway(value) {
const text = String(value || "").trim().replace(/\/+$/, "");
return /^https?:\/\//i.test(text) ? text : "";
}
export function gatewayCandidates(options = {}) {
const out = [];
const push = (value) => {
const text = normalizeGateway(value);
if (text && !out.includes(text)) out.push(text);
};
push(options.gateway);
push(process.env.MAGPIE_USAGE_TREE_GATEWAY);
push(process.env.MAGPIE_GATEWAY);
const addr = process.env.MAGPIE_ADDR;
if (addr) {
const loopback = String(addr).replace(/^(0\.0\.0\.0|\[::\]):/, "127.0.0.1:");
if (/^[\w.-]+:\d+$/.test(loopback)) push(`http://${loopback}`);
}
push(DEFAULT_GATEWAY);
return out;
}
let picked = { at: 0, url: "" };
export function resetGatewayCache() {
picked = { at: 0, url: "" };
}
function gatewayHeaders() {
const key = String(process.env.MAGPIE_API_KEY || process.env.MAGPIE_GATEWAY_KEY || "").trim();
return key ? { Authorization: `Bearer ${key}` } : {};
}
export async function resolveGateway(options = {}) {
// An explicit gateway belongs to the caller and is never replaced by a
// remembered one. Tests use this, and so does a manual serve.mjs run.
if (options.gateway) {
const explicit = normalizeGateway(options.gateway);
if (!explicit) throw new Error("invalid Magpie gateway URL");
return explicit;
}
if (picked.url && Date.now() - picked.at < 60_000) return picked.url;
for (const url of gatewayCandidates(options)) {
try {
const res = await fetch(`${url}/v1/magpie/usage?period=today`, {
headers: gatewayHeaders(),
signal: AbortSignal.timeout(2500),
});
if (res.ok) {
await res.body?.cancel().catch(() => {});
picked = { at: Date.now(), url };
return url;
}
await res.body?.cancel().catch(() => {});
} catch {
// Try the next candidate.
}
}
return gatewayCandidates(options)[0] || DEFAULT_GATEWAY;
}
function getJSON(url, timeout = 10_000) {
return new Promise((resolve, reject) => {
let request;
try {
const target = new URL(url);
const client = target.protocol === "https:" ? https : http;
request = client.get(
target,
{
agent: false,
headers: {
...gatewayHeaders(),
Accept: "application/json",
"Accept-Encoding": "identity",
Connection: "close",
},
},
(res) => {
const chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on("error", reject);
res.on("end", () => {
const raw = Buffer.concat(chunks).toString("utf8");
let body = null;
try {
body = JSON.parse(raw);
} catch {
// Keep body null so a failed response still reports its HTTP status.
}
const status = Number(res.statusCode) || 0;
if (status < 200 || status >= 300) {
reject(new Error(body?.error || `Magpie gateway returned HTTP ${status}`));
return;
}
if (!body || typeof body !== "object" || Array.isArray(body)) {
reject(new Error("Magpie gateway returned an invalid JSON object"));
return;
}
resolve(body);
});
},
);
request.setTimeout(timeout, () => {
request.destroy(new Error("Magpie gateway request timed out"));
});
request.on("error", reject);
} catch (error) {
reject(error);
}
});
}
function query(params) {
const out = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value != null && value !== "") out.set(key, String(value));
}
return out.toString();
}
export async function gatewayUsage(period, options = {}) {
const base = await resolveGateway(options);
return getJSON(`${base}/v1/magpie/usage?${query({ period })}`, options.timeout);
}
export async function gatewayRequests(period, options = {}) {
const base = await resolveGateway(options);
return getJSON(`${base}/v1/magpie/usage/requests?${query({ period })}`, options.timeout);
}
export async function gatewayAccountRequests(period, account, provider = "", options = {}) {
const base = await resolveGateway(options);
return getJSON(
`${base}/v1/magpie/usage/requests?${query({ period, account, provider })}`,
options.timeout,
);
}
+482
View File
@@ -0,0 +1,482 @@
import { createServer } from "node:http";
import { createHash, randomBytes } from "node:crypto";
import { readFile } from "node:fs/promises";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { displaySettings, loadUsageData } from "./data.mjs";
import { PERIODS } from "./usage.mjs";
const UI_DIR = fileURLToPath(new URL("../ui/", import.meta.url));
const CACHE_MS = 25_000;
export const PLUGIN_NAME = "magpie-usage-tree";
// The build's own version, so an older service on the port is told apart
// from this one.
export function version() {
try {
const raw = JSON.parse(
readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"),
);
return typeof raw.version === "string" ? raw.version : "0";
} catch {
return "0";
}
}
let cachedBuild = "";
export const BUILD_FILES = Object.freeze([
"server.mjs",
"data.mjs",
"gateway.mjs",
"usage.mjs",
"../index.mjs",
"../serve.mjs",
"../package.json",
"../page/index.html",
"../page/boot.js",
"../page/icon.svg",
"../ui/app.html",
"../ui/app.js",
"../ui/view.js",
"../ui/i18n.js",
"../ui/style.css",
]);
// A version alone cannot tell a rebuilt local plugin from the code already
// loaded in the host. Hash every runtime asset as well, so a same-version
// but changed build is never mistaken for the running one.
export function buildId() {
if (cachedBuild) return cachedBuild;
try {
const base = new URL("./", import.meta.url);
const hash = createHash("sha256");
for (const name of BUILD_FILES) {
hash.update(name);
hash.update("\0");
hash.update(readFileSync(fileURLToPath(new URL(name, base))));
}
cachedBuild = hash.digest("hex").slice(0, 16);
} catch {
cachedBuild = `version:${version()}`;
}
return cachedBuild;
}
const STATIC = new Map([
["/app.js", ["app.js", "text/javascript; charset=utf-8"]],
["/view.js", ["view.js", "text/javascript; charset=utf-8"]],
["/i18n.js", ["i18n.js", "text/javascript; charset=utf-8"]],
["/style.css", ["style.css", "text/css; charset=utf-8"]],
// The page's own icon lives beside the launcher, not in ui/.
["/icon.svg", ["../page/icon.svg", "image/svg+xml"]],
]);
function json(res, status, value) {
const body = JSON.stringify(value);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
});
res.end(body);
}
function allowedOrigin(origin, port) {
if (!origin || origin === "null") return true;
return (
origin === `http://127.0.0.1:${port}` ||
origin === `http://localhost:${port}` ||
origin === `http://[::1]:${port}`
);
}
// A plugin page is a sandboxed frame, so it reaches this service with an
// opaque origin ("null"). Its own token still guards the data; these
// headers only let that frame read the answer it asked for.
function allowNullOrigin(req, res) {
if (req.headers.origin === "null") {
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("Vary", "Origin");
}
}
function allowedHost(host, port) {
const value = String(host || "").toLowerCase();
return (
value === `127.0.0.1:${port}` ||
value === `localhost:${port}` ||
value === `[::1]:${port}`
);
}
function escHTML(value) {
return String(value)
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function parseTokens(raw) {
if (!raw) return {};
try {
const value = JSON.parse(Buffer.from(String(raw), "base64").toString("utf8"));
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const out = {};
for (const [key, item] of Object.entries(value)) {
if (/^[a-z0-9-]{1,40}$/i.test(key) && typeof item === "string" && item.length <= 160) {
out[key] = item;
}
}
return out;
} catch {
return {};
}
}
// probeService asks an already running copy of this page's service whether
// it is up, and the token its page was given. Both the app's plugin host and
// the host a `magpie plugin` command starts load this plugin, so one of them
// wins the port; the other must treat that as success, not a failure.
async function probeService(port) {
try {
const res = await fetch(`http://127.0.0.1:${port}/healthz`, {
signal: AbortSignal.timeout(1200),
});
if (!res.ok) {
await res.body?.cancel().catch(() => {});
return null;
}
const body = await res.json();
if (!body || body.name !== PLUGIN_NAME) return null;
// The token stays with the copy that owns the port; a page is always
// served by that copy, so the second host needs nothing from it.
return {
reused: true,
version: body.version || "",
build: body.build || "",
};
} catch {
return null;
}
}
export async function startServer(options = {}) {
const port = Number(options.port);
const requestedPort = Number.isInteger(port) && port >= 0 && port <= 65535 ? port : 3494;
// A restarting host normally frees the port within a fraction of a second.
// Sixteen 100 ms retries bound the worst-case start delay to 1.6 s; waiting
// longer would make the plugin host look hung when another build is live.
const retryAttempts =
Number.isInteger(options.retryAttempts) && options.retryAttempts > 0
? options.retryAttempts
: 16;
const retryDelayMs =
Number.isInteger(options.retryDelayMs) && options.retryDelayMs >= 0
? options.retryDelayMs
: 100;
const token = randomBytes(24).toString("base64url");
const loader = options.load || loadUsageData;
const cache = new Map();
let boundPort = requestedPort;
async function dataFor(period, options = {}) {
const wanted = PERIODS.has(period) ? period : "7d";
const hit = cache.get(wanted);
const now = Date.now();
// What was read last is shown at once, whatever its age; a new read
// never stands between the reader and the numbers they had a moment
// ago. Only a first read waits, as there is nothing to show yet.
if (!options.fresh && hit?.data) {
const stale = hit.data.stale === true || now - hit.at >= (hit.ttl ?? CACHE_MS);
if (stale) void refreshInBackground(wanted, { fresh: true });
return {
data: { ...hit.data, stale },
cache: stale ? "stale" : "fresh",
};
}
// 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: await hit.pending, cache: "shared" };
}
const loaded = await refreshInBackground(wanted, { wait: true, fresh: options.fresh });
return { data: loaded, cache: loaded?.stale ? "stale" : "miss" };
}
function refreshInBackground(wanted, options = {}) {
const hit = cache.get(wanted);
if (hit?.pending) {
return options.wait ? hit.pending : Promise.resolve(hit.data);
}
const pending = loader(wanted, { fresh: Boolean(options.fresh) })
.then((data) => {
cache.set(wanted, { at: Date.now(), data, ttl: CACHE_MS });
return data;
})
.catch((error) => {
if (hit?.data) {
hit.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;
}
throw error;
})
.finally(() => {
const current = cache.get(wanted);
if (current?.pending === pending) current.pending = null;
});
cache.set(wanted, { at: hit?.at || 0, data: hit?.data, pending });
if (!options.wait) {
void pending.catch(() => {});
return Promise.resolve(hit?.data);
}
return pending;
}
const handler = async (req, res) => {
try {
const host = req.headers.host || "";
if (!allowedHost(host, boundPort)) {
json(res, 403, { error: "invalid host" });
return;
}
const url = new URL(req.url || "/", `http://${host}`);
if (req.method !== "GET" && req.method !== "HEAD" && req.method !== "OPTIONS") {
json(res, 405, { error: "method not allowed" });
return;
}
if (url.pathname === "/healthz") {
json(res, 200, {
ok: true,
name: PLUGIN_NAME,
version: version(),
build: buildId(),
});
return;
}
if (
req.method === "OPTIONS" &&
(url.pathname === "/api/tree" || url.pathname === "/api/settings")
) {
allowNullOrigin(req, res);
res.writeHead(204, {
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
});
res.end();
return;
}
if (url.pathname === "/") {
if (!allowedOrigin(req.headers.origin, boundPort)) {
json(res, 403, { error: "invalid origin" });
return;
}
const template = await readFile(join(UI_DIR, "app.html"), "utf8");
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")),
usdCny: url.searchParams.get("usdCny") || options.usdCny || 0,
}),
};
const lang = String(url.searchParams.get("lang") || boot.lang).slice(0, 12);
const html = template
.replaceAll("__USAGE_TREE_TOKEN__", escHTML(token))
.replaceAll("__USAGE_TREE_THEME__", escHTML(boot.theme))
.replaceAll("__USAGE_TREE_LANG__", escHTML(lang))
.replaceAll("__USAGE_TREE_TOKENS__", escHTML(JSON.stringify(boot.tokens)))
.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_TITLE__",
escHTML(lang.toLowerCase().startsWith("zh") ? "账号用量" : "Account usage"),
);
res.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
"Content-Security-Policy":
`default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' http://127.0.0.1:${boundPort} http://localhost:${boundPort}; base-uri 'none'; form-action 'none'`,
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
});
res.end(req.method === "HEAD" ? undefined : html);
return;
}
if (url.pathname === "/api/tree") {
allowNullOrigin(req, res);
if (!allowedOrigin(req.headers.origin, boundPort)) {
json(res, 403, { error: "invalid origin" });
return;
}
if (req.headers["x-usage-tree-token"] !== token) {
json(res, 401, { error: "missing or invalid token" });
return;
}
const period = url.searchParams.get("period") || "7d";
if (!PERIODS.has(period)) {
json(res, 400, { error: "period must be today, 7d, 30d or all" });
return;
}
const loaded = await dataFor(period, { fresh: url.searchParams.get("fresh") === "1" });
res.setHeader("X-Usage-Tree-Cache", loaded.cache);
json(res, 200, loaded.data);
return;
}
if (url.pathname === "/api/settings") {
// The page no longer polls settings. Keep the endpoint for callers
// that still use it, and answer its preflight above.
allowNullOrigin(req, res);
if (!allowedOrigin(req.headers.origin, boundPort)) {
json(res, 403, { error: "invalid origin" });
return;
}
if (req.headers["x-usage-tree-token"] !== token) {
json(res, 401, { error: "missing or invalid token" });
return;
}
json(res, 200, displaySettings(options));
return;
}
const item = STATIC.get(url.pathname);
if (item) {
const body = await readFile(join(UI_DIR, item[0]));
res.writeHead(200, {
"Content-Type": item[1],
"Content-Length": body.length,
"Cache-Control": "no-cache",
"X-Content-Type-Options": "nosniff",
});
res.end(req.method === "HEAD" ? undefined : body);
return;
}
json(res, 404, { error: "not found" });
} catch (error) {
json(res, 500, { error: error?.message || "usage tree failed" });
}
};
// A restarted plugin host can overlap the one it replaces for a moment.
// Bind first, and only after the port stays busy for a while accept that
// another live host already serves this plugin; a dying host releases the
// port and the retry then takes it.
let server = null;
const bind = () =>
new Promise((resolve, reject) => {
const instance = createServer(handler);
const onError = (error) => {
instance.off("listening", onListening);
reject(error);
};
const onListening = () => {
instance.off("error", onError);
resolve(instance);
};
instance.once("error", onError);
instance.once("listening", onListening);
instance.listen(requestedPort, "127.0.0.1");
});
if (requestedPort === 0) {
server = await bind();
} else {
let bound = false;
// A host that is on its way out keeps the port for a moment: the new
// build waits for it, and takes the port when it is free. A live service
// of another build is never killed: it may be the same plugin host that
// serves every other plugin.
for (let attempt = 0; attempt < retryAttempts; attempt += 1) {
try {
server = await bind();
bound = true;
break;
} catch (error) {
if (error?.code !== "EADDRINUSE") throw error;
const running = await probeService(requestedPort);
if (running && running.version === version() && running.build === buildId()) {
return {
port: requestedPort,
token: "",
server: null,
reused: true,
close: async () => {},
};
}
if (retryDelayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
}
}
}
if (!bound) {
const running = await probeService(requestedPort);
if (running && running.version === version() && running.build === buildId()) {
return {
port: requestedPort,
token: "",
server: null,
reused: true,
close: async () => {},
};
}
throw new Error(
running
? `port ${requestedPort} is held by another build of this plugin (${running.version || "unknown"})`
: `port ${requestedPort} is in use and not by this plugin`,
);
}
}
boundPort = server.address().port;
// Warm only when there is a real loader behind the service. A test loader
// is cheap, but a pending warm read can outlive the server's close.
if (!options.load) void dataFor("today").catch(() => {});
return {
port: boundPort,
token,
server,
close: () =>
new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
// Fetch may still be retiring a reused connection when close()
// reports done on Windows. One turn is enough for that to settle.
setTimeout(resolve, 25);
};
server.close(finish);
// Fetch keeps idle sockets alive. Release them so a stopped plugin
// host does not wait for the client's connection timeout.
server.closeIdleConnections?.();
}),
};
}
+336
View File
@@ -0,0 +1,336 @@
// Builds the page's provider -> account -> model tree from magpie's own
// gateway answers. The gateway has already applied magpie's accounting
// rules (handed-on tries, rejected calls, API keys, session-file rows),
// pricing and account aliases, so this file only groups and sorts them.
const PROVIDER_NAMES = {
codex: "Codex",
openai: "OpenAI",
anthropic: "Anthropic",
workbuddy: "WorkBuddy",
"workbuddy-ai": "WorkBuddy AI",
raccoon: "Raccoon",
"minimax-code": "MiniMax Code",
"minimax-code-global": "MiniMax Code",
"trae-cn": "Trae CN",
"trae-global": "Trae",
"opencode-zen-free": "OpenCode Zen",
"autoclaw-cn": "AutoClaw",
autoclaw: "AutoClaw",
zcode: "ZCode",
};
const PERIODS = new Set(["today", "7d", "30d", "all"]);
function text(value) {
return value == null ? "" : String(value).trim();
}
function number(value) {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
}
export function providerName(id) {
return PROVIDER_NAMES[id] || id || "unknown";
}
function providerLabel(item) {
const sub = text(item?.sub);
// The gateway writes "Provider · account" in model subtitles; the
// provider is the part before the account separator. Older answers used
// a hyphen, so accept both spellings.
const beforeAlias = sub.split(" · ")[0].split(" - ")[0].trim();
return beforeAlias || text(item?.providerName) || providerName(text(item?.provider));
}
function blankStats() {
return {
calls: 0,
errors: 0,
retried: 0,
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
reasoning: 0,
cost: 0,
unpriced: 0,
credits: 0,
timed: 0,
ttftMs: 0,
decodeMs: 0,
decodeOut: 0,
decodeN: 0,
lastAt: "",
};
}
function finishStats(target) {
target.tokens = target.input + target.output;
target.cache = target.cacheRead + target.cacheWrite;
target.allTokens = target.tokens + target.cache;
return target;
}
function gatewayStats(item) {
const stats = blankStats();
for (const [to, from] of [
["calls", "calls"],
["errors", "errors"],
["retried", "retried"],
["input", "input"],
["output", "output"],
["cacheRead", "cache_read"],
["cacheWrite", "cache_write"],
["reasoning", "reasoning"],
["cost", "cost"],
["unpriced", "unpriced"],
["credits", "credits"],
["timed", "timed"],
["ttftMs", "ttft_ms"],
["decodeMs", "decode_ms"],
["decodeOut", "decode_out"],
["decodeN", "decode_n"],
]) {
stats[to] = number(item?.[from]);
}
stats.lastAt = text(item?.last_at || item?.lastAt || item?.last?.at);
return finishStats(stats);
}
function addTotals(total, item) {
for (const key of [
"calls",
"errors",
"retried",
"input",
"output",
"cacheRead",
"cacheWrite",
"reasoning",
"cost",
"unpriced",
"credits",
"timed",
"ttftMs",
"decodeMs",
"decodeOut",
"decodeN",
]) {
total[key] += number(item[key]);
}
const lastAt = text(item?.lastAt);
if (lastAt && lastAt > text(total.lastAt)) total.lastAt = lastAt;
}
function isApiKey(item) {
const account = text(item?.account);
const access = text(item?.access).toLowerCase();
return account === "API key" || access === "key" || access === "api-key";
}
export function accountKey(provider, account) {
return `${text(provider)}\u001f${text(account)}`;
}
function modelFromId(item, fallbackProvider) {
const id = text(item?.id);
const slash = id.indexOf("/");
const provider = text(item?.provider) || (slash >= 0 ? id.slice(0, slash) : fallbackProvider);
const model = text(item?.model) || (slash >= 0 ? id.slice(slash + 1) : id);
return { id, provider, model };
}
function mergeModelRows(items, account) {
const rows = new Map();
const hostsByModel = new Map();
for (const item of items) {
const model = modelFromId(item, account.provider);
if (!model.model || model.provider !== account.provider) continue;
const key = `${model.provider}\u001f${model.model}`;
let row = rows.get(key);
const stats = gatewayStats(item);
if (!row) {
row = {
id: `${account.id}\u001f${model.provider}\u001f${model.model}`,
model: model.model,
provider: model.provider,
providerName: account.providerName,
...stats,
hostNotes: [],
};
rows.set(key, row);
} else {
addTotals(row, stats);
}
const host = text(item?.host) || text(account.alias) || text(account.account);
if (host) {
let hosts = hostsByModel.get(key);
if (!hosts) {
hosts = new Map();
hostsByModel.set(key, hosts);
}
hosts.set(host, (hosts.get(host) || 0) + number(item?.calls));
}
}
for (const [key, row] of rows) {
finishStats(row);
const hosts = [...(hostsByModel.get(key) || new Map()).entries()]
.map(([host, calls]) => ({ account: host, calls }))
.sort((a, b) => b.calls - a.calls || a.account.localeCompare(b.account));
row.hostNotes = hosts.length > 1 ? hosts : [];
}
return [...rows.values()];
}
// The usage answer already has a Models table, with the account that made
// the calls in `host`. Using it avoids one requests read per account: on a
// large 30-day ledger that was the slowest part of the first load. A model
// row without a host belongs to the provider's only account, or the
// requests read below fills the gap.
function modelRowsFromUsage(usage, account, siblings) {
const rows = Array.isArray(usage?.models) ? usage.models : [];
const providerRows = rows.filter((item) => text(item?.provider) === account.provider);
const exact = providerRows.filter((item) => {
const host = text(item?.host);
return host && (host === account.account || host === account.alias);
});
const withoutHost = providerRows.filter((item) => !text(item?.host));
const chosen = exact.length ? exact : siblings === 1 ? withoutHost : [];
if (!chosen.length) return null;
const total = chosen.reduce((sum, item) => sum + number(item?.calls), 0);
// The top-level model table may be capped or may omit calls handed on to
// another account. Use it only when it accounts for every call; otherwise
// the requests answer carries this account's complete model table.
if (total < account.calls) return null;
return mergeModelRows(chosen, account);
}
function modelRows(requests, account) {
const rows = Array.isArray(requests?.by?.modelAt) ? requests.by.modelAt : [];
return mergeModelRows(rows, account);
}
// usage is GET /v1/magpie/usage; requestsByAccount maps the account id to
// GET /v1/magpie/usage/requests?account=...
export function aggregateGatewayUsage(usage, requestsByAccount = {}, options = {}) {
const period = PERIODS.has(options.period) ? options.period : "today";
const accountItems = Array.isArray(usage?.accounts) ? usage.accounts : [];
const accounts = [];
let apiKeyGroups = 0;
const providerCounts = new Map();
for (const item of accountItems) {
const provider = text(item?.provider);
if (provider) providerCounts.set(provider, (providerCounts.get(provider) || 0) + 1);
}
for (const item of accountItems) {
const provider = text(item?.provider);
const account = text(item?.account) || text(item?.id);
if (!provider || !account) continue;
const apiKey = isApiKey(item);
const accountRow = {
id: `${provider}\u001f${account}`,
account,
alias: apiKey ? "" : (text(item?.name) !== account ? text(item?.name) : ""),
provider,
providerName: providerLabel(item),
kind: apiKey ? "api-key" : "account",
models: modelRowsFromUsage(usage, {
id: accountKey(provider, account),
account,
alias: apiKey ? "" : (text(item?.name) !== account ? text(item?.name) : ""),
provider,
providerName: providerLabel(item),
calls: number(item?.calls),
}, providerCounts.get(provider) || 0) ?? modelRows(requestsByAccount[accountKey(provider, account)], {
id: accountKey(provider, account),
provider,
providerName: providerLabel(item),
}),
...gatewayStats(item),
};
accounts.push(accountRow);
if (apiKey) apiKeyGroups += 1;
}
const summary = gatewayStats(usage);
summary.accounts = accounts.filter((account) => account.kind !== "api-key").length;
summary.apiKeyGroups = apiKeyGroups;
summary.providers = 0;
summary.models = 0;
const maxAccountTokens = Math.max(1, ...accounts.map((account) => account.tokens));
for (const account of accounts) {
account.share = summary.tokens > 0 ? account.tokens / summary.tokens : 0;
account.bar = Math.max(0.015, account.tokens / maxAccountTokens);
account.models.sort(
(a, b) =>
b.tokens - a.tokens ||
b.cost - a.cost ||
b.calls - a.calls ||
a.model.localeCompare(b.model),
);
const maxModelTokens = Math.max(1, ...account.models.map((model) => model.tokens));
for (const model of account.models) {
model.share = account.tokens > 0 ? model.tokens / account.tokens : 0;
model.bar = Math.max(0.02, model.tokens / maxModelTokens);
}
summary.models += account.models.length;
}
const providerGroups = new Map();
for (const account of accounts) {
let provider = providerGroups.get(account.provider);
if (!provider) {
provider = {
id: account.provider,
provider: account.provider,
providerName: account.providerName,
accounts: [],
...blankStats(),
};
providerGroups.set(account.provider, provider);
}
provider.accounts.push(account);
addTotals(provider, account);
}
const providers = [...providerGroups.values()];
for (const provider of providers) {
finishStats(provider);
provider.accounts.sort(
(a, b) => b.tokens - a.tokens || b.cost - a.cost || a.account.localeCompare(b.account),
);
}
providers.sort(
(a, b) => b.tokens - a.tokens || b.cost - a.cost || a.providerName.localeCompare(b.providerName),
);
summary.providers = providers.length;
finishStats(summary);
accounts.sort(
(a, b) =>
b.tokens - a.tokens ||
b.cost - a.cost ||
b.calls - a.calls ||
a.account.localeCompare(b.account),
);
return {
period,
generatedAt: new Date().toISOString(),
summary,
providers,
accounts,
warnings: summary.calls ? [] : [{ code: "no-usage" }],
source: "Magpie gateway usage",
};
}
export { PERIODS };
+71
View File
@@ -0,0 +1,71 @@
{
"name": "@magpie-community/page-usage-tree",
"version": "0.1.0",
"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",
"files": [
"index.mjs",
"serve.mjs",
"lib",
"page",
"ui",
"assets",
"LICENSE",
"README.md"
],
"scripts": {
"start": "node serve.mjs",
"test": "node --test test/*.test.mjs"
},
"engines": {
"magpie": ">=0.1.1340"
},
"keywords": [
"magpie",
"magpie-page",
"magpie-plugin",
"usage",
"accounts",
"models",
"tokens",
"cost"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/page-usage-tree"
},
"homepage": "https://github.com/magpie-community/plugins/tree/main/packages/page-usage-tree",
"bugs": {
"url": "https://github.com/magpie-community/plugins/issues"
},
"magpie": {
"name": "账号用量 / Account usage",
"summary": {
"en": "A provider -> account -> model usage tree with per-account calls, errors, tokens and cost. Adds the account layer that Usage Glance's usage:summary does not contain, read from Magpie's local usage API.",
"zh": "按供应商 -> 账号 -> 模型查看用量,逐级展开调用、错误、Token 与费用。补充用量速览没有的账号层,数据来自 Magpie 本地用量 API。"
},
"page": {
"title": "Account usage",
"titles": {
"en": "Account usage",
"zh": "账号用量"
},
"file": "page/index.html",
"service": {
"port": 3494,
"option": "port"
},
"icon": "page/icon.svg"
},
"options": {
"port": 3494,
"currency": "usd",
"chineseUnits": false,
"usdCny": 0
},
"icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4IiB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgZmlsbD0ibm9uZSI+CiAgPHJlY3Qgd2lkdGg9IjEyOCIgaGVpZ2h0PSIxMjgiIHJ4PSIyOCIgZmlsbD0iIzNhM2Y0YiIvPgogIDxnIHN0cm9rZT0iI2U5ZTdmMiIgc3Ryb2tlLXdpZHRoPSI5LjYiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+CiAgICA8cmVjdCB4PSI0Mi40IiB5PSIxMy42IiB3aWR0aD0iNDMuMiIgaGVpZ2h0PSIyNi40IiByeD0iMTAuNCIvPgogICAgPHBhdGggZD0iTTY0IDQwdjE2Ii8+CiAgICA8cGF0aCBkPSJNMzAuNCA4Mi40VjcyLjhhMTAuNCAxMC40IDAgMCAxIDEwLjQtMTAuNGg0Ni40YTEwLjQgMTAuNCAwIDAgMSAxMC40IDEwLjR2OS42Ii8+CiAgICA8cmVjdCB4PSIxNC40IiB5PSI4Mi40IiB3aWR0aD0iMzAuNCIgaGVpZ2h0PSIyMi40IiByeD0iOS42Ii8+CiAgICA8cmVjdCB4PSI0OC44IiB5PSI4Mi40IiB3aWR0aD0iMzAuNCIgaGVpZ2h0PSIyMi40IiByeD0iOS42Ii8+CiAgICA8cmVjdCB4PSI4My4yIiB5PSI4Mi40IiB3aWR0aD0iMzAuNCIgaGVpZ2h0PSIyMi40IiByeD0iOS42Ii8+CiAgICA8cGF0aCBkPSJNMTguNCAxMTQuNGg5MS4yIi8+CiAgPC9nPgo8L3N2Zz4K"
}
}
+133
View File
@@ -0,0 +1,133 @@
(async () => {
const DEFAULT_PORT = 3494;
const words = {
en: {
title: "Account usage",
connecting: "Connecting to the local usage service...",
stopped: (port) => `The local usage service is not running (127.0.0.1:${port}).`,
retry: "Retry",
},
zh: {
title: "账号用量",
connecting: "正在连接本地用量服务...",
stopped: (port) => `本地用量服务没有在运行(127.0.0.1:${port})。`,
retry: "重试",
},
};
let port = DEFAULT_PORT;
let theme = "light";
let lang = "en";
let tokens = null;
let service = "";
const display = {
currency: "usd",
chineseUnits: false,
usdCny: 0,
};
function followDisplay(value) {
if (!value || typeof value !== "object") return;
if (value.currency === "cny" || value.currency === "usd") {
display.currency = value.currency;
}
if (typeof value.chineseUnits === "boolean") {
display.chineseUnits = value.chineseUnits;
}
const rate = Number(value.usdCny);
if (Number.isFinite(rate) && rate > 0) display.usdCny = rate;
}
function followLanguage(value) {
lang = String(value || "").toLowerCase().startsWith("zh") ? "zh" : "en";
const text = words[lang];
document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
document.title = text.title;
document.getElementById("title").textContent = text.title;
document.getElementById("said").textContent = text.connecting;
document.getElementById("retry").textContent = text.retry;
}
try {
const current = await window.magpie?.ready;
if (current) {
theme = current.dark ? "dark" : "light";
lang = String(current.lang || lang).toLowerCase().startsWith("zh") ? "zh" : "en";
tokens = current.tokens || null;
followDisplay(current);
}
} catch {
// The page still works without the bridge.
}
try {
const options = await window.magpie?.options?.get?.();
const value = Number(options?.port);
if (Number.isInteger(value) && value > 0 && value < 65536) port = value;
followDisplay(options);
} catch {
// Use the declared default.
}
try {
const value = window.magpie?.service;
if (typeof value === "string" && /^https?:\/\//.test(value)) service = value;
} catch {
// Desktop windows navigate directly to loopback.
}
followLanguage(lang);
window.magpie?.onTheme?.((next) => {
if (!next) return;
if (typeof next.dark === "boolean") theme = next.dark ? "dark" : "light";
if (typeof next.lang === "string") {
const before = lang;
followLanguage(next.lang);
// The frame is about to be replaced; only update the waiting text.
if (before !== lang) {
const retry = document.getElementById("retry");
if (retry && !retry.hidden) retry.textContent = words[lang].retry;
}
}
});
const query = new URLSearchParams();
query.set("theme", theme);
query.set("lang", lang);
query.set("currency", display.currency);
query.set("chineseUnits", display.chineseUnits ? "1" : "0");
if (display.usdCny > 0) query.set("usdCny", String(display.usdCny));
if (tokens && typeof tokens === "object") {
try {
const slim = {};
for (const [key, value] of Object.entries(tokens)) {
const item = String(value ?? "").trim();
if (item && item.length <= 160) slim[key] = item;
}
if (Object.keys(slim).length) {
query.set("tokens", btoa(unescape(encodeURIComponent(JSON.stringify(slim)))));
}
} catch {
// Theme tokens are optional.
}
}
const target = service || `http://127.0.0.1:${port}/`;
const url = new URL(target, location.href);
for (const [key, value] of query) url.searchParams.set(key, value);
const timer = setTimeout(() => {
const said = document.getElementById("said");
if (!said) return;
said.textContent = words[lang].stopped(port);
const retry = document.getElementById("retry");
if (retry) retry.hidden = false;
}, 5000);
document.getElementById("retry")?.addEventListener("click", () => {
clearTimeout(timer);
location.reload();
});
location.replace(url.href);
})();
+10
View File
@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"
fill="none" stroke="#7b8089" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">
<rect x="5.1" y="1.4" width="5.8" height="3.6" rx="1.3"/>
<path d="M8 5v2.1"/>
<path d="M3.7 9.6V8.5a1.4 1.4 0 0 1 1.4-1.4h5.8a1.4 1.4 0 0 1 1.4 1.4v1.1"/>
<rect x="1.7" y="9.6" width="3.9" height="3.2" rx="1.2"/>
<rect x="6.05" y="9.6" width="3.9" height="3.2" rx="1.2"/>
<rect x="10.4" y="9.6" width="3.9" height="3.2" rx="1.2"/>
<path d="M1.7 14.6h12.6"/>
</svg>

After

Width:  |  Height:  |  Size: 564 B

+38
View File
@@ -0,0 +1,38 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Account usage</title>
<style>
:root { color-scheme: light dark; }
html, body { height: 100%; margin: 0; }
body {
display: grid;
place-items: center;
font: 13px/1.6 "Aptos", "Segoe UI Variable", "Noto Sans SC", "PingFang SC", sans-serif;
color: var(--magpie-fg, CanvasText);
background: var(--magpie-bg, Canvas);
}
.waiting {
display: grid;
gap: 6px;
max-width: 460px;
padding: 0 20px;
color: var(--magpie-muted, GrayText);
text-align: center;
}
.waiting b { color: var(--magpie-fg, CanvasText); font-size: 14px; font-weight: 600; }
.waiting button { justify-self: center; margin-top: 8px; padding: 5px 14px; font: inherit; }
</style>
</head>
<body>
<div class="waiting">
<b id="title">Account usage</b>
<div id="said">Connecting to the local usage service...</div>
<button id="retry" type="button" hidden>Retry</button>
</div>
<script src="_magpie/bridge.js"></script>
<script src="boot.js"></script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
import { startServer } from "./lib/server.mjs";
function arg(name, fallback) {
const at = process.argv.indexOf(name);
return at >= 0 && process.argv[at + 1] ? process.argv[at + 1] : fallback;
}
const port = Number(arg("--port", process.env.MAGPIE_USAGE_TREE_PORT || 3494));
const currency = arg("--currency", process.env.MAGPIE_USAGE_TREE_CURRENCY || "usd");
const usdCny = Number(arg("--usd-cny", process.env.MAGPIE_USAGE_TREE_USD_CNY || 0));
const chineseUnits = arg("--chinese-units", "") === "1";
const info = await startServer({ port, currency, usdCny, chineseUnits });
console.log(`[usage-tree] listening on http://127.0.0.1:${info.port}`);
@@ -0,0 +1,77 @@
import test from "node:test";
import assert from "node:assert/strict";
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";
test("a stale disk cache says so while it refreshes behind the page", async (t) => {
const root = mkdtempSync(join(tmpdir(), "usage-tree-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() - 60_000,
data: {
period: "today",
generatedAt: "old",
summary: { calls: 1 },
providers: [],
accounts: [],
warnings: [],
},
}),
"utf8",
);
const gateway = createServer((req, res) => {
if (req.url.startsWith("/v1/magpie/usage")) {
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: [],
}));
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));
if (previousCache === undefined) delete process.env.MAGPIE_CACHE_DIR;
else process.env.MAGPIE_CACHE_DIR = previousCache;
rmSync(root, { recursive: true, force: true });
});
const first = await loadUsageData("today", { gateway: base });
assert.equal(first.cached, true);
assert.equal(first.stale, true);
assert.equal(first.summary.calls, 1);
let latest = first;
for (let attempt = 0; attempt < 40 && latest.summary.calls !== 2; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 25));
latest = await loadUsageData("today", { gateway: base });
}
assert.equal(latest.summary.calls, 2);
assert.equal(latest.stale, false);
if (process.platform !== "win32") {
assert.equal(statSync(join(root, "usage-tree")).mode & 0o777, 0o700);
assert.equal(statSync(join(root, "usage-tree", "today.json")).mode & 0o777, 0o600);
}
});
@@ -0,0 +1,52 @@
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 pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
// How magpie's Discover finds a repository: topic magpie-plugin
// (internal/plugin/github.go, Topic). The page says the topic it searches.
test("is published as a repository tagged magpie-plugin", () => {
const repo = pkg.repository;
assert.ok(repo, "package.json names a repository");
assert.match(repo.url ?? repo, /github\.com/);
});
// The community's listing: name and where it lives (PUBLISHING.md, route B).
test("is named and placed as a community page package", () => {
assert.equal(pkg.name, "@magpie-community/page-usage-tree");
assert.equal(pkg.repository.url, "git+https://github.com/magpie-community/plugins.git");
assert.equal(pkg.repository.directory, "packages/page-usage-tree");
});
// internal/plugin/github.go: a repository is listed as a page only when it
// has neither main nor exports, and names magpie.page.file. This package has
// a host part, so it is not that: its listing has to say kind "page" itself.
test("says it is a page in its own right", () => {
assert.equal(pkg.magpie.page.file, "page/index.html");
const autoListedAsPage = Boolean(
(pkg.main == null || pkg.main === "") &&
(pkg.exports == null) &&
pkg.magpie.page.file,
);
// documented, so the listing is never left to look like a provider
assert.equal(autoListedAsPage, false, "has a host part: needs kind in the listing");
});
// market.go: an entry is taken from the community registry only when it is
// marked community, and market() lists it under its kind.
test("carries what a community listing needs", () => {
assert.ok(pkg.magpie.icon?.startsWith("data:image/"), "magpie.icon is a data URI");
assert.equal(pkg.license, "MIT");
assert.ok(pkg.keywords.includes("magpie-page"));
});
// The card's picture is the file it is drawn from: a data URI left behind
// after the icon was redrawn is the old picture on everyone's Discover.
test("the listing icon is the icon file", () => {
const icon = readFileSync(join(dir, "assets", "icon.svg"), "utf8");
const want = `data:image/svg+xml;base64,${Buffer.from(icon).toString("base64")}`;
assert.equal(pkg.magpie.icon, want);
});
@@ -0,0 +1,29 @@
import test from "node:test";
import assert from "node:assert/strict";
import { aggregateGatewayUsage } from "../lib/usage.mjs";
import { startServer } from "../lib/server.mjs";
// A fresh install has no usage yet. The gateway answers with zero calls and
// no accounts, and the page must show an empty tree with a note, not a 500.
test("a fresh install has an empty tree, not an error", async (t) => {
const empty = aggregateGatewayUsage({ calls: 0, accounts: [] }, {}, { period: "7d" });
assert.deepEqual(empty.providers, []);
assert.deepEqual(empty.accounts, []);
assert.equal(empty.summary.calls, 0);
assert.equal(empty.summary.accounts, 0);
assert.ok(empty.warnings.some((item) => item.code === "no-usage"));
const info = await startServer({
port: 0,
load: async () => empty,
});
t.after(() => info.close());
const res = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, {
headers: { "x-usage-tree-token": info.token },
});
assert.equal(res.status, 200);
const body = await res.json();
assert.deepEqual(body.accounts, []);
assert.ok(body.warnings.some((item) => item.code === "no-usage"));
});
@@ -0,0 +1,25 @@
import test from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { gatewayUsage } from "../lib/gateway.mjs";
test("a successful HTTP answer that is not a JSON object is an error", async (t) => {
const replies = [
["text/html", "<html>not the usage API</html>"],
["application/json", "[1, 2, 3]"],
];
const gateway = createServer((_req, res) => {
const [type, body] = replies.shift() || ["application/json", "null"];
res.writeHead(200, { "Content-Type": type });
res.end(body);
});
await new Promise((resolve) => gateway.listen(0, "127.0.0.1", resolve));
t.after(() => new Promise((resolve) => gateway.close(resolve)));
const options = {
gateway: `http://127.0.0.1:${gateway.address().port}`,
timeout: 2_000,
};
await assert.rejects(gatewayUsage("today", options), /invalid JSON object/);
await assert.rejects(gatewayUsage("today", options), /invalid JSON object/);
});
@@ -0,0 +1,117 @@
import test from "node:test";
import assert from "node:assert/strict";
import http, { createServer } from "node:http";
import { BUILD_FILES, startServer, version } from "../lib/server.mjs";
function status(port, path) {
return new Promise((resolve, reject) => {
const req = http.get(
{
host: "127.0.0.1",
port,
path,
agent: false,
headers: { Connection: "close" },
},
(res) => {
res.resume();
resolve(res.statusCode);
},
);
req.on("error", reject);
});
}
test("the build ID covers every runtime asset", () => {
for (const file of [
"../package.json",
"../page/boot.js",
"../page/icon.svg",
"../ui/app.html",
"../ui/app.js",
"../ui/view.js",
"../ui/i18n.js",
"../ui/style.css",
]) {
assert.ok(BUILD_FILES.includes(file), `${file} is part of the build ID`);
}
});
test("a second copy of this build reuses the running service", async (t) => {
const first = await startServer({
port: 0,
load: async () => ({ summary: {}, providers: [], accounts: [] }),
});
t.after(() => first.close());
const second = await startServer({
port: first.port,
load: async () => ({ summary: {}, providers: [], accounts: [] }),
});
assert.equal(second.reused, true);
assert.equal(second.port, first.port);
assert.equal(second.token, "");
const res = await fetch(`http://127.0.0.1:${first.port}/healthz`);
const body = await res.json();
assert.equal(body.name, "magpie-usage-tree");
assert.equal(body.version, version());
assert.match(body.build, /^[a-f0-9]{16}$/);
});
test("another build on the port is reported, never killed", async (t) => {
const old = createServer((_req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, name: "magpie-usage-tree", version: "0.0.1" }));
});
await new Promise((resolve) => old.listen(0, "127.0.0.1", resolve));
const port = old.address().port;
t.after(() => new Promise((resolve) => old.close(resolve)));
await assert.rejects(
startServer({
port,
retryAttempts: 1,
load: async () => ({ summary: {}, providers: [], accounts: [] }),
}),
/held by another build of this plugin/i,
);
const res = await fetch(`http://127.0.0.1:${port}/healthz`);
const body = await res.json();
assert.equal(res.status, 200, "the running build was left alone");
assert.equal(body.version, "0.0.1");
});
test("a host on its way out releases the port and the new copy takes it", async (t) => {
const sockets = new Set();
const leaving = createServer((_req, res) => {
res.writeHead(503, { "Content-Type": "text/plain" });
res.end("leaving");
});
leaving.on("connection", (socket) => {
sockets.add(socket);
socket.on("close", () => sockets.delete(socket));
});
await new Promise((resolve) => leaving.listen(0, "127.0.0.1", resolve));
const port = leaving.address().port;
setTimeout(() => {
// A host that is going away drops its clients; Bun otherwise keeps the
// listener alive until a probed connection closes.
for (const socket of sockets) socket.destroy();
leaving.close();
}, 800);
t.after(() => {
if (leaving.listening) {
return new Promise((resolve) => leaving.close(resolve));
}
});
const info = await startServer({
port,
load: async () => ({ summary: {}, providers: [], accounts: [] }),
});
t.after(() => info.close());
assert.equal(await status(port, "/healthz"), 200);
});
+398
View File
@@ -0,0 +1,398 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
const dir = join(import.meta.dirname, "..");
const pageDir = join(dir, "page");
const uiDir = join(dir, "ui");
const read = (base, file) => readFileSync(join(base, file), "utf8");
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
// view.js is a classic script, as the page loads it.
const scope = {};
new Function("globalThis", read(uiDir, "i18n.js"))(scope);
new Function("globalThis", read(uiDir, "view.js"))(scope);
const V = scope.UsageView;
const summary = {
period: "7d",
accounts: 2,
models: 3,
calls: 120,
errors: 3,
input: 1200000,
output: 300000,
cache: 900000,
tokens: 1500000,
cost: 42.5,
unpriced: 2,
};
const accounts = [
{
id: "codex\u001falice@example.com",
account: "alice@example.com",
alias: "10月学生Plus",
provider: "codex",
providerName: "Codex",
calls: 100,
errors: 3,
tokens: 1400000,
cost: 40,
unpriced: 2,
share: 0.8,
bar: 1,
models: [
{
id: "m1",
model: "gpt-6-luna",
providerName: "Codex",
calls: 100,
errors: 3,
tokens: 1400000,
cost: 40,
unpriced: 2,
share: 1,
bar: 1,
hostNotes: [{ account: "chatgpt.com", calls: 14 }],
},
],
},
{
id: "raccoon\u001fbob",
account: "bob",
alias: "",
provider: "raccoon",
providerName: "Raccoon",
calls: 20,
errors: 0,
tokens: 100000,
cost: 2.5,
unpriced: 0,
share: 0.2,
bar: 0.15,
models: [],
},
];
test("the page reads nothing of magpie and reaches no network", () => {
assert.deepEqual(pkg.magpie.permissions ?? [], []);
const reads = new Set();
for (const file of readdirSync(pageDir).filter((f) => f.endsWith(".js"))) {
const source = read(pageDir, file);
for (const match of source.matchAll(/magpie\.read\(\s*"([^"]+)"/g)) reads.add(match[1]);
// magpie's policy refuses these anyway; the page must not try.
assert.doesNotMatch(
source,
/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts/,
);
}
assert.deepEqual([...reads], []);
});
test("plugin metadata speaks Chinese and English", () => {
assert.equal(pkg.magpie.name, "账号用量 / Account usage");
assert.equal(pkg.magpie.page.titles.zh, "账号用量");
assert.match(pkg.magpie.summary.zh, /供应商 -> 账号 -> 模型/);
assert.match(pkg.magpie.summary.en, /provider -> account -> model/);
assert.match(pkg.description, /在 Magpie 窗口中/);
assert.match(pkg.description, /A page in Magpie's window/);
const readme = read(join(dir), "README.md");
assert.match(readme, /## 中文说明/);
assert.ok(readme.indexOf("## 中文说明") < readme.indexOf("## English"));
for (const text of [pkg.description, pkg.magpie.page.titles.zh, pkg.magpie.summary.zh, readme]) {
assert.doesNotMatch(text, /\uFFFD/);
}
});
test("is a page magpie serves: its files in page/, scripts as files", () => {
assert.equal(pkg.magpie.page.file, "page/index.html");
assert.equal(pkg.magpie.page.icon, "page/icon.svg");
const html = read(pageDir, "index.html");
assert.match(html, /<script src="_magpie\/bridge\.js"><\/script>/);
for (const match of html.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/g)) {
assert.match(match[1], /\ssrc="/);
assert.equal(match[2].trim(), "");
}
for (const match of html.matchAll(/(?:src|href)="([^"]+)"/g)) {
if (match[1].startsWith("_magpie/")) continue;
assert.doesNotMatch(match[1], /^(?:[a-z]+:|\/|\.\.)/i);
assert.ok(readdirSync(pageDir).includes(match[1]), `${match[1]} is in page/`);
}
});
test("the launcher only navigates to the local service", () => {
const boot = read(pageDir, "boot.js");
assert.match(boot, /location\.replace\(/);
// it must not probe the service first: the page's CSP is connect-src 'none'
assert.doesNotMatch(boot, /\bfetch\(/);
assert.match(boot, /window\.magpie\?\.service/);
});
test("the launcher forwards currency and unit options", () => {
const boot = read(pageDir, "boot.js");
assert.match(boot, /query\.set\("currency", display\.currency\)/);
assert.match(boot, /query\.set\("chineseUnits", display\.chineseUnits \? "1" : "0"\)/);
assert.match(boot, /followDisplay\(options\)/);
assert.equal(pkg.magpie.options.currency, "usd");
assert.equal(pkg.magpie.options.chineseUnits, false);
assert.equal(pkg.magpie.options.usdCny, 0);
});
test("the summary says accounts, calls, tokens and cost", () => {
V.setChineseUnits(true);
V.setLang("zh");
const tiles = V.tiles(summary, "zh", "cny", 6.6696);
assert.equal(tiles.length, 4);
assert.equal(tiles[0].value, "2");
assert.match(tiles[0].sub, /0 个供应商/);
assert.equal(tiles[1].value, "120");
assert.equal(tiles[1].bad, true);
assert.equal(tiles[2].value, "240万");
assert.match(tiles[3].value, /^¥/);
});
test("cache can be included or excluded from token totals", () => {
V.setChineseUnits(true);
V.setLang("zh");
assert.equal(V.tokenTotal({ tokens: 150, cache: 50 }, true), 200);
assert.equal(V.tokenTotal({ tokens: 150, cache: 50 }, false), 150);
assert.equal(V.tokenTotal({ tokens: 150, allTokens: 220, cache: 50 }, true), 220);
assert.equal(V.tiles(summary, "zh", "usd", 6.6696, true)[2].value, "240万");
assert.equal(V.tiles(summary, "zh", "usd", 6.6696, false)[2].value, "150万");
});
test("an account shows the name the user gave it", () => {
const rows = V.accounts(accounts, "tokens", "zh");
assert.equal(rows[0].name, "10月学生Plus");
assert.equal(rows[1].name, "bob");
assert.equal(rows[0].share, "93%");
});
test("search matches account aliases and only keeps matching children", () => {
const provider = {
id: "codex",
provider: "codex",
providerName: "Codex",
accounts,
};
assert.equal(V.accountMatches(accounts[0], "10月学生plus"), true);
assert.equal(V.accountSelfMatches(accounts[0], "10月学生plus"), true);
assert.equal(V.modelMatches(accounts[0].models[0], "gpt-6"), true);
assert.deepEqual(
V.visibleAccounts(provider, "gpt-6").map((account) => account.account),
["alice@example.com"],
);
assert.equal(V.visibleAccounts(provider, "codex").length, 2);
});
test("expand-all follows the accounts visible under the current search", () => {
const source = read(uiDir, "app.js");
assert.match(
source,
/const accounts = providers\.flatMap\(\(provider\) => V\.visibleAccounts\(provider, state\.query\)\)/,
);
assert.match(source, /function updateExpandLabel\(\)[\s\S]*?allExpanded\(\)/);
assert.match(source, /function allExpanded\(\)[\s\S]*?V\.visibleAccounts\(provider, state\.query\)/);
assert.match(source, /const shownAccounts = V\.visibleAccounts\(provider, state\.query\)/);
assert.match(source, /countModels\(shownAccounts\)/);
});
test("a model's own host difference is a note, not a second row", () => {
const rows = V.models(accounts[0], "zh", "cny", 6.6696);
assert.equal(rows.length, 1);
assert.deepEqual(rows[0].hosts, ["chatgpt.com 14"]);
});
test("an empty or incomplete tree sorts without throwing", () => {
for (const sort of V.SORTS) {
assert.deepEqual(V.sortProviders([], sort, true), []);
assert.deepEqual(V.sortProviders(null, sort, false), []);
}
const rows = V.sortProviders(
[
{ id: "missing-fields" },
{ id: "b", providerName: "B", calls: 2, cost: 1, tokens: 10 },
{ id: "a", providerName: "A", calls: 1, cost: 2, tokens: 20 },
],
"cost",
true,
);
assert.deepEqual(rows.map((row) => row.id), ["a", "b", "missing-fields"]);
});
test("numbers read short", () => {
V.setChineseUnits(true);
V.setLang("zh");
assert.equal(V.count(999), "999");
assert.equal(V.count(1500000), "150万");
assert.equal(V.percent(0.8), "80%");
assert.equal(V.percent(0.004), "0.40%");
});
test("an error rate is errors of the calls", () => {
assert.equal(V.errorRate(3, 120), "2.5%");
assert.equal(V.errorRate(1, 1), "100%");
assert.equal(V.errorRate(0, 50), "");
// no calls, no rate: 0% would read as a clean record it never had
assert.equal(V.errorRate(2, 0), "");
});
test("english is english, chinese is chinese", () => {
const words = scope.UsageI18n.get("en");
V.setLang("en");
V.setChineseUnits(false);
assert.equal(V.count(1500000), "1.5M");
assert.equal(words.title, "Account usage");
assert.equal(words.detail, "Account details");
assert.match(V.tiles(summary, "en", "usd", 6.6696)[2].sub, /^In /);
assert.equal(V.shareWord("cost"), "Cost share");
V.setLang("zh");
assert.equal(V.shareWord("cost"), "费用占比");
assert.match(V.tiles(summary, "zh", "usd", 6.6696)[2].sub, /^入 /);
});
test("english counts singular accounts, providers and models", () => {
V.setLang("en");
const words = scope.UsageI18n.get("en");
assert.equal(words.accountsAndModels(1, 1), "1 account · 1 model");
assert.equal(words.accountsAndModels(0, 2), "0 accounts · 2 models");
assert.equal(words.modelsOnly(1), "1 model");
assert.equal(words.providerModels(1, 1), "1 provider · 1 model");
assert.equal(words.providerModels(3, 4), "3 providers · 4 models");
assert.match(V.tiles({ ...summary, accounts: 1, models: 1, providers: 1 }, "en", "usd", 0)[0].sub,
/^1 provider · 1 model$/);
});
test("the model table has one column per value and follows the cache switch", () => {
const source = read(uiDir, "app.js");
const start = source.indexOf("function modelList");
const head = source.slice(start, source.indexOf("const query = state.query", start));
assert.equal((head.match(/el\("span", "", /g) || []).length, 7);
assert.match(
head,
/el\("span", "", state\.includeCache \? W\.modelTokensWithCache : W\.modelTokensWithoutCache\)/,
);
assert.doesNotMatch(head, /el\("span", "", "Token"\)/);
assert.equal(scope.UsageI18n.get("zh").token, "Token");
assert.equal(scope.UsageI18n.get("en").token, "Token");
});
test("model calls sit under the right-aligned calls header", () => {
const source = read(uiDir, "app.js");
assert.match(source, /\(model\.errors \? "bad " : ""\) \+ "calls-cell"/);
const css = read(uiDir, "style.css");
assert.match(css, /\.calls-cell,[\s\S]*?text-align: right;/);
});
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)"));
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)"));
assert.match(block, /\.summary-sub \{[\s\S]*?white-space: normal;/);
});
test("no function of the page calls itself", () => {
// A function that calls itself runs until the stack is gone: the page
// would show "Maximum call stack size exceeded" instead of its rows.
const source = read(uiDir, "app.js");
const bodies = source.matchAll(/function\s+([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{([\s\S]*?)\n \}/g);
const offenders = [];
for (const [, name, body] of bodies) {
// a call of itself, not a call of the same name on something else
const calls = [...body.matchAll(new RegExp(`(?<![.\\w$])${name}\\s*\\(`, "g"))];
if (!calls.length) continue;
// a call that waits for a timer is a retry, not a loop
const deferred = calls.every((call) => {
const before = body.slice(0, call.index);
return /setTimeout\s*\(/.test(before.split("\n").slice(-4).join("\n"));
});
if (!deferred) offenders.push(name);
}
assert.deepEqual(offenders, []);
});
test("sorting uses the segmented control and updates its selected state", () => {
const source = read(uiDir, "app.js");
assert.match(source, /\$\("sort"\)\.addEventListener\("click"/);
assert.match(source, /state\.sort = validSorts\.has\(value\) \? value : "tokens";[\s\S]*?renderPeriod\(\);[\s\S]*?renderAccounts\(\);/);
assert.match(source, /button\.setAttribute\("aria-selected", String\(button\.dataset\.sort === state\.sort\)\)/);
});
test("the token-cache switch is native-looking, persistent and default-on", () => {
const html = read(uiDir, "app.html");
const source = read(uiDir, "app.js");
assert.match(
html,
/<button class="cache-toggle" id="token-cache"[^>]*role="switch"[^>]*aria-checked="true"/,
);
assert.match(html, /data-i18n="includeCache"/);
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/);
const providerSort = source.slice(
source.indexOf("function visibleProviders"),
source.indexOf("function providersOf", source.indexOf("function visibleProviders")),
);
assert.match(providerSort, /V\.sortProviders\(list, state\.sort, state\.includeCache\)/);
assert.doesNotMatch(providerSort, /b\.tokens - a\.tokens/);
});
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, /W = globalThis\.UsageI18n\.get\(lang\)/);
// Nothing is polled: the theme message carries the language.
assert.doesNotMatch(source, /setInterval/);
assert.match(source, /message\.event !== "theme"/);
assert.match(source, /event\.source !== window\.parent/);
assert.match(source, /applyThemeEvent\(message\.data\);/);
assert.match(source, /wanted\.startsWith\("zh"\) \? "zh" : "en"/);
assert.match(source, /getAttribute\("content"\) \|\| "en"/);
});
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",
"account.lastAt",
"model.errors",
]) {
assert.match(source, new RegExp(field.replace(".", "\\.")), field);
}
assert.match(source, /const delay = attempt === 1 \? 1200 : attempt === 2 \? 2500 : 5000;/);
});
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(scope.UsageI18n.get("en").refreshFailed, /previous data/);
});
test("the launcher speaks English and Chinese, not Chinese only", () => {
const html = read(pageDir, "index.html");
const boot = read(pageDir, "boot.js");
assert.match(html, /<html lang="en">/);
assert.match(html, /Account usage/);
assert.match(boot, /lang === "zh" \? "zh-CN" : "en"/);
assert.match(boot, /words\[lang\]/);
});
test("the service keeps the settings endpoint guarded", () => {
const source = readFileSync(join(dir, "lib", "server.mjs"), "utf8");
assert.match(source, /url\.pathname === "\/api\/settings"/);
assert.match(source, /json\(res, 200, displaySettings\(options\)\)/);
});
@@ -0,0 +1,281 @@
import test from "node:test";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { existsSync } from "node:fs";
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 { gatewayCandidates } from "../lib/gateway.mjs";
const execFileAsync = promisify(execFile);
function magpieBinary() {
for (const key of ["MAGPIE_BIN", "MAGPIE_BINARY", "MAGPIE_EXE"]) {
if (process.env[key] && existsSync(process.env[key])) return process.env[key];
}
const names = process.platform === "win32"
? ["magpie", "magpie.exe", "magpie.com", "magpie.cmd"]
: ["magpie"];
for (const directory of String(process.env.PATH || "").split(delimiter).filter(Boolean)) {
for (const name of names) {
const candidate = join(directory, name);
if (existsSync(candidate)) return candidate;
}
}
return "";
}
async function usageSnapshot(gateway) {
const res = await fetch(`${gateway}/v1/magpie/usage?period=7d`);
assert.equal(res.status, 200);
return res.json();
}
function compactNumber(value) {
const match = String(value || "").match(/^(\d+(?:\.\d+)?)([KMB])?$/i);
if (!match) return NaN;
const scale = { K: 1e3, M: 1e6, B: 1e9 }[match[2]?.toUpperCase()] || 1;
return Number(match[1]) * scale;
}
function parseCLIUsage(stdout) {
const lines = stdout.split(/\r?\n/);
const summaryLine = lines.find((line) => /\btokens last\b/.test(line) && /\bcalls?\b/.test(line));
const detailLine = lines.find((line) => /^\s{2}in\s+\S+\s+out\s+\S+/.test(line));
assert.ok(summaryLine, "the CLI printed its usage summary");
assert.ok(detailLine, "the CLI printed its token and error details");
const calls = Number(summaryLine.match(/·\s*(\d+)\s+calls?\b/)?.[1]);
const cost = Number(summaryLine.match(/≈\$([0-9]+(?:\.[0-9]+)?)/)?.[1]);
const input = compactNumber(detailLine.match(/^\s{2}in\s+(\S+)/)?.[1]);
const output = compactNumber(detailLine.match(/\sout\s+(\S+)/)?.[1]);
const errors = Number(detailLine.match(/·\s*(\d+)\s+errors?\b/)?.[1]);
assert.ok(Number.isFinite(calls), "the CLI printed a call count");
assert.ok(Number.isFinite(errors), "the CLI printed an error count");
assert.ok(Number.isFinite(input) && Number.isFinite(output), "the CLI printed input and output");
assert.ok(Number.isFinite(cost), "the CLI printed an estimated cost");
return { calls, errors, tokens: input + output, cost };
}
function modelCallTotals(snapshot) {
const totals = new Map();
for (const item of snapshot.models || []) {
const provider = String(item?.provider || "");
const model = String(item?.model || "");
if (!provider || !model) continue;
const key = `${provider}/${model}`;
totals.set(key, (totals.get(key) || 0) + (Number(item.calls) || 0));
}
return totals;
}
function aggregateModelCallTotals(tree) {
const totals = new Map();
for (const account of tree.accounts) {
for (const model of account.models) {
const key = `${model.provider}/${model.model}`;
totals.set(key, (totals.get(key) || 0) + model.calls);
}
}
return totals;
}
function parseCLIModelCalls(stdout) {
const totals = new Map();
let section = "";
for (const line of stdout.split(/\r?\n/)) {
const heading = line.match(/^\s{2}([a-z][a-z ]*)\s*$/);
if (heading) {
section = heading[1].trim();
continue;
}
if (section !== "models") continue;
const row = line.match(
/^\s{2}([a-z0-9_.-]+)\/([^\s]+)\s+(?:@\s+.*?\s+)?\d+%\s+\S+\s+(\d+)\s+calls?\b/,
);
if (!row) continue;
const key = `${row[1]}/${row[2]}`;
totals.set(key, (totals.get(key) || 0) + Number(row[3]));
}
return totals;
}
function assertBetween(name, value, before, after) {
const low = Math.min(before, after);
const high = Math.max(before, after);
assert.ok(
value >= low && value <= high,
`${name}: ${value} is outside the gateway's concurrent-read range ${low}..${high}`,
);
}
function assertDisplayedNearRange(name, displayed, before, after, relative = 0.015) {
const low = Math.min(before, after);
const high = Math.max(before, after);
const tolerance = Math.max(1, Math.max(Math.abs(low), Math.abs(high)) * relative);
assert.ok(
displayed >= low - tolerance && displayed <= high + tolerance,
`${name}: CLI display ${displayed} is outside the gateway's ${low}..${high} range`,
);
}
function gatewayReachable(gateway) {
return new Promise((resolve) => {
let client;
try {
client = new URL(gateway).protocol === "https:" ? https : http;
} catch {
resolve(false);
return;
}
const req = client.get(
`${gateway}/v1/magpie/usage?period=today`,
{ agent: false, headers: { connection: "close" } },
(res) => {
res.resume();
res.on("end", () => resolve(res.statusCode >= 200 && res.statusCode < 300));
res.on("error", () => resolve(false));
},
);
req.on("error", () => resolve(false));
req.setTimeout(1200, () => {
req.destroy();
resolve(false);
});
});
}
// 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) => {
const binary = magpieBinary();
const gateway = gatewayCandidates()[0];
if (!binary) {
t.skip("magpie CLI is not available");
return;
}
if (!(await gatewayReachable(gateway))) {
t.skip("magpie gateway is not available");
return;
}
// The ledger can receive a call while the CLI runs. Take a snapshot on
// either side of the CLI read: a call made during the test must be in the
// inclusive range, while a real accounting difference still fails.
const before = await usageSnapshot(gateway);
const { stdout } = await execFileAsync(binary, ["usage", "7d"], {
encoding: "utf8",
maxBuffer: 64 * 1024 * 1024,
});
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
// table, not just the Accounts table below it.
assertBetween("summary.calls", mine.summary.calls, before.calls, after.calls);
assertBetween("summary.errors", mine.summary.errors, before.errors, after.errors);
assertBetween("summary.tokens", mine.summary.tokens, before.input + before.output, after.input + after.output);
assertBetween("summary.cost", mine.summary.cost, before.cost, after.cost);
assertBetween("CLI calls", cli.calls, before.calls, after.calls);
assertBetween("CLI errors", cli.errors, before.errors, after.errors);
assertDisplayedNearRange(
"CLI tokens",
cli.tokens,
before.input + before.output,
after.input + after.output,
);
assertDisplayedNearRange("CLI cost", cli.cost, before.cost, after.cost);
const cliModels = parseCLIModelCalls(stdout);
const beforeModels = modelCallTotals(before);
const afterModels = modelCallTotals(after);
const mineModels = aggregateModelCallTotals(mine);
assert.ok(cliModels.size > 0, "the CLI printed a models table");
for (const [key, calls] of cliModels) {
assertBetween(
`CLI model ${key}`,
calls,
beforeModels.get(key) || 0,
afterModels.get(key) || 0,
);
assertBetween(
`aggregated model ${key}`,
mineModels.get(key) || 0,
beforeModels.get(key) || 0,
afterModels.get(key) || 0,
);
}
const cliAccounts = new Map();
let section = "";
for (const line of stdout.split(/\r?\n/)) {
const heading = line.match(/^\s{2}([a-z][a-z ]*)\s*$/);
if (heading) {
section = heading[1].trim();
continue;
}
if (section !== "accounts") continue;
const row = line.match(/^\s{2}(\S+)\s+\/\s+(.*?)\s{2,}(\d+)%\s+(\S+)\s+(\d+)\s+calls?/);
if (row) cliAccounts.set(`${row[1]}@${row[2].trim()}`, Number(row[5]));
}
// The CLI prints each account's display name, while the gateway keeps
// both that name and the sign-in id. Compare display names, and leave out
// API-key-only providers: depending on the magpie version, its accounts
// table either hides them or labels them differently.
const apiKeyProviders = new Set();
const regularProviders = new Set();
for (const account of [...(before.accounts || []), ...(after.accounts || [])]) {
if (
account.account === "API key" ||
account.access === "key" ||
account.access === "api-key"
) {
apiKeyProviders.add(account.provider);
}
else regularProviders.add(account.provider);
}
const ignoredProviders = new Set(
[...apiKeyProviders].filter((provider) => !regularProviders.has(provider)),
);
const gatewayAccounts = new Map();
for (const [snapshot, label] of [[before, "before"], [after, "after"]]) {
for (const account of snapshot.accounts || []) {
if (account.account === "API key" || account.access === "key") continue;
const key = `${account.provider}@${account.name || account.account}`;
const row = gatewayAccounts.get(key) || { before: Infinity, after: -Infinity };
const calls = Number(account.calls) || 0;
if (label === "before") row.before = Math.min(row.before, calls);
else row.after = Math.max(row.after, calls);
gatewayAccounts.set(key, row);
}
}
const cliRegularAccounts = new Map(
[...cliAccounts].filter(([key]) => !ignoredProviders.has(key.split("@")[0])),
);
assert.ok(cliRegularAccounts.size > 0, "the CLI printed an accounts table");
assert.ok(gatewayAccounts.size > 0, "the gateway answered with account rows");
assert.deepEqual([...gatewayAccounts.keys()].sort(), [...cliRegularAccounts.keys()].sort());
for (const [key, calls] of cliRegularAccounts) {
const range = gatewayAccounts.get(key);
assert.ok(range, `the gateway has ${key}`);
assert.ok(
calls >= range.before && calls <= range.after,
`${key}: CLI ${calls} is outside the gateway's concurrent-read range ${range.before}..${range.after}`,
);
}
// The aggregation's account rows use the same calls the gateway reports.
for (const account of mine.accounts) {
if (account.kind === "api-key") continue;
const range = gatewayAccounts.get(`${account.provider}@${account.alias || account.account}`);
assert.ok(range, `the aggregation has ${account.provider}/${account.account}`);
assert.ok(account.calls >= range.before && account.calls <= range.after);
}
});
@@ -0,0 +1,136 @@
import test from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { startServer } from "../lib/server.mjs";
const data = {
period: "7d",
generatedAt: "2026-10-31T00:00:00.000Z",
summary: { accounts: 0, calls: 0, tokens: 0 },
accounts: [],
warnings: [],
};
// Several loopback servers run in this file. On Windows the HTTP client can
// still be retiring a reused socket as the next test finishes; keep them
// serial so one server's teardown cannot overlap another's.
test("the page's service routes", { concurrency: false }, async (t) => {
await t.test("serves a token-protected account tree", async (t) => {
const info = await startServer({
port: 0,
load: async () => data,
});
t.after(async () => {
await info.close();
});
const html = await fetch(`http://127.0.0.1:${info.port}/`);
assert.equal(html.status, 200);
const htmlBody = await html.text();
assert.match(htmlBody, /meta name="usage-tree-token"/);
assert.match(htmlBody, /<main class="view">/);
assert.match(htmlBody, /usage-tree-currency" content="usd"/);
const configured = await fetch(
`http://127.0.0.1:${info.port}/?lang=zh&theme=dark&currency=cny&chineseUnits=1&usdCny=7.2`,
);
assert.equal(configured.status, 200);
const configuredBody = await configured.text();
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"/);
const denied = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`);
assert.equal(denied.status, 401);
const allowed = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, {
headers: { "x-usage-tree-token": info.token },
});
assert.equal(allowed.status, 200);
const jsonBody = await allowed.json();
assert.deepEqual(jsonBody, data);
});
await t.test("answers the preflight for both page APIs", async (t) => {
const info = await startServer({
port: 0,
load: async () => data,
});
t.after(async () => {
await info.close();
});
for (const path of ["/api/tree", "/api/settings"]) {
const res = await fetch(`http://127.0.0.1:${info.port}${path}`, {
method: "OPTIONS",
headers: {
Origin: "null",
"Access-Control-Request-Headers": "x-usage-tree-token",
},
});
assert.equal(res.status, 204, `${path} preflight`);
assert.equal(res.headers.get("access-control-allow-origin"), "null");
assert.match(res.headers.get("access-control-allow-headers"), /token/);
}
});
await t.test("a failed fresh read keeps the old answer marked stale", async (t) => {
let calls = 0;
const info = await startServer({
port: 0,
load: async (_period, options) => {
calls += 1;
if (options.fresh) 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 first = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d`, {
headers: { "x-usage-tree-token": token },
});
assert.equal(first.status, 200);
const fresh = await fetch(`http://127.0.0.1:${info.port}/api/tree?period=7d&fresh=1`, {
headers: { "x-usage-tree-token": token },
});
const body = await fresh.json();
assert.equal(fresh.status, 200);
assert.equal(fresh.headers.get("x-usage-tree-cache"), "stale");
assert.equal(body.stale, true);
assert.equal(body.revision, 1);
});
await t.test("rejects a non-loopback host", async (t) => {
const info = await startServer({
port: 0,
load: async () => data,
});
const status = await new Promise((resolve, reject) => {
const req = http.request(
{
host: "127.0.0.1",
port: info.port,
path: "/healthz",
headers: { Host: `example.com:${info.port}` },
},
(res) => {
res.resume();
resolve(res.statusCode);
},
);
req.on("error", reject);
req.end();
});
assert.equal(status, 403);
await new Promise((resolve) => setTimeout(resolve, 20));
await info.close();
});
});
@@ -0,0 +1,222 @@
import test from "node:test";
import assert from "node:assert/strict";
import { accountKey, aggregateGatewayUsage, PERIODS } from "../lib/usage.mjs";
import { cacheUsable } from "../lib/data.mjs";
const usage = {
period: "today",
calls: 5,
errors: 1,
input: 1000,
output: 100,
cache_read: 500,
cache_write: 0,
reasoning: 10,
cost: 0.5,
unpriced: 2,
accounts: [
{
id: "codex@alice",
provider: "codex",
account: "alice@example.com",
name: "10月学生Plus",
sub: "Codex",
calls: 3,
errors: 1,
input: 800,
output: 50,
cache_read: 500,
cost: 0.5,
unpriced: 0,
},
{
id: "codex@bob",
provider: "codex",
account: "bob@example.com",
name: "bob@example.com",
sub: "Codex",
last_at: "2026-11-04T12:00:00.000Z",
calls: 2,
errors: 0,
input: 200,
output: 50,
cost: 0,
unpriced: 2,
},
],
};
const requests = {
[accountKey("codex", "alice@example.com")]: {
by: {
modelAt: [
{
id: "codex/gpt-a",
calls: 3,
errors: 1,
input: 800,
output: 50,
cache_read: 500,
cost: 0.5,
unpriced: 0,
},
],
},
},
[accountKey("codex", "bob@example.com")]: {
by: {
modelAt: [
{
id: "codex/gpt-b",
calls: 2,
errors: 0,
input: 200,
output: 50,
cost: 0,
unpriced: 2,
},
],
},
},
};
test("builds provider, account and model from the gateway's own totals", () => {
const data = aggregateGatewayUsage(usage, requests, { period: "today" });
assert.deepEqual([...PERIODS].sort(), ["30d", "7d", "all", "today"]);
assert.equal(data.summary.calls, 5);
assert.equal(data.summary.errors, 1);
assert.equal(data.summary.tokens, 1100);
assert.equal(data.summary.cache, 500);
assert.equal(data.summary.cost, 0.5);
assert.equal(data.summary.unpriced, 2);
assert.equal(data.summary.accounts, 2);
assert.equal(data.summary.providers, 1);
assert.equal(data.summary.models, 2);
assert.equal(data.providers.length, 1);
assert.equal(data.providers[0].providerName, "Codex");
assert.equal(data.providers[0].accounts.length, 2);
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.models.length, 1);
assert.equal(alice.models[0].model, "gpt-a");
assert.equal(alice.models[0].errors, 1);
const bob = data.accounts.find((account) => account.account === "bob@example.com");
assert.equal(bob.lastAt, "2026-11-04T12:00:00.000Z");
});
test("API-key calls are a marked group, never an account", () => {
const keyed = {
...usage,
accounts: [
...usage.accounts,
{
id: "anthropic@API key",
provider: "anthropic",
account: "API key",
access: "key",
sub: "Anthropic",
calls: 1,
errors: 0,
input: 10,
output: 1,
},
],
};
const data = aggregateGatewayUsage(keyed, requests, { period: "today" });
assert.equal(data.summary.accounts, 2);
assert.equal(data.summary.apiKeyGroups, 1);
const group = data.accounts.find((account) => account.kind === "api-key");
assert.ok(group);
assert.equal(group.account, "API key");
});
test("one account's model rows merge even when the gateway splits them by host", () => {
const split = {
period: "today",
calls: 3,
errors: 1,
input: 30,
output: 6,
cache_read: 12,
cache_write: 3,
cost: 0.3,
unpriced: 0,
accounts: [
{
provider: "codex",
account: "alice@example.com",
name: "Alice",
calls: 3,
errors: 1,
input: 30,
output: 6,
cache_read: 12,
cache_write: 3,
cost: 0.3,
unpriced: 0,
},
],
models: [
{
provider: "codex",
model: "gpt-6",
host: "alice@example.com",
calls: 2,
errors: 1,
input: 20,
output: 4,
cache_read: 8,
cache_write: 2,
cost: 0.2,
last_at: "2026-11-04T10:00:00.000Z",
},
{
provider: "codex",
model: "gpt-6",
host: "Alice",
calls: 1,
errors: 0,
input: 10,
output: 2,
cache_read: 4,
cache_write: 1,
cost: 0.1,
last_at: "2026-11-04T12:00:00.000Z",
},
],
};
const data = aggregateGatewayUsage(split, {}, { period: "today" });
const account = data.accounts[0];
assert.equal(data.summary.models, 1);
assert.equal(account.models.length, 1);
assert.equal(account.models[0].model, "gpt-6");
assert.equal(account.models[0].id, "codex\u001falice@example.com\u001fcodex\u001fgpt-6");
assert.equal(account.models[0].calls, 3);
assert.equal(account.models[0].errors, 1);
assert.equal(account.models[0].tokens, 36);
assert.equal(account.models[0].cache, 15);
assert.equal(Number(account.models[0].cost.toFixed(6)), 0.3);
assert.equal(account.models[0].lastAt, "2026-11-04T12:00:00.000Z");
assert.deepEqual(account.models[0].hostNotes, [
{ account: "alice@example.com", calls: 2 },
{ account: "Alice", calls: 1 },
]);
});
test("an empty gateway answer is an empty tree with a note", () => {
const data = aggregateGatewayUsage({ calls: 0, accounts: [] }, {}, { period: "7d" });
assert.deepEqual(data.providers, []);
assert.deepEqual(data.accounts, []);
assert.deepEqual(data.warnings, [{ code: "no-usage" }]);
});
test("a read from before the three-level shape is not served as current", () => {
assert.equal(cacheUsable({ summary: {}, accounts: [{ id: "a" }] }), false);
assert.equal(cacheUsable({ summary: {}, providers: [], accounts: [] }), true);
assert.equal(cacheUsable(null), false);
});
+92
View File
@@ -0,0 +1,92 @@
<!doctype html>
<html lang="__USAGE_TREE_LANG__">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="usage-tree-token" content="__USAGE_TREE_TOKEN__">
<meta name="usage-tree-theme" content="__USAGE_TREE_THEME__">
<meta name="usage-tree-lang" content="__USAGE_TREE_LANG__">
<meta name="usage-tree-tokens" content="__USAGE_TREE_TOKENS__">
<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__">
<title>__USAGE_TREE_TITLE__</title>
<link rel="icon" href="icon.svg" type="image/svg+xml">
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="view">
<header class="head">
<div class="head-text">
<h1 data-i18n="title">Account usage</h1>
<p data-i18n="subtitle">Start with each account, then expand it to see the models it used</p>
</div>
<div class="head-tools">
<div class="segs" id="period" role="group">
<button type="button" data-period="today" data-i18n-period="today"></button>
<button type="button" data-period="7d" data-i18n-period="7d"></button>
<button type="button" data-period="30d" data-i18n-period="30d"></button>
<button type="button" data-period="all" data-i18n-period="all"></button>
</div>
<button class="cache-toggle" id="token-cache" type="button" role="switch" aria-checked="true">
<span class="switch" aria-hidden="true"><i></i></span>
<span data-i18n="includeCache"></span>
</button>
<button class="icon" id="refresh" type="button">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1.02 6.74 2.74L21 8"/>
<path d="M21 3v5h-5"/>
</svg>
</button>
</div>
</header>
<div class="progress" id="progress" role="progressbar" aria-hidden="true" hidden></div>
<section class="stats" id="summary" aria-live="polite"></section>
<section class="panel" aria-labelledby="ledger-title">
<div class="panel-head">
<h2 id="ledger-title" data-i18n="detail">Account details</h2>
<div class="tools">
<label class="search">
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="m16 16 4 4"/></svg>
<input id="search" type="search" autocomplete="off">
</label>
<div class="sort" id="sort" role="group" aria-label="Sort">
<span data-i18n="sort">Sort</span>
<button type="button" class="sort-button" data-sort="tokens" data-i18n-sort="tokens"></button>
<button type="button" class="sort-button" data-sort="cost" data-i18n-sort="cost"></button>
<button type="button" class="sort-button" data-sort="calls" data-i18n-sort="calls"></button>
<button type="button" class="sort-button" data-sort="name" data-i18n-sort="name"></button>
</div>
<button class="text" id="expand-all" type="button"></button>
</div>
</div>
<div class="warn" id="warning" hidden></div>
<div class="cols" aria-hidden="true">
<span class="col-name" data-i18n-column="identity"></span>
<span data-i18n-column="calls"></span>
<span class="col-tokens" data-i18n-column="tokens"></span>
<span class="col-share"></span>
<span class="col-share-label" data-i18n-column="share"></span>
<span class="col-cost" data-i18n-column="cost"></span>
<span class="col-status" data-i18n-column="status"></span>
<span></span>
</div>
<div class="accounts" id="accounts" aria-live="polite"></div>
<div class="state" id="state-card" hidden></div>
</section>
<footer class="foot">
<span id="source-note"></span>
<span id="updated"></span>
</footer>
</main>
<script src="i18n.js"></script>
<script src="view.js"></script>
<script src="app.js"></script>
</body>
</html>
+959
View File
@@ -0,0 +1,959 @@
(() => {
const V = globalThis.UsageView;
let W = globalThis.UsageI18n.get(metaLang());
// A plugin page runs in a sandboxed frame, whose origin is opaque: even
// reading localStorage throws there. Fall back to memory so the page
// still works, only without remembering the last filters.
const store = (() => {
const memory = new Map();
return {
get(key) {
try {
return localStorage.getItem(key);
} catch {
return memory.has(key) ? memory.get(key) : null;
}
},
set(key, value) {
try {
localStorage.setItem(key, value);
} catch {
memory.set(key, String(value));
}
},
};
})();
const meta = (name) =>
document.querySelector(`meta[name="usage-tree-${name}"]`)?.getAttribute("content") || "";
const token = meta("token");
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";
V.setLang(lang);
V.setChineseUnits(chineseUnits && lang === "zh");
const saved = {
period: store.get("usage-tree.period") || "today",
sort: store.get("usage-tree.sort") || "tokens",
includeCache: store.get("usage-tree.include-cache") !== "0",
expanded: readSet("usage-tree.expanded"),
};
const validPeriods = new Set(["today", "7d", "30d", "all"]);
const validSorts = new Set(["tokens", "cost", "calls", "name"]);
const state = {
period: validPeriods.has(saved.period) ? saved.period : "today",
sort: validSorts.has(saved.sort) ? saved.sort : "tokens",
includeCache: saved.includeCache,
expanded: saved.expanded,
openProviders: readSet("usage-tree.providers"),
query: "",
data: null,
loading: false,
error: "",
loadedAt: 0,
requestId: 0,
controller: null,
previewFirst: new URLSearchParams(location.search).get("preview") === "first",
};
const $ = (id) => document.getElementById(id);
const summary = $("summary");
const accounts = $("accounts");
const stateCard = $("state-card");
const warning = $("warning");
const refresh = $("refresh");
const progress = $("progress");
const expandAll = $("expand-all");
function metaLang() {
return document.querySelector('meta[name="usage-tree-lang"]')?.getAttribute("content") || "en";
}
function applyI18n() {
document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
document.title = W.title;
for (const node of document.querySelectorAll("[data-i18n]")) node.textContent = W[node.dataset.i18n];
for (const node of document.querySelectorAll("[data-i18n-period]")) node.textContent = W.periods[node.dataset.i18nPeriod];
for (const node of document.querySelectorAll("[data-i18n-sort]")) node.textContent = W.sortBy[node.dataset.i18nSort];
for (const node of document.querySelectorAll("[data-i18n-column]")) node.textContent = W.columns[node.dataset.i18nColumn];
$("search").placeholder = W.search;
$("period").setAttribute("aria-label", W.period);
$("token-cache").title = W.includeCacheHint;
$("token-cache").setAttribute("aria-checked", String(state.includeCache));
$("sort").setAttribute("aria-label", W.sort);
$("refresh").setAttribute("aria-label", W.refresh);
$("refresh").title = W.refresh;
updateExpandLabel();
$("source-note").textContent = W.source;
}
// Magpie tells every open plugin page when its language, theme or
// colours change. The page takes the words of the new language at
// once, without a reload.
function applyThemeEvent(data) {
if (!data) return;
if (data.tokens && typeof data.tokens === "object") {
for (const [key, value] of Object.entries(data.tokens)) {
if (typeof value === "string") {
document.documentElement.style.setProperty(`--magpie-${key}`, value);
}
}
}
if (typeof data.dark === "boolean") {
document.documentElement.dataset.theme = data.dark ? "dark" : "light";
}
if (typeof data.lang === "string") applyDisplay({ lang: data.lang });
}
window.addEventListener("message", (event) => {
const message = event.data;
if (!message || message.magpie !== 1 || message.event !== "theme") return;
// 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.
});
// What the window sends lands here: the page redraws in place, without a
// reload.
function applyDisplay(display) {
if (!display) return false;
let changed = false;
const wanted = String(display.lang || "").toLowerCase();
// "system" means the window follows the OS: the window's own message
// says which language that is, and this keeps the last one.
if (wanted && wanted !== "system") {
const nextLang = wanted.startsWith("zh") ? "zh" : "en";
if (nextLang !== lang) {
lang = nextLang;
W = globalThis.UsageI18n.get(lang);
V.setLang(lang);
V.setChineseUnits(chineseUnits && lang === "zh");
changed = true;
}
}
if (typeof display.currency === "string") {
const nextCurrency = display.currency === "cny" ? "cny" : "usd";
if (nextCurrency !== currency) {
currency = nextCurrency;
changed = true;
}
}
if (Number.isFinite(Number(display.usdCny))) {
const nextRate = Number(display.usdCny);
if (nextRate !== usdCny) {
usdCny = nextRate;
changed = true;
}
}
if (typeof display.chineseUnits === "boolean") {
const nextUnits = display.chineseUnits === true;
if (nextUnits !== chineseUnits) {
chineseUnits = nextUnits;
V.setChineseUnits(chineseUnits && lang === "zh");
changed = true;
}
}
const nextTheme = display.theme === "dark" || display.theme === "light" ? display.theme : "";
if (nextTheme && nextTheme !== document.documentElement.dataset.theme) {
document.documentElement.dataset.theme = nextTheme;
changed = true;
}
if (changed) {
applyI18n();
if (state.data) render();
else applyTheme();
}
return changed;
}
applyI18n();
applyTheme();
buildSummarySkeleton();
bind();
load();
function readSet(key) {
try {
const value = JSON.parse(store.get(key) || "[]");
return new Set(Array.isArray(value) ? value.map(String) : []);
} catch {
return new Set();
}
}
function saveSet() {
store.set("usage-tree.expanded", JSON.stringify([...state.expanded]));
store.set("usage-tree.providers", JSON.stringify([...state.openProviders]));
}
function applyTheme() {
document.documentElement.dataset.theme = theme;
try {
const tokens = JSON.parse(meta("tokens") || "{}");
for (const [key, value] of Object.entries(tokens)) {
if (typeof value === "string") {
document.documentElement.style.setProperty(`--magpie-${key}`, value);
}
}
} catch {
// Theme tokens are optional.
}
}
function bind() {
$("period").addEventListener("click", (event) => {
const value = event.target.closest("button")?.dataset.period;
if (!value || value === state.period) return;
state.period = value;
state.stalePolls = 0;
store.set("usage-tree.period", value);
renderPeriod();
load({ force: true });
});
$("sort").addEventListener("click", (event) => {
const value = event.target.closest("[data-sort]")?.dataset.sort;
if (!value) return;
state.sort = validSorts.has(value) ? value : "tokens";
store.set("usage-tree.sort", state.sort);
renderPeriod();
renderAccounts();
});
$("token-cache").addEventListener("click", () => {
state.includeCache = !state.includeCache;
store.set("usage-tree.include-cache", state.includeCache ? "1" : "0");
if (state.data) render();
else buildSummarySkeleton();
});
$("search").addEventListener("input", (event) => {
state.query = event.target.value.trim().toLowerCase();
renderAccounts();
});
expandAll.addEventListener("click", () => {
const providers = visibleProviders();
const accounts = providers.flatMap((provider) => V.visibleAccounts(provider, state.query));
const allOpen =
providers.length > 0 &&
providers.every((provider) => state.openProviders.has(provider.id)) &&
accounts.every((account) => state.expanded.has(account.id));
for (const provider of providers) {
if (allOpen) state.openProviders.delete(provider.id);
else state.openProviders.add(provider.id);
}
for (const account of accounts) {
if (allOpen) state.expanded.delete(account.id);
else state.expanded.add(account.id);
}
saveSet();
renderAccounts();
});
refresh.addEventListener("click", () => {
state.stalePolls = 0;
load({ force: true });
});
window.addEventListener("focus", () => {
if (Date.now() - state.loadedAt > 60_000) load();
});
}
function renderPeriod() {
for (const button of $("period").querySelectorAll("button")) {
button.setAttribute("aria-selected", String(button.dataset.period === state.period));
}
for (const button of $("sort").querySelectorAll("[data-sort]")) {
button.setAttribute("aria-selected", String(button.dataset.sort === state.sort));
}
$("token-cache").setAttribute("aria-checked", String(state.includeCache));
expandAll.textContent = allExpanded() ? W.collapse : W.expand;
}
async function load(options = {}) {
const requestedPeriod = state.period;
const requestId = ++state.requestId;
if (state.controller) state.controller.abort();
clearTimeout(state.spinTimer);
clearTimeout(state.staleTimer);
state.controller = new AbortController();
state.loading = true;
state.error = "";
const spinStarted = Date.now();
if (!options.quiet) {
refresh.classList.add("busy");
refresh.disabled = true;
progress.hidden = false;
progress.setAttribute("aria-hidden", "false");
}
warning.hidden = true;
if (!state.data) {
stateCard.hidden = true;
accounts.hidden = true;
buildSummarySkeleton();
}
try {
const fresh = options.force ? "&fresh=1" : "";
const endpoint = new URL(`api/tree?period=${encodeURIComponent(requestedPeriod)}${fresh}`, location.href);
const res = await fetch(endpoint.href, {
headers: { "x-usage-tree-token": token },
cache: "no-store",
signal: AbortSignal.any([
state.controller.signal,
AbortSignal.timeout(10000),
]),
});
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;
const next = fingerprint(body);
const changed = next !== state.fingerprint || !state.rendered;
state.data = body;
state.fingerprint = next;
state.loadedAt = Date.now();
// The service answers with the numbers it had and reads again behind
// the page; ask for them again in a moment, so the page catches up
// without the reader asking.
if (body.stale) {
const attempt = state.stalePolls = (state.stalePolls || 0) + 1;
if (attempt <= 3) {
clearTimeout(state.staleTimer);
const delay = attempt === 1 ? 1200 : attempt === 2 ? 2500 : 5000;
state.staleTimer = setTimeout(() => {
if (!document.hidden && requestedPeriod === state.period) load({ quiet: true });
}, delay);
}
} else {
state.stalePolls = 0;
}
if (state.previewFirst && state.data.accounts?.length && !store.get("usage-tree.expanded")) {
state.expanded.add(state.data.accounts[0].id);
}
if (changed) {
state.rendered = true;
render();
} else {
renderFoot();
}
} catch (error) {
if (requestId !== state.requestId || error?.name === "AbortError") return;
state.error = `${error?.name || "Error"}: ${error?.message || W.readFailed}`;
if (state.data?.period === requestedPeriod) {
warning.hidden = false;
warning.textContent = W.refreshFailed;
renderFoot();
return;
}
renderError();
} finally {
if (requestId !== state.requestId) 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;
state.loading = false;
state.controller = null;
refresh.classList.remove("busy");
refresh.disabled = false;
progress.hidden = true;
progress.setAttribute("aria-hidden", "true");
};
if (options.quiet) {
settle();
} else if (elapsed >= 450) {
settle();
} else {
state.spinTimer = setTimeout(settle, 450 - elapsed);
}
}
}
setTimeout(() => {
if (!state.data && state.loading) {
clearTimeout(state.spinTimer);
state.error = W.serviceTimeout;
renderError();
state.loading = false;
refresh.classList.remove("busy");
refresh.disabled = false;
progress.hidden = true;
progress.setAttribute("aria-hidden", "true");
}
}, 10500);
// 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 parts = [
data?.period,
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),
];
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),
);
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,
);
for (const model of account.models || []) {
parts.push(
model.id,
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 || []),
);
}
}
}
return parts.join("|");
}
// The foot names when the numbers are from; the rows stay as they are.
function renderFoot() {
const data = state.data;
if (!data) return;
const source = data.source || "Magpie gateway usage";
$("source-note").textContent = `${W.source} · ${source}`;
$("updated").textContent = data.generatedAt
? `${W.updated} ${new Date(data.generatedAt).toLocaleTimeString(lang === "en" ? "en-US" : "zh-CN", { hour: "2-digit", minute: "2-digit" })}`
: "";
}
function buildSummarySkeleton() {
summary.replaceChildren(
...[W.accounts, W.calls, state.includeCache ? W.tokensWithCache : W.tokensWithoutCache, W.cost].map((label) => {
const card = el("article", "summary-card loading");
const head = el("div", "summary-label");
head.append(icon("dot"), document.createTextNode(label));
card.append(
head,
el("div", "summary-value", "—"),
el("span", "summary-sub", W.firstRead),
);
return card;
}),
);
}
function render() {
const data = state.data;
if (!data) return;
renderPeriod();
renderSummary(data.summary || {});
renderWarnings(data.warnings || []);
renderAccounts();
renderFoot();
}
function renderSummary(data) {
// A read from before the three-level shape has no provider count; the
// rows still know their providers, so count those.
const summaryData = { ...data, providers: data.providers ?? providersOf(state.data).length };
const items = V.tiles(summaryData, lang, currency, usdCny, state.includeCache).map((tile, index) => ({
...tile,
icon: ["accounts", "calls", "tokens", "cost"][index],
}));
summary.replaceChildren(
...items.map((item) => {
const card = el("article", "summary-card");
const head = el("div", "summary-label");
head.append(icon(item.icon), document.createTextNode(item.label));
const value = el("div", "summary-value", item.value);
if (item.bad) value.style.color = "var(--magpie-red)";
card.append(head, value, el("span", "summary-sub", item.sub));
return card;
}),
);
}
function renderWarnings(warnings) {
if (!warnings.length) {
warning.hidden = true;
return;
}
warning.hidden = false;
warning.textContent = warnings
.map((item) => {
if (typeof item === "string") return item;
if (item.code === "no-usage") return W.noUsage;
return "";
})
.filter(Boolean)
.join(" ");
}
function renderError() {
state.rendered = false;
summary.replaceChildren();
accounts.replaceChildren();
accounts.hidden = true;
stateCard.hidden = false;
stateCard.replaceChildren();
const strong = el("strong", "", W.noData);
const button = el("button", "", W.reload);
button.type = "button";
button.addEventListener("click", () => load({ force: true }));
stateCard.append(strong, document.createTextNode(state.error), button);
}
function visibleAccounts() {
return visibleProviders()
.flatMap((provider) => V.visibleAccounts(provider, state.query));
}
function visibleProviders() {
const list = [...providersOf(state.data)];
const query = state.query;
if (query) {
list.splice(0, list.length, ...list.filter(
(provider) => V.visibleAccounts(provider, query).length > 0,
));
}
return V.sortProviders(list, state.sort, state.includeCache);
}
// What the list draws: the providers the service sent. A read written
// before the three-level shape existed has none, so its accounts are
// grouped here rather than shown as "no usage".
function providersOf(data) {
if (Array.isArray(data?.providers) && data.providers.length) return data.providers;
const accounts = data?.accounts || [];
if (!accounts.length) return [];
const byProvider = new Map();
for (const account of accounts) {
let provider = byProvider.get(account.provider);
if (!provider) {
provider = {
id: account.provider,
provider: account.provider,
providerName: account.providerName,
accounts: [],
calls: 0,
tokens: 0,
cache: 0,
allTokens: 0,
cost: 0,
errors: 0,
unpriced: 0,
};
byProvider.set(account.provider, provider);
}
provider.accounts.push(account);
provider.calls += account.calls || 0;
provider.tokens += account.tokens || 0;
provider.cache += account.cache || 0;
provider.allTokens +=
Number(account.allTokens) || (Number(account.tokens) || 0) + (Number(account.cache) || 0);
provider.cost += account.cost || 0;
provider.errors += account.errors || 0;
provider.unpriced += account.unpriced || 0;
}
return [...byProvider.values()];
}
function renderAccounts() {
if (!state.data) return;
const list = visibleProviders();
accounts.hidden = false;
stateCard.hidden = true;
if (!list.length) {
accounts.hidden = true;
stateCard.hidden = false;
stateCard.replaceChildren(
el("strong", "", state.query ? W.noMatch : W.noCalls),
document.createTextNode(
state.query
? W.noMatchHint
: W.noCallsHint,
),
);
updateExpandLabel();
return;
}
accounts.replaceChildren(...list.map((provider, index) => providerCard(provider, index)));
updateExpandLabel();
}
function providerCard(provider, index) {
const shownAccounts = V.visibleAccounts(provider, state.query);
const article = el("section", "provider" + (state.openProviders.has(provider.id) ? " open" : ""));
article.dataset.id = provider.id;
article.style.animationDelay = `${Math.min(index, 8) * 30}ms`;
const main = el("button", "provider-main");
main.type = "button";
main.setAttribute("aria-expanded", String(state.openProviders.has(provider.id)));
const identity = el("div", "identity");
const badge = el("span", "provider-badge", shortProvider(provider.provider));
const identityText = el("div", "identity-text");
const name = el("div", "level-name", provider.providerName);
identityText.append(
name,
el("div", "level-sub", W.accountsAndModels(
shownAccounts.filter((account) => account.kind !== "api-key").length,
countModels(shownAccounts),
)),
);
identity.append(badge, identityText);
const calls = metric("", compact(provider.calls), "", "calls-cell");
const all = providersOf(state.data);
const total = totalForSort(all);
const share = shareCell(provider, total, all);
const cost = metric(
"",
money(provider.cost, provider.unpriced, provider.calls),
"",
"cost-cell" + (provider.unpriced ? " unpriced" : ""),
);
const errors = metric(
"",
provider.errors ? `${provider.errors} ${W.failed}` : W.allOk,
V.errorRate(provider.errors, provider.calls),
"errors-cell" + (provider.errors ? " bad" : ""),
);
const chevron = el("span", "chevron");
chevron.append(icon("chevron"));
main.append(identity, calls, ...share, cost, errors, chevron);
main.addEventListener("click", () => {
if (state.openProviders.has(provider.id)) state.openProviders.delete(provider.id);
else state.openProviders.add(provider.id);
saveSet();
article.classList.toggle("open", state.openProviders.has(provider.id));
main.setAttribute("aria-expanded", String(state.openProviders.has(provider.id)));
updateExpandLabel();
});
const accountBox = el("div", "provider-accounts");
const accounts = [...shownAccounts].sort(compareItems);
for (const account of accounts) {
accountBox.append(accountCard(account, provider.accounts));
}
article.append(main, accountBox);
return article;
}
function compareItems(a, b) {
if (state.sort === "name") {
return (a.alias || a.account || a.model).localeCompare(b.alias || b.account || b.model);
}
return sortMetric(b) - sortMetric(a) || (a.alias || a.account || a.model).localeCompare(b.alias || b.account || b.model);
}
function countModels(accounts) {
return accounts.reduce((sum, account) => sum + account.models.length, 0);
}
function accountCard(account, siblings) {
const article = el("article", "account" + (state.expanded.has(account.id) ? " open" : ""));
article.dataset.id = account.id;
const main = el("button", "account-main");
main.type = "button";
main.setAttribute("aria-expanded", String(state.expanded.has(account.id)));
const identity = el("div", "identity");
const badge = el("span", "provider-badge", shortProvider(account.provider));
const identityText = el("div", "identity-text");
const name = el("div", "level-name", account.alias || account.account);
name.title = account.account;
const sub = el("div", "level-sub");
// The provider is the row above, so the account says what is its own:
// the raw sign-in when the reader named it, how many models, when last.
const subParts = [
account.alias ? account.account : "",
account.kind === "api-key" ? W.apiKeyNote : "",
W.modelsOnly(account.models.length),
account.lastAt ? lastSeen(account.lastAt) : "",
].filter(Boolean);
subParts.forEach((part, index) => {
if (index) sub.append(el("i"));
sub.append(document.createTextNode(part));
});
identityText.append(name, sub);
identity.append(badge, identityText);
const calls = metric("", compact(account.calls), "", "calls-cell");
const share = shareCell(account, totalForSort(siblings), siblings);
const cost = metric(
"",
money(account.cost, account.unpriced, account.calls),
account.unpriced ? W.unpricedCalls(compact(account.unpriced)) : "",
"cost-cell" + (account.unpriced ? " unpriced" : ""),
);
const errors = metric(
"",
account.errors ? `${account.errors} ${W.failed}` : W.allOk,
V.errorRate(account.errors, account.calls),
"errors-cell" + (account.errors ? " bad" : ""),
);
const chevron = el("span", "chevron");
chevron.append(icon("chevron"));
main.append(identity, calls, ...share, cost, errors, chevron);
main.addEventListener("click", () => {
if (state.expanded.has(account.id)) state.expanded.delete(account.id);
else state.expanded.add(account.id);
saveSet();
article.classList.toggle("open", state.expanded.has(account.id));
main.setAttribute("aria-expanded", String(state.expanded.has(account.id)));
updateExpandLabel();
});
article.append(main, modelList(account));
return article;
}
function modelList(account) {
const box = el("div", "model-list");
const head = el("div", "model-head");
// The row has seven columns: model, calls, tokens, bar, share, cost and
// the chevron-aligned end. Keep the header on the same grid.
head.append(
el("span", "", W.model),
el("span", "", W.calls),
el("span", "", state.includeCache ? W.modelTokensWithCache : W.modelTokensWithoutCache),
el("span", "", ""),
el("span", "", W.columns.share),
el("span", "", W.cost),
el("span", "", ""),
);
box.append(head);
const query = state.query;
const models = account.models.filter(
(model) =>
!query ||
V.accountSelfMatches(account, query) ||
V.modelMatches(model, query),
);
models.sort((a, b) => {
if (state.sort === "name") return a.model.localeCompare(b.model);
return sortMetric(b) - sortMetric(a) || a.model.localeCompare(b.model);
});
for (const model of models) {
const row = el("div", "model-row");
const who = el("div");
const name = el("div", "model-name", model.model);
name.title = model.model;
who.append(name, el("div", "model-provider", model.providerName));
if (model.hostNotes?.length) {
who.append(
el(
"div",
"model-host",
W.hostNotes(model.hostNotes.map((h) => `${h.account} ${compact(h.calls)} ${W.calls.toLowerCase()}`).join(" · ")),
),
);
}
const calls = metric(
"",
compact(model.calls),
model.errors
? `${model.errors} ${W.failed} · ${V.errorRate(model.errors, model.calls)}`
: "",
(model.errors ? "bad " : "") + "calls-cell",
);
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)}`);
who.append(split);
const cost = metric(
"",
money(model.cost, model.unpriced, model.calls),
"",
"cost-cell" + (model.unpriced ? " unpriced" : ""),
);
row.append(who, calls, ...share, cost, el("span", "chevron-spacer"));
box.append(row);
}
return box;
}
function updateExpandLabel() {
expandAll.textContent = allExpanded() ? W.collapse : W.expand;
}
function allExpanded() {
const providers = visibleProviders();
const accounts = providers.flatMap((provider) => V.visibleAccounts(provider, state.query));
return providers.length > 0 &&
providers.every((provider) => state.openProviders.has(provider.id)) &&
accounts.every((account) => state.expanded.has(account.id));
}
function metric(label, value, detail = "", className = "") {
const box = el("div", `metric ${className}`.trim());
if (label) box.append(el("div", "metric-label", label));
box.append(el("div", "metric-value", value));
if (detail) box.append(el("div", "metric-detail", detail));
return box;
}
// A row's share: the number of tokens, the bar of the share and the
// percentage of it, in three columns of their own so the numbers line
// up down the page.
function shareCell(item, total, list) {
const share = sharePercent(item, total);
const tokens = el("div", "metric tokens-cell");
tokens.append(el("div", "metric-value", compact(V.tokenTotal(item, state.includeCache))));
const barCell = el("div", "share-cell");
const bar = el("div", "bar");
bar.setAttribute("aria-label", `${V.shareWord(state.sort)} ${percent(share)}`);
const fill = el("i");
fill.style.setProperty(
"--bar",
`${(Math.max(0.015, barShare(item, list)) * 100).toFixed(1)}%`,
);
bar.append(fill);
barCell.append(bar);
const labelCell = el("div", "share-label-cell", percent(share));
labelCell.title = V.shareWord(state.sort);
return [tokens, barCell, labelCell];
}
// A percentage and a bar follow the sort picked: tokens, cost or calls.
// A name sort keeps tokens, as the list's own order is the name's.
function sortMetric(item) {
if (state.sort === "cost") return Number(item.cost) || 0;
if (state.sort === "calls") return Number(item.calls) || 0;
return V.tokenTotal(item, state.includeCache);
}
function totalForSort(list) {
return list.reduce((sum, item) => sum + sortMetric(item), 0);
}
function barShare(item, list) {
const max = Math.max(0, ...list.map(sortMetric));
return max > 0 ? sortMetric(item) / max : 0;
}
function sharePercent(item, total) {
return total > 0 ? sortMetric(item) / total : 0;
}
function compact(value) {
return V.count(value);
}
function money(usd, unpriced, calls) {
return V.money(usd, unpriced, calls, currency, usdCny);
}
function percent(value) {
return V.percent(value);
}
function lastSeen(value) {
if (!value) return W.noTime;
const diff = Date.now() - Date.parse(value);
if (!Number.isFinite(diff)) return W.usedRecently;
if (diff < 60_000) return W.justUsed;
if (diff < 3_600_000) return W.minutesAgo(Math.max(1, Math.round(diff / 60_000)));
if (diff < 86_400_000) return W.hoursAgo(Math.max(1, Math.round(diff / 3_600_000)));
return new Date(value).toLocaleDateString(lang === "en" ? "en-US" : "zh-CN", { month: "numeric", day: "numeric" });
}
function shortProvider(id) {
const words = String(id || "??")
.replaceAll("_", "-")
.split("-")
.filter(Boolean);
if (words.length > 1) return (words[0][0] + words[1][0]).toUpperCase();
return String(id || "??").slice(0, 2).toUpperCase();
}
function el(tag, className = "", value) {
const node = document.createElement(tag);
if (className) node.className = className;
if (value != null) node.textContent = String(value);
return node;
}
function icon(name) {
const box = document.createElement("span");
box.setAttribute("aria-hidden", "true");
box.style.display = "contents";
const paths = {
dot: '<circle cx="12" cy="12" r="7"/>',
accounts: '<circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0M16 5.5a3 3 0 0 1 0 5.5M17 14a5 5 0 0 1 3.5 5"/>',
calls: '<path d="M4 18V9M10 18V5M16 18v-7M22 18V3"/>',
tokens: '<path d="M4 7h16M4 12h10M4 17h7"/><circle cx="18" cy="12" r="2"/><circle cx="15" cy="17" r="2"/>',
cost: '<path d="M12 3v18M17 7.5c0-2-2.24-3.5-5-3.5S7 5.5 7 7.5s2.24 3.5 5 3.5 5 1.5 5 3.5-2.24 3.5-5 3.5-5-1.5-5-3.5"/>',
chevron: '<path d="m7 10 5 5 5-5"/>',
};
box.innerHTML = `<svg viewBox="0 0 24 24">${paths[name] || paths.dot}</svg>`;
return box;
}
})();
+150
View File
@@ -0,0 +1,150 @@
(function (root) {
const WORDS = {
zh: {
title: "账号用量",
subtitle: "先看账号,再展开查看它使用的模型",
periods: { today: "今天", "7d": "7 天", "30d": "30 天", all: "全部" },
refresh: "刷新用量",
period: "统计周期",
summary: "用量汇总",
accounts: "账号",
providers: "供应商",
calls: "调用",
tokens: "输入 + 输出 Token",
tokensWithCache: "输入 + 输出 + 缓存 Token",
tokensWithoutCache: "输入 + 输出 Token",
includeCache: "Token 含缓存",
includeCacheHint: "切换是否把缓存 Token 计入总量、排序和占比",
cost: "估算费用",
models: "模型",
detail: "账号明细",
search: "搜索账号、供应商或模型",
sort: "排序",
sortBy: { tokens: "按 Token", cost: "按费用", calls: "按调用", name: "按名称" },
expand: "展开全部",
collapse: "收起全部",
columns: {
identity: "供应商 / 账号",
calls: "调用",
tokens: "Token",
share: "占比",
cost: "费用",
status: "状态",
},
model: "模型",
token: "Token",
modelTokensWithCache: "Token + 缓存",
modelTokensWithoutCache: "Token",
allOk: "正常",
failed: "失败",
unpriced: "次未定价",
noCalls: "这个周期还没有账号用量",
noMatch: "没有匹配的账号",
noCallsHint: "通过 Magpie 网关产生调用后,这里会按账号汇总。",
noMatchHint: "试试搜索其他账号、供应商或模型。",
noData: "没有读到用量数据",
reload: "重新加载",
firstRead: "首次读取约需数秒",
source: "只读聚合",
updated: "更新于",
input: "入",
output: "出",
cache: "缓存",
share: { tokens: "Token 占比", cost: "费用占比", calls: "调用占比", name: "Token 占比" },
unpricedOnly: "未定价",
unpricedCalls: (n) => `${n} 次未定价`,
noTime: "无时间",
justUsed: "刚刚使用",
usedRecently: "最近使用",
minutesAgo: (n) => `${n} 分钟前`,
hoursAgo: (n) => `${n} 小时前`,
readFailed: "无法读取用量数据",
refreshFailed: "刷新失败,仍显示上次数据",
apiKeyNote: "API key 调用,不计入账号",
accountsAndModels: (a, m) => `${a} 个账号 · ${m} 个模型`,
modelsOnly: (m) => `${m} 个模型`,
providerModels: (p, m) => `${p} 个供应商 · ${m} 个模型`,
hostNotes: (items) => `含 ${items}`,
noUsage: "这个周期还没有用量:Magpie 网关记录第一次调用后会显示在这里。",
serviceTimeout: "数据请求超过 10 秒。请检查 Magpie 网关是否可访问。",
localService: (port) => `本地用量服务没有在运行(127.0.0.1:${port})`,
},
en: {
title: "Account usage",
subtitle: "Start with each account, then expand it to see the models it used",
periods: { today: "Today", "7d": "7 days", "30d": "30 days", all: "All" },
refresh: "Refresh usage",
period: "Period",
summary: "Usage summary",
accounts: "Accounts",
providers: "providers",
calls: "Calls",
tokens: "Input + output tokens",
tokensWithCache: "Input + output + cache tokens",
tokensWithoutCache: "Input + output tokens",
includeCache: "Tokens include cache",
includeCacheHint: "Include cache tokens in totals, sorting and shares",
cost: "Estimated cost",
models: "models",
detail: "Account details",
search: "Search accounts, providers or models",
sort: "Sort",
sortBy: { tokens: "By tokens", cost: "By cost", calls: "By calls", name: "By name" },
expand: "Expand all",
collapse: "Collapse all",
columns: {
identity: "Provider / account",
calls: "Calls",
tokens: "Tokens",
share: "Share",
cost: "Cost",
status: "Status",
},
model: "Model",
token: "Token",
modelTokensWithCache: "Token + cache",
modelTokensWithoutCache: "Token",
allOk: "OK",
failed: "failed",
unpriced: "unpriced",
noCalls: "No account usage in this period",
noMatch: "No matching account",
noCallsHint: "Usage will be grouped by account after calls pass through the Magpie gateway.",
noMatchHint: "Try another account, provider or model.",
noData: "Could not read usage data",
reload: "Reload",
firstRead: "The first read may take a few seconds",
source: "Read-only aggregate",
updated: "Updated at",
input: "In",
output: "Out",
cache: "Cache",
share: { tokens: "Token share", cost: "Cost share", calls: "Call share", name: "Token share" },
unpricedOnly: "Not priced",
unpricedCalls: (n) => `${n} unpriced`,
noTime: "no time",
justUsed: "used just now",
usedRecently: "used recently",
minutesAgo: (n) => `${n} min ago`,
hoursAgo: (n) => `${n} hr ago`,
readFailed: "Could not read usage data",
refreshFailed: "Refresh failed; showing the previous data",
apiKeyNote: "API key calls, not counted as accounts",
accountsAndModels: (a, m) =>
`${a} ${a === 1 ? "account" : "accounts"} · ${m} ${m === 1 ? "model" : "models"}`,
modelsOnly: (m) => `${m} ${m === 1 ? "model" : "models"}`,
providerModels: (p, m) =>
`${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.",
localService: (port) => `The local usage service is not running (127.0.0.1:${port})`,
},
};
root.UsageI18n = {
get(lang) {
return String(lang || "").toLowerCase().startsWith("zh") ? WORDS.zh : WORDS.en;
},
};
})(globalThis);
File diff suppressed because it is too large Load Diff
+249
View File
@@ -0,0 +1,249 @@
// What the page says, in English and Chinese, with no DOM: the test loads
// it. The page's app.js draws with it.
(function (root) {
const PERIODS = ["today", "7d", "30d", "all"];
const SORTS = ["tokens", "cost", "calls", "name"];
const I18N = globalThis.UsageI18n;
let lang = "en";
function text(which) {
return I18N.get(which);
}
let chineseUnits = false;
const short = (value) => {
const text = value.toFixed(2).replace(/\.?0+$/, "");
return text || "0";
};
function count(value, useChinese = chineseUnits) {
const n = Number(value) || 0;
if (Math.abs(n) < 1000) return String(Math.round(n));
// Magpie shortens a count in 万 and 亿 only when it speaks Chinese.
if (useChinese && lang === "zh") {
if (n >= 1e8) return `${+(n / 1e8).toFixed(2)}亿`;
if (n >= 1e4) return `${+(n / 1e4).toFixed(1)}万`;
}
if (n >= 1e9) return `${short(n / 1e9)}B`;
if (n >= 1e6) return `${short(n / 1e6)}M`;
if (n >= 1e3) return `${short(n / 1e3)}K`;
return String(Math.round(n));
}
function percent(value) {
const n = Math.max(0, Number(value) || 0) * 100;
if (n >= 10) return `${n.toFixed(0)}%`;
if (n >= 1) return `${n.toFixed(1)}%`;
return `${n.toFixed(2)}%`;
}
// 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) {
const bad = Math.max(0, Number(errors) || 0);
const total = Math.max(0, Number(calls) || 0);
if (!bad || !total) return "";
return percent(bad / total);
}
function has(value, query) {
return String(value || "").toLowerCase().includes(query);
}
function accountSelfMatches(account, query) {
const q = String(query || "").trim().toLowerCase();
if (!q) return true;
return (
has(account?.alias, q) ||
has(account?.account, q) ||
has(account?.providerName, q) ||
has(account?.provider, q)
);
}
function modelMatches(model, query) {
const q = String(query || "").trim().toLowerCase();
return !q || has(model?.model, q) || has(model?.name, q);
}
function accountMatches(account, query) {
if (accountSelfMatches(account, query)) return true;
return Array.isArray(account?.models) && account.models.some((model) => modelMatches(model, query));
}
function providerMatches(provider, query) {
const q = String(query || "").trim().toLowerCase();
if (!q) return true;
return (
has(provider?.providerName, q) ||
has(provider?.provider, q) ||
has(provider?.id, q)
);
}
function visibleAccounts(provider, query) {
const list = Array.isArray(provider?.accounts) ? provider.accounts : [];
if (providerMatches(provider, query)) return [...list];
return list.filter((account) => accountMatches(account, query));
}
// Magpie reports fresh input/output and cache as separate totals. Some
// providers bill cache beside the request, so the page can choose whether
// cache belongs in the token measure. allTokens is the gateway's direct
// answer when present; the sum fallback keeps older cached reads working.
function tokenTotal(item, includeCache = true) {
const tokens = Number(item?.tokens) || 0;
if (!includeCache) return tokens;
const allTokens = Number(item?.allTokens);
return Number.isFinite(allTokens) && allTokens >= tokens ? allTokens : tokens + (Number(item?.cache) || 0);
}
// Sorting lives here so an empty answer, a missing field or a stale cached
// row can never make the page throw while it redraws.
function sortProviders(list, sort, includeCache = true) {
const rows = Array.isArray(list) ? [...list] : [];
const tokenOf = (item) => tokenTotal(item, includeCache);
const costOf = (item) => Number(item?.cost) || 0;
const callsOf = (item) => Number(item?.calls) || 0;
const nameOf = (item) => String(item?.providerName || item?.provider || item?.id || "");
return rows.sort((a, b) => {
if (sort === "name") return nameOf(a).localeCompare(nameOf(b));
if (sort === "cost") return costOf(b) - costOf(a) || tokenOf(b) - tokenOf(a);
if (sort === "calls") return callsOf(b) - callsOf(a) || tokenOf(b) - tokenOf(a);
return tokenOf(b) - tokenOf(a) || costOf(b) - costOf(a);
});
}
// shareWord names what a share is of, so a percentage keeps its meaning
// when the list is sorted by cost or calls.
function shareWord(sort) {
const share = text(lang).share;
return share[sort] || share.tokens;
}
function money(usd, unpriced, calls, currency, usdCny) {
const value = Number(usd) || 0;
const words = text(lang);
if (calls > 0 && unpriced >= calls) return words.unpricedOnly;
const rate = Number(usdCny) > 0 ? Number(usdCny) : 0;
const cny = currency === "cny" && rate > 0;
const amount = cny ? value * rate : value;
const symbol = cny ? "¥" : "$";
const digits = amount >= 100 ? 0 : amount >= 1 ? 2 : 3;
return `${symbol}${amount.toFixed(digits)}${unpriced ? "+" : ""}`;
}
function tiles(summary, lang, currency, usdCny, includeCache = true) {
const w = text(lang);
const accounts = Number(summary.accounts) || 0;
const tokenLabel = includeCache ? w.tokensWithCache : w.tokensWithoutCache;
const providers = Number(summary.providers ?? 0) || 0;
const models = Number(summary.models) || 0;
const accountSub = w.providerModels
? w.providerModels(providers, models)
: `${count(providers)} ${w.providers} · ${count(models)} ${w.models}`;
return [
{
key: "accounts",
label: w.accounts,
value: count(accounts),
sub: accountSub,
},
{
key: "calls",
label: w.calls,
value: count(summary.calls),
sub: summary.errors
? `${count(summary.errors)} ${w.failed} · ${errorRate(summary.errors, summary.calls)}`
: w.allOk,
bad: summary.errors > 0,
},
{
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)}`,
},
{
key: "cost",
label: w.cost,
value: money(summary.cost, summary.unpriced, summary.calls, currency, usdCny),
sub: summary.unpriced ? `${count(summary.unpriced)} ${w.unpriced}` : "",
},
];
}
function accounts(list, sort, lang, currency = "usd", usdCny = 0, includeCache = true) {
const w = text(lang);
const rows = [...list];
const tokenOf = (item) => tokenTotal(item, includeCache);
const totalTokens = rows.reduce((sum, item) => sum + tokenOf(item), 0);
const maxTokens = Math.max(1, ...rows.map(tokenOf));
rows.sort((a, b) => {
if (sort === "name") return a.account.localeCompare(b.account);
if (sort === "cost") return b.cost - a.cost || tokenOf(b) - tokenOf(a);
if (sort === "calls") return b.calls - a.calls || tokenOf(b) - tokenOf(a);
return tokenOf(b) - tokenOf(a) || b.cost - a.cost;
});
return rows.map((account) => ({
id: account.id,
name: account.alias || account.account,
account: account.account,
provider: account.providerName,
calls: count(account.calls),
tokens: count(tokenOf(account)),
share: percent(totalTokens > 0 ? tokenOf(account) / totalTokens : account.share),
bar: Math.max(0.015, tokenOf(account) / maxTokens),
cost: money(account.cost, account.unpriced, account.calls, currency, usdCny),
errors: account.errors ? `${count(account.errors)} ${w.failed}` : w.allOk,
errorRate: errorRate(account.errors, account.calls),
models: account.models.length,
}));
}
function models(account, lang, currency, usdCny, includeCache = true) {
const w = text(lang);
const tokenOf = (model) => tokenTotal(model, includeCache);
const totalTokens = account.models.reduce((sum, model) => sum + tokenOf(model), 0);
const maxTokens = Math.max(1, ...account.models.map(tokenOf));
return account.models.map((model) => ({
id: model.id,
name: model.model,
provider: model.providerName,
calls: count(model.calls),
tokens: count(tokenOf(model)),
share: percent(totalTokens > 0 ? tokenOf(model) / totalTokens : model.share),
bar: Math.max(0.02, tokenOf(model) / maxTokens),
cost: money(model.cost, model.unpriced, model.calls, currency, usdCny),
errors: model.errors ? `${count(model.errors)} ${w.failed}` : "",
errorRate: errorRate(model.errors, model.calls),
unpriced: model.unpriced ? `${count(model.unpriced)} ${w.unpriced}` : "",
hosts: (model.hostNotes || []).map((host) => `${host.account} ${count(host.calls)}`),
}));
}
root.UsageView = {
PERIODS,
SORTS,
text,
count,
percent,
errorRate,
accountSelfMatches,
modelMatches,
accountMatches,
providerMatches,
visibleAccounts,
tokenTotal,
sortProviders,
shareWord,
money,
tiles,
accounts,
models,
setChineseUnits(value) { chineseUnits = value === true; },
setLang(value) {
lang = String(value || "").toLowerCase().startsWith("zh") ? "zh" : "en";
chineseUnits = chineseUnits && lang === "zh";
},
};
})(globalThis);
+2
View File
@@ -132,6 +132,8 @@
"summary": { "en": "A chat page in magpie's window by Magic_zero: talk to magpie's own models with your MCP servers, instructions and skills, images and LaTeX. Runs a local service on 127.0.0.1 that only its own page can use.", "zh": "Magic_zero 做的 magpie 窗口内「对话」页面:用 magpie 自己的模型聊天,带上你的 MCP 服务器、指令和技能,支持图片与 LaTeX。本地服务只在 127.0.0.1,只给自己的页面用。" } },
{ "package": "@magpie-community/page-agent-office", "name": "Agent Office", "kind": "page", "community": true,
"summary": { "en": "Reads the session files of Claude Code, Codex, Copilot CLI, Kimi Code, DeepSeek Harness, Gemini CLI, Qwen Code, Pi, omp, Qoder, WorkBuddy, CodeBuddy and Grok Build on this computer (prompts, replies and tool commands; text can be turned off). Shows them in a real WebGL 3D office with eleven scenes, an isometric/2D office, or a grouped workbench with Today usage, recent conversations and approvals.", "zh": "读取本机 Claude Code、Codex、Copilot CLI、Kimi Code、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy、Grok Build 的会话文件(含提问、回复与工具命令,可关闭文本),用真 3D 办公室(十一种场景)、等距/2D 办公室或分组工作台展示,带今日用量、最近对话与批准状态。" } },
{ "package": "@magpie-community/page-usage-tree", "name": "Account usage", "kind": "page", "community": true,
"summary": { "en": "A provider -> account -> model usage tree with per-account calls, errors and cost. Adds the account layer that Usage Glance's usage:summary does not contain, read from Magpie's local usage API.", "zh": "按供应商 -> 账号 -> 模型展示用量,包含每个账号的调用、错误和费用;补充 Usage Glance 的 usage:summary 所没有的账号层,数据来自 Magpie 本地用量 API。" } },
{"package": "@magpie-community/agent-kimi-desktop", "name": "Kimi", "kind": "agent", "community": true, "summary": {"en": "Kimi desktop Work on Magpie's Agents page: select a model from Magpie, then disconnect to restore the original service. Not Kimi Code CLI.", "zh": "把普通 Kimi 桌面版 Work 接入 Magpie Agent 页,使用已配置的模型;断开恢复原连接。不是 Kimi Code CLI。"}},
{ "package": "@magpie-community/gateway-notify", "name": "Notify", "kind": "middleware", "community": true,
"summary": { "en": "A push when an agent's turn is done or fails, after it ran long enough to be worth one: ntfy, Bark, Gotify, Server酱, Feishu, DingTalk, WeCom, Telegram or your own webhook. Agent, project, model and time only by default; the reply's text is opt-in.", "zh": "agent 一轮任务跑完或失败时推送提醒(只提醒跑够设定时长的任务):支持 ntfy、Bark、Gotify、Server酱、飞书、钉钉、企业微信、Telegram 和自定义 webhook。默认只发 agent、项目、模型和用时,回复正文需手动开启。" } },