usage charts on the shared chart module: my-usage chart + co-op trend tooltips

Both usage views get charts. The co-op trend refactor onto the shared
coop_chart.js module replaces its native <title> tooltips with the panel's
exact-value hover tooltips (registerChartTips contract). NEW: the my-usage
view gets a per-day chart (Spend/Requests metric toggle, 30/90/all-time
period toggle) fed by /broker/usage's new daily series, same shared module,
same tooltip contract. No chart library, no CDN.
CI: .woodpecker.yml (oidc + chart sync pins, both harnesses via the vendored
check-page-js.sh, which splices the module as the app does).
Verified: rendering captured across all chart states matches the panel's
shared-module output; harnesses exercise exact values, zero days, gaps,
clamping, no-refetch toggles.
This commit is contained in:
inference-bot committed 2026-11-13 16:11:23 +00:00
1 parent 622982a371
commit 8c469c1242
6 files changed
+750 -67

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
# Woodpecker CI pipeline for the member dashboard — THIN on purpose.
#
# Runs the dashboard's EXISTING checks, unchanged:
# tests/test_oidc_sync.py the app's oidc.py is byte-identical to the
# canonical module in ops-docs (any hand edit goes red)
# tests/test_chart_sync.py the app's coop_chart.js is byte-identical to the
# canonical shared chart module in ops-docs
# tests/check-page-js.sh + harnesses: the page JS checker (node --check on the
# real <script> block, then stub + page JS + harness
# in ONE node scope) against every harness:
# dashboard-chart-harness.js (usage charts: shared module tooltips, exact
# values, gaps, 30/90/all toggles)
# dashboard-guests-harness.js (guest trail state rendering)
#
# tests/check-page-js.sh is vendored byte-identically from the admin panel's
# vendored copy (the CI agent container has no host filesystem) — keep the
# copies in step; both splices the shared chart module into the extracted page
# JS exactly as the app does at import time.
#
# Gating: `push` fires on every push (including branch pushes) so a red run
# blocks the merge via Gitea branch protection (status check
# `ci/woodpecker/push/main`). `manual` kept for hand-triggered runs.
#
# Backend note (why there are no container images here):
# The agent is a Cloudron app with no Docker socket → Woodpecker `local`
# backend: each step is a shell command INSIDE the agent container and the
# step's `image:` field selects the SHELL. python3 + node + bash are baked
# into the agent image (co-op/woodpecker-agent). Nothing to install at run
# time — the sync tests are stdlib-only by design.
when:
- event: push
- event: manual
steps:
- name: tests
image: bash
commands:
# Sync pins first: a drifted copy fails the run before anything else.
- python3 tests/test_oidc_sync.py
- python3 tests/test_chart_sync.py
# Run every harness even when one fails, then fail the step — a plain
# command chain would hide all failures after the first.
- |
fails=0
for h in dashboard-chart-harness.js dashboard-guests-harness.js; do
echo "== harness: $h"
bash tests/check-page-js.sh app/main.py "$h" || fails=$((fails+1))
done
if [ "$fails" -ne 0 ]; then
echo "FAILED: $fails harness run(s) red"
exit 1
fi
echo "all member-dashboard checks green"
+261
View File
@@ -0,0 +1,261 @@
/* Inference Cooperative — shared hand-rolled chart module.
*
* Canonical copy: co-op/ops-docs repo, scripts/shared/coop_chart.js.
* Byte-identical copies ship in admin-panel/app/ and member-dashboard/app/
* (each repo's tests/test_chart_sync.py pins its copy to this revision — CI
* has no ops-docs checkout). Editing a copy by hand is a dead end: edit the
* canonical file and run ops-docs/scripts/sync-chart-module.sh, which
* re-copies and re-pins both repos in one step.
*
* No chart library, no CDN (the co-op's no-external-dependency rule applies
* to charts like everything else). Colors come from each app's CSS vars, so a
* chart matches the tables around it. The module exposes ONE global,
* CoOpChart; each app's page JS destructures the pieces it needs, so call
* sites keep their bare function names.
*
* Tooltips — exact values on hover (the panel's registerChartTips contract):
* 1. At render time, stamp each hoverable data element with
* data-tip-host="<hostId>" and data-tip-i="<index into the data>"
* 2. registerChartTips("<hostId>", points) with one point per index:
* { label: "2026-11-07", series: [["Spend", "$12.34"], ...] }
* Values MUST come from the chart's own data arrays (exact), never
* pixel-estimated, and `series` carries EVERY series at that x.
* One delegated listener set on document serves every chart, so innerHTML
* re-renders need no re-binding and new charts join chart-by-chart as they
* render. The box is a fixed-position div with pointer-events:none, clamped
* inside the viewport. NULL points get no stamp and no tooltip (the gap
* rule). Styling lives in each app's .chart-tip CSS block.
*
* Drawing helpers — extracted from the admin panel's chart code so both apps
* produce the same shapes from the same code:
* niceStep(raw, continuous) axis step. continuous=true: the 1/2/5 x 10^k
* rule (money, energy, carbon — ticks read $10,
* not $4.92). false: whole counts rounded up to
* a half power of ten, never below 1 (a
* 2,900-request day reads 3,000; a near-empty
* series still gets an integer axis).
* measuredRuns(vals) contiguous non-null index runs. A NULL metric
* renders as a GAP, never a zero, and the line
* is never drawn through unmeasured history.
* chartFrame(cfg) opens the SVG, draws gridlines + y labels
* (top = one round step x 4 ticks, so labels
* land on round numbers by construction).
* dateMarks(fr, days) 3 x-axis date labels (start/mid/end).
* 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.
*/
(function (global) {
"use strict";
// HTML escaping, self-contained: identical mapping to both apps' esc() /
// escapeHtml(), so tooltip output bytes match what each app rendered before.
function esc(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
// ---- Chart tooltips: exact values on hover ----
const chartTipData = {}; // hostId -> [{ label, series: [[name, value], ...] }]
let chartTipBox = null; // the singleton tooltip div, created on first use
let chartTipCur = null; // { host, idx } the point currently shown
function registerChartTips(hostId, points) { chartTipData[hostId] = points; }
function chartTipTarget(el) {
return el && el.closest ? el.closest("[data-tip-host]") : null;
}
function hideChartTip() {
chartTipCur = null;
if (chartTipBox) chartTipBox.style.display = "none";
}
function showChartTip(hostId, idx, cx, cy) {
const p = (chartTipData[hostId] || [])[idx];
if (!p) { hideChartTip(); return; }
if (!chartTipBox) {
chartTipBox = global.document.createElement("div");
chartTipBox.className = "chart-tip";
global.document.body.appendChild(chartTipBox);
}
const same = chartTipCur && chartTipCur.host === hostId && chartTipCur.idx === idx;
if (!same) {
let html = '<div class="tip-day">' + esc(p.label) + "</div>";
for (let s = 0; s < p.series.length; s++) {
html += '<div class="tip-row"><span>' + esc(p.series[s][0]) + "</span><b>" + esc(p.series[s][1]) + "</b></div>";
}
chartTipBox.innerHTML = html;
chartTipCur = { host: hostId, idx: idx };
}
chartTipBox.style.display = "block";
moveChartTip(cx, cy);
}
// Position beside the pointer, flipped/clamped so the box stays fully inside
// the viewport at chart edges.
function moveChartTip(cx, cy) {
if (!chartTipBox || chartTipBox.style.display === "none") return;
const pad = 12, m = 4;
const w = chartTipBox.offsetWidth, h = chartTipBox.offsetHeight;
let x = cx + pad, y = cy + pad;
if (x + w > window.innerWidth - m) x = cx - pad - w;
if (x < m) x = m;
if (y + h > window.innerHeight - m) y = cy - pad - h;
if (y < m) y = m;
chartTipBox.style.left = x + "px";
chartTipBox.style.top = y + "px";
}
document.addEventListener("pointerover", (e) => {
const t = chartTipTarget(e.target);
if (!t) return;
showChartTip(t.getAttribute("data-tip-host"), parseInt(t.getAttribute("data-tip-i"), 10), e.clientX, e.clientY);
});
document.addEventListener("pointermove", (e) => {
const t = chartTipTarget(e.target);
if (!t) return;
const host = t.getAttribute("data-tip-host");
const idx = parseInt(t.getAttribute("data-tip-i"), 10);
const cur = chartTipCur;
if (!cur || cur.host !== host || cur.idx !== idx) showChartTip(host, idx, e.clientX, e.clientY);
else moveChartTip(e.clientX, e.clientY);
});
document.addEventListener("pointerout", (e) => {
const from = chartTipTarget(e.target);
if (!from) return;
const to = e.relatedTarget ? chartTipTarget(e.relatedTarget) : null;
if (!to || to.getAttribute("data-tip-host") !== from.getAttribute("data-tip-host")) hideChartTip();
});
// Basic touch: tap/drag shows and follows, release hides it after a beat.
document.addEventListener("pointerup", (e) => {
if (e.pointerType === "touch") setTimeout(hideChartTip, 1600);
});
document.addEventListener("pointercancel", hideChartTip);
// Scrolling or resizing moves the chart under a fixed-position box - hide
// rather than show a tooltip for the wrong point.
window.addEventListener("scroll", hideChartTip, { passive: true });
window.addEventListener("resize", hideChartTip);
// ---- Axis step (see header: continuous vs count rule) ----
function niceStep(raw, continuous) {
if (continuous) {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
}
// ---- Contiguous measured runs: a NULL day stays a gap ----
function measuredRuns(vals) {
const runs = [];
let run = [];
for (let i = 0; i < vals.length; i++) {
if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
return runs;
}
// ---- Frame: opens the SVG, draws gridlines + y-tick labels ----
// cfg: { n, top, step, tickLabel(v)->string, aria, W, H, padL, padR, padT,
// padB, gridStroke }. Defaults match the panel's chart geometry
// (W 1000, H 250, padL 62, padR 14, padT 14, padB 30).
// Axis top = one round step times four ticks: labels land on round numbers
// and the peak still clears the frame.
function chartFrame(cfg) {
const W = cfg.W || 1000, H = cfg.H || 250;
const padL = cfg.padL === undefined ? 62 : cfg.padL;
const padR = cfg.padR === undefined ? 14 : cfg.padR;
const padT = cfg.padT === undefined ? 14 : cfg.padT;
const padB = cfg.padB === undefined ? 30 : cfg.padB;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = cfg.n;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / cfg.top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + cfg.aria + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="' + (cfg.gridStroke || "var(--border)") + '"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + cfg.tickLabel(cfg.step * g) + '</text>');
}
return { W, H, padL, padR, baseY, n, xAt, yAt, parts };
}
// ---- X-axis date marks: start / middle / end, day strings YYYY-MM-DD ----
function dateMarks(fr, days) {
const marks = fr.n > 2 ? [0, Math.floor((fr.n - 1) / 2), fr.n - 1] : [0, fr.n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
fr.parts.push('<text x="' + fr.xAt(i) + '" y="' + (fr.H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(days[i]).slice(5) + '</text>');
}
}
// ---- Bars. opts: { color, host } — host stamps the elements for tooltips.
// NULL values are skipped (no zero bars, no tooltip on an unmeasured day).
function drawBars(fr, vals, opts) {
const bw = Math.max(1, (fr.W - fr.padL - fr.padR) / fr.n - 1);
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = fr.yAt(v);
fr.parts.push('<rect x="' + (fr.xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, fr.baseY - yy) + '" fill="' + opts.color + '"' + (opts.host ? ' data-tip-host="' + opts.host + '" data-tip-i="' + i + '"' : "") + "></rect>");
}
}
// ---- Lines broken into contiguous measured runs. opts:
// color stroke (and default fill for single-point dots)
// area draw the fill-under-line area path (panel Trends style)
// areaColor / areaOpacity area fill override (defaults: color / 0.10)
// dotSingle draw a dot (r = dotR, default 3) for a 1-point run instead of
// nothing — a single measured day still shows (money style)
function drawLineRuns(fr, vals, opts) {
const runs = measuredRuns(vals);
for (let s = 0; s < runs.length; s++) {
const r0 = runs[s];
if (opts.area) {
fr.parts.push('<path d="M' + fr.xAt(r0[0]) + "," + fr.baseY + " L" + r0.map(i => fr.xAt(i) + "," + fr.yAt(vals[i])).join(" L") + " L" + fr.xAt(r0[r0.length - 1]) + "," + fr.baseY + ' Z" fill="' + (opts.areaColor || opts.color) + '" fill-opacity="' + (opts.areaOpacity === undefined ? "0.10" : opts.areaOpacity) + '"/>');
}
if (r0.length > 1 || opts.area) {
fr.parts.push('<polyline points="' + r0.map(i => fr.xAt(i) + "," + fr.yAt(vals[i])).join(" ") + '" fill="none" stroke="' + opts.color + '" stroke-width="2" stroke-linejoin="round"/>');
} else if (opts.dotSingle) {
// A single measured day (e.g. the first balance snapshot) still shows.
fr.parts.push('<circle cx="' + fr.xAt(r0[0]) + '" cy="' + fr.yAt(vals[r0[0]]) + '" r="' + (opts.dotR === undefined ? 3 : opts.dotR) + '" fill="' + opts.color + '"/>');
}
}
}
// ---- Hover targets: one transparent circle per measured point; the
// tooltip lists every series at that x. NULL points get no stamp.
function hoverTargets(fr, vals, host) {
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
fr.parts.push('<circle cx="' + fr.xAt(i) + '" cy="' + fr.yAt(v) + '" r="7" fill="transparent" data-tip-host="' + host + '" data-tip-i="' + i + '"></circle>');
}
}
// chartTipData is exported for inspection (harnesses assert on the exact
// registered points); treat it as read-only in page code.
global.CoOpChart = {
chartTipData,
registerChartTips,
chartTipTarget,
hideChartTip,
showChartTip,
moveChartTip,
niceStep,
measuredRuns,
chartFrame,
dateMarks,
drawBars,
drawLineRuns,
hoverTargets
};
})(typeof globalThis !== "undefined" ? globalThis : window);
+156 -67
View File
@@ -18,6 +18,7 @@ Environment (all provided by Cloudron env vars):
import os
import logging
from pathlib import Path
import re
import httpx
@@ -426,6 +427,12 @@ def render_page(identity: str) -> str:
)
# The shared chart module (canonical: ops-docs scripts/shared/coop_chart.js,
# byte-identical copy at app/coop_chart.js — tests/test_chart_sync.py pins it)
# is spliced into the page's single <script> block at import time, above the
# page JS, which destructures CoOpChart into bare function names.
CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()
PAGE_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
@@ -537,7 +544,17 @@ PAGE_HTML = """<!DOCTYPE html>
.model-sub { color: var(--muted); font-size: 12px; }
.model-spend { font-size: 13px; font-weight: 600; color: var(--ink); text-align: right; }
/* Shared chart module tooltip (same block as the admin panel's, so the
hover boxes read identically on both UIs). */
.chart-tip { position: fixed; display: none; z-index: 60; pointer-events: none; background: #fff; border: 1px solid var(--border, #e4e0d8); border-radius: 8px; box-shadow: 0 2px 10px rgba(45,51,39,0.16); padding: 7px 10px; font-size: 12px; max-width: 280px; }
.chart-tip .tip-day { color: var(--muted); font-size: 11px; margin-bottom: 3px; }
.chart-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
.chart-tip .tip-row span { color: var(--muted); }
.chart-tip .tip-row b { color: var(--ink); font-variant-numeric: tabular-nums; }
.mine-chart { margin-top: 18px; }
.mine-chart .coop-trend-body { margin-top: 10px; }
/* Usage mode switch */
.usage-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.usage-header h2 { margin-bottom: 0; }
.mode-switch { display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
@@ -772,6 +789,22 @@ PAGE_HTML = """<!DOCTYPE html>
<button class="cancel-keep" onclick="hideCancelGuest()">Keep it</button>
</span>
</div>
<div class="mine-chart" id="mine-chart" style="display:none;">
<div class="coop-trend-controls">
<span class="trend-group">
<span class="board-note" style="margin:0;">Show</span>
<button class="mode-btn active" id="mm-spend" onclick="setMineMetric('spend')">Spend</button>
<button class="mode-btn" id="mm-requests" onclick="setMineMetric('requests')">Requests</button>
</span>
<span class="trend-group">
<span class="board-note" style="margin:0;">Period</span>
<button class="mode-btn" id="md-30" onclick="setMineDays(30)">30 days</button>
<button class="mode-btn active" id="md-90" onclick="setMineDays(90)">90 days</button>
<button class="mode-btn" id="md-all" onclick="setMineDays(0)">All time</button>
</span>
</div>
<div id="mine-chart-body" class="coop-trend-body"></div>
</div>
<div class="models" id="models"></div>
</div>
@@ -881,6 +914,7 @@ PAGE_HTML = """<!DOCTYPE html>
</footer>
<script>
/*@@CHART_MODULE@@*/
const $ = (id) => document.getElementById(id);
function flash(msg, ok) {
@@ -1169,6 +1203,8 @@ async function load() {
$('alltime').textContent = fmtMoney(d.all_time_spend ?? 0);
$('calls').textContent = calls.toLocaleString();
mineData = d.daily || [];
renderMineChart();
renderModels(d.models || []);
renderBoard(d.coop_models || []);
renderKeys(d.keys || [], d.key_spend || []);
@@ -1287,11 +1323,11 @@ let trendMetric = "members"; // members | requests | spend
let trendDays = 90; // 0 = all time
const TREND_CONF = {
members: { kind: "line", title: "The co-op over time" },
requests: { kind: "bar", title: "Requests the co-op served" },
spend: { kind: "bar", title: "What the co-op spent (members + the co-op's own accounts)" },
energy: { kind: "bar", title: "Energy the co-op used" },
co2e: { kind: "bar", title: "Carbon the co-op emitted" }
members: { kind: "line", title: "The co-op over time", cont: false },
requests: { kind: "bar", title: "Requests the co-op served", cont: false },
spend: { kind: "bar", title: "What the co-op spent (members + the co-op's own accounts)", cont: true },
energy: { kind: "bar", title: "Energy the co-op used", cont: true },
co2e: { kind: "bar", title: "Carbon the co-op emitted", cont: true }
};
async function loadMetrics() {
@@ -1350,18 +1386,18 @@ function trendVal(row) {
return row.requests;
}
// Y-axis step: counts are people and things, so ticks stay whole numbers;
// money uses the 1/2/5 x 10^k rule so ticks read $10.00, not $4.92.
function niceStep(raw) {
if (trendMetric === "spend" || trendMetric === "energy" || trendMetric === "co2e") {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
}
// ---- Shared chart module ----
// Chart rendering + the exact-value hover tooltips come from the shared
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
// byte-identical copy shipped in this image and spliced in above). The full
// contract (stamp data-tip-host/i, then registerChartTips with the EXACT
// values; NULL renders as a gap, never a zero) is documented in the module
// header.
const {
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
drawLineRuns, hoverTargets
} = CoOpChart;
function trendLabel(v) {
if (v === null || v === undefined) return "not measured";
@@ -1374,73 +1410,120 @@ function trendLabel(v) {
function renderTrends() {
const host = $("trend-body");
if (!host || !trendsData) return;
hideChartTip();
const conf = TREND_CONF[trendMetric];
const rows = trendDays === 0 ? trendsData : trendsData.slice(-trendDays);
const vals = rows.map(trendVal);
// Exact-value hover tooltips (the shared module's contract): register one
// point per row, straight from the data — same convention as the panel.
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 = "<div class=empty>Not enough history yet.</div>";
return;
}
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
const top = step * 4;
const W = 1000, H = 250, padL = 62, padR = 14, padT = 14, padB = 30;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = vals.length;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + conf.title + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="var(--border, #e4e0d8)"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + trendLabel(step * g) + '</text>');
}
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,
gridStroke: "var(--border, #e4e0d8)"
});
if (conf.kind === "bar") {
const bw = Math.max(1, plotW / n - 1);
for (let i = 0; i < n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = yAt(v);
parts.push('<rect x="' + (xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, baseY - yy) + '" fill="var(--green-mid)"><title>' + rows[i].day + ": " + trendLabel(v) + "</title></rect>");
}
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
} else {
// Contiguous measured runs: a day we never recorded stays a gap.
const runs = [];
let run = [];
for (let i = 0; i < n; i++) {
if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
for (let s = 0; s < runs.length; s++) {
const r0 = runs[s];
parts.push('<path d="M' + xAt(r0[0]) + "," + baseY + " L" + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" L") + " L" + xAt(r0[r0.length - 1]) + "," + baseY + ' Z" fill="var(--green-deep)" fill-opacity="0.10"/>');
parts.push('<polyline points="' + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" ") + '" fill="none" stroke="var(--green-deep)" stroke-width="2" stroke-linejoin="round"/>');
}
for (let i = 0; i < n; i++) {
if (vals[i] === null || vals[i] === undefined) continue;
parts.push('<circle cx="' + xAt(i) + '" cy="' + yAt(vals[i]) + '" r="7" fill="transparent"><title>' + rows[i].day + ": " + trendLabel(vals[i]) + "</title></circle>");
}
// Measured runs only: a day we never recorded stays a gap.
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, "trend-body");
}
const marks = n > 2 ? [0, Math.floor((n - 1) / 2), n - 1] : [0, n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
parts.push('<text x="' + xAt(i) + '" y="' + (H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(rows[i].day).slice(5) + '</text>');
}
parts.push("</svg>");
host.innerHTML = parts.join("");
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
let usageMode = 'mine'; // 'mine' | 'coop'
// ---- My usage over time (chart) ----
// Per-day spend/requests for the signed-in member, from /api/usage's `daily`
// series (the portal builds it from the same spend logs the co-op charts read;
// interior zero days are explicit, so spacing is true). Fetched once at the
// widest range with the usage payload; the toggles re-render client-side.
let mineData = null; // [{day, spend, requests}]
let mineMetric = "spend"; // spend | requests
let mineDays = 90; // 0 = all time
const MINE_CONF = {
spend: { title: "What you used per day", cont: true, val: r => r.spend },
requests: { title: "Requests you made per day", cont: false, val: r => r.requests }
};
function mineLabel(v) {
if (v === null || v === undefined) return "not measured";
if (mineMetric === "spend") return fmtMoney(v);
return Number(v).toLocaleString();
}
function setMineMetric(m) {
mineMetric = m;
$("mm-spend").className = "mode-btn" + (m === "spend" ? " active" : "");
$("mm-requests").className = "mode-btn" + (m === "requests" ? " active" : "");
renderMineChart();
}
function setMineDays(d) {
mineDays = d;
$("md-30").className = "mode-btn" + (d === 30 ? " active" : "");
$("md-90").className = "mode-btn" + (d === 90 ? " active" : "");
$("md-all").className = "mode-btn" + (d === 0 ? " active" : "");
renderMineChart();
}
function renderMineChart() {
const block = $("mine-chart");
if (!block) return;
const all = mineData || [];
// No usage rows at all: no chart yet (the empty state would be noise).
if (!all.length) { block.style.display = "none"; return; }
block.style.display = "";
const rows = mineDays === 0 ? all : all.slice(-mineDays);
block.style.display = "";
const host = $("mine-chart-body");
const conf = MINE_CONF[mineMetric];
const vals = rows.map(conf.val);
// Exact-value hover tooltips, same contract as every other chart here.
registerChartTips("mine-chart-body", rows.map((row, i) => ({
label: row.day,
series: [[conf.title, mineLabel(vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) {
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
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: mineLabel,
aria: conf.title,
gridStroke: "var(--border, #e4e0d8)"
});
drawBars(fr, vals, { color: "var(--green-mid)", host: "mine-chart-body" });
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
let usageMode = 'mine'; // 'mine' | 'coop'
function setUsageMode(mode) {
usageMode = mode;
@@ -1579,6 +1662,12 @@ load();
</body>
</html>"""
# Splice the shared chart module into the page's single <script> block. The
# placeholder is a JS comment, so the extracted-and-checked block stays valid
# even before the splice (check-page-js.sh performs the same splice when it
# runs the harnesses).
PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
+128
View File
@@ -0,0 +1,128 @@
// Harness for the member dashboard's USAGE CHARTS (my-usage + co-op trend),
// run through the vendored checker:
// bash tests/check-page-js.sh app/main.py dashboard-chart-harness.js
//
// Both charts render through the SHARED module (ops-docs
// scripts/shared/coop_chart.js). Assert the invariants that matter:
// * my-usage chart: bars render from the portal's `daily` series, hidden
// entirely when the member has no usage rows yet; tooltips carry the
// EXACT values through the page's formatters; the 30/90/all toggles
// re-render client-side without refetching;
// * co-op trend: native <title> tooltips are gone (replaced by the shared
// helper), NULL days are stamped with no tooltip (the gap rule);
// * clamping: the tooltip box stays inside the viewport at the edges.
// The checker evals in CommonJS (no top-level await), so the body is wrapped.
const assert = (cond, msg) => { if (!cond) { console.error("FAIL: " + msg); process.exit(1); } };
function mkDaily() {
// 10 days, one with zero usage (a real zero, not an unmeasured gap) and a
// span long enough to exercise the 30/90 slicing.
const rows = [];
for (let i = 0; i < 10; i++) {
rows.push({
day: "2026-11-0" + (i + 1),
spend: i === 4 ? 0 : +(1.25 * (i + 1)).toFixed(2),
requests: i === 4 ? 0 : 10 * (i + 1),
});
}
return rows;
}
(async () => {
// Drive load() with a realistic /api/usage payload.
globalThis.fetch = async () => ({
status: 200,
json: async () => ({
email: "member@example.com", guest: false,
balance: 15, allowance: 15, credits: 0, credits_remaining: 0,
spend: 6.25, all_time_spend: 68.75, remaining: 8.75,
models: [{ model: "greenpt/glm-5.3-flash", spend: 6.25, tokens: 900, calls: 41 }],
key_spend: [], daily: mkDaily(),
coop_models: [],
}),
});
await load();
// ---- my-usage chart ----
{
const block = document.getElementById("mine-chart");
assert(block.style.display === "", "chart block shown when the member has usage rows");
const body = document.getElementById("mine-chart-body").innerHTML;
assert(/<svg /.test(body), "my-usage chart renders an SVG");
assert(!/<title>/.test(body), "native <title> tooltips are gone (shared helper)");
const bars = (body.match(/data-tip-host="mine-chart-body"/g) || []).length;
assert(bars === 10, "one stamped bar per day incl. the zero day (got " + bars + ")");
// EXACT tooltip values: straight from the payload through the page formatters.
const pts = chartTipData["mine-chart-body"];
assert(Array.isArray(pts) && pts.length === 10, "registry: one point per day");
assert(pts[0].label === "2026-11-01", "registry label is the exact day");
assert(pts[0].series[0][1] === "$1.25", "exact spend for 11-01 (got " + pts[0].series[0][1] + ")");
assert(pts[4].series[0][1] === "$0.00", "a zero-usage day reads $0.00, not not-measured");
assert(pts[9].series[0][1] === "$12.50", "exact spend for 11-10 (got " + pts[9].series[0][1] + ")");
// Metric toggle re-renders from the SAME data (no refetch): exact counts.
setMineMetric("requests");
const ptsReq = chartTipData["mine-chart-body"];
assert(ptsReq[0].series[0][1] === "10", "requests tooltip exact (got " + ptsReq[0].series[0][1] + ")");
const bodyReq = document.getElementById("mine-chart-body").innerHTML;
assert((bodyReq.match(/data-tip-host="mine-chart-body"/g) || []).length === 10,
"requests mode still stamps every day");
setMineMetric("spend");
// Period toggles slice client-side: 30 keeps all 10 rows here; verify the
// all-time toggle does not refetch by watching the fetch counter.
let fetches = 0;
globalThis.fetch = async () => { fetches++; return { status: 200, json: async () => ({}) }; };
setMineDays(30);
setMineDays(0);
setMineDays(90);
assert(fetches === 0, "period toggles re-render client-side, never refetch");
assert(document.getElementById("md-all").className.indexOf("active") === -1,
"the 90d button is active again after the round trip");
}
// ---- my-usage chart hidden for a member with no usage ----
{
mineData = [];
renderMineChart();
assert(document.getElementById("mine-chart").style.display === "none",
"no usage rows: the chart block is hidden, not an empty frame");
// restore
mineData = mkDaily();
renderMineChart();
}
// ---- co-op trend (shared module; portal-shaped rows with a NULL day) ----
{
trendsData = [
{ day: "2026-11-01", members_total: 71, spend_usd: 12.34, requests: 2900, energy_wh: 8400.5, co2e_g: 2100.25 },
{ day: "2026-11-02", members_total: 72, spend_usd: null, requests: null, energy_wh: null, co2e_g: null },
{ day: "2026-11-03", members_total: 74, spend_usd: 5.01, requests: 1204, energy_wh: 9100, co2e_g: 2300 },
];
setTrendMetric("spend");
setTrendDays(90);
const body = document.getElementById("trend-body").innerHTML;
assert(!/<title>/.test(body), "co-op trend: native <title> tooltips are gone");
assert((body.match(/data-tip-host="trend-body"/g) || []).length === 2,
"gap day carries no bar/stamp (2 measured days of 3)");
const pts = chartTipData["trend-body"];
assert(pts[1].series[0][1] === "not measured", "NULL day registers as not measured");
assert(pts[0].series[0][1] === "$12.34" && pts[2].series[0][1] === "$5.01",
"co-op trend tooltips carry exact spend");
// Tooltip box behavior through the shared helper.
showChartTip("trend-body", 0, 500, 300);
const box = globalThis.__lastAppended;
assert(box && box.className === "chart-tip", "tooltip box created on first show");
assert(box.innerHTML.indexOf("2026-11-01") !== -1, "tooltip shows the exact date");
assert(box.innerHTML.indexOf("$12.34") !== -1, "tooltip shows the exact value");
moveChartTip(1430, 890);
const x = parseInt(box.style.left, 10), y = parseInt(box.style.top, 10);
assert(x + 120 <= 1440 && y + 48 <= 900, "clamped inside the viewport (got " + x + "," + y + ")");
hideChartTip();
assert(box.style.display === "none", "tooltip hides off-chart");
}
console.log("DASHBOARD CHART HARNESS OK: shared module tooltips, exact values, gaps, toggles");
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env bash
# Pre-deploy check for the panel/dashboard PAGE_HTML frontends.
#
# scripts/check-page-js.sh <path/to/app/main.py> [harness.js]
#
# 1. Slices PAGE_HTML out of the SOURCE TEXT. Do NOT import the module instead:
# app/oidc.py needs authlib, which is not installed on the steward host.
# 2. Extracts the single <script> block and runs `node --check` on it.
# 3. Given a harness file, runs stub + page JS + harness in ONE node eval scope,
# so the harness can call the page's real functions against real data.
#
# Never skip step 2. It is load-bearing, not ritual: it has caught a broken
# string escape and a duplicate `const` that py_compile passed, either of which
# blanks every data table on the live page.
#
# Harness rules (learned the hard way — see references/panel-and-dashboard-patterns.md):
# * Assert invariants, not the shape you happened to observe. Parse the
# rendered markup into value/position pairs and check the RELATIONSHIP.
# * A regex ending in `<` swallows the closing bracket and garbles every
# captured label. Match `[^<]*` and stop.
# * parseFloat("10-28") is 10. Date labels impersonate numeric ticks; filter
# them out by their dash before trusting a numeric parse.
# * When a check fails, suspect the ASSERTION first and fix it — never loosen
# it to get a green run.
set -euo pipefail
MAIN="${1:?usage: check-page-js.sh <path/to/app/main.py> [harness.js]}"
HARNESS="${2:-}"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
python3 - "$MAIN" "$TMP/page.js" <<'PY'
import re, sys
src = open(sys.argv[1]).read()
marker = 'PAGE_HTML = """'
start = src.index(marker) + len(marker)
html = src[start:src.index('"""', start)]
blocks = re.findall(r"<script>(.*?)</script>", html, re.S)
if len(blocks) != 1:
sys.exit(f"expected exactly 1 <script> block in PAGE_HTML, found {len(blocks)}")
js = blocks[0]
# Splice the shared chart module exactly as the app does at import time, so
# the checked/eval'd JS is what actually serves. The placeholder is a comment,
# and a missing module file leaves the placeholder in place (the harness then
# fails loudly on the missing CoOpChart instead of silently checking stale JS).
from pathlib import Path
placeholder = "/*@@CHART_MODULE@@*/"
if placeholder in js:
module = Path(sys.argv[1]).resolve().parent / "coop_chart.js"
if module.exists():
js = js.replace(placeholder, module.read_text())
print(f"spliced shared chart module ({module.name}) into the extracted page JS")
open(sys.argv[2], "w").write(js)
print(f"extracted {len(js)} chars of page JS from PAGE_HTML")
PY
node --check "$TMP/page.js"
echo "node --check: OK"
if [ -n "$HARNESS" ]; then
cat > "$TMP/stub.js" <<'JS'
// 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) => ({
id, style: {}, textContent: "", innerHTML: "", className: "",
offsetWidth: 120, offsetHeight: 48,
getAttribute: () => null,
appendChild: () => {},
});
globalThis.document = {
getElementById: (id) => (els[id] = els[id] || mkEl(id)),
querySelectorAll: () => [],
body: { innerHTML: "", appendChild: (el) => { globalThis.__lastAppended = el; } },
createElement: (tag) => mkEl(undefined),
addEventListener: (type, fn) => { (globalThis.__listeners = globalThis.__listeners || {})[type] = fn; },
};
globalThis.fetch = async () => ({
status: 200,
json: async () => ({ series: [], totals: {}, members: [], admins: [], models: [] }),
});
globalThis.window = {
innerWidth: 1440,
innerHeight: 900,
addEventListener: (type, fn) => {},
};
JS
node -e 'const fs=require("fs"), r=p=>fs.readFileSync(p,"utf8");
eval(r(process.argv[1]) + r(process.argv[2]) + r(process.argv[3]));' \
"$TMP/stub.js" "$TMP/page.js" "$HARNESS"
fi
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""coop_chart.js sync pin — the repo copy is byte-identical to the canonical
module, and main.py splices it into the served page.
WHY THIS EXISTS
app/coop_chart.js is a byte-identical copy of the canonical module
(co-op/ops-docs repo: scripts/shared/coop_chart.js) — the single source for
the hand-rolled chart rendering + hover tooltips both UIs ship. This test
pins the copy to the canonical revision recorded below: ANY hand edit to
app/coop_chart.js breaks the pin and goes red. To change the module, edit
the canonical file and run ops-docs/scripts/sync-chart-module.sh, which
re-copies and re-pins both repos in one step (check-chart-sync.py is the
pre-deploy gate).
Generated by sync-chart-module.sh — do not edit by hand.
Run: python3 tests/test_chart_sync.py
"""
import hashlib
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANONICAL_SHA256 = "a029fd40189acc38b8b218921c56e24e0208c8c8e0ab550a320bbd57449f5fed"
SPLICE = 'PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)'
failures = []
copy = ROOT / "app" / "coop_chart.js"
if not copy.exists():
failures.append("app/coop_chart.js missing")
else:
got = hashlib.sha256(copy.read_bytes()).hexdigest()
if got == CANONICAL_SHA256:
print(f"ok - app/coop_chart.js matches the pinned canonical revision ({got[:16]}…)")
else:
failures.append(
"app/coop_chart.js DRIFTED from the pinned canonical revision\n"
f" pinned {CANONICAL_SHA256}\n"
f" actual {got}\n"
" fix: edit the canonical module (ops-docs: scripts/shared/coop_chart.js) "
"and run ops-docs/scripts/sync-chart-module.sh — never hand-edit the copy.")
main_src = (ROOT / "app" / "main.py")
if not main_src.exists():
failures.append("app/main.py missing")
else:
msrc = main_src.read_text()
if SPLICE not in msrc:
failures.append(
"app/main.py does not splice the shared chart module into PAGE_HTML:\n"
f" expected literal: {SPLICE}")
if 'parent / "coop_chart.js"' not in msrc:
failures.append("app/main.py does not load app/coop_chart.js")
if failures:
print()
print("FAILED: " + ", ".join(failures))
sys.exit(1)
print("chart sync pin: OK")