Files
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

198 lines
6.4 KiB
JavaScript

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 = 8;
export function cacheUsable(data) {
if (!data || !Array.isArray(data.providers) || !Array.isArray(data.accounts)) return false;
const fields = [
"cacheRead",
"cacheWrite",
"cacheUnknown",
"cacheUnknownCalls",
];
const hasFields = (part) => part && typeof part === "object" && fields.every(
(field) => typeof part[field] === "number" && Number.isFinite(part[field]),
);
const parts = [data.summary, ...data.providers, ...data.accounts];
for (const account of data.accounts) parts.push(...(Array.isArray(account?.models) ? account.models : []));
for (const provider of data.providers) {
for (const account of Array.isArray(provider?.accounts) ? provider.accounts : []) {
parts.push(...(Array.isArray(account?.models) ? account.models : []));
}
}
for (const part of parts) {
if (!part || typeof part !== "object") return false;
if (!hasFields(part)) return false;
}
return true;
}
function readCached(period) {
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 = {};
let failures = 0;
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.
failures += 1;
out[key] = null;
}
}),
);
return { requests: out, failures };
}
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 detailRead = missing.length
? await requestsForAccounts(
{ ...usage, accounts: usage.accounts.filter((item) =>
missing.some((account) => account.provider === item.provider && account.account === item.account)) },
period,
options,
)
: { requests: {}, failures: 0 };
return aggregateGatewayUsage(usage, detailRead.requests, {
period,
missingModelAccounts: detailRead.failures,
});
}
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 };