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
+386 -284

No files matched your search

+161 -1
View File
@@ -44,6 +44,21 @@
* drawBars(fr, vals, opts) bars; NULLs skipped (no zero bars).
* drawLineRuns(fr, vals, opts) lines broken into measured runs.
* hoverTargets(fr, vals, host) transparent hover circles on measured points.
*
* Definition layer — the ONE place a chart is described (both UIs read it):
* CHART_METRICS the metric list, in order: id, title, kind (line|bar|multi),
* cont (continuous axis), fmt (money|count|wh|g), val(row);
* "multi" carries `series` (the money chart). Anything a
* member may see belongs in this list.
* metricDef(id) the definition for a metric id.
* fmtMoney/fmtMetric/fmtMoneyTick shared value formatters, so both apps'
* labels match byte for byte.
* renderChart({host, def, rows, aria}) -> { svg, legend, empty? }
* one renderer for both UIs: registers the EXACT tooltip
* values, breaks lines at NULLs (a gap is never a zero), and
* returns markup plus legend items. The APP writes the DOM —
* element ids, toggle class names and empty-state markup are
* the only parts that legitimately differ per app.
*/
(function (global) {
"use strict";
@@ -241,6 +256,144 @@
}
}
// ==== Chart definitions — the ONE place a chart is described ==============
// A chart is DATA here, not markup: the same metrics, in the same order, with
// the same titles and the same shape in every UI. Each app supplies its own
// data rows and its own DOM (its toggle classes, its empty-state markup, its
// legend element), which is the only thing that legitimately differs.
//
// WHY: the two UIs had drifted while sharing only the drawing primitives —
// the same five metrics shipped with different titles and different chart
// kinds (the panel's "Spend per day" was the dashboard's "What the co-op
// spent (members + the co-op's own accounts)"). Anything a member may see
// belongs in THIS list, so it exists once and cannot drift again.
//
// fmt selects the value formatter: "money" | "count" | "wh" | "g".
// kind is "line" | "bar" | "multi" (multi = N series on one axis, the money
// chart: cumulative revenue, cumulative token spend, and the OC balance,
// which only exists from the day the snapshots began, so it draws as a gap
// before that — never as a zero).
const CHART_METRICS = [
{ id: "members", title: "Members", kind: "line", cont: false, fmt: "count",
val: r => r.members_total },
{ id: "requests", title: "Requests per day", kind: "bar", cont: false, fmt: "count",
val: r => r.requests },
{ id: "spend", title: "Token spend per day", kind: "bar", cont: true, fmt: "money",
val: r => r.spend_usd },
{ id: "money", title: "Money", kind: "multi", cont: true, fmt: "money",
aria: "Cumulative revenue, token spend and OC balance over time",
series: [
{ name: "Revenue", key: "revenue_cum", color: "var(--green-deep)" },
{ name: "Token spend", key: "spend_cum", color: "#4a6a8a" },
{ name: "OC balance", key: "oc_balance", color: "#a97a2a", dotSingle: true }
] },
{ id: "energy", title: "Energy per day", kind: "bar", cont: true, fmt: "wh",
val: r => r.energy_wh },
{ id: "co2e", title: "Carbon per day", kind: "bar", cont: true, fmt: "g",
val: r => r.co2e_g }
];
function metricDef(id) {
for (let i = 0; i < CHART_METRICS.length; i++) if (CHART_METRICS[i].id === id) return CHART_METRICS[i];
return CHART_METRICS[0];
}
// ---- Value formatting (shared so the two apps' labels match byte for byte;
// both already agreed, this only stops them from diverging) ----
function fmtMoney(v) {
const n = Math.abs(Number(v)) < 0.005 ? 0 : (Number(v) || 0);
return "$" + n.toFixed(2);
}
function fmtMetric(def, v) {
if (v === null || v === undefined) return "not measured"; // the gap rule
switch (def && def.fmt) {
case "money": return fmtMoney(v);
case "wh": return Number(v).toLocaleString() + " Wh";
case "g": return Number(v).toLocaleString() + " g";
default: return Number(v).toLocaleString();
}
}
// Money-axis ticks: the 1/2/5 x 10^k rule (niceStep continuous) with integer
// dollars at or above $1 and cents below, so a $0.50 tick does not read "$1".
function fmtMoneyTick(v) {
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
}
// ---- The chart renderer: one implementation for both UIs ----
// renderChart({ host, def, rows, aria }) -> { svg, legend }
// * registers the EXACT tooltip values (the module's contract) under `host`
// * returns the SVG string and the legend items; the APP writes the DOM,
// because that is the part that differs (element ids, class names)
// * a NULL value stays a GAP: no zero, no bar, and no tooltip stamp
// `rows` for a "multi" chart carry the series keys; otherwise `def.val(row)`.
function renderChart(cfg) {
const def = cfg.def, rows = cfg.rows || [], host = cfg.host;
const legend = [];
if (def.kind === "multi") {
const series = def.series || [];
const vals = series.map(s => rows.map(r => r[s.key]));
const tops = [];
for (let si = 0; si < vals.length; si++) {
for (let i = 0; i < vals[si].length; i++) {
const v = vals[si][i];
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: def.fmt === "money" ? fmtMoneyTick : (v => fmtMetric(def, v)),
aria: cfg.aria || def.aria || def.title,
gridStroke: cfg.gridStroke || "var(--border)"
});
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: series.map((s, si) => [s.name, fmtMetric(def, vals[si][i])])
})));
for (let si = 0; si < series.length; si++) {
const s = series[si];
drawLineRuns(fr, vals[si], {
color: s.color, dotSingle: s.dotSingle !== false, dotR: 3,
area: !!s.area, areaOpacity: s.areaOpacity
});
hoverTargets(fr, vals[si], host);
legend.push({ color: s.color, name: s.name });
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
const vals = rows.map(def.val);
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: [[def.title, fmtMetric(def, vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) return { svg: "", legend, empty: true };
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, def.cont);
const tickLabel = v => fmtMetric(def, v);
const fr = chartFrame({
n: vals.length, top: step * 4, step, tickLabel,
aria: cfg.aria || (def.title + " over time"),
gridStroke: cfg.gridStroke || "var(--border)"
});
if (def.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host });
} else {
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, host);
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
// chartTipData is exported for inspection (harnesses assert on the exact
// registered points); treat it as read-only in page code.
global.CoOpChart = {
@@ -256,6 +409,13 @@
dateMarks,
drawBars,
drawLineRuns,
hoverTargets
hoverTargets,
// the definition layer both UIs read
CHART_METRICS,
metricDef,
fmtMoney,
fmtMetric,
fmtMoneyTick,
renderChart
};
})(typeof globalThis !== "undefined" ? globalThis : window);
+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>
+10 -2
View File
@@ -62,12 +62,20 @@ if [ -n "$HARNESS" ]; then
// Minimal browser stubs, loaded BEFORE the page JS: these pages call
// load()/loadModels() at the end of the script, which need document + fetch.
const els = {};
const mkEl = (id) => ({
const mkEl = (id) => {
const el = {
id, style: {}, textContent: "", innerHTML: "", className: "",
offsetWidth: 120, offsetHeight: 48,
getAttribute: () => null,
setAttribute: () => {},
appendChild: () => {},
});
};
// The pages build some markup by inserting HTML into a container
// (buildMetricButtons inserts the SHARED metric list), so the stub has to
// support it or the harness cannot exercise that path at all.
el.insertAdjacentHTML = (pos, html) => { el.innerHTML += html; };
return el;
};
globalThis.document = {
getElementById: (id) => (els[id] = els[id] || mkEl(id)),
querySelectorAll: () => [],
+87 -34
View File
@@ -1,6 +1,16 @@
// Money-chart harness: exercises the real renderMoney against a realistic
// fixture (spend from 09-04, revenue from 09-06, balance only on the last
// day — the deploy-day shape). Asserts chart invariants, not observed shape.
// Money-chart harness: exercises the REAL shared renderer through the panel's
// renderTrends() with the money metric selected, against a realistic fixture
// (spend from 09-04, revenue from 09-06, balance only on the last day — the
// deploy-day shape). Asserts chart invariants, not the shape we happened to see.
//
// WHAT CHANGED AND WHY THIS HARNESS IS DIFFERENT
// Money used to be its own tab with its own renderers (renderMoney,
// renderMoneyCumulative, renderMoneyDaily, renderMoneyLegend) and its own
// period/spend-mode toggles. It is now one metric among the others, defined in
// the shared module (CoOpChart.CHART_METRICS) and drawn by the one shared
// renderer — the same chart the member dashboard draws. So this harness drives
// the metric the way the page does, and asserts the invariants that must hold
// wherever the chart is drawn.
function mkSeries() {
const rows = [];
const start = new Date(Date.UTC(2026, 8, 4)); // 2026-09-04
@@ -18,6 +28,15 @@ function mkSeries() {
}
return rows;
}
function mkMetrics() {
return mkSeries().map((r, i) => ({
day: r.day, members_total: 100 + i, requests: 10 + i,
spend_usd: 1.5 + (i % 7), energy_wh: 40 + i, co2e_g: 12 + i,
operator_spend_usd: 0.5,
}));
}
moneyData = {
caveat: "Balance history begins 2026-11-08: the Open Collective API exposes only the current balance.",
balance_history_start: "2026-11-08",
@@ -25,27 +44,47 @@ moneyData = {
errors: [],
series: mkSeries(),
};
moneyLoaded = true;
trendsData = mkMetrics();
trendDays = 0;
// --- cumulative mode (default) ---
renderMoney();
let svg = $("money-body").innerHTML;
const count = (re) => (svg.match(re) || []).length;
// --- the metric buttons come from the SHARED list (Money included) ---
buildMetricButtons();
for (const def of CHART_METRICS) {
if (!$("tm-" + def.id)) throw new Error("metric button missing for the shared metric: " + def.id);
}
if (!CHART_METRICS.some(d => d.id === "money")) {
throw new Error("the shared metric list must carry Money — it is one of the charts now");
}
// --- money metric: cumulative lines, exact tooltips, gap-safe balance ---
trendMetric = "money";
renderTrends();
svg = $("trend-body").innerHTML;
const polys = count(/<polyline /g);
const rects = count(/<rect /g);
if (polys !== 2) throw new Error("expected 2 cumulative polylines (revenue+spend; balance is single-point), got " + polys);
if (rects !== 0) throw new Error("cumulative mode must not draw bars, got " + rects);
if (!count(/<circle cx="[^"]+" cy="[^"]+" r="3" fill="#a97a2a"/)) throw new Error("single balance point marker missing");
if (!count(/data-tip-host="money-body"/)) throw new Error("hover targets missing");
const legend = $("money-legend").innerHTML;
for (const frag of ["Revenue — OC contributions (cumulative)", "Token spend — cumulative", "OC balance"]) {
if (!legend.includes(frag)) throw new Error("legend missing: " + frag);
if (!count(/data-tip-host="trend-body"/)) throw new Error("hover targets missing");
// The legend must be the DEFINITION's series names — not a second hand-written
// list that can drift from the chart it labels.
const legend = $("trend-legend").innerHTML;
const def = metricDef("money");
for (const s of def.series) {
if (!legend.includes(s.name)) throw new Error("legend missing series: " + s.name);
}
if ((legend.match(/class="key"/g) || []).length !== def.series.length) {
throw new Error("legend lists " + (legend.match(/class="key"/g) || []).length
+ " series, the definition has " + def.series.length);
}
// No caveat anywhere, in any rendering state — even though the fixture still
// carries the payload's caveat field, which the panel must ignore.
// No caveat anywhere, in any rendering state — the panel deliberately has no
// caption under the money chart, even though the fixture carries the caveat.
function assertNoCaveat() {
const rendered = $("money-body").innerHTML + " " + $("money-legend").innerHTML;
const rendered = $("trend-body").innerHTML + " " + $("trend-legend").innerHTML;
for (const bad of ["Balance history begins", "history begins", "Open Collective API exposes", "money-caption"]) {
if (rendered.includes(bad)) throw new Error("caveat/caption text rendered: " + bad);
}
@@ -71,32 +110,46 @@ if (xTicks.length !== 3) throw new Error("expected 3 date marks, got " + xTicks.
const ys = yTicks.map(o => parseFloat(o.y));
if (Math.min.apply(null, ys) !== Math.max.apply(null, ys) && ys[0] !== Math.max.apply(null, ys)) throw new Error("zero tick not lowest");
// --- daily mode: spend bars only, legend relabels, no lines ---
setMoneySpendMode("daily");
svg = $("money-body").innerHTML;
const rects2 = (svg.match(/<rect /g) || []).length;
if (rects2 !== 66) throw new Error("daily mode: expected 66 bars, got " + rects2);
if ((svg.match(/<polyline /g) || []).length !== 0) throw new Error("daily mode must draw no lines");
if (!$("money-legend").innerHTML.includes("Token spend — daily")) throw new Error("legend not relabelled in daily mode");
if ($("money-legend").innerHTML.includes("OC balance")) throw new Error("balance must not be legend-listed in daily mode");
// --- the daily token-spend view is now the shared `spend` metric ---
trendMetric = "spend";
renderTrends();
svg = $("trend-body").innerHTML;
const bars = count(/<rect /g);
if (bars !== 66) throw new Error("spend metric: expected 66 bars, got " + bars);
if (count(/<polyline /g) !== 0) throw new Error("a bar metric must draw no lines");
if ($("trend-legend").innerHTML.includes("OC balance")) throw new Error("the spend metric must not list money series");
// --- period slice: 30 days → 30 bars, no refetch ---
setMoneyPeriod(30);
svg = $("money-body").innerHTML;
const rects3 = (svg.match(/<rect /g) || []).length;
if (rects3 !== 30) throw new Error("30-day slice: expected 30 bars, got " + rects3);
setMoneyPeriod(90);
setMoneySpendMode("cum");
renderMoney();
trendDays = 30;
renderTrends();
svg = $("trend-body").innerHTML;
const bars30 = count(/<rect /g);
if (bars30 !== 30) throw new Error("30-day slice: expected 30 bars, got " + bars30);
trendMetric = "money";
renderTrends();
svg = $("trend-body").innerHTML;
const revPoints = (svg.match(/<polyline points="([^"]+)"/) || [])[1];
const nPoints = revPoints ? revPoints.trim().split(/\s+/).length : 0;
if (nPoints !== 30) throw new Error("30-day money slice: expected 30 points, got " + nPoints);
trendDays = 0;
renderTrends();
assertNoCaveat();
// --- a metric this page has no source for says so, instead of drawing another ---
const savedSource = METRIC_SOURCE.energy;
delete METRIC_SOURCE.energy;
trendMetric = "energy";
renderTrends();
if ($("trend-body").innerHTML.indexOf("Not available on this page") === -1) {
throw new Error("a metric with no source must say so, not render something else");
}
METRIC_SOURCE.energy = savedSource;
// --- balance-only deploy-day shape: one point renders as a marker, no crash ---
moneyData.series = [{ day: "2026-11-08", revenue_cum: null, spend_day: null, spend_cum: null, oc_balance: 1160.25 }];
renderMoney();
const svg2 = $("money-body").innerHTML;
trendMetric = "money";
renderTrends();
const svg2 = $("trend-body").innerHTML;
if (svg2.indexOf("trend-empty") === -1 && svg2.indexOf("<circle") === -1 && svg2.indexOf("<polyline") === -1) {
throw new Error("single-row series rendered nothing");
}
moneyData.series = mkSeries();
console.log("MONEY CHART HARNESS: ALL CHECKS PASSED");
+1 -1
View File
@@ -21,7 +21,7 @@ import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANONICAL_SHA256 = "a029fd40189acc38b8b218921c56e24e0208c8c8e0ab550a320bbd57449f5fed"
CANONICAL_SHA256 = "233c39faa7b40a9827fefd21aeb5505fdfa770833de2decebc8fe8bbbaee1903"
SPLICE = 'PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)'
failures = []