page-usage 0.1.0: a page with calls, errors, tokens and cost at a glance

A new kind of package: a page in magpie's window (magpie.page), with
magpie.permissions ["usage:summary"] and nothing else. Today, 7 or 30
days; models by tokens, calls or cost; the picks are saved through
magpie.options.set (debounced past the bridge's once-a-second limit).
Theme from --magpie-* variables; en and zh text.

Run:
- bun test packages/usage: 6 tests (permissions are exactly what the
  scripts read; no fetch/XHR/WebSocket; no inline scripts; every local
  reference exists; what tiles and rows say).
- Sandbox magpie from yetone/magpie origin/main b03031738: `magpie plugin`
  lists "page Usage glance (reads usage:summary)". `magpie web` on
  127.0.0.1:3595 serves every page file under the sandbox CSP
  (connect-src 'none'); /api/plugin-pages/read usage:summary answers the
  sandbox's 10 calls; providers:list is refused 403. Headless Chromium and
  WebKit (playwright 1.62.0) opened the sidebar tab: tiles "Calls 10,
  Errors 0, Tokens 70, Cost $0", row "stub-1 70 · 10 calls", no console
  errors; picking 7 days wrote "period": "7d" to plugins.json.
This commit is contained in:
yetone
2026-10-16 02:57:43 +08:00
parent bd6e1ed387
commit 8828f7731c
8 changed files with 409 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
# @magpie-community/page-usage
A page in [magpie](https://usemagpie.ai)'s window with your usage at a glance. It shows calls, errors, tokens and cost for today, 7 days or 30 days, and the models that took them.
Install it from magpie's **Plugins › Discover**, or with `magpie plugin add @magpie-community/page-usage`. It then has a tab, **Usage glance**, under Plugins in the sidebar, in the app and in `magpie web`.
## What it reads
Only `usage:summary`, the one permission its `package.json` declares (`magpie.permissions`). That is magpie's totals for a period, and the top models in it. magpie refuses any other read the page asks for.
Like every plugin page, it runs in a sandboxed frame. It has no network (`connect-src 'none'`), no inline scripts, and no access to magpie's API except through `_magpie/bridge.js`.
## Options
```json
{ "period": "today", "sort": "tokens" }
```
The page saves the period (`today`, `7d`, `30d`) and the model sort (`tokens`, `calls`, `cost`) you last picked, so it opens the same next time.
## Files
- `page/index.html`, `page/style.css`: the page. It takes magpie's theme from the `--magpie-*` variables, light or dark.
- `page/view.js`: what the numbers and rows say, in English and Chinese, with no DOM. The test loads it.
- `page/app.js`: reads through the bridge, draws, and refreshes every minute.
## Test
```sh
bun test packages/usage
```
中文:在 magpie 窗口里加一个「Usage glance」页面,一眼看到今天、7 天或 30 天的调用、错误、token 和费用,以及用到的模型。它只读取声明过的 `usage:summary`,运行在无网络的沙盒 frame 里。
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@magpie-community/page-usage",
"version": "0.1.0",
"description": "A page in magpie's window with your usage at a glance: calls, errors, tokens and cost for today, 7 or 30 days, and the models that took them",
"files": ["page", "README.md"],
"keywords": ["magpie", "magpie-page", "usage", "tokens", "cost"],
"license": "MIT",
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/usage" },
"magpie": {
"page": { "title": "Usage glance", "file": "page/index.html", "icon": "page/icon.svg" },
"permissions": ["usage:summary"],
"options": { "period": "today", "sort": "tokens" }
}
}
+106
View File
@@ -0,0 +1,106 @@
// The page: reads usage:summary (the only read package.json declares) for
// the period picked, and keeps the period and the sort in this plugin's
// own options so the page opens where it was left.
(async () => {
const V = globalThis.UsageView;
const $ = (id) => document.getElementById(id);
const theme = await magpie.ready;
let lang = theme.lang;
let opts = {};
try { opts = (await magpie.options.get()) || {}; } catch {}
const state = {
period: V.PERIODS.includes(opts.period) ? opts.period : "today",
sort: V.SORTS.includes(opts.sort) ? opts.sort : "tokens",
summary: null,
};
function words() {
const t = V.text(lang);
document.querySelectorAll("[data-t]").forEach((e) => { e.textContent = t[e.dataset.t]; });
}
function select(group, attr, value) {
$(group).querySelectorAll("button").forEach((b) => b.setAttribute("aria-selected", String(b.dataset[attr] === value)));
}
function paint() {
select("periods", "period", state.period);
select("sorts", "sort", state.sort);
const s = state.summary;
if (!s) return;
$("since").textContent = V.since(s, lang);
$("tiles").replaceChildren(...V.tiles(s, lang).map((t) => {
const d = document.createElement("div");
d.className = "tile" + (t.bad ? " bad" : "");
for (const [cls, v] of [["k", t.label], ["v", t.value], ["s", t.sub]]) {
const e = document.createElement("div");
e.className = cls;
e.textContent = v;
d.append(e);
}
return d;
}));
const rows = V.rows(s, state.sort, lang);
$("empty").hidden = rows.length > 0;
$("empty").textContent = V.text(lang).noCalls;
$("models").replaceChildren(...rows.map((r) => {
const li = document.createElement("li");
const name = document.createElement("span");
name.className = "name";
name.textContent = name.title = r.name;
const num = document.createElement("span");
num.className = "num";
num.textContent = `${r.value} · ${r.detail}`;
const bar = document.createElement("span");
bar.className = "bar";
const fill = document.createElement("i");
fill.style.width = `${Math.max(2, Math.round(r.share * 100))}%`;
bar.append(fill);
li.append(name, num, bar);
return li;
}));
}
async function load() {
try {
state.summary = await magpie.read("usage:summary", { period: state.period });
$("error").hidden = true;
} catch (e) {
$("error").hidden = false;
$("error").textContent = `${V.text(lang).failed}: ${e.message}`;
}
paint();
}
// options can be set once a second: a quick second click is saved with
// the next one
let saving = null;
function save() {
if (saving) return;
saving = setTimeout(async () => {
saving = null;
try { opts = await magpie.options.set({ ...opts, period: state.period, sort: state.sort }); } catch {}
}, 1100);
}
$("periods").addEventListener("click", (e) => {
const p = e.target.closest("button")?.dataset.period;
if (!p || p === state.period) return;
state.period = p;
paint();
load();
save();
});
$("sorts").addEventListener("click", (e) => {
const s = e.target.closest("button")?.dataset.sort;
if (!s || s === state.sort) return;
state.sort = s;
paint();
save();
});
magpie.onTheme((t) => { lang = t.lang; words(); paint(); });
// fresh numbers while the page is open
setInterval(load, 60_000);
words();
await load();
})();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M3 13V8M7 13V4M11 13V9" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 177 B

+37
View File
@@ -0,0 +1,37 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Usage glance</title>
<link rel="stylesheet" href="style.css">
<script src="_magpie/bridge.js"></script>
<script src="view.js"></script>
<script src="app.js" defer></script>
</head>
<body>
<header>
<h1 data-t="title">Usage</h1>
<div class="seg" role="tablist" id="periods">
<button type="button" role="tab" data-period="today" data-t="today">Today</button>
<button type="button" role="tab" data-period="7d" data-t="7d">7 days</button>
<button type="button" role="tab" data-period="30d" data-t="30d">30 days</button>
</div>
</header>
<p class="since" id="since"></p>
<section class="tiles" id="tiles"></section>
<section class="models">
<div class="models-head">
<h2 data-t="models">Models</h2>
<div class="seg small" role="tablist" id="sorts">
<button type="button" role="tab" data-sort="tokens" data-t="tokens">Tokens</button>
<button type="button" role="tab" data-sort="calls" data-t="calls">Calls</button>
<button type="button" role="tab" data-sort="cost" data-t="cost">Cost</button>
</div>
</div>
<ol id="models"></ol>
<p class="empty" id="empty" hidden></p>
</section>
<p class="error" id="error" hidden></p>
</body>
</html>
+36
View File
@@ -0,0 +1,36 @@
:root {
--bg: var(--magpie-bg, #fff);
--card: var(--magpie-card, #f6f6f7);
--fg: var(--magpie-fg, #1d1d1f);
--muted: var(--magpie-muted, #6e6e73);
--line: var(--magpie-line, #e5e5ea);
--accent: var(--magpie-accent, #4f46e5);
--accent-soft: var(--magpie-accent-soft, rgba(79, 70, 229, .14));
--red: var(--magpie-red, #d70015);
}
* { box-sizing: border-box; }
html, body { margin: 0; background: var(--bg); color: var(--fg); }
body { padding: 20px 24px 32px; font: 13px/1.45 var(--magpie-font, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif); }
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
h1 { font-size: 20px; font-weight: 600; margin: 0; letter-spacing: -.01em; }
h2 { font-size: 13px; font-weight: 600; margin: 0; }
.since { color: var(--muted); margin: 4px 0 16px; min-height: 1.45em; }
.seg { display: inline-flex; padding: 2px; border-radius: 8px; background: var(--card); border: 1px solid var(--line); }
.seg button { font: inherit; color: var(--muted); background: none; border: 0; border-radius: 6px; padding: 3px 10px; cursor: default; }
.seg button[aria-selected="true"] { color: var(--fg); background: var(--bg); box-shadow: 0 1px 2px rgba(0, 0, 0, .12); }
.seg.small button { padding: 2px 8px; font-size: 12px; }
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; margin-bottom: 22px; }
.tile { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; min-width: 0; }
.tile .k { color: var(--muted); font-size: 12px; }
.tile .v { font-size: 20px; font-weight: 600; font-variant-numeric: tabular-nums; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tile .s { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
.tile.bad .v { color: var(--red); }
.models-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
ol { list-style: none; margin: 0; padding: 0; }
li { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; padding: 7px 0; border-bottom: 1px solid var(--line); }
li .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--magpie-code, ui-monospace, SFMono-Regular, Menlo, monospace); font-size: 12px; }
li .num { color: var(--muted); font-variant-numeric: tabular-nums; text-align: right; font-size: 12px; }
li .bar { grid-column: 1 / -1; height: 4px; border-radius: 2px; background: var(--accent-soft); overflow: hidden; }
li .bar i { display: block; height: 100%; background: var(--accent); border-radius: 2px; }
.empty, .error { color: var(--muted); margin: 12px 0; }
.error { color: var(--red); }
+90
View File
@@ -0,0 +1,90 @@
// What the page shows, worked out from usage:summary without the DOM, so
// a test can check it. A classic script: it sets globalThis.UsageView.
(() => {
const TEXT = {
en: {
title: "Usage", today: "Today", "7d": "7 days", "30d": "30 days", models: "Models",
tokens: "Tokens", calls: "Calls", cost: "Cost", errors: "Errors", input: "Input", output: "Output",
cacheRead: "cache read", since: "Since", noCalls: "No calls in this period.", rate: "of calls",
perCall: "per call", failed: "Couldn't read usage",
},
zh: {
title: "用量", today: "今天", "7d": "7 天", "30d": "30 天", models: "模型",
tokens: "Token", calls: "调用", cost: "费用", errors: "错误", input: "输入", output: "输出",
cacheRead: "缓存读取", since: "起始于", noCalls: "这段时间没有调用。", rate: "的调用",
perCall: "每次调用", failed: "读取用量失败",
},
};
const PERIODS = ["today", "7d", "30d"];
const SORTS = ["tokens", "calls", "cost"];
function text(lang) {
return String(lang || "").toLowerCase().startsWith("zh") ? TEXT.zh : TEXT.en;
}
// 1234 → "1,234"; 1234567 → "1.23M"
function count(n) {
n = Number(n) || 0;
const a = Math.abs(n);
if (a >= 1e9) return (n / 1e9).toFixed(a >= 1e10 ? 1 : 2) + "B";
if (a >= 1e6) return (n / 1e6).toFixed(a >= 1e7 ? 1 : 2) + "M";
if (a >= 1e5) return (n / 1e3).toFixed(0) + "K";
return Math.round(n).toLocaleString("en-US");
}
function money(n) {
n = Number(n) || 0;
if (n === 0) return "$0";
if (n < 0.01) return "<$0.01";
return "$" + n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function percent(part, whole) {
if (!whole) return "0%";
const p = (part / whole) * 100;
return (p < 1 && p > 0 ? p.toFixed(1) : Math.round(p)) + "%";
}
// tiles are the totals: [{ key, label, value, sub, bad }]
function tiles(s, lang) {
const t = text(lang);
const calls = Number(s.calls) || 0;
const errors = Number(s.errors) || 0;
const input = Number(s.input) || 0;
const output = Number(s.output) || 0;
const cache = Number(s.cacheRead) || 0;
const cost = Number(s.cost) || 0;
return [
{ key: "calls", label: t.calls, value: count(calls), sub: "" },
{ key: "errors", label: t.errors, value: count(errors), sub: calls ? `${percent(errors, calls)} ${t.rate}` : "", bad: errors > 0 },
{ key: "tokens", label: t.tokens, value: count(input + output), sub: `${t.input} ${count(input)} · ${t.output} ${count(output)}` + (cache ? ` · ${t.cacheRead} ${count(cache)}` : "") },
{ key: "cost", label: t.cost, value: money(cost), sub: calls ? `${money(cost / calls)} ${t.perCall}` : "" },
];
}
// rows are the models, by sort: [{ name, value, detail, share }], share
// being the bar's width, 0–1, of the first row's
function rows(s, sort, lang) {
if (!SORTS.includes(sort)) sort = "tokens";
const of = (m) => (sort === "calls" ? Number(m.calls) || 0 : sort === "cost" ? Number(m.cost) || 0 : (Number(m.input) || 0) + (Number(m.output) || 0));
const list = (Array.isArray(s.models) ? s.models : []).slice().sort((a, b) => of(b) - of(a) || String(a.model).localeCompare(String(b.model)));
const top = list.length ? of(list[0]) : 0;
return list.map((m) => ({
name: String(m.model || "?"),
value: sort === "cost" ? money(m.cost) : count(of(m)),
detail: sort === "calls" ? money(m.cost) : `${count(m.calls)} ${text(lang).calls.toLowerCase()}`,
share: top > 0 ? of(m) / top : 0,
}));
}
// since is when the period starts, in the reader's own words
function since(s, lang) {
const t = text(lang);
const d = new Date(s.since);
if (!s.since || isNaN(d)) return "";
const day = d.toLocaleDateString(lang || "en", { year: "numeric", month: "short", day: "numeric" });
return `${t.since} ${day}`;
}
globalThis.UsageView = { PERIODS, SORTS, text, count, money, percent, tiles, rows, since };
})();
+92
View File
@@ -0,0 +1,92 @@
import { expect, test } from "bun:test"
import { readFileSync, readdirSync } from "node:fs"
import { join } from "node:path"
const dir = import.meta.dir
const page = join(dir, "page")
const read = (f) => readFileSync(join(page, f), "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("view.js"))(scope)
const V = scope.UsageView
// usage:summary as magpie answers it (pluginpage.go, pageRead)
const summary = {
period: "7d", since: "2026-10-09T00:00:00+08:00", calls: 1234, errors: 12,
input: 3456789, output: 210000, cacheRead: 2000000, cost: 41.5,
models: [
{ model: "claude-sonnet-4-5", calls: 200, input: 3000000, output: 150000, cost: 30 },
{ model: "gpt-5-codex", calls: 1000, input: 450000, output: 50000, cost: 11 },
{ model: "deepseek-chat", calls: 34, input: 6789, output: 10000, cost: 0.5 },
],
}
test("asks for one read, usage:summary, and nothing else", () => {
expect(pkg.magpie.permissions).toEqual(["usage:summary"])
const reads = new Set()
for (const f of readdirSync(page).filter((f) => f.endsWith(".js"))) {
for (const m of read(f).matchAll(/magpie\.read\(\s*"([^"]+)"/g)) reads.add(m[1])
// no way out of the frame: magpie's policy refuses these anyway
expect(read(f)).not.toMatch(/\bfetch\(|XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts/)
}
expect([...reads]).toEqual(["usage:summary"])
})
test("is a page magpie serves: its files in page/, scripts as files", () => {
expect(pkg.main).toBeUndefined()
expect(pkg.exports).toBeUndefined()
expect(pkg.magpie.page).toEqual({ title: "Usage glance", file: "page/index.html", icon: "page/icon.svg" })
const html = read("index.html")
expect(html).toContain('<script src="_magpie/bridge.js"></script>')
// the policy runs no inline script
for (const m of html.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/g)) {
expect(m[1]).toMatch(/\ssrc="/)
expect(m[2].trim()).toBe("")
}
for (const m of html.matchAll(/(?:src|href)="([^"]+)"/g)) {
if (m[1].startsWith("_magpie/")) continue
expect(m[1]).not.toMatch(/^(?:[a-z]+:|\/|\.\.)/i)
expect(readdirSync(page)).toContain(m[1])
}
})
test("totals: calls, errors with their share, tokens, cost", () => {
expect(V.tiles(summary, "en")).toEqual([
{ key: "calls", label: "Calls", value: "1,234", sub: "" },
{ key: "errors", label: "Errors", value: "12", sub: "1.0% of calls", bad: true },
{ key: "tokens", label: "Tokens", value: "3.67M", sub: "Input 3.46M · Output 210K · cache read 2.00M" },
{ key: "cost", label: "Cost", value: "$41.50", sub: "$0.03 per call" },
])
expect(V.tiles(summary, "zh-CN")[0].label).toBe("调用")
})
test("an empty period has nothing to divide by", () => {
const t = V.tiles({ calls: 0, errors: 0, input: 0, output: 0, cacheRead: 0, cost: 0, models: [] }, "en")
expect(t.map((x) => x.value)).toEqual(["0", "0", "0", "$0"])
expect(t[1]).toMatchObject({ sub: "", bad: false })
expect(V.rows({ models: [] }, "tokens")).toEqual([])
expect(V.since({ since: "0001-01-01T00:00:00Z" }, "en")).toContain("Since")
expect(V.since({}, "en")).toBe("")
})
test("models sort by tokens, calls or cost, the bar a share of the first", () => {
const byTokens = V.rows(summary, "tokens", "en")
expect(byTokens.map((r) => r.name)).toEqual(["claude-sonnet-4-5", "gpt-5-codex", "deepseek-chat"])
expect(byTokens[0]).toEqual({ name: "claude-sonnet-4-5", value: "3.15M", detail: "200 calls", share: 1 })
expect(V.rows(summary, "calls", "en").map((r) => [r.name, r.value, r.detail])).toEqual([
["gpt-5-codex", "1,000", "$11.00"], ["claude-sonnet-4-5", "200", "$30.00"], ["deepseek-chat", "34", "$0.50"],
])
const byCost = V.rows(summary, "cost", "zh")
expect(byCost.map((r) => r.value)).toEqual(["$30.00", "$11.00", "$0.50"])
expect(byCost[1].share).toBeCloseTo(11 / 30)
expect(byCost[0].detail).toBe("200 调用")
// a sort it doesn't know is tokens
expect(V.rows(summary, "nope", "en")[0].name).toBe("claude-sonnet-4-5")
})
test("numbers read short", () => {
expect([V.count(999), V.count(12345), V.count(123456), V.count(1234567), V.count(12345678), V.count(2.5e9)]).toEqual(["999", "12,345", "123K", "1.23M", "12.3M", "2.50B"])
expect([V.money(0), V.money(0.004), V.money(1234.5)]).toEqual(["$0", "<$0.01", "$1,234.50"])
})