Trends: one chart area for every metric, Money included, drawn by the shared module
ci/woodpecker/push/woodpecker Pipeline failed

Money was its own tab with its own renderers (renderMoney, renderMoneyCumulative,
renderMoneyDaily, renderMoneyLegend), its own period and spend-mode toggles, and
its own titles. It is now a metric of Trends like the others: the definitions come
from CoOpChart.CHART_METRICS, the chart is drawn by the shared renderChart(), and
the Money tab is a shortcut into Trends with that metric selected.

Removed: TREND_CONF, trendVal, trendLabel, the four money renderers, the
period/spend-mode toggles (the single Period row governs every metric now) — 5.1k
chars of duplicate chart code. Added: METRIC_SOURCE (which fetch each metric
needs), buildMetricButtons() (buttons rendered from the shared list, so the panel
and dashboard describe the same charts in the same order), and the metric-aware
renderTrends() that delegates.

The daily token-spend view is now the shared "spend" metric — the same numbers the
metrics endpoint already served, so nothing is lost by dropping the second source.
No caption under the money chart, as before.

Harness rewritten for the new path (it drove renderMoney): invariants preserved —
2 cumulative polylines + single-point balance marker, shared tooltip host, legend
that IS the definition's series list, 5 ascending ticks with the top clearing the
max, 30-day slice. New: every shared metric has a button, and a metric with no
source says so instead of drawing another chart. Tests green (page JS, pins,
guest guard).
This commit is contained in:
inference-admin committed 2026-11-13 20:55:59 +00:00
1 parent 79f3f00165
commit fba50e3f93
5 files changed
+390 -288

No files matched your search

