Compare commits

..
Author SHA1 Message Date
Casey Gollan 40792d6387 dashboard: always-visible 'Buy a credit pack' link out to Open Collective
Members expected to add usage from the dashboard and couldn't find it —
the buy path (OpenCollective contribute page) was invisible. Payments
still happen on OC; this just surfaces the door:

- green 'Buy a credit pack' button in the My usage card, always visible
- hint shows the member's real credit status ('Credits never expire
  ($X purchased all-time).' — moved out of the meta line, which keeps
  'Shared across chat and API · Allowance renews <date>.')
- 'More about allowance & credits' links to the docs section
  (getting-started.md#need-more-than-the-allowance)

Verified desktop + 390px mobile rendering.
2026-11-01 18:23:36 -05:00
13 changed files with 233 additions and 2010 deletions

No files matched your search

-54
View File
@@ -1,54 +0,0 @@
# 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"
+1 -6
View File
@@ -17,10 +17,5 @@
"manifestVersion": 2, "manifestVersion": 2,
"website": "https://inference.coop", "website": "https://inference.coop",
"contactEmail": "info@inference.coop", "contactEmail": "info@inference.coop",
"tags": [ "tags": ["member", "dashboard", "cooperative"]
"member",
"dashboard",
"cooperative"
],
"dockerImage": "registry.inference.coop/code/member-dashboard:20261117-5a3df91"
} }
-421
View File
@@ -1,421 +0,0 @@
/* 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.
*
* 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";
// 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>');
}
}
// ==== 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", kind: "bar", cont: false, fmt: "count",
val: r => r.requests },
{ id: "spend", title: "Spend", 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", kind: "bar", cont: true, fmt: "wh",
val: r => r.energy_wh },
{ id: "co2e", title: "Carbon", 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 = {
chartTipData,
registerChartTips,
chartTipTarget,
hideChartTip,
showChartTip,
moveChartTip,
niceStep,
measuredRuns,
chartFrame,
dateMarks,
drawBars,
drawLineRuns,
hoverTargets,
// the definition layer both UIs read
CHART_METRICS,
metricDef,
fmtMoney,
fmtMetric,
fmtMoneyTick,
renderChart
};
})(typeof globalThis !== "undefined" ? globalThis : window);
+160 -884
View File
File diff suppressed because it is too large. Load diff
+10 -52
View File
@@ -1,12 +1,7 @@
"""OIDC client for Cloudron's OpenID Connect addon — ONE shared module. """OIDC client for Cloudron's OpenID Connect addon.
This file is the SINGLE SOURCE for the two thin Cloudron apps that implement Implements the authorization-code flow against Cloudron's built-in OIDC
the authorization-code flow themselves (admin-panel, member-dashboard). The provider, so the app no longer depends on the proxyAuth header wall.
copies in those repos' app/oidc.py are byte-identical to this file — verified
by ops-docs/scripts/check-oidc-sync.py and enforced by each repo's
tests/test_oidc_sync.py — so a fix lands here, is synced to both repos, and
can never drift. Do not edit a repo copy directly: sync-oidc-module.sh
overwrites it, and the pin test goes red on any hand edit.
Cloudron exports these env vars (they change on every restart — read per-call, Cloudron exports these env vars (they change on every restart — read per-call,
never cache at import): never cache at import):
@@ -21,16 +16,8 @@ never cache at import):
CLOUDRON_APP_DOMAIN the app's public domain CLOUDRON_APP_DOMAIN the app's public domain
Identity: Cloudron's `sub` claim is the username (the unique user identifier). Identity: Cloudron's `sub` claim is the username (the unique user identifier).
We use `sub` as the identity; each host app decides what it authorizes — the We use `sub` (username) as the identity — the portal's broker accepts it as
panel matches it against its ADMIN_USERNAMES allowlist, the dashboard `X-Member-User` and resolves username → email.
forwards it to the portal's broker as `X-Member-User` (which resolves
username → email).
Per-app identity: the ONLY differences the two copies used to carry were the
logger name, the session cookie name and the session salt. The host app now
supplies those via configure() at import time (see each app's main.py), which
keeps this file byte-identical everywhere while preserving each app's
existing cookie names and salts (so existing sessions survive a redeploy).
""" """
import os import os
@@ -42,44 +29,15 @@ import httpx
from authlib.jose import JsonWebToken, JsonWebKey from authlib.jose import JsonWebToken, JsonWebKey
from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired from itsdangerous import URLSafeTimedSerializer, BadSignature, SignatureExpired
# Per-app identity — set by the host app at import time via configure(). logger = logging.getLogger("member-dashboard")
# The unset sentinels below are loud on purpose: a copy that reaches a
# request without its host app having configured itself is a sync/setup bug.
APP_NAME = "unset-app"
SESSION_COOKIE = "unset_oidc_session"
_SESSION_SALT = "unset-oidc-session"
SESSION_MAX_AGE = 60 * 60 * 8 # 8 hours, roughly a working day # Session cookie name + max age (8 hours, roughly a working day).
SESSION_COOKIE = "member_oidc_session"
SESSION_MAX_AGE = 60 * 60 * 8
SCOPES = "openid profile email" SCOPES = "openid profile email"
def configure(app_name: str, session_cookie: str, session_salt: str) -> None:
"""Set this app's identity. The host app MUST call this at import time."""
global APP_NAME, SESSION_COOKIE, _SESSION_SALT
APP_NAME = app_name
SESSION_COOKIE = session_cookie
_SESSION_SALT = session_salt
class _LazyLogger:
"""Resolves at CALL time, not import time.
The host app calls configure() AFTER this module is imported (from its
main.py), so an eagerly-created module-level logger would bind the
'unset-app' sentinel name and every OIDC log line would carry the wrong
attribution. Logging through this proxy reads the configured APP_NAME
when the line is actually emitted; logging.getLogger caches by name, so
the per-call lookup is free.
"""
def __getattr__(self, name):
return getattr(logging.getLogger(APP_NAME), name)
logger = _LazyLogger()
def _oidc_env(name: str) -> str: def _oidc_env(name: str) -> str:
return os.environ.get(name, "").strip() return os.environ.get(name, "").strip()
@@ -97,7 +55,7 @@ def _session_serializer() -> URLSafeTimedSerializer:
# Derive a stable, secret signing key from the OIDC client secret (already # Derive a stable, secret signing key from the OIDC client secret (already
# a secret the app holds, and stable across restarts). # a secret the app holds, and stable across restarts).
secret = _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET") or _secrets.token_urlsafe(32) secret = _oidc_env("CLOUDRON_OIDC_CLIENT_SECRET") or _secrets.token_urlsafe(32)
return URLSafeTimedSerializer(secret, salt=_SESSION_SALT) return URLSafeTimedSerializer(secret, salt="member-dashboard-oidc-session")
def _redirect_uri(request_host: str) -> str: def _redirect_uri(request_host: str) -> str:
-194
View File
@@ -1,194 +0,0 @@
// 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");
}
// ---- the money metric: the SHARED definition, the same chart the panel draws ----
{
moneyData = { series: [
{ day: "2026-11-01", revenue_cum: 100, spend_cum: 20, oc_balance: null },
{ day: "2026-11-02", revenue_cum: 220, spend_cum: 45, oc_balance: null },
{ day: "2026-11-03", revenue_cum: 260, spend_cum: 51, oc_balance: 1160.25 },
] };
setTrendMetric("money");
const body = document.getElementById("trend-body").innerHTML;
const def = metricDef("money");
assert(def.series.length === 3, "the shared money definition carries 3 series");
assert((body.match(/<polyline /g) || []).length === 2,
"money chart draws revenue + spend as lines");
assert(/<circle cx="[^"]+" cy="[^"]+" r="3"/.test(body),
"the balance (one measured day) renders as a marker, not a line through gaps");
const legend = document.getElementById("trend-legend").innerHTML;
for (const sr of def.series) {
assert(legend.indexOf(sr.name) !== -1, "legend is the definition's series: " + sr.name);
}
const pts = chartTipData["trend-body"];
assert(pts[0].series.length === 3, "the tooltip lists EVERY series at that x");
assert(pts[0].series[2][1] === "not measured",
"the balance before snapshots began reads not measured, never $0.00");
assert(pts[2].series[2][1] === "$1,160.25" || pts[2].series[2][1] === "$1160.25",
"the balance value is exact (got " + pts[2].series[2][1] + ")");
// The metric row comes from the shared list, filtered to what this page can fetch.
buildMetricButtons();
let expected = 0;
for (const m of CHART_METRICS) if (METRIC_SOURCE[m.id]) expected++;
let rendered = 0;
for (const m of CHART_METRICS) if (document.getElementById("tm-" + m.id)) rendered++;
assert(rendered === expected && expected === 6,
"every shared metric this page can fetch has a button (got " + rendered + "/" + expected + ")");
assert(document.getElementById("tm-money") !== null,
"Money is a metric here too, not an admin-only tab");
// A metric in the shared list with no source here must SAY so.
const savedIntro = METRIC_SOURCE.energy;
delete METRIC_SOURCE.energy;
setTrendMetric("energy");
assert(document.getElementById("trend-body").innerHTML.indexOf("Not available here") !== -1,
"a metric this page cannot fetch says so instead of drawing another chart");
METRIC_SOURCE.energy = savedIntro;
buildMetricButtons();
}
// ---- the metric buttons are DELEGATED, so prove a click reaches setTrendMetric ----
// (An inline onclick inside PAGE_HTML is where a quote escape silently kills the
// whole page: it happened, and it shipped, because the gate read the raw source
// text instead of the string Python serves. Delegation removes that trap — and
// this is the check that the wiring still works.)
{
buildMetricButtons();
const rowEl = document.getElementById("trend-metrics");
assert(!!(rowEl.__handlers && rowEl.__handlers.click),
"the metric row has a delegated click listener");
setTrendMetric("members");
const fired = rowEl.__fire("click", { target: { closest: () => ({ getAttribute: () => "money" }) } });
assert(trendMetric === "money",
"clicking a metric button selects that metric (got " + trendMetric + ")");
setTrendMetric("members");
rowEl.__fire("click", { target: { closest: () => null } });
assert(trendMetric === "members", "a click that misses a button is ignored");
}
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); });
-65
View File
@@ -1,65 +0,0 @@
// Harness for the member dashboard's GUEST TRAIL (the member's own invite
// history), run through the panel's vendored checker:
// bash ../admin-panel/tests/check-page-js.sh app/main.py dashboard-guests-harness.js
//
// The portal derives the trail's display state (the SINGLE derivation, tested
// in the portal's tests/test_guest_invited_state.py); this page CONSUMES it:
// * state='invited' wins even though the ledger status underneath is still
// 'active' — a provisioned-but-not-set-up guest is never 'active';
// * state carries the ledger status once accepted/ended (expired ...);
// * an older payload with status only falls back to it (the thin shim).
// 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); } };
const count = (s, re) => (String(s).match(re) || []).length;
async function runRender(payload) {
globalThis.fetch = async () => ({ status: 200, json: async () => payload });
await loadGuests();
}
(async () => {
// New payload: the portal serves `state` on every trail entry.
await runRender({
eligible: false,
next_eligible_at: "2026-12-15T00:00:00Z",
trail: [
{ kind: "guest", recipient: "pending@example.com", created_at: "2026-11-10 10:00:00",
status: "active", state: "invited" },
{ kind: "guest", recipient: "lapsed@example.com", created_at: "2026-09-01 10:00:00",
decided_at: "2026-10-30 10:00:00", status: "expired", state: "expired" },
],
});
{
const t = document.getElementById("guest-trail").innerHTML;
assert(/gpill invited[^>]*>Invited — awaiting setup</.test(t),
"portal-served state='invited' renders the awaiting-setup pill even though the ledger says active");
assert(!/>active guest</.test(t),
"a pending guest is never rendered as an active guest");
assert(/gpill done[^>]*>ended — time ran out</.test(t),
"state='expired' renders the ended pill");
assert(t.indexOf("pending@example.com") !== -1 && t.indexOf("lapsed@example.com") !== -1,
"both trail rows render");
assert(document.getElementById("guest-invite-wrap").style.display === "none",
"used invite: the form is hidden (next-date hint takes its place)");
assert(document.getElementById("guest-allowance").textContent.indexOf("next invite is available") !== -1,
"the next-open date is surfaced");
}
// Old payload shape: status only, no state — the shim falls back to it.
await runRender({
eligible: true,
trail: [
{ kind: "guest", recipient: "friend@example.com", created_at: "2026-11-09 10:00:00",
status: "active" },
],
});
{
const t = document.getElementById("guest-trail").innerHTML;
assert(/gpill ok[^>]*>active guest</.test(t),
"old payload (status only) falls back to the ledger status");
assert(document.getElementById("guest-invite-wrap").style.display === "",
"eligible: the invite form is shown");
}
console.log("DASHBOARD GUESTS HARNESS OK: consumes the portal's state, old-shape fallback intact");
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
-96
View File
@@ -1,96 +0,0 @@
// The API keys as a chart: one bar row per key, the chat key included, and a
// Spend/Requests toggle that changes both the values and the order.
// Assertions are invariants (proportional lengths, sorting, presence), not the
// markup that happened to be rendered the day this was written.
const assert = (cond, msg) => { if (!cond) { console.error("FAIL: " + msg); process.exit(1); } };
const KEYS = [
{ name: "my-laptop", fingerprint: "abcd1234", created_at: "2026-11-01T10:00:00Z" },
{ name: "script", fingerprint: "efgh5678", created_at: "2026-11-02T10:00:00Z" },
];
const SPEND = [
{ name: "my-laptop", is_chat: false, spend: 12.5, requests: 100 },
{ name: "script", is_chat: false, spend: 2.5, requests: 400 },
{ name: "chat", is_chat: true, spend: 5.0, requests: 250 },
];
const widthOf = (html, label) => {
// the bar immediately following this key's label
const i = html.indexOf(label);
assert(i !== -1, "the chart has a row labelled " + label);
const seg = html.slice(i);
const m = seg.match(/key-bar-fill[^>]*width:(\d+)%/);
assert(m, "the " + label + " row has a bar width");
return parseInt(m[1], 10);
};
const valueOf = (html, label) => {
const i = html.indexOf(label);
const seg = html.slice(i, html.indexOf("key-bar-row", i + 1) === -1 ? undefined : html.indexOf("key-bar-row", i + 1));
const m = seg.match(/key-bar-val">([^<]*)</);
return m ? m[1] : "";
};
renderKeys(KEYS, SPEND);
let html = document.getElementById("keys").innerHTML;
console.log("1. every key is a row, the chat key included");
assert((html.match(/key-bar-row/g) || []).length === 3,
"three rows: two API keys + the built-in chat key (got " + (html.match(/key-bar-row/g) || []).length + ")");
assert(html.indexOf("Chat (built-in)") !== -1, "the chat key is a row, not a footnote");
assert(html.indexOf("No API keys yet") === -1, "not the empty state");
console.log("2. bars are proportional to the value, longest = 100%");
assert(widthOf(html, "my-laptop") === 100, "the top spender is the full-width bar (got " + widthOf(html, "my-laptop") + "%)");
assert(widthOf(html, "Chat (built-in)") === 40, "half the top spend reads as 40% (got " + widthOf(html, "Chat (built-in)") + "%)");
assert(widthOf(html, "script") === 20, "a fifth reads as 20% (got " + widthOf(html, "script") + "%)");
assert(html.indexOf("$12.50") !== -1, "the value is printed exactly, not just drawn");
console.log("3. rows are ordered by the chosen metric, biggest first");
assert(html.indexOf("my-laptop") < html.indexOf("Chat (built-in)") &&
html.indexOf("Chat (built-in)") < html.indexOf("script"),
"spend order: my-laptop ($12.50) > chat ($5.00) > script ($2.50)");
console.log("4. the toggle re-renders by REQUESTS, values and order together");
setKeyMetric("requests");
html = document.getElementById("keys").innerHTML;
assert(document.getElementById("km-requests").className.indexOf("active") !== -1, "Requests is the active button");
assert(document.getElementById("km-spend").className.indexOf("active") === -1, "Spend is no longer active");
assert(widthOf(html, "script") === 100, "by requests, the biggest requester is full width (got " + widthOf(html, "script") + "%)");
assert(html.indexOf("400 requests") !== -1, "requests are labelled as such, with a thousands separator");
assert(html.indexOf("script") < html.indexOf("my-laptop"), "the order changed with the metric");
setKeyMetric("spend");
html = document.getElementById("keys").innerHTML;
assert(widthOf(html, "my-laptop") === 100, "and switching back restores the spend view");
console.log("5. revoke stays where it belongs");
assert((html.match(/revokeKey\(/g) || []).length === 2,
"one Revoke per real key, none for the built-in chat key (got " + (html.match(/revokeKey\(/g) || []).length + ")");
console.log("5b. a key with usage but no metadata row is STILL charted");
renderKeys([], SPEND); // the live case: usage rows, an empty key list
{
const h = document.getElementById("keys").innerHTML;
assert((h.match(/key-bar-row/g) || []).length === 3,
"all three usage rows appear even with no key metadata (got " + (h.match(/key-bar-row/g) || []).length + ")");
assert(h.indexOf("my-laptop") !== -1 && h.indexOf("script") !== -1,
"the named usage rows are charted, not dropped for want of a metadata entry");
assert((h.match(/revokeKey\(/g) || []).length === 2,
"and each still gets its Revoke control");
}
renderKeys([{ name: "unused-key", fingerprint: "zz", created_at: "2026-11-03T00:00:00Z" }], SPEND);
{
const h = document.getElementById("keys").innerHTML;
assert((h.match(/key-bar-row/g) || []).length === 4,
"a key you own but have not used still gets a row (got " + (h.match(/key-bar-row/g) || []).length + ")");
}
console.log("6. the empty state means NO rows at all");
renderKeys([], []); // no keys and no chat usage
assert(document.getElementById("keys").innerHTML.indexOf("No API keys yet") !== -1,
"with nothing to show, the card says so");
renderKeys([], [{ name: "chat", is_chat: true, spend: 1, requests: 2 }]);
const chatOnly = document.getElementById("keys").innerHTML;
assert(chatOnly.indexOf("No API keys yet") === -1 && chatOnly.indexOf("Chat (built-in)") !== -1,
"with only chat usage, the chat row still shows — a chat key IS usage worth seeing");
console.log("DASHBOARD KEYS HARNESS OK: proportional bars, sorting, toggle, revoke placement");
Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

@@ -0,0 +1,62 @@
# Buy-a-credit-pack link in the member dashboard — design
Date: 2026-11-01 · Status: awaiting approval · Size: small change
## Intent
Members expect to add usage from the dashboard and can't find it (a real
member got lost and had to ask the AI chat). The buy path lives on the
OpenCollective contribute page, and the dashboard never mentions it.
Payments stay on OpenCollective for now (per Nathan); the fix is making
that path visible from the dashboard, always.
## Goals
- A always-visible "Buy a credit pack" affordance in the **My usage**
view of `app/main.py`, linking to
`https://opencollective.com/inference-cooperative/contribute`
(opens in a new tab).
- The meta line under the balance bar keeps its existing shape:
"Shared across chat and API · Allowance renews <date>." The credits
clause moves out of it.
- The hint next to the button shows the member's real credit status,
same copy the app already used: "Credits never expire ($X purchased
all-time)." For members with no packs yet, the static default reads
"Credit packs never expire · used after your monthly allowance."
- A link to the docs section that explains allowance and credits —
`getting-started.md` → "Need more than the allowance?" — following the
dashboard's existing docs-link pattern
(`https://git.inference.coop/co-op/docs/src/branch/main/...`), so
members can read the full story.
## Non-goals
- In-dashboard checkout or handling money in this app (this app holds no
privileged credentials by design).
- Showing pack prices or sizes in the dashboard — those live on OC and
can change there without a deploy here.
- Any low-balance gating — always visible, per Casey's call.
## Approaches
1. **Always-visible button + hint line in the usage card** (chosen) —
sits right under the balance bar where a member looks when they're
running low. Discoverable every visit.
2. Low-balance-only (appears when allowance exhausted / bar amber) —
quieter, but repeats the original problem for anyone who wants to
top up early. Rejected.
3. Link in the page header next to "Member Home" — far from the usage
context it explains. Rejected.
## How it gets made (decided)
- One new block in `#view-mine` after the `.meta` line: a green
primary-style anchor (`Buy a credit pack`) plus a muted hint span on
the same row (with the docs link at the end of the hint), wrapping on
narrow phones.
- Reuses existing palette vars and button look; ~8 lines of CSS, no JS,
no new endpoints, no API changes.
## Left to the builder
- Exact copy tweak of the hint line is builder's call.
-123
View File
@@ -1,123 +0,0 @@
#!/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 ast, re, sys
# Read PAGE_HTML the way PYTHON does, not the way the file is typed. Slicing the
# source text between the triple quotes gives you the escapes as written; the app
# gets them INTERPRETED. A JS line written `\" onclick=...` in a plain triple-
# quoted string serves as `" onclick=...` — a syntax error that kills the whole
# page, while a text slice still looks like valid JS and node --check passes.
# That is not hypothetical: on 2026-11-13 this gate certified a page whose script
# died at the first button, and both UIs served no data at all.
tree = ast.parse(open(sys.argv[1]).read())
html = None
for node in ast.walk(tree):
if not isinstance(node, ast.Assign):
continue
if not any(getattr(t, "id", "") == "PAGE_HTML" for t in node.targets):
continue
# Only the triple-quoted literal — the module-splice line below it reassigns
# PAGE_HTML to a Call, which is not a literal and is not what we check.
if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
html = node.value.value
if html is None:
sys.exit("no PAGE_HTML string literal found")
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) => {
const attrs = {};
const el = {
id, style: {}, textContent: "", innerHTML: "", className: "",
offsetWidth: 120, offsetHeight: 48,
// Stateful attributes, like a real element: a stub that always answers null
// cannot tell "wired once" from "wired on every call".
getAttribute: (k) => (k in attrs ? attrs[k] : null),
setAttribute: (k, v) => { attrs[k] = String(v); },
appendChild: () => {},
};
// Delegated listeners are how the pages wire their metric buttons now, so the
// stub must have them — and must be able to fire them, or the harness cannot
// prove the wiring reaches setTrendMetric at all.
el.addEventListener = (type, fn) => { (el.__handlers = el.__handlers || {})[type] = fn; };
el.__fire = (type, ev) => { const h = (el.__handlers || {})[type]; if (h) h(ev); };
// 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: () => [],
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
@@ -1,60 +0,0 @@
#!/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 = "d25195d5079da499d6c3788b5678b86af65d9fee8e366cfb08fd5a0201ec1a2e"
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")
-55
View File
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
"""oidc.py sync pin — the repo copy is byte-identical to the canonical module.
WHY THIS EXISTS
app/oidc.py is a byte-identical copy of the canonical module
(co-op/ops-docs repo: scripts/shared/oidc_client.py) — the single source for
the OIDC client the thin apps ship copies of, so their login never depends
on another app being up. This test pins the copy to the canonical revision
recorded below: ANY hand edit to app/oidc.py breaks the pin and goes red.
To change the module, edit the canonical file and run
ops-docs/scripts/sync-oidc-module.sh, which re-copies and re-pins both
repos in one step (check-oidc-sync.py is the pre-deploy gate).
Generated by sync-oidc-module.sh — do not edit by hand.
Run: python3 tests/test_oidc_sync.py
"""
import hashlib
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CANONICAL_SHA256 = "0b17a491b26bceab42fc95f1a091cee50b7ab298096e99ac7b09c771ce99cd55"
EXPECTED_CONFIGURE = '''oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session")'''
failures = []
copy = ROOT / "app" / "oidc.py"
if not copy.exists():
failures.append("app/oidc.py missing")
else:
got = hashlib.sha256(copy.read_bytes()).hexdigest()
if got == CANONICAL_SHA256:
print(f"ok - app/oidc.py matches the pinned canonical revision ({got[:16]}…)")
else:
failures.append(
"app/oidc.py 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/oidc_client.py) "
"and run ops-docs/scripts/sync-oidc-module.sh — never hand-edit the copy.")
main_src = (ROOT / "app" / "main.py")
if not main_src.exists():
failures.append("app/main.py missing")
elif EXPECTED_CONFIGURE not in main_src.read_text():
failures.append(
"app/main.py does not configure this app's oidc identity:\n"
f" expected literal: {EXPECTED_CONFIGURE}")
if failures:
print()
print("FAILED: " + ", ".join(failures))
sys.exit(1)
print("oidc sync pin: OK")