diff --git a/README.md b/README.md index d961dc5..400386f 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/packages/page-usage-tree/LICENSE b/packages/page-usage-tree/LICENSE new file mode 100644 index 0000000..3d54f1e --- /dev/null +++ b/packages/page-usage-tree/LICENSE @@ -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. diff --git a/packages/page-usage-tree/README.md b/packages/page-usage-tree/README.md new file mode 100644 index 0000000..cbb4b60 --- /dev/null +++ b/packages/page-usage-tree/README.md @@ -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/.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. diff --git a/packages/page-usage-tree/assets/icon.svg b/packages/page-usage-tree/assets/icon.svg new file mode 100644 index 0000000..dbb9b1a --- /dev/null +++ b/packages/page-usage-tree/assets/icon.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/packages/page-usage-tree/index.mjs b/packages/page-usage-tree/index.mjs new file mode 100644 index 0000000..2695e64 --- /dev/null +++ b/packages/page-usage-tree/index.mjs @@ -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 {}; + }, +}; diff --git a/packages/page-usage-tree/lib/data.mjs b/packages/page-usage-tree/lib/data.mjs new file mode 100644 index 0000000..68df8d1 --- /dev/null +++ b/packages/page-usage-tree/lib/data.mjs @@ -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 }; diff --git a/packages/page-usage-tree/lib/gateway.mjs b/packages/page-usage-tree/lib/gateway.mjs new file mode 100644 index 0000000..a7a9949 --- /dev/null +++ b/packages/page-usage-tree/lib/gateway.mjs @@ -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, + ); +} diff --git a/packages/page-usage-tree/lib/server.mjs b/packages/page-usage-tree/lib/server.mjs new file mode 100644 index 0000000..faa8c08 --- /dev/null +++ b/packages/page-usage-tree/lib/server.mjs @@ -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("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """); +} + +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?.(); + }), + }; +} diff --git a/packages/page-usage-tree/lib/usage.mjs b/packages/page-usage-tree/lib/usage.mjs new file mode 100644 index 0000000..c53d5a7 --- /dev/null +++ b/packages/page-usage-tree/lib/usage.mjs @@ -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 }; diff --git a/packages/page-usage-tree/package.json b/packages/page-usage-tree/package.json new file mode 100644 index 0000000..19f04fe --- /dev/null +++ b/packages/page-usage-tree/package.json @@ -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" + } +} diff --git a/packages/page-usage-tree/page/boot.js b/packages/page-usage-tree/page/boot.js new file mode 100644 index 0000000..4d5c1b2 --- /dev/null +++ b/packages/page-usage-tree/page/boot.js @@ -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); +})(); diff --git a/packages/page-usage-tree/page/icon.svg b/packages/page-usage-tree/page/icon.svg new file mode 100644 index 0000000..0ab6f0d --- /dev/null +++ b/packages/page-usage-tree/page/icon.svg @@ -0,0 +1,10 @@ + + + + + + + + + diff --git a/packages/page-usage-tree/page/index.html b/packages/page-usage-tree/page/index.html new file mode 100644 index 0000000..1077678 --- /dev/null +++ b/packages/page-usage-tree/page/index.html @@ -0,0 +1,38 @@ + + + + + + Account usage + + + +
+ Account usage +
Connecting to the local usage service...
+ +
+ + + + diff --git a/packages/page-usage-tree/serve.mjs b/packages/page-usage-tree/serve.mjs new file mode 100644 index 0000000..0bc23ef --- /dev/null +++ b/packages/page-usage-tree/serve.mjs @@ -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}`); diff --git a/packages/page-usage-tree/test/cache.test.mjs b/packages/page-usage-tree/test/cache.test.mjs new file mode 100644 index 0000000..abcc452 --- /dev/null +++ b/packages/page-usage-tree/test/cache.test.mjs @@ -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); + } +}); diff --git a/packages/page-usage-tree/test/discover.test.mjs b/packages/page-usage-tree/test/discover.test.mjs new file mode 100644 index 0000000..8db1aee --- /dev/null +++ b/packages/page-usage-tree/test/discover.test.mjs @@ -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); +}); diff --git a/packages/page-usage-tree/test/empty.test.mjs b/packages/page-usage-tree/test/empty.test.mjs new file mode 100644 index 0000000..5221b9a --- /dev/null +++ b/packages/page-usage-tree/test/empty.test.mjs @@ -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")); +}); diff --git a/packages/page-usage-tree/test/gateway.test.mjs b/packages/page-usage-tree/test/gateway.test.mjs new file mode 100644 index 0000000..55e902d --- /dev/null +++ b/packages/page-usage-tree/test/gateway.test.mjs @@ -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", "not the usage API"], + ["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/); +}); diff --git a/packages/page-usage-tree/test/lifecycle.test.mjs b/packages/page-usage-tree/test/lifecycle.test.mjs new file mode 100644 index 0000000..6b7de3d --- /dev/null +++ b/packages/page-usage-tree/test/lifecycle.test.mjs @@ -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); +}); diff --git a/packages/page-usage-tree/test/page.test.mjs b/packages/page-usage-tree/test/page.test.mjs new file mode 100644 index 0000000..a841449 --- /dev/null +++ b/packages/page-usage-tree/test/page.test.mjs @@ -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, / + + + + diff --git a/packages/page-usage-tree/ui/app.js b/packages/page-usage-tree/ui/app.js new file mode 100644 index 0000000..527c5d4 --- /dev/null +++ b/packages/page-usage-tree/ui/app.js @@ -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: '', + accounts: '', + calls: '', + tokens: '', + cost: '', + chevron: '', + }; + box.innerHTML = `${paths[name] || paths.dot}`; + return box; + } +})(); diff --git a/packages/page-usage-tree/ui/i18n.js b/packages/page-usage-tree/ui/i18n.js new file mode 100644 index 0000000..bf89fc9 --- /dev/null +++ b/packages/page-usage-tree/ui/i18n.js @@ -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); diff --git a/packages/page-usage-tree/ui/style.css b/packages/page-usage-tree/ui/style.css new file mode 100644 index 0000000..3c65962 --- /dev/null +++ b/packages/page-usage-tree/ui/style.css @@ -0,0 +1,1043 @@ +/* magpie's own base, as pagebridge.js gives a plugin page: the window's + font, colours and control shapes. This page is served by its own service + instead of by magpie, so the same baseline lives here. The real values + arrive as --magpie-* variables; the ones below are only fallbacks. */ + +:root { + --magpie-bg: #f5f6f8; + --magpie-card: #ffffff; + --magpie-fg: #23262e; + --magpie-fg-2: #3a3f4a; + --magpie-muted: #6b7280; + --magpie-faint: #9aa0aa; + --magpie-line: #e2e4e9; + --magpie-accent: #5b5bd6; + --magpie-accent-soft: #ececfb; + --magpie-green: #1f7a4d; + --magpie-red: #b3352f; + color-scheme: light; +} + +html[data-theme="dark"] { + --magpie-bg: #15171c; + --magpie-card: #1c1f26; + --magpie-fg: #e8e9ee; + --magpie-fg-2: #c9ccd4; + --magpie-muted: #9aa0aa; + --magpie-faint: #70757f; + --magpie-line: #2c3038; + --magpie-accent: #8f8ff0; + --magpie-accent-soft: #262a3a; + --magpie-green: #5ac08a; + --magpie-red: #e0716a; + color-scheme: dark; +} + +html { + background: var(--magpie-bg); + color: var(--magpie-fg); + font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); + -webkit-font-smoothing: antialiased; +} + +body { + margin: 0; + padding: 20px 24px; +} + +h1, h2 { + margin: 0 0 8px; + font-weight: 600; + letter-spacing: -.01em; +} + +h1 { font-size: 20px; } +h2 { font-size: 15px; } +p { margin: 0 0 8px; } + +button, input, select { + font: inherit; + color: inherit; +} + +button { + padding: 3px 10px; + border: 1px solid var(--magpie-line); + border-radius: 6px; + background: var(--magpie-card); +} + +button:hover:not(:disabled) { + border-color: var(--magpie-muted); +} + +button:disabled { + opacity: .5; +} + +input, select { + padding: 4px 8px; + border: 1px solid var(--magpie-line); + border-radius: 6px; + background: var(--magpie-card); +} + +:focus-visible { + outline: 2px solid var(--magpie-accent); + outline-offset: 1px; +} + +/* This page takes magpie's own look: the bridge already sets the window's + font, colours, headings and controls (:where rules of no weight). What is + below is layout only, in the same tokens magpie's built-in pages use. */ + +.view { + display: flex; + flex-direction: column; + gap: 12px; + max-width: 1180px; +} + +/* ---- the head: the page's name, the period, a refresh ------------------- */ + +.head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; +} + +.head-text h1 { + margin: 0; +} + +.head-text p { + margin: 2px 0 0; + color: var(--magpie-muted); + font-size: 11.5px; +} + +.head-tools { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.segs { + display: inline-flex; + gap: 2px; + padding: 2px; + border: 0; + border-radius: 7px; + background: color-mix(in srgb, var(--magpie-fg) 7%, transparent); +} + +.segs button { + min-width: 52px; + height: 22px; + padding: 0 10px; + border: 0; + border-radius: 5px; + background: transparent; + color: var(--magpie-muted); + font-size: 12px; +} + +.segs button:hover { + color: var(--magpie-fg-2); +} + +.segs button[aria-selected="true"] { + background: var(--magpie-card); + color: var(--magpie-fg); + box-shadow: 0 1px 2px color-mix(in srgb, var(--magpie-fg) 14%, transparent); +} + +.icon { + display: grid; + position: relative; + width: 26px; + height: 26px; + padding: 0; + border-radius: 7px; + place-items: center; +} + +.icon svg { + width: 14px; + height: 14px; + fill: none; + stroke: currentColor; + stroke-width: 1.6; + stroke-linecap: round; + stroke-linejoin: round; +} + +.cache-toggle { + display: inline-flex; + align-items: center; + gap: 6px; + height: 26px; + padding: 0 8px; + border-color: var(--magpie-line); + color: var(--magpie-muted); + font-size: 11.5px; + white-space: nowrap; +} + +.cache-toggle:hover { + color: var(--magpie-fg-2); +} + +.cache-toggle .switch { + position: relative; + width: 20px; + height: 12px; + flex: none; + border-radius: 999px; + background: var(--magpie-line); +} + +.cache-toggle .switch i { + position: absolute; + top: 2px; + left: 2px; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--magpie-muted); + transition: left .15s, background .15s; +} + +.cache-toggle[aria-checked="true"] { + color: var(--magpie-fg-2); +} + +.cache-toggle[aria-checked="true"] .switch { + background: var(--magpie-accent); +} + +.cache-toggle[aria-checked="true"] .switch i { + left: 10px; + background: var(--magpie-card); +} + +/* While a read runs the button turns accent: with reduced motion the spin + below is cut short, and the colour is what still says "reading". The + button is disabled then, so the shared `button:disabled { opacity: .5 }` + would fade the spin away: this keeps it at full strength. */ +.icon.busy, +.icon.busy:disabled { + opacity: 1; + color: var(--magpie-accent); + border-color: color-mix(in srgb, var(--magpie-accent) 35%, var(--magpie-line)); +} + +/* A turning refresh glyph reads as nothing: its circle is all but + symmetrical, and at 14px the tick is too small to notice. A ring under + it says little more at that size, so the read is shown twice: the + button takes the accent, and a thin bar under the head runs a band + across, magpie's own indeterminate progress (.u__bar:indeterminate). */ +.icon.busy svg { + opacity: .45; +} + +/* ---- the read in progress: a band crossing a hairline ------------------- */ + +.progress { + position: relative; + height: 3px; + margin: -2px 0 10px; + overflow: hidden; + border-radius: 2px; + background: color-mix(in srgb, var(--magpie-line) 40%, transparent); +} + +.progress::before { + content: ""; + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: 28%; + border-radius: 2px; + background: var(--magpie-accent); + transform: translateX(-100%); + animation: sweep .95s ease-in-out infinite; +} + +@keyframes sweep { + to { transform: translateX(360%); } +} + +@media (prefers-reduced-motion: reduce) { + .progress::before { + width: 100%; + transform: none; + animation: none; + opacity: .55; + } +} + +/* ---- the totals: magpie's .stats, four cells on one card ---------------- */ + +.stats { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 1px; + overflow: hidden; + border: 1px solid var(--magpie-line); + border-radius: 12px; + background: var(--magpie-line); +} + +.stats:empty { + display: none; +} + +.summary-card { + display: flex; + min-width: 0; + flex-direction: column; + padding: 12px 14px 11px; + background: var(--magpie-card); +} + +.summary-label { + display: flex; + align-items: center; + gap: 5px; + color: var(--magpie-muted); + font-size: 11px; + font-weight: 600; + letter-spacing: .05em; + text-transform: uppercase; +} + +.summary-label svg { + width: 12px; + height: 12px; + fill: none; + stroke: currentColor; + stroke-width: 1.6; + stroke-linecap: round; + stroke-linejoin: round; +} + +.summary-value { + overflow: hidden; + margin-top: 3px; + font-size: 20px; + font-weight: 600; + font-variant-numeric: tabular-nums; + letter-spacing: -.01em; + line-height: 1.15; + text-overflow: ellipsis; + white-space: nowrap; +} + +.summary-sub { + overflow: hidden; + margin-top: 3px; + color: var(--magpie-muted); + font-size: 11px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.summary-card.loading { + animation: breathe 1.3s ease-in-out infinite alternate; +} + +/* ---- the list ----------------------------------------------------------- */ + +.panel { + overflow: hidden; + border: 1px solid var(--magpie-line); + border-radius: 12px; + background: var(--magpie-card); +} + +.panel-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + padding: 10px 14px; + border-bottom: 1px solid var(--magpie-line); +} + +.panel-head h2 { + margin: 0; + font-size: 13px; + font-weight: 600; +} + +.tools { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.search { + display: flex; + align-items: center; + gap: 6px; + height: 26px; + padding: 0 9px; + border: 1px solid var(--magpie-line); + border-radius: 6px; + background: var(--magpie-card); +} + +.search:focus-within { + border-color: var(--magpie-muted); +} + +.search svg { + width: 13px; + height: 13px; + flex: none; + fill: none; + stroke: var(--magpie-muted); + stroke-width: 1.7; + stroke-linecap: round; + stroke-linejoin: round; +} + +.search input { + width: 190px; + min-width: 0; + padding: 0; + border: 0; + outline: 0; + background: transparent; + font-size: 11.5px; +} + +.search input::placeholder { + color: var(--magpie-faint); +} + +.sort { + display: flex; + align-items: center; + gap: 4px; + height: 26px; + padding-left: 8px; + border: 1px solid var(--magpie-line); + border-radius: 6px; + color: var(--magpie-muted); + font-size: 11.5px; +} + +.sort-button { + height: 24px; + padding: 0 7px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--magpie-muted); + font-size: 11.5px; +} + +.sort-button[aria-selected="true"] { + background: var(--magpie-accent-soft); + color: var(--magpie-fg); +} + +.text { + height: 26px; + padding: 0 10px; + font-size: 11.5px; + color: var(--magpie-muted); +} + +.text:hover { + color: var(--magpie-fg); +} + +.warn { + margin: 10px 14px 0; + padding: 6px 10px; + border-radius: 7px; + background: var(--magpie-accent-soft); + color: var(--magpie-muted); + font-size: 11px; + line-height: 1.5; +} + +/* one set of column names for the two list levels, so a row needs no + labels of its own and the numbers line up down the page */ +.cols { + display: grid; + grid-template-columns: minmax(170px, 1.2fr) 64px 82px minmax(72px, 0.55fr) 46px 82px 76px 20px; + gap: 12px; + align-items: center; + padding: 7px 14px 6px; + border-bottom: 1px solid var(--magpie-line); + color: var(--magpie-faint); + font-size: 10px; + letter-spacing: .04em; + text-transform: uppercase; +} + +.cols span:not(:first-child) { + text-align: right; +} + +.cols .col-share { + text-align: right; +} + +.cols .col-share-label { + text-align: right; +} + +/* ---- an account, and the models it opens -------------------------------- */ + +.accounts:empty { + display: none; +} + +/* ---- the tree: a provider, its accounts, their models -------------------- */ + +.provider { + border-bottom: 1px solid var(--magpie-line); +} + +.provider:last-child { + border-bottom: 0; +} + +.provider-main { + display: grid; + grid-template-columns: minmax(170px, 1.2fr) 64px 82px minmax(72px, 0.55fr) 46px 82px 76px 20px; + gap: 12px; + align-items: center; + width: 100%; + padding: 9px 14px; + border: 0; + border-radius: 0; + background: transparent; + text-align: left; +} + +.provider-main:hover { + background: color-mix(in srgb, var(--magpie-fg) 4%, transparent); +} + +.provider.open .provider-main { + background: color-mix(in srgb, var(--magpie-fg) 3%, transparent); +} + +.provider-main .provider-badge { + width: 26px; + height: 26px; + border-radius: 7px; + font-size: 10px; +} + +.provider-main .level-name { + font-size: 13px; + font-weight: 600; +} + +/* the provider's own errors, where the account's are under it */ +.provider-main .errors-cell { + display: block; +} + +.provider-accounts { + display: none; + border-top: 1px solid var(--magpie-line); + background: color-mix(in srgb, var(--magpie-fg) 2%, transparent); +} + +.provider.open .provider-accounts { + display: block; +} + +/* the account, one level in: the provider's own name is above it */ +.provider-accounts .account { + border-bottom: 1px solid color-mix(in srgb, var(--magpie-line) 60%, transparent); +} + +.provider-accounts .account:last-child { + border-bottom: 0; +} + +.provider-accounts .account-main { + padding: 7px 14px 7px 38px; +} + +.provider-accounts .provider-badge { + display: none; +} + +.account { + border-bottom: 1px solid var(--magpie-line); +} + +.account:last-child { + border-bottom: 0; +} + +.account-main { + display: grid; + grid-template-columns: minmax(170px, 1.2fr) 64px 82px minmax(72px, 0.55fr) 46px 82px 76px 20px; + gap: 12px; + align-items: center; + width: 100%; + padding: 9px 14px; + border: 0; + border-radius: 0; + background: transparent; + text-align: left; +} + +.account-main:hover { + background: color-mix(in srgb, var(--magpie-fg) 4%, transparent); +} + +.account.open .account-main { + background: color-mix(in srgb, var(--magpie-fg) 3%, transparent); +} + +.identity { + display: flex; + align-items: center; + gap: 9px; + min-width: 0; +} + +.provider-badge { + display: grid; + width: 24px; + height: 24px; + flex: none; + border-radius: 6px; + background: var(--magpie-accent-soft); + color: var(--magpie-accent); + font-size: 9.5px; + font-weight: 600; + letter-spacing: .02em; + place-items: center; +} + +.identity-text { + min-width: 0; +} + +.level-name { + overflow: hidden; + font-size: 12.5px; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} + +.level-sub { + display: flex; + align-items: center; + gap: 5px; + overflow: hidden; + color: var(--magpie-muted); + font-size: 10.5px; + white-space: nowrap; +} + +.level-sub i { + width: 2px; + height: 2px; + flex: none; + border-radius: 50%; + background: var(--magpie-faint); +} + +.metric { + min-width: 0; +} + +.metric-label { + color: var(--magpie-faint); + font-size: 10px; + letter-spacing: .04em; + text-transform: uppercase; +} + +.metric-value { + overflow: hidden; + font-size: 12.5px; + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* the numbers line up under the shared column names */ +.calls-cell, +.cost-cell, +.errors-cell { + text-align: right; +} + +.metric-detail { + overflow: hidden; + color: var(--magpie-muted); + font-size: 10.5px; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* the share: a bar of the list's own scale and the share of it */ +.share-cell { + min-width: 0; +} + +.share-label-cell { + color: var(--magpie-muted); + font-size: 10.5px; + font-variant-numeric: tabular-nums; + text-align: right; +} + +.tokens-cell .metric-value { + text-align: right; +} + +.model-split { + overflow: hidden; + color: var(--magpie-faint); + font-size: 10px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bar { + height: 4px; + margin-top: 5px; + overflow: hidden; + border-radius: 2px; + background: var(--magpie-line); +} + +.bar i { + display: block; + width: var(--bar, 0%); + height: 100%; + border-radius: 2px; + background: var(--magpie-accent); + opacity: .7; +} + +.cost-cell .metric-value { + color: var(--magpie-green); +} + +/* a call with no known price is no cost: it is not a green one */ +.cost-cell.unpriced .metric-value { + color: var(--magpie-faint); +} + +.metric.bad .metric-value, +.metric.bad .metric-detail { + color: var(--magpie-red); +} + +.chevron { + display: grid; + color: var(--magpie-muted); + place-items: center; +} + +.chevron svg { + width: 12px; + height: 12px; + fill: none; + stroke: currentColor; + stroke-width: 1.8; + stroke-linecap: round; + stroke-linejoin: round; + transition: transform .15s; +} + +.account.open .chevron svg { + transform: rotate(180deg); +} + +.model-list { + display: none; + border-top: 1px solid var(--magpie-line); + background: color-mix(in srgb, var(--magpie-fg) 2%, transparent); +} + +.account.open .model-list { + display: block; +} + +.model-head, +.model-row { + display: grid; + /* the calls column holds "N failed · x.xx%" on one line, so it is wider + than the plain count the provider and account rows carry */ + grid-template-columns: minmax(170px, 1.2fr) 96px 82px minmax(72px, 0.55fr) 46px 82px 76px; + gap: 12px; + align-items: center; +} + +.model-head { + padding: 6px 48px 0 62px; + color: var(--magpie-faint); + font-size: 10px; + letter-spacing: .04em; + text-transform: uppercase; +} + +.model-head span:nth-child(2), +.model-head span:nth-child(3), +.model-head span:nth-child(5), +.model-head span:nth-child(6) { + text-align: right; +} + +.model-head span:not(:first-child) { + text-align: right; +} + +.model-row { + padding: 6px 48px 7px 62px; + border-top: 1px solid color-mix(in srgb, var(--magpie-line) 60%, transparent); +} + +/* the model, the third level: the lightest of the three */ +.model-name { + color: var(--magpie-fg-2); +} + +.model-name { + overflow: hidden; + font-size: 11.5px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.model-provider { + color: var(--magpie-muted); + font-size: 10.5px; +} + +.model-host { + overflow: hidden; + color: var(--magpie-faint); + font-size: 10px; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* ---- an empty or failed read -------------------------------------------- */ + +.state { + margin: 14px; + padding: 22px 16px; + border: 1px dashed var(--magpie-line); + border-radius: 10px; + color: var(--magpie-muted); + font-size: 12px; + text-align: center; +} + +.state strong { + display: block; + margin-bottom: 4px; + color: var(--magpie-fg); + font-size: 12.5px; + font-weight: 600; +} + +.state button { + margin-top: 10px; + font-size: 11.5px; +} + +.foot { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 0 2px 4px; + color: var(--magpie-faint); + font-size: 10.5px; +} + +[hidden] { + display: none !important; +} + +@keyframes spin { + to { transform: rotate(360deg); } +} + +@keyframes breathe { + from { opacity: .55; } + to { opacity: .9; } +} + +@media (max-width: 900px) { + .stats { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .account-main { + grid-template-columns: minmax(150px, 1fr) 60px 74px minmax(80px, 0.7fr) 44px 74px 20px; + } + + .provider-main { + grid-template-columns: minmax(150px, 1fr) 60px 74px minmax(80px, 0.7fr) 44px 74px 20px; + } + + .account-main .errors-cell, + .provider-main .errors-cell { + display: none; + } + + .model-head, + .model-row { + grid-template-columns: minmax(150px, 1fr) 92px 74px minmax(80px, 0.7fr) 46px 74px; + } + + .model-head > :last-child, + .model-row > :last-child { + display: none; + } + + .cols { + grid-template-columns: minmax(150px, 1fr) 60px 74px minmax(80px, 0.7fr) 74px 74px 20px; + } + + .cols .col-share { + display: none; + } +} + +@media (max-width: 620px) { + .cols { + grid-template-columns: minmax(0, 1fr) 48px 82px 18px; + gap: 8px; + } + + .cols .col-share, + .cols .col-share-label, + .cols .col-cost, + .cols .col-status { + display: none !important; + } + + .head { + align-items: flex-start; + flex-direction: column; + gap: 8px; + } + + .head-tools { + justify-content: space-between; + width: 100%; + } + + .tools { + width: 100%; + } + + .search { + flex: 1 1 auto; + } + + .search input { + width: 100%; + } + + .sort { + flex: 1 1 100%; + width: 100%; + overflow-x: auto; + } + + .account-main { + grid-template-columns: minmax(0, 1fr) 48px 82px 18px; + gap: 8px; + } + + .provider-main { + grid-template-columns: minmax(0, 1fr) 48px 82px 18px; + gap: 8px; + } + + .provider-main .share-cell, + .provider-main .share-label-cell, + .provider-main .cost-cell, + .provider-main .errors-cell { + display: none; + } + + .account-main .share-cell, + .account-main .share-label-cell, + .account-main .cost-cell, + .account-main .errors-cell { + display: none; + } + + .model-head { + display: none; + } + + .model-row { + grid-template-columns: minmax(0, 1fr) 58px 74px; + gap: 8px; + padding: 7px 12px 8px 20px; + border-top: 1px solid var(--magpie-line); + } + + .model-row .share-cell, + .model-row .share-label-cell, + .model-row .cost-cell, + .model-row > :last-child { + display: none; + } + + .model-row .tokens-cell { + display: block; + } + + .model-row .model-provider, + .model-row .model-split, + .model-row .metric-detail { + display: none; + } + + /* A 420 px tile is too narrow for one line of "In ... · Out ... · + Cache ...". Wrap it instead of cutting the last value off. */ + .summary-sub { + overflow-wrap: anywhere; + text-overflow: clip; + white-space: normal; + } + + .foot { + flex-direction: column; + align-items: flex-start; + gap: 2px; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: .01ms !important; + animation-iteration-count: 1 !important; + transition-duration: .01ms !important; + } +} diff --git a/packages/page-usage-tree/ui/view.js b/packages/page-usage-tree/ui/view.js new file mode 100644 index 0000000..163cd56 --- /dev/null +++ b/packages/page-usage-tree/ui/view.js @@ -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); diff --git a/registry.json b/registry.json index 6b6a981..f46687d 100644 --- a/registry.json +++ b/registry.json @@ -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、项目、模型和用时,回复正文需手动开启。" } },