Compare commits

...
Author SHA1 Message Date
inference-admin c4aa072e7f manifest: pin to 20261117-5a3df91 2026-11-17 05:01:52 +00:00
inference-admin 5a3df91587 dashboard: explain a lapsed membership instead of flashing an error
On a 403 from usage, the page already asked the portal whether this was an ended
guest. It now also asks /api/membership-status, and renders state, the last
allowance decision with its evidence, the OC minimum, and a contribute link —
reusing the ended-state panel styles.
2026-11-17 05:01:36 +00:00
inference-admin 38b8d25d74 manifest: pin to 20261114-90e320e 2026-11-14 19:03:40 +00:00
inference-admin 90e320e190 dashboard: drop the dash for the chat row's missing Revoke
The chat key has nothing to revoke, and ' - ' never centred in a grid cell sized
for a button, so it read as misalignment rather than as a deliberate blank. The
action column is empty for that row; the other rows still define the columns.
2026-11-14 19:03:24 +00:00
inference-admin 0eb11dd221 manifest: pin to 20261114-83b52f4 2026-11-14 19:02:25 +00:00
inference-admin 83b52f4675 dashboard: equal columns in the API key chart, and a dash where the chat key has no Revoke
Four equal columns (the name/meta, the bar, the value, the action) instead of a
wider bar column, and the chat row shows ' - ' in the action column rather than
rendering an empty cell that made the row look broken.
2026-11-14 19:02:08 +00:00
inference-admin 628e89fc99 manifest: pin to 20261113-b5b0703 2026-11-13 21:47:27 +00:00
inference-admin b5b0703f0c keys chart: chart the keys that HAVE usage, not the ones with metadata
The first cut built a row per key in the metadata list and attached usage to it.
Live, an account with three keys that had spent real money (homebot $11.84,
office-pi $0.19, base-pi $0.19) came back with an EMPTY key list and four usage
rows, so the chart drew one bar — the chat key — and quietly dropped the rest.
Exactly the kind of "listing" this chart exists to compare.

Now the usage rows are the authoritative set: every row gets a bar, metadata is
attached when we have it, and a key with no usage still gets a zero row so a key
you own is never invisible. The harness pins all three cases.
2026-11-13 21:47:07 +00:00
inference-admin ffd42a2045 manifest: pin to 20261113-b37b954 2026-11-13 21:45:46 +00:00
inference-admin b37b9549e4 dashboard: the panel's button shape, the server's spend figure, and keys as a chart
* Chart buttons take the admin panel's look: bordered, 8px radius, green-mid when
  active (was a borderless segmented control). One design across both apps.