+127 -246
View File
@@ -484,7 +484,7 @@ PAGE_HTML = """<!DOCTYPE html>
<button class="tab-btn active" id="tab-members" onclick="switchView('members')">Members</button>
<button class="tab-btn" id="tab-models" onclick="switchView('models')">Model usage</button>
<button class="tab-btn" id="tab-trends" onclick="switchView('trends')">Trends</button>
<button class="tab-btn" id="tab-money" onclick="switchView('money')">Money</button>
<button class="tab-btn" id="tab-money" onclick="showMoney()">Money</button>
<span class="range-group" id="member-mode-group">
<button class="range-btn active" id="mmode-balance" onclick="setMemberMode('balance')">Balance</button>
<button class="range-btn" id="mmode-all" onclick="setMemberMode('all')">All time</button>
@@ -552,13 +552,13 @@ PAGE_HTML = """<!DOCTYPE html>
<div id="trends-section" style="display:none;">
<div class="trend-controls">
<span class="range-group">
<span class="range-group" id="trend-metrics">
<span class="range-label">Show</span>
<button class="range-btn active" id="tm-members" onclick="setTrendMetric('members')">Members</button>
<button class="range-btn" id="tm-spend" onclick="setTrendMetric('spend')">Spend</button>
<button class="range-btn" id="tm-energy" onclick="setTrendMetric('energy')">Energy</button>
<button class="range-btn" id="tm-co2e" onclick="setTrendMetric('co2e')">Carbon</button>
<button class="range-btn" id="tm-requests" onclick="setTrendMetric('requests')">Requests</button>
<!-- The metric buttons are rendered from CoOpChart.CHART_METRICS, so this
panel and the member dashboard describe the same charts, in the same
order, with the same titles — Money included, as one metric among the
others. Editing the list here would defeat that: edit the canonical
module (ops-docs scripts/shared/coop_chart.js) instead. -->
</span>
<span class="range-group">
<span class="range-label">Period</span>
@@ -570,34 +570,12 @@ PAGE_HTML = """<!DOCTYPE html>
<div class="trend-card">
<div class="trend-head">
<span class="trend-title" id="trend-title">Members</span>
<span id="trend-legend" class="money-legend"></span>
</div>
<div id="trend-body" class="trend-body"><p class="trend-empty">Loading</p></div>
</div>
</div>
<div id="money-section" style="display:none;">
<div class="trend-controls">
<span class="range-group">
<span class="range-label">Period</span>
<button class="range-btn" id="mp-30" onclick="setMoneyPeriod(30)">Last 30 days</button>
<button class="range-btn active" id="mp-90" onclick="setMoneyPeriod(90)">Last 90 days</button>
<button class="range-btn" id="mp-all" onclick="setMoneyPeriod(0)">All time</button>
</span>
<span class="range-group">
<span class="range-label">Token spend</span>
<button class="range-btn active" id="ms-cum" onclick="setMoneySpendMode('cum')">Cumulative</button>
<button class="range-btn" id="ms-daily" onclick="setMoneySpendMode('daily')">Daily</button>
</span>
</div>
<div class="trend-card">
<div class="trend-head">
<span class="trend-title" id="money-title">Revenue, spend and balance</span>
<span id="money-legend" class="money-legend"></span>
</div>
<div id="money-body" class="trend-body"><p class="trend-empty">Loading</p></div>
</div>
</div>
<div id="agents-section" style="display:none;">
<h3 style="margin:20px 0 8px;">Agents</h3>
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Bot and sandbox accounts. Not members — excluded from member counts; their usage is a collective expense.</p>
@@ -733,14 +711,43 @@ let trendsData = null;
let trendMetric = "members"; // members | spend | requests
let trendDays = 90; // 0 = all time
const TREND_CONF = {
members: { kind: "line", title: "Members", cont: false },
requests: { kind: "bar", title: "Requests per day", cont: false },
spend: { kind: "bar", title: "Spend per day", cont: true },
energy: { kind: "bar", title: "Energy per day", cont: true },
co2e: { kind: "bar", title: "Carbon per day", cont: true }
// ---- Trends: ONE chart area, described by the shared module ----
// Every metric this page can show — Money included — is defined once in
// CoOpChart.CHART_METRICS (canonical: ops-docs scripts/shared/coop_chart.js),
// which the member dashboard reads as well. This app owns the DATA (which
// endpoint feeds a metric, and which fetch it is allowed to make) and the DOM;
// the chart itself — titles, shape, axis rule, formatters — comes from the
// module, so the two UIs cannot drift apart again.
//
// A metric with no entry here is one this page can draw from ANOTHER source:
// METRIC_SOURCE maps metric -> fetch. Adding a metric to the shared list puts
// its button in both UIs at once; wiring it in one app only is what this map is.
const METRIC_SOURCE = {
members: "metrics", requests: "metrics", spend: "metrics",
energy: "metrics", co2e: "metrics",
money: "money"
};
function buildMetricButtons() {
const row = $("trend-metrics");
if (!row || row.getAttribute("data-built") === "1") return;
let html = "";
for (const def of CHART_METRICS) {
html += '<button class="range-btn" id="tm-' + def.id + '"'
+ " onclick=\"setTrendMetric('" + def.id + "')\">" + esc(def.title) + "</button>";
}
row.insertAdjacentHTML("beforeend", html);
row.setAttribute("data-built", "1");
syncMetricButtons();
}
function syncMetricButtons() {
for (const def of CHART_METRICS) {
const b = $("tm-" + def.id);
if (b) b.className = "range-btn" + (def.id === trendMetric ? " active" : "");
}
}
async function loadMetrics() {
if (trendsData) { renderTrends(); return; }
const host = $("trend-body");
@@ -756,14 +763,42 @@ async function loadMetrics() {
}
}
// The money metric's rows come from /api/money-series (the OC queries behind it
// are slow, so the portal caches them server-side). Fetched on first use.
async function loadMoneySeries() {
if (moneyData) { renderTrends(); return; }
const host = $("trend-body");
try {
const r = await fetch("/api/money-series");
if (r.status === 403) { host.innerHTML = "<p class=trend-empty>Forbidden</p>"; return; }
const d = await r.json();
if (d.error) { host.innerHTML = "<p class=trend-empty>" + esc(d.error) + "</p>"; return; }
moneyData = d;
renderTrends();
} catch (e) {
host.innerHTML = "<p class=trend-empty>Could not load the money series.</p>";
}
}
// Rows for a metric, or null when this page cannot get them. One place decides
// which fetch a metric needs, so setTrendMetric and the first paint agree.
function metricRows(id) {
const src = METRIC_SOURCE[id];
if (!src) return null;
if (src === "money") return moneyData ? (moneyData.series || []) : null;
return trendsData;
}
function loadForMetric() {
const src = METRIC_SOURCE[trendMetric];
if (src === "money") { if (moneyData) renderTrends(); else loadMoneySeries(); return; }
if (trendsData) renderTrends(); else loadMetrics();
}
function setTrendMetric(m) {
trendMetric = m;
$("tm-members").className = "range-btn" + (m === "members" ? " active" : "");
$("tm-spend").className = "range-btn" + (m === "spend" ? " active" : "");
$("tm-energy").className = "range-btn" + (m === "energy" ? " active" : "");
$("tm-co2e").className = "range-btn" + (m === "co2e" ? " active" : "");
$("tm-requests").className = "range-btn" + (m === "requests" ? " active" : "");
renderTrends();
syncMetricButtons();
loadForMetric();
}
function setTrendDays(d) {
@@ -774,22 +809,6 @@ function setTrendDays(d) {
renderTrends();
}
function trendVal(row) {
if (trendMetric === "members") return row.members_total;
if (trendMetric === "spend") return row.spend_usd;
if (trendMetric === "energy") return row.energy_wh;
if (trendMetric === "co2e") return row.co2e_g;
return row.requests;
}
function trendLabel(v) {
if (v === null || v === undefined) return "not measured";
if (trendMetric === "spend") return fmt(v);
if (trendMetric === "energy") return Number(v).toLocaleString() + " Wh";
if (trendMetric === "co2e") return Number(v).toLocaleString() + " g";
return Number(v).toLocaleString();
}
// ---- Shared chart module ----
// Chart rendering + the exact-value hover tooltips come from the shared
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
@@ -800,198 +819,53 @@ function trendLabel(v) {
const {
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
drawLineRuns, hoverTargets
drawLineRuns, hoverTargets,
CHART_METRICS, metricDef, fmtMetric, fmtMoney, renderChart
} = CoOpChart;
function renderTrends() {
const host = $("trend-body");
if (!host || !trendsData) return;
if (!host) return;
hideChartTip();
const conf = TREND_CONF[trendMetric];
const rows = trendDays === 0 ? trendsData : trendsData.slice(-trendDays);
$("trend-title").textContent = conf.title;
const vals = rows.map(trendVal);
// Register the EXACT values the tooltips will show, straight from the data
// rows - one point per index, in the same order as the stamped elements.
registerChartTips("trend-body", rows.map((row, i) => ({
label: row.day,
series: [[conf.title, trendLabel(vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) {
host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>";
const def = metricDef(trendMetric);
const legendEl = $("trend-legend");
$("trend-title").textContent = def.title;
const all = metricRows(trendMetric);
if (!all) {
// Two different situations, said differently: a metric this page HAS a
// source for but has not fetched yet, and one it has no source for at all.
host.innerHTML = METRIC_SOURCE[trendMetric]
? "<p class=trend-empty>Loading</p>"
: "<p class=trend-empty>Not available on this page.</p>";
if (legendEl) legendEl.innerHTML = "";
return;
}
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, conf.cont);
const fr = chartFrame({
n: vals.length,
top: step * 4,
step,
tickLabel: trendLabel,
aria: conf.title + " over time",
gridStroke: "var(--border)"
});
if (conf.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
} else {
// Measured runs only: a gap stays a gap (the module breaks the line).
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, "trend-body");
const rows = trendDays === 0 ? all : all.slice(-trendDays);
// One renderer for every metric, shared with the member dashboard: it draws
// the chart, registers the exact tooltip values, and hands back the legend.
const out = renderChart({ host: "trend-body", def, rows, gridStroke: "var(--border)" });
if (out.empty) {
host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>";
if (legendEl) legendEl.innerHTML = "";
return;
}
host.innerHTML = out.svg;
if (legendEl) {
legendEl.innerHTML = out.legend.map(it =>
'<span class="key"><span class="sw" style="background:' + it.color + '"></span>'
+ esc(it.name) + "</span>").join("");
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
// ---- Money: revenue / token spend / OC balance over time ----
// Three series with different provenance, from the portal's
// /admin/money-series (hourly-cached server-side; the OC queries are slow).
// One fetch at full range; the period and spend-mode toggles re-render
// client-side. The balance series exists only from the daily-snapshot
// deployment date onward (the OC API exposes just the CURRENT balance), so
// it renders as a gap before that — never a zero. No caption under the chart:
// the data explains itself (the operator dropped the balance-history caveat).
// ---- Money is now a metric of Trends, like everything else ------------
// The chart (cumulative revenue, cumulative token spend, and the OC balance —
// which exists only from the day the snapshots began, so it draws as a gap
// before that, never a zero) is DEFINED in the shared module and drawn by
// renderTrends() when the money metric is selected: the same chart the member
// dashboard draws from the same definition. This page keeps only the rows it
// fetched; the period toggle above governs it like every other metric, so the
// separate period/spend-mode controls are gone.
let moneyData = null;
let moneyLoaded = false;
let moneyPeriod = 90; // 0 = all time
let moneySpendMode = "cum"; // "cum" = cumulative lines | "daily" = daily bars
const MONEY_COLORS = { revenue: "var(--green-deep)", spend: "#4a6a8a", balance: "#a97a2a" };
async function loadMoney() {
if (moneyLoaded) { renderMoney(); return; }
const host = $("money-body");
try {
const r = await fetch("/api/money-series");
if (r.status === 403) { host.innerHTML = "<p class=trend-empty>Forbidden</p>"; return; }
const d = await r.json();
if (d.error) { host.innerHTML = "<p class=trend-empty>" + esc(d.error) + "</p>"; return; }
moneyData = d;
moneyLoaded = true;
renderMoney();
} catch (e) {
host.innerHTML = "<p class=trend-empty>Could not load the money series.</p>";
}
}
function setMoneyPeriod(d) {
moneyPeriod = d;
$("mp-30").className = "range-btn" + (d === 30 ? " active" : "");
$("mp-90").className = "range-btn" + (d === 90 ? " active" : "");
$("mp-all").className = "range-btn" + (d === 0 ? " active" : "");
renderMoney();
}
function setMoneySpendMode(m) {
moneySpendMode = m;
$("ms-cum").className = "range-btn" + (m === "cum" ? " active" : "");
$("ms-daily").className = "range-btn" + (m === "daily" ? " active" : "");
renderMoney();
}
function moneyFmt(v) {
if (v === null || v === undefined) return "not measured";
return fmt(v);
}
// Money ticks use the 1/2/5 x 10^k rule (niceStep(raw, true) from the shared
// module). Steps at or above $1 are integers; below, show cents so a $0.50
// tick does not round to $1.
function moneyTickLabel(v) {
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
}
function renderMoney() {
const host = $("money-body");
if (!host || !moneyData) return;
hideChartTip();
renderMoneyLegend();
const all = moneyData.series || [];
const rows = moneyPeriod === 0 ? all : all.slice(-moneyPeriod);
if (rows.length < 2) { host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>"; return; }
if (moneySpendMode === "daily") renderMoneyDaily(host, rows);
else renderMoneyCumulative(host, rows);
}
function renderMoneyLegend() {
const items = [
{ c: MONEY_COLORS.revenue, t: "Revenue — OC contributions (cumulative)" },
{ c: MONEY_COLORS.spend, t: moneySpendMode === "daily" ? "Token spend — daily" : "Token spend — cumulative" }
];
if (moneySpendMode !== "daily") {
items.push({ c: MONEY_COLORS.balance, t: "OC balance" });
}
$("money-legend").innerHTML = items.map(it =>
'<span class="key"><span class="sw" style="background:' + it.c + '"></span>' + esc(it.t) + '</span>'
).join("");
}
function renderMoneyCumulative(host, rows) {
const series = [
{ name: "Revenue", key: "revenue_cum", color: MONEY_COLORS.revenue },
{ name: "Token spend", key: "spend_cum", color: MONEY_COLORS.spend },
{ name: "OC balance", key: "oc_balance", color: MONEY_COLORS.balance }
];
const tops = [];
for (const s of series) {
for (const r of rows) { const v = r[s.key]; if (v !== null && v !== undefined) tops.push(v); }
}
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length,
top: step * 4,
step,
tickLabel: moneyTickLabel,
aria: "Cumulative revenue, token spend and OC balance over time"
});
registerChartTips("money-body", rows.map(r => ({
label: r.day,
series: series.map(s => [s.name, moneyFmt(r[s.key])])
})));
for (const s of series) {
// Measured runs only: a NULL (the balance before snapshots began) stays a
// gap — the line is never drawn through invented history.
drawLineRuns(fr, rows.map(r => r[s.key]), { color: s.color, dotSingle: true, dotR: 3 });
}
// Hover targets: one transparent circle per measured point on every series;
// the tooltip lists all three series at that x.
for (const s of series) {
hoverTargets(fr, rows.map(r => r[s.key]), "money-body");
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
function renderMoneyDaily(host, rows) {
// Daily token spend as bars. Revenue and balance are cumulative figures and
// would need a second axis beside daily ones, so this mode is spend-only —
// the legend says which series is shown.
const vals = rows.map(r => r.spend_day);
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) { host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>"; return; }
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length,
top: step * 4,
step,
tickLabel: moneyTickLabel,
aria: "Token spend per day"
});
registerChartTips("money-body", rows.map(r => ({
label: r.day,
series: [["Token spend (daily)", moneyFmt(r.spend_day)]]
})));
drawBars(fr, vals, { color: MONEY_COLORS.spend, host: "money-body" });
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
// ---- shared state ----
let membersData = [];
@@ -1020,6 +894,14 @@ function clearArrows(table, sortState) {
});
}
// Money: a shortcut into Trends with the money metric selected — one chart
// area, one code path, the same chart the member dashboard draws.
function showMoney() {
buildMetricButtons();
switchView('trends');
setTrendMetric('money');
}
function switchView(view) {
currentView = view;
hideChartTip();
@@ -1031,22 +913,20 @@ function switchView(view) {
$('admins-section').style.display = view === 'members' ? '' : 'none';
$('agents-section').style.display = view === 'members' ? '' : 'none';
$('trends-section').style.display = view === 'trends' ? '' : 'none';
$('money-section').style.display = view === 'money' ? '' : 'none';
$('tab-members').className = 'tab-btn' + (view === 'members' ? ' active' : '');
$('tab-models').className = 'tab-btn' + (view === 'models' ? ' active' : '');
$('tab-trends').className = 'tab-btn' + (view === 'trends' ? ' active' : '');
$('tab-money').className = 'tab-btn' + (view === 'money' ? ' active' : '');
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : (view === 'trends' ? 'Trends' : 'Money'));
// Money is a metric of Trends, so its tab shows the Trends title.
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : 'Trends');
// Mode groups: Balance/All-time for members; Period for models; the guest
// invite form belongs to the members view too.
$('range-group').style.display = view === 'models' ? '' : 'none';
$('member-mode-group').style.display = view === 'members' ? '' : 'none';
$('guest-invite-section').style.display = view === 'members' ? '' : 'none';
// Trends renders on first visit only, so the panel's initial load stays fast.
if (view === 'trends') loadMetrics();
// Money renders on first visit only, same rule: one fetch, then the
// period/spend toggles re-render client-side.
if (view === 'money') loadMoney();
// loadForMetric fetches whatever the SELECTED metric needs (the money rows
// come from a different endpoint than the rest).
if (view === 'trends') loadForMetric();
render();
}
@@ -1349,6 +1229,7 @@ async function sendGuestAccess(ev) {
// inviter, credits, expiry and status, exactly like admin-created ones.
// The portal's /admin/guest-ledger still feeds the duplicate-send guard.
buildMetricButtons();
load();
loadModels();
</script>