Files
plugins/packages/page-usage-tree/page/boot.js
T
CHENZUDE 1e060e6163 page-usage-tree 0.1.1: refresh warning only on a real failure, hit rate and model-detail fixes (#960)
page-usage-tree 0.1.1 (CHENZUDE):

- A failed refresh is kept on the cache entry the page reads, so
  "Refresh failed; showing the previous data" shows when a refresh threw
  (on 0.1.0 it was written to an entry already replaced and never shown).
  Only a loader that threw counts: an older disk cache marked stale does
  not, and a retry from a failed entry stays failed until a loader succeeds.
  The page takes the server's X-Usage-Tree-Refresh on every answer, quiet
  follow-ups included, so the warning clears once the gateway recovers.
- Hit rate uses magpie's hitPct rounding (0.9996 shows 99.96%, not 100%).
- A failed per-account model-detail read keeps the account totals and says
  model details are incomplete (zh, en). Disk cache v8.
- Not in the PR body: a /bridge.js shim served by the service (talks only to
  parent: hello, options.get/set, theme and visibility), request timeout
  10s -> 30s, narrow breakpoint 620px -> 700px, model split on narrow
  screens, "permissions": [] added (same as absent), zh warnings joined
  with ";".

Run at the reviewed head 74363201570d9f69866ac0e4afff7a2b898e6dab:
- WSL (magpie-desktop), fresh HOME: bun test packages/page-usage-tree
  62 pass 1 skip (parity needs a live magpie); node --test 68 pass 1 skip;
  bun scripts/check.mjs ok.
- Windows (xiaomi-gpu), fresh HOME and USERPROFILE: bun test
  packages/page-usage-tree exit 0; bun scripts/check.mjs ok. CI green.
- Playwright 1.62 Chromium and WebKit on WSL, sandbox server with fake
  data, 1280 and 420px, en and zh: a first open from a stale disk cache
  never shows the refresh warning; a failed manual refresh shows it, it
  stays while the gateway is down, and clears on the quiet follow-ups after
  recovery while the model-detail warning stays; no page errors, no
  horizontal scroll. The same probe on e3da32bed fails 3 checks (false
  warning on open, warning never clears, zh joined by a space).
- Broken by hand: counting data.stale as failed, a retry entry forgetting
  the failure, and a quiet load never clearing each turn a test red.
  Not covered by a test: dropping warningStateChanged (render also runs
  renderWarnings) and the zh join between two data warnings.
- Host/Origin/token handling on /api/tree unchanged from main; /bridge.js
  is static and behind the Host check. dist had only 0.1.0.
2026-11-11 15:18:33 +08:00

160 lines
5.1 KiB
JavaScript

(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,
};
let officialDisplay = false;
function hasOfficialDisplay(value) {
if (!value || typeof value !== "object") return false;
return (
value.currency === "cny" ||
value.currency === "usd" ||
typeof value.chineseUnits === "boolean" ||
(Number.isFinite(Number(value.usdCny)) && Number(value.usdCny) > 0) ||
(Number.isFinite(Number(value.fx?.rate)) && Number(value.fx.rate) > 0)
);
}
function followDisplay(value, official = false) {
// A future bridge can carry Magpie's own display settings. Until it does,
// this plugin's options are the only supported fallback.
if (official && !hasOfficialDisplay(value)) return;
if (official && !officialDisplay) {
display.currency = "usd";
display.chineseUnits = false;
display.usdCny = 0;
}
if (official) officialDisplay = true;
if (officialDisplay && !official) return;
if (!value || typeof value !== "object") return;
if (value.currency === "cny" || value.currency === "usd") {
display.currency = value.currency;
}
if (typeof value.chineseUnits === "boolean") {
display.chineseUnits = value.chineseUnits;
}
const rate = Number(value.usdCny);
if (Number.isFinite(rate) && rate > 0) display.usdCny = rate;
const nestedRate = Number(value.fx?.rate);
if (Number.isFinite(nestedRate) && nestedRate > 0) display.usdCny = nestedRate;
}
function followLanguage(value) {
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, true);
}
} 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;
followDisplay(next, true);
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));
query.set("settings", "1");
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);
})();