* "co-op spend, all time" now reads the portal's figure from /api/metrics instead
  of summing the chart series in the browser. The second card ("of which the
  co-op's own accounts") is gone: it was that same client-side sum, and the
  portal's own breakdown is a panel-side notion I will not fake here.
* The API keys are a chart: one bar row per key — the chat key included, so the
  built-in key's usage is comparable rather than a footnote — with a Spend /
  Requests toggle. Revoke stays on each real key's row.
2026-11-13 21:44:14 +00:00
inference-admin 6e044c0f05 manifest: pin to 20261113-2b8b8ad 2026-11-13 21:27:14 +00:00
inference-admin 2b8b8ade18 charts: take the shared concise metric titles (Members · Requests · Spend · Money · Energy · Carbon)
Same menu, same order, same words as the panel — the two UIs now differ only in
whose usage they show and in their own visual style.
2026-11-13 21:26:28 +00:00
inference-admin 2172202315 manifest: pin to 20261113-8f67896 2026-11-13 21:19:25 +00:00
inference-admin 8f67896407 page: Cache-Control no-store (same reason as the panel: no validators on a single inline script, so a cached copy runs the previous deploy's JS) 2026-11-13 21:18:41 +00:00
inference-admin a6a70a0754 manifest: pin to 20261113-f72af43 2026-11-13 21:18:14 +00:00
inference-admin f72af43051 dashboard: build the shared metric row at boot
buildMetricButtons() was defined but never called — a one-shot replace had
slipped the call into loadGuests()'s 401 branch, and removing that left no call
at all. So the dashboard rendered its data with an empty metric row: no way to
switch between the shared metrics. Called at boot now, anchored on the closing
script tag, and the harnesses plus the served-page browser check confirm the row
exists with all six data-metric buttons.
2026-11-13 21:17:59 +00:00
inference-admin 1340548859 manifest: pin to registry.inference.coop/code/member-dashboard:20261113-e2a5018 2026-11-13 21:14:40 +00:00
inference-admin e2a5018150 fix: same broken metric-button line, plus a mangled location.reload()
The dashboard carried the identical inline-handler line inside PAGE_HTML — the
served JS was a syntax error from there on, so the page loaded and then did
nothing — and a second casualty of the same sloppy one-shot replace:
`location.reload()` had become `location.rebuildMetricButtons()\nload()` inside
loadGuests(). Both are fixed, and the same gate fix applies (the gate now reads
PAGE_HTML via ast.literal_eval, i.e. the string the app serves, not the source
text between the quotes).

Buttons are delegated data-metric clicks now, the harness proves the click
reaches setTrendMetric, and the stub gained stateful attributes plus
addEventListener/__fire to make that possible.
2026-11-13 21:14:03 +00:00
inference-admin 36d8ba6e35 manifest: pin to member-dashboard:20261113-d10b817 2026-11-13 21:02:58 +00:00
inference-admin d10b817fdc dashboard: the co-op charts come from the shared definitions (Money included)
The dashboard kept its own TREND_CONF with its own titles ("The co-op over time",
"What the co-op spent (members + the co-op's own accounts)") and its own toggles —
the other half of the drift the panel just lost. The metric list is now
CoOpChart.CHART_METRICS, the chart is drawn by the shared renderChart(), and the
buttons are built from the shared list, so members and stewards read the same
charts with the same names.

Money arrives as a metric here too, fed by a new /api/money-series proxy to the
portal's /broker/money-series — the co-op's cumulative revenue, cumulative token
spend and OC balance (a gap before snapshots began, never a zero). Deleting the
local TREND_CONF/trendVal/trendLabel also removes the second set of formatters.

Two page-blanking bugs caught by check-page-js.sh before they could ship: a
destructured fmtMoney colliding with this page's own (duplicate const), and `esc`
(which the panel defines and this page does not — it uses escapeHtml).

Harness extended: the money metric draws 2 lines + a single-point balance marker,
the tooltip lists every series and reports the unmeasured balance as not
measured, the metric row equals the shared list filtered by METRIC_SOURCE, and a
metric with no source says so. Geometry proof: 15 captured renders (5 metrics x 3
ranges) byte-identical to the predecessor with aria stripped.
2026-11-13 21:01:38 +00:00
inference-admin c5d4677ec3 chart module: re-pin to the canonical revision that adds the definition layer
Same byte-identical module as the panel; the dashboard's own port to the shared
definitions is the next commit. check-page-js.sh's DOM stub now supports
setAttribute/insertAdjacentHTML, which the shared metric-button builder needs.
2026-11-13 20:55:52 +00:00
inference-bot 8c469c1242 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.
2026-11-13 16:11:23 +00:00
inference-bot 622982a371 oidc.py: single-sourced shared module; guest trail consumes the portal's state
- app/oidc.py is now a byte-identical copy of the canonical module
  (ops-docs: scripts/shared/oidc_client.py); this app's identity (logger
  name, session cookie, session salt) is set via oidc.configure() in
  main.py with the app's historical values, so existing sessions survive.
  tests/test_oidc_sync.py pins the copy to the canonical revision — a hand
  edit goes red; changes go through the canonical + sync-oidc-module.sh.
- The guest trail pill consumes the portal-served `state` (the single
  invited-vs-active derivation, tested in the portal) with the old
  status-only payload fallback kept; dashboard-guests-harness.js asserts
  both shapes through the real page JS.
2026-11-11 05:21:31 +00:00
inference-bot 1e6e9e481c Guest invite: hide the form once the 30-day invite is used; guest errors render in the guest card
When the member has no invite left (one per rolling 30 days), the invite
form is REMOVED and a dated line takes its place: 'You have already
invited a guest this month. Your next invite is available <date>' — the
date computed by the portal from the last invite (next_eligible_at).

All guest-invite feedback (errors, refusals, success) now renders in a
dedicated #guest-flash inside the guest access card — never the #flash
element in the API-keys card, which is a different feature (the bug the
operator reported: over-limit refusals surfaced in the API key area).
Hiding the form is UX only; the portal refuses direct over-limit calls
server-side regardless.
2026-11-08 20:53:51 +00:00
Inferencebot e5162afa05 Gift trail: invited guest reads 'Invited — awaiting setup', not active
The portal's trail now carries a derived state per guest entry — 'invited'
while the Cloudron invite is un-accepted (the guest cannot log in yet) —
rendered as a pale-blue pill; the ledger status stays the fallback for
older payloads. Display only.
2026-11-08 20:40:26 +00:00
inference-bot 1e9d212bd0 Guest section: invitations send directly — remove the pending-approval state
The portal provisions member invites immediately now (approval gate removed
2026-11-08), so the dashboard drops the trial-gate UI: no auto_approve
branch, no 'pending approval' pill or its CSS, button is always 'Send
invite', and the confirmation says the friend can set up their account now.
The trail still shows each guest active with its expiry (legacy rejected
requests from the trial period remain as history).
2026-11-08 20:20:33 +00:00
inference-bot 032068bfb4 Guest copy: $5 -> $2 of AI credits/usage 2026-11-08 20:13:22 +00:00
inference-bot e59ba4d05a Guest-invite form: keep a name field, optional and clearly labelled
Same standard form as the admin panel: the guest's email (required) plus
an OPTIONAL display name ('Their name (optional)' placeholder). Passed
through as the initial display name; an empty name is never derived from
the email. Full-width inputs in the stacked mobile form.
2026-11-08 02:57:30 +00:00
inference-bot 8f8106742a Standard guest-invite form: one email field, no name input
Same form as the admin panel: 'Invite a guest' heading, a single required
email input, a 'Send invite' button, submit on Enter. The inviter is the
logged-in member (automatic); the portal applies the one-per-30-days rule,
recipient checks and the pending-approval gate as before. No name is
collected or derived — the guest chooses their own at Cloudron setup.
2026-11-08 02:55:23 +00:00
inference-bot 84d5389eb6 Member self-serve guest access: invite a friend from the dashboard
New Guest access card (members only — a guest's dashboard keeps its own
ended-state view): invite a friend by email with an optional display name,
the remaining invitation allowance (one guest per member per rolling 30
days, with the next open date), and the member's own guest trail — who they
invited, when, and the honest status (pending approval / not approved /
active guest / became a member / ended). Under the trial gate the button
says 'Send request' and the hint says the co-op approves before the account
is created; the portal's auto_approve flag flips both to 'Send invite' with
no deploy. Portal refusals pass through verbatim (429 member-facing text).
/api/guests GET+POST are one hop to the portal's /broker/guests endpoints.
2026-11-08 02:44:02 +00:00
inference-bot 7430811ddc Rename 'gift' to 'guest' throughout: guest-status/cancel-guest routes, cancel-link wording, ended-state lines (pure rename, no behaviour change) 2026-11-08 02:35:52 +00:00
inference-bot 19361e27e4 guest cancel: self-service end-of-access with the ended state, and the plain OC-payment note
Guests get a one-click-reveal, one-click-confirm Cancel control under the
Become-a-member row: it ends the gift via the portal broker (/api/cancel-gift
→ /broker/cancel-gift), which returns unspent credit to the co-op. An ended
guest (cancelled, expired or spent out — via /api/gift-status on the usage
403, or straight from the cancel response) renders the ended state plainly:
access ended, unspent credit returned where it was, account and data kept,
Become-a-member still present. Members see the new plain line under the
balance: membership continues while the Open Collective contribution is
active — ending the contribution ends the membership, allowance stops
renewing after the current cycle — with the contribute page as the place to
manage the payment. Informational only.
2026-11-08 02:28:55 +00:00
inference-bot 67c10bae25 dashboard: guest accounts — no Matrix section, Become-a-member instead of buy
Gift accounts (portal flag on /broker/usage) get a different dashboard: the
Matrix card is hidden in the markup and only revealed for members (a guest
never sees it, even before the usage fetch returns), the credit-pack buy
button becomes 'Become a member' pointing at the OC contribution page, and
the meta line names the gift. Everything else (spend, models, keys, docs
links) unchanged.
2026-11-08 02:06:50 +00:00
inference-bot 3453131c73 dashboard: point docs links (Docs/Terms/Privacy, models, energy, allowance) at docs.inference.coop 2026-11-03 21:47:35 +00:00
inference-bot 55e81bfff9 dashboard: show the co-op's own share in Co-op usage
The Co-op usage view charted the co-op-wide spend (which spans the co-op's own
operator accounts) with nothing saying so. Adds a stats pair — co-op spend all
time, and of which the co-op's own accounts — summed from the series' new
operator_spend_usd (NULL days skipped, not counted as zero), and labels the
spend chart and the model board as including the co-op's own accounts.
2026-11-02 15:44:34 +00:00
inference-bot 094a3cb588 credit the member whose diagnosis produced the buy path
code/member-dashboard PR #1 by cag identified that members looked for a way to add usage and could not find it. The implementation that shipped (b352b1f) took that intent with a configurable destination, but its commit message did not name the contributor, which is the sort of thing that stops people bothering next time. Credited in the source where the feature lives. Source-only: no rebuild, so the running image does not contain this comment.
2026-11-02 02:08:39 +00:00
InferenceBot b352b1f427 dashboard: always-visible "Buy a credit pack" link in My usage
Members looked for a way to add usage from the dashboard and could not
find it — the buy path was invisible unless someone pointed them at it.
Add an always-visible green button in the "My usage" card, opening in a
new tab, plus the member's real credit status and a docs link.

The destination comes from CREDIT_PACK_URL on the dashboard app (same
convention the portal uses), defaulting to the Open Collective
contribute page — configurable in one place, not hardcoded in the
template. When the member has purchased credits the hint reads
"Credits never expire ($X purchased all-time)"; otherwise it keeps the
static "Credit packs never expire · used after your monthly allowance".

Docs link points at getting-started.md#user-content-need-more-than-the-allowance
(the rendered heading id Gitea actually serves), not the bare anchor.
2026-11-02 00:50:45 +00:00
11 changed files with 2034 additions and 174 deletions

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"
+6 -1
View File
@@ -17,5 +17,10 @@
"manifestVersion": 2, "manifestVersion": 2,
"website": "https://inference.coop", "website": "https://inference.coop",
"contactEmail": "info@inference.coop", "contactEmail": "info@inference.coop",
"tags": ["member", "dashboard", "cooperative"] "tags": [
"member",
"dashboard",
"cooperative"
],
"dockerImage": "registry.inference.coop/code/member-dashboard:20261117-5a3df91"
} }
+421
View File
@@ -0,0 +1,421 @@
/* 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);
+908 -163
View File
File diff suppressed because it is too large. Load diff
+52 -10
View File
@@ -1,7 +1,12 @@
"""OIDC client for Cloudron's OpenID Connect addon. """OIDC client for Cloudron's OpenID Connect addon — ONE shared module.
Implements the authorization-code flow against Cloudron's built-in OIDC This file is the SINGLE SOURCE for the two thin Cloudron apps that implement
provider, so the app no longer depends on the proxyAuth header wall. the authorization-code flow themselves (admin-panel, member-dashboard). The
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):
@@ -16,8 +21,16 @@ 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` (username) as the identity — the portal's broker accepts it as We use `sub` as the identity; each host app decides what it authorizes — the
`X-Member-User` and resolves username → email. panel matches it against its ADMIN_USERNAMES allowlist, the dashboard
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
@@ -29,15 +42,44 @@ 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
logger = logging.getLogger("member-dashboard") # Per-app identity — set by the host app at import time via configure().
# 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 cookie name + max age (8 hours, roughly a working day). SESSION_MAX_AGE = 60 * 60 * 8 # 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()
@@ -55,7 +97,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="member-dashboard-oidc-session") return URLSafeTimedSerializer(secret, salt=_SESSION_SALT)
def _redirect_uri(request_host: str) -> str: def _redirect_uri(request_host: str) -> str:
+194
View File
@@ -0,0 +1,194 @@
// 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
@@ -0,0 +1,65 @@
// 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
@@ -0,0 +1,96 @@
// 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");
+123
View File
@@ -0,0 +1,123 @@
#!/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
@@ -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 = "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
@@ -0,0 +1,55 @@
#!/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")