Files
member-dashboard/app/main.py
T
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

1546 lines
68 KiB
Python

"""Member Dashboard — read-only usage view + API-key management.
Security model:
- Authentication is done by Cloudron's proxyAuth wall (SSO). Cloudron injects
the authenticated user's identity via the X-Remote-User header (username).
- This app holds NO privileged credentials. It calls the member portal's
broker endpoints, authenticated with a shared BROKER_SECRET, and scopes
every request to the logged-in member.
Environment (all provided by Cloudron env vars):
PORTAL_BASE — base URL of the member portal (e.g. https://portal.inference.coop)
BROKER_SECRET — shared secret for the portal's broker endpoints
CREDIT_PACK_URL — where the "Buy a credit pack" link sends members (defaults to
the Open Collective contribute page, which is what actually
credits a member). Configuration, not code, because the
destination can move (a future pack page) without a deploy here.
"""
import os
import logging
import re
import httpx
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from app import oidc
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("member-dashboard")
PORTAL_BASE = os.environ.get("PORTAL_BASE", "").rstrip("/")
BROKER_SECRET = os.environ.get("BROKER_SECRET", "")
# Where the always-visible "Buy a credit pack" link points. Configuration, not a
# constant in the template: the co-op sets this per app (same convention the
# portal uses) so the destination changes in one place. The Open Collective
# contribution page is the default because that is what actually credits a
# member today (the webhook settles contributions into credits).
DEFAULT_CREDIT_PACK_URL = "https://opencollective.com/inference-cooperative/contribute"
CREDIT_PACK_URL = (os.environ.get("CREDIT_PACK_URL") or "").strip() or DEFAULT_CREDIT_PACK_URL
# Where a GUEST account's "Become a member" button points (the contribution
# page — what actually starts a membership). Deliberately independent of
# CREDIT_PACK_URL: a guest needs a membership, not a credit pack, even if the
# credit-pack link is ever repointed at a pack page.
BECOME_MEMBER_URL = "https://opencollective.com/inference-cooperative/contribute"
app = FastAPI()
# ---------------------------------------------------------------------------
# Identity — Cloudron OIDC session cookie (username). proxyAuth header is the
# legacy fallback during the transition.
# ---------------------------------------------------------------------------
def get_user_identity(request: Request) -> str:
"""Return the logged-in user's identity (Cloudron username).
Reads the validated OIDC session cookie. No header fallback — the app no
longer trusts a client-supplied identity header (that path existed only
during the proxyAuth → OIDC transition and is now removed).
"""
if not oidc.is_oidc_configured():
return ""
token = request.cookies.get(oidc.SESSION_COOKIE)
if not token:
return ""
return oidc.read_session(token) or ""
# ---------------------------------------------------------------------------
# Broker calls (to the member portal)
# ---------------------------------------------------------------------------
def broker_headers(identity: str) -> dict:
return {"X-Broker-Secret": BROKER_SECRET, "X-Member-User": identity}
async def broker_get(identity: str, path: str) -> dict:
async with httpx.AsyncClient(timeout=20.0) as client:
r = await client.get(f"{PORTAL_BASE}{path}", headers=broker_headers(identity))
if r.status_code == 401:
raise HTTPException(500, "Portal rejected broker credentials")
if r.status_code == 403:
raise HTTPException(403, "Not an active member")
if r.status_code != 200:
raise HTTPException(502, f"Portal error {r.status_code}")
return r.json()
async def broker_post(identity: str, path: str, payload: dict | None = None) -> dict:
async with httpx.AsyncClient(timeout=20.0) as client:
r = await client.post(f"{PORTAL_BASE}{path}", headers=broker_headers(identity), json=payload or {})
if r.status_code in (401, 403):
raise HTTPException(r.status_code, r.text)
if r.status_code not in (200, 201):
raise HTTPException(502, f"Portal error {r.status_code}: {r.text}")
return r.json()
async def broker_delete(identity: str, path: str) -> dict:
async with httpx.AsyncClient(timeout=20.0) as client:
r = await client.delete(f"{PORTAL_BASE}{path}", headers=broker_headers(identity))
if r.status_code in (401, 403):
raise HTTPException(r.status_code, r.text)
if r.status_code not in (200, 204):
raise HTTPException(502, f"Portal error {r.status_code}")
return r.json() if r.content else {}
async def broker_call(identity: str, method: str, path: str, payload: dict | None = None) -> tuple[int, dict]:
"""Portal call that returns the portal's OWN status + payload.
The guest path's 429 refusals are member-facing text ("one guest per
member per month") — transport-error wrapping (502) would bury them, so
the guest routes surface the portal's status and detail verbatim.
"""
async with httpx.AsyncClient(timeout=20.0) as client:
r = await client.request(method, f"{PORTAL_BASE}{path}",
headers=broker_headers(identity), json=payload)
try:
data = r.json()
except Exception:
data = {"error": r.text or "portal returned no body"}
if r.status_code == 401:
# Broker credentials broken — an app fault, not a member condition.
data = {"error": "The portal rejected this dashboard's credentials"}
return r.status_code, data
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@app.get("/healthz")
async def healthz():
return {"status": "ok"}
@app.get("/")
async def index(request: Request):
identity = get_user_identity(request)
if not identity:
if oidc.is_oidc_configured():
return RedirectResponse("/auth/openid/login", status_code=302)
return HTMLResponse(
"<h1>Not authenticated</h1><p>Please log in via the dashboard login.</p>",
status_code=401,
)
return HTMLResponse(render_page(identity))
@app.get("/api/usage")
async def api_usage(request: Request):
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
data = await broker_get(identity, "/broker/usage")
keys = await broker_get(identity, "/broker/keys")
data["keys"] = keys.get("keys", [])
# Co-op-wide model popularity (aggregate, anonymized) for the leaderboard.
try:
board = await broker_get(identity, "/broker/model-leaderboard?days=30")
data["coop_models"] = board.get("models", [])
except HTTPException:
data["coop_models"] = [] # best-effort; never block the main view
return data
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.get("/api/metrics")
async def api_metrics(request: Request):
"""Co-op metrics over time, for the Co-op usage view.
Aggregate and non-personal (co-op size, requests served, spend), the same
class as the model leaderboard. Fetched at the widest range so the metric
and period toggles re-render client-side without refetching.
"""
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
return await broker_get(identity, "/broker/metrics?days=730")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/keys")
async def api_create_key(request: Request):
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
body = await request.json()
name = (body.get("name") or "").strip()
if not re.fullmatch(r"[A-Za-z0-9._-]{1,64}", name):
return JSONResponse({"error": "Invalid key name"}, status_code=400)
try:
return await broker_post(identity, "/broker/keys", {"name": name})
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.delete("/api/keys/{name}")
async def api_revoke_key(name: str, request: Request):
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
return await broker_delete(identity, f"/broker/keys/{name}")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.get("/api/matrix-mxid")
async def api_get_matrix_mxid(request: Request):
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
return await broker_get(identity, "/broker/matrix-mxid")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/matrix-mxid")
async def api_set_matrix_mxid(request: Request):
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
body = await request.json()
mxid = (body.get("matrix_mxid") or "").strip()
try:
return await broker_post(identity, "/broker/matrix-mxid", {"matrix_mxid": mxid})
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.get("/api/guest-status")
async def api_guest_status(request: Request):
"""What became of the caller's guest account (guest view).
Loaded when the usage view refuses a GUEST (access ended): the portal
answers for ended guest accounts so the dashboard can say plainly that
access ended, the data is kept, and a membership is still available.
Members get guest: false — the caller falls back to the usage error.
"""
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
return await broker_get(identity, "/broker/guest-status")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/cancel-guest")
async def api_cancel_guest(request: Request):
"""End the caller's own guest account (self-service cancel, guest view).
One hop to the portal broker, which holds the actual semantics: access
ends immediately, unspent credit returns to the co-op, the ledger keeps
the trail, and a repeat call is a no-op. Guest accounts only — the portal
refuses a paying member with 403.
"""
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
return await broker_post(identity, "/broker/cancel-guest")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.get("/api/guests")
async def api_guests(request: Request):
"""The caller's guest-access view: invitation allowance + their trail.
One hop to the portal broker's GET /broker/guests: whether this member
can send a guest invitation now (the rolling one-per-30-days rule,
counting pending and approved requests) and every invitation they have
made, with its status. The portal's refusal statuses pass through as-is.
"""
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
status, data = await broker_call(identity, "GET", "/broker/guests")
return JSONResponse(data, status_code=status)
@app.post("/api/guests")
async def api_guest_invite(request: Request):
"""Invite a guest, from the member dashboard (self-serve guest access).
Body: {"email": "<recipient>", "name": "<optional display name>"}. One
hop to the portal broker, which holds every protection (active-member
inviter, one invitation per member per 30 days, recipient never an
existing member / prior guest / pending request / manual account) and
the trial gate: with approval on, the request waits for the co-op's
approve/reject and nothing goes to the recipient until then. The
portal's refusals are member-facing text and pass through verbatim.
"""
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
body = await request.json()
payload = {
"email": (body.get("email") or "").strip().lower(),
"name": (body.get("name") or "").strip(),
}
if not payload["email"] or "@" not in payload["email"]:
return JSONResponse({"error": "Enter their email address"}, status_code=400)
status, data = await broker_call(identity, "POST", "/broker/guests", payload)
return JSONResponse(data, status_code=status)
# ---------------------------------------------------------------------------
# OIDC routes — authorization-code flow against Cloudron's OIDC provider.
# Active only when the `oidc` addon is configured (CLOUDRON_OIDC_* present).
# During the transition the legacy proxyAuth header still works as a fallback.
# ---------------------------------------------------------------------------
@app.get("/auth/openid/login")
async def oidc_login(request: Request):
if not oidc.is_oidc_configured():
raise HTTPException(404, "OIDC not configured")
login_url, state, nonce = oidc.build_login_url(request.headers.get("host", ""))
resp = RedirectResponse(login_url, status_code=302)
resp.set_cookie("oidc_state", state, max_age=600, httponly=True, samesite="lax")
resp.set_cookie("oidc_nonce", nonce, max_age=600, httponly=True, samesite="lax")
return resp
@app.get("/auth/openid/callback")
async def oidc_callback(request: Request):
if not oidc.is_oidc_configured():
raise HTTPException(404, "OIDC not configured")
code = request.query_params.get("code")
state = request.query_params.get("state")
expected_state = request.cookies.get("oidc_state")
nonce = request.cookies.get("oidc_nonce")
if not code or not state or not expected_state or not nonce:
return HTMLResponse("<h1>Login failed</h1><p>Incomplete OIDC callback.</p>", status_code=400)
if state != expected_state:
return HTMLResponse("<h1>Login failed</h1><p>State mismatch (possible CSRF).</p>", status_code=400)
try:
identity = await oidc.exchange_code(code, request.headers.get("host", ""), nonce)
except ValueError as e:
logger.warning("OIDC login failed: %s", e)
return HTMLResponse("<h1>Login failed</h1><p>Could not complete sign-in.</p>", status_code=400)
session = oidc.write_session(identity)
resp = RedirectResponse("/", status_code=302)
resp.set_cookie(oidc.SESSION_COOKIE, session, max_age=oidc.SESSION_MAX_AGE, httponly=True, samesite="lax")
resp.delete_cookie("oidc_state")
resp.delete_cookie("oidc_nonce")
return resp
@app.get("/logout")
async def logout(request: Request):
"""Log out: clear our session, then show an explicit logged-out page.
Cloudron's OIDC provider removed its RP-initiated logout endpoint (forum:
"no app supports this properly"), so we cannot end the SSO session
programmatically. Redirecting to / would silently re-authenticate through
the still-valid SSO cookie — the "logout does nothing" bug. Instead we
clear our cookies and show a page with a manual link to sign out of
Cloudron SSO (my.inference.coop/logout) for a full sign-out.
"""
html = """<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Logged out — Inference Cooperative</title>
<style>
body { font-family: 'Figtree', -apple-system, system-ui, sans-serif; background: #faf8f5;
color: #2d3327; display: flex; align-items: center; justify-content: center;
min-height: 100vh; margin: 0; }
.card { background: #fff; border: 1px solid #e4e0d8; border-radius: 14px;
padding: 32px 40px; max-width: 440px; text-align: center; }
h1 { font-size: 20px; margin: 0 0 12px; color: #2d3327; }
p { font-size: 14px; line-height: 1.6; color: #4a5442; margin: 0 0 16px; }
a.btn { display: inline-block; background: #5b8c5a; color: #fff; text-decoration: none;
padding: 9px 18px; border-radius: 8px; font-weight: 600; font-size: 14px; }
a.btn:hover { background: #4e7a4d; }
a.link { color: #3f6e3e; font-size: 13px; }
</style></head>
<body><div class="card">
<h1>You're logged out</h1>
<p>Your dashboard session has been cleared.</p>
<p>Note: you may still be signed in to Inference Cooperative SSO
(chat, portal, forum share that sign-in). To fully sign out everywhere,
log out of your Cloudron account too.</p>
<p><a class="btn" href="https://my.inference.coop/logout">Sign out of SSO</a></p>
<p><a class="link" href="/">Log back in</a></p>
</div></body></html>"""
resp = HTMLResponse(html)
resp.delete_cookie(oidc.SESSION_COOKIE)
resp.delete_cookie("oidc_state")
resp.delete_cookie("oidc_nonce")
return resp
# ---------------------------------------------------------------------------
# UI (brand-matched, self-contained, no external requests)
# ---------------------------------------------------------------------------
def _esc(s: str) -> str:
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
def render_page(identity: str) -> str:
return (
PAGE_HTML.replace("@@IDENTITY@@", _esc(identity))
.replace("@@CREDIT_PACK_URL@@", _esc(CREDIT_PACK_URL))
.replace("@@BECOME_MEMBER_URL@@", _esc(BECOME_MEMBER_URL))
)
PAGE_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inference Cooperative · Your membership</title>
<style>
:root {
--cream: #faf8f5;
--ink: #2d3327;
--muted: #6b7a62;
--green-deep: #5b8c5a;
--green-mid: #6ba86b;
--green-light: #7ab87a;
--border: #e4e0d8;
--danger: #b3543a;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Figtree', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
background: var(--cream);
color: var(--ink);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
display: flex; flex-direction: column; min-height: 100vh;
}
.wrap { width: 100%; max-width: 760px; margin: 0 auto; padding: 32px 24px 24px; flex: 1; }
header { display: flex; align-items: flex-start; gap: 16px; margin-bottom: 8px; }
.logo svg { display: block; }
.brand { flex: 1; }
.brand h1 { font-size: 20px; font-weight: 700; letter-spacing: -0.01em; }
.brand .sub { color: var(--muted); font-size: 14px; }
.identity { margin-top: 6px; font-size: 13px; color: var(--muted); }
.identity code {
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
background: #f4f2ec; padding: 1px 6px; border-radius: 5px; font-size: 12px;
}
.header-actions { display: flex; gap: 14px; align-items: center; flex-shrink: 0; }
a.link { color: var(--green-deep); text-decoration: none; font-size: 14px; font-weight: 600; }
a.link:hover { text-decoration: underline; }
.card {
background: #fff;
border: 1px solid var(--border);
border-radius: 14px;
padding: 24px 28px;
margin-top: 20px;
}
.card h2 { font-size: 15px; font-weight: 600; margin-bottom: 14px; }
.balance { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
.balance .big { font-size: 34px; font-weight: 700; color: var(--green-deep); }
.balance .lbl { color: var(--muted); font-size: 15px; }
.stats { display: flex; gap: 28px; margin-top: 12px; flex-wrap: wrap; }
.stat .num { font-size: 18px; font-weight: 700; color: var(--ink); }
.stat .lbl { font-size: 12px; color: var(--muted); }
.bar { height: 10px; background: #eef0ea; border-radius: 6px; margin-top: 16px; overflow: hidden; }
.bar .fill { height: 100%; background: var(--green-mid); border-radius: 6px; transition: width .3s ease; }
.bar .fill.warn { background: #d99a3e; }
.meta { color: var(--muted); font-size: 13px; margin-top: 8px; }
/* Always-visible buy path: members could not find a way to add usage.
A green button (same green + radius as the other buttons) out to the
configured pack page, plus the member's real credit status and a link
to the docs section that explains allowance vs. credits. */
.buy-row { display: flex; align-items: center; gap: 14px; margin-top: 14px; flex-wrap: wrap; }
a.buy-btn {
display: inline-block; background: var(--green-deep); color: #fff;
border-radius: 8px; font-size: 14px; font-weight: 600;
padding: 8px 16px; text-decoration: none; transition: background .15s ease;
}
a.buy-btn:hover { background: #4e7a4d; }
.buy-hint { color: var(--muted); font-size: 12px; }
a.buy-docs { color: var(--green-deep); font-weight: 600; text-decoration: none; white-space: nowrap; }
a.buy-docs:hover { text-decoration: underline; }
/* The membership-payment line: how a membership ends, in one plain
sentence under the balance. Members only (a guest has no payment). */
.oc-note { color: var(--muted); font-size: 12px; margin-top: 12px; }
.oc-note a { color: var(--green-deep); font-weight: 600; text-decoration: none; }
.oc-note a:hover { text-decoration: underline; }
/* Guest self-service cancel: a quiet link that reveals the confirm step,
then ends the access. Sits under the Become-a-member row. */
.cancel-row { margin-top: 14px; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
.cancel-link {
font-family: inherit; cursor: pointer; background: none; border: none;
color: var(--danger); font-size: 12px; font-weight: 600; text-decoration: underline;
padding: 0;
}
.cancel-confirm-note { color: var(--muted); font-size: 12px; }
button.cancel-go {
font-family: inherit; cursor: pointer; background: #fff; color: var(--danger);
border: 1px solid var(--danger); border-radius: 8px; font-size: 13px;
font-weight: 600; padding: 6px 14px;
}
button.cancel-go:hover { background: var(--danger); color: #fff; }
button.cancel-keep {
font-family: inherit; cursor: pointer; background: none; border: none;
color: var(--muted); font-size: 12px; font-weight: 600; text-decoration: underline;
}
/* The ended state: access over, account and data kept, membership one
contribution away. Replaces the usage numbers for an ended guest. */
.ended { padding: 4px 0 2px; }
.ended h3 { font-size: 17px; font-weight: 700; margin-bottom: 8px; color: var(--ink); }
.ended .hint { color: var(--muted); font-size: 13px; margin-bottom: 10px; }
.ended .buy-btn { margin-top: 4px; }
.models { margin-top: 16px; }
.model-row {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 9px 0; border-top: 1px solid #f0ede6;
}
.model-name { font-weight: 600; font-size: 13px; }
.model-sub { color: var(--muted); font-size: 12px; }
.model-spend { font-size: 13px; font-weight: 600; color: var(--ink); text-align: right; }
/* Usage mode switch */
.usage-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.usage-header h2 { margin-bottom: 0; }
.mode-switch { display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
.mode-btn {
font-family: inherit; cursor: pointer; border: none; background: #fff; color: var(--muted);
font-size: 12px; font-weight: 600; padding: 6px 12px; border-radius: 0;
}
.mode-btn.active { background: var(--green-deep); color: #fff; }
.docs-link { display: inline-block; margin-top: 14px; color: var(--green-deep); font-size: 13px; font-weight: 600; text-decoration: none; }
.docs-link:hover { text-decoration: underline; }
/* Leaderboard */
.board-note { color: var(--muted); font-size: 12px; margin-bottom: 10px; }
/* The co-op over time: same chart as the admin panel's Trends tab, sized for
members. Inline SVG, no library, colours from the shared palette vars. */
.coop-trend { border: 1px solid var(--border, #e4e0d8); border-radius: 12px; padding: 14px 16px 12px; margin-bottom: 20px; }
.coop-trend-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; }
.coop-trend-title { font-weight: 700; font-size: 15px; color: var(--ink, #2d3327); }
.coop-trend-controls { display: flex; gap: 18px; flex-wrap: wrap; margin-bottom: 10px; }
.coop-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin: 2px 0 12px; }
.coop-stats .num { font-size: 20px; font-weight: 700; color: var(--ink, #2d3327); }
.coop-stats .lbl { font-size: 12px; color: var(--muted); }
.trend-group { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.coop-trend-body svg { display: block; width: 100%; height: auto; overflow: visible; }
.board-row {
display: flex; align-items: flex-start; gap: 14px;
padding: 12px 0; border-top: 1px solid #f0ede6;
}
.board-rank {
width: 26px; height: 26px; border-radius: 50%;
background: #eaf3ea; color: #2f5c30; font-weight: 700; font-size: 13px;
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
margin-top: 2px;
}
.board-main { flex: 1; min-width: 0; }
.board-line { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
.board-cost { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
.board-name { font-weight: 600; font-size: 13px; margin-bottom: 5px; }
.board-bar { height: 6px; background: #eef0ea; border-radius: 4px; overflow: hidden; }
.board-fill { height: 100%; background: var(--green-mid); border-radius: 4px; }
.board-sub { color: var(--muted); font-size: 11px; margin-top: 4px; }
.keys { margin-top: 8px; }
.key-row {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 14px 0; border-bottom: 1px solid var(--border);
}
.key-row:last-child { border-bottom: none; }
.key-name { font-weight: 600; font-size: 14px; }
.key-meta { color: var(--muted); font-size: 12px; margin-top: 2px; }
.key-chat { color: var(--muted); font-size: 12px; margin-top: 10px; }
.key-chat-name { font-weight: 600; }
.key-chat-num { color: var(--ink); font-weight: 600; font-variant-numeric: tabular-nums; }
.key-token {
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
font-size: 12px; color: var(--muted);
background: #f4f2ec; padding: 4px 8px; border-radius: 6px;
word-break: break-all; max-width: 280px;
}
button {
font-family: inherit; cursor: pointer;
border-radius: 8px; font-size: 14px; font-weight: 600;
padding: 8px 16px; border: none; transition: background .15s ease, opacity .15s ease;
}
button.primary { background: var(--green-deep); color: #fff; }
button.primary:hover { background: #4e7a4d; }
button.ghost { background: transparent; color: var(--danger); }
button.ghost:hover { background: #f6e9e5; }
button:disabled { opacity: .5; cursor: not-allowed; }
.new-key { display: flex; gap: 10px; margin-top: 16px; }
.new-key input {
flex: 1; font-family: inherit; font-size: 14px;
padding: 9px 12px; border: 1px solid var(--border); border-radius: 8px;
background: #fff; color: var(--ink);
}
.new-key input:focus { outline: none; border-color: var(--green-mid); }
.hint { color: var(--muted); font-size: 12px; margin-top: 10px; }
.hint.ok { color: #2f5c30; }
.key-reveal {
margin-top: 16px; padding: 16px;
background: #eaf3ea; border: 1px solid var(--green-mid); border-radius: 10px;
}
.key-reveal-title { font-weight: 700; font-size: 14px; margin-bottom: 4px; }
.key-reveal-name { color: var(--muted); font-size: 12px; margin-bottom: 8px; }
.key-reveal-value {
display: block; font-family: ui-monospace, 'SF Mono', Menlo, monospace;
font-size: 12px; background: #fff; padding: 8px 10px; border-radius: 6px;
word-break: break-all; margin-bottom: 10px; user-select: all;
}
.empty { color: var(--muted); font-size: 14px; padding: 12px 0; }
.flash {
padding: 12px 16px; border-radius: 8px; margin-top: 16px; font-size: 14px;
display: none;
}
.flash.show { display: block; }
.flash.ok { background: #eaf3ea; color: #2f5c30; }
.flash.err { background: #f6e9e5; color: var(--danger); }
/* ---------- Guest access (members inviting a friend) ---------- */
.guest-hint { color: var(--muted); font-size: 12px; margin-bottom: 12px; }
.new-key .name-input { max-width: 200px; }
.guest-trail { margin-top: 6px; }
.guest-row {
display: flex; align-items: baseline; justify-content: space-between; gap: 12px;
padding: 10px 0; border-bottom: 1px solid #f0ede6;
}
.guest-row:last-child { border-bottom: none; }
.guest-who { font-weight: 600; font-size: 13px; }
.guest-meta { color: var(--muted); font-size: 12px; margin-top: 2px; }
.gpill { display: inline-block; padding: 2px 9px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }
.gpill.pending { background: #fdf3e3; color: #a97a2a; }
.gpill.ok { background: #eaf3ea; color: #2f5c30; }
.gpill.done { background: #f1e8da; color: #a97a4a; }
.gpill.bad { background: #f6e9e5; color: var(--danger); }
footer {
border-top: 1px solid var(--border);
padding: 20px 24px; margin-top: 32px;
text-align: center; font-size: 13px; color: var(--muted);
}
footer a { color: var(--green-deep); text-decoration: none; margin: 0 8px; }
footer a:hover { text-decoration: underline; }
/* ---------- Mobile (≤600px) ---------- */
@media (max-width: 600px) {
.wrap { padding: 20px 14px 16px; }
header { flex-direction: column; gap: 8px; }
.header-actions { width: 100%; justify-content: flex-start; }
.card { padding: 18px 16px; border-radius: 12px; margin-top: 16px; }
.balance .big { font-size: 28px; }
.stats { gap: 14px 22px; }
.stat { min-width: 40%; } /* two columns of stats instead of cramped one-row wrap */
.model-row { flex-wrap: wrap; }
.model-spend { text-align: left; width: 100%; padding-left: 2px; }
.key-row { flex-wrap: wrap; }
.key-token { max-width: 100%; }
.new-key { flex-direction: column; }
.new-key button { width: 100%; }
.key-reveal-value { font-size: 11px; }
footer { padding: 16px 14px; }
footer a { display: inline-block; margin: 4px 8px; }
}
/* Very narrow phones: keep key/token text from overflowing */
@media (max-width: 380px) {
.balance .big { font-size: 24px; }
.stats { gap: 12px 16px; }
}
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="logo">
<svg width="44" height="44" viewBox="0 0 130 130" fill="none" aria-label="logo">
<circle cx="65" cy="14" r="5" fill="#5b8c5a"/>
<circle cx="58" cy="30" r="6" fill="#7ab87a"/>
<circle cx="74" cy="30" r="4" fill="#6ba86b"/>
<circle cx="51.5" cy="46" r="6.5" fill="#5b8c5a"/>
<circle cx="65" cy="46" r="5" fill="#7ab87a"/>
<circle cx="81" cy="46" r="4" fill="#6ba86b"/>
<circle cx="44" cy="62" r="7" fill="#6ba86b"/>
<circle cx="61" cy="62" r="5.5" fill="#5b8c5a"/>
<circle cx="76" cy="62" r="4.5" fill="#7ab87a"/>
<circle cx="89.5" cy="62" r="3.5" fill="#6ba86b"/>
<circle cx="36.5" cy="78" r="7.5" fill="#5b8c5a"/>
<circle cx="54" cy="78" r="6" fill="#7ab87a"/>
<circle cx="70" cy="78" r="5" fill="#6ba86b"/>
<circle cx="84" cy="78" r="4" fill="#5b8c5a"/>
<circle cx="97.5" cy="78" r="3.5" fill="#7ab87a"/>
<circle cx="44" cy="94" r="6.5" fill="#6ba86b"/>
<circle cx="61" cy="94" r="5.5" fill="#5b8c5a"/>
<circle cx="76" cy="94" r="4.5" fill="#7ab87a"/>
<circle cx="89.5" cy="94" r="3.5" fill="#6ba86b"/>
<circle cx="51.5" cy="110" r="5.5" fill="#5b8c5a"/>
<circle cx="65" cy="110" r="4.5" fill="#7ab87a"/>
<circle cx="81" cy="110" r="3.5" fill="#6ba86b"/>
</svg>
</div>
<div class="brand">
<h1>Inference Cooperative</h1>
<div class="sub">Your membership</div>
<div class="identity" id="identity">Signed in as <code>@@IDENTITY@@</code></div>
</div>
<div class="header-actions">
<a class="link" href="https://my.inference.coop">Member Home</a>
<a class="link" href="/logout">Log out</a>
</div>
</header>
<div class="card">
<div class="usage-header" id="usage-header">
<h2>Usage</h2>
<span class="mode-switch">
<button class="mode-btn active" id="mode-mine" onclick="setUsageMode('mine')">My usage</button>
<button class="mode-btn" id="mode-coop" onclick="setUsageMode('coop')">Co-op usage</button>
</span>
</div>
<div id="view-mine">
<div class="balance">
<span class="big" id="spend">—</span>
<span class="lbl" id="of">of your current balance used</span>
</div>
<div class="stats">
<div class="stat"><div class="num" id="remaining">—</div><div class="lbl">remaining now</div></div>
<div class="stat"><div class="num" id="allowance">—</div><div class="lbl">allowance left</div></div>
<div class="stat"><div class="num" id="credits">—</div><div class="lbl">credits left (never expire)</div></div>
<div class="stat"><div class="num" id="alltime">—</div><div class="lbl">total spend, all time</div></div>
<div class="stat"><div class="num" id="calls">—</div><div class="lbl">requests, all time</div></div>
</div>
<div class="bar"><div class="fill" id="fill" style="width:0%"></div></div>
<div class="meta" id="meta">Shared across chat and API.</div>
<div class="buy-row">
<a class="buy-btn" id="buy-btn" href="@@CREDIT_PACK_URL@@" target="_blank" rel="noopener">Buy a credit pack</a>
<span class="buy-hint"><span id="buy-credits">Credit packs never expire · used after your monthly allowance</span>
<a class="buy-docs" href="https://docs.inference.coop/getting-started/#need-more-than-the-allowance" target="_blank" rel="noopener">More about allowance &amp; credits →</a>
</span>
</div>
<p class="oc-note" id="oc-note" style="display:none">
Your membership continues while your Open Collective contribution is active — ending the contribution ends your membership, and your allowance stops renewing after the current cycle.
<a href="@@BECOME_MEMBER_URL@@" target="_blank" rel="noopener">Manage your payment on Open Collective →</a>
</p>
<div class="cancel-row" id="cancel-row" style="display:none">
<button class="cancel-link" id="cancel-reveal" onclick="revealCancelGuest()">Cancel guest access</button>
<span id="cancel-confirm" style="display:none;">
<span class="cancel-confirm-note">This ends your access now. Unspent guest credit returns to the co-op; your account and data are kept.</span>
<button class="cancel-go" id="cancel-go" onclick="doCancelGuest()">Confirm — end my access</button>
<button class="cancel-keep" onclick="hideCancelGuest()">Keep it</button>
</span>
</div>
<div class="models" id="models"></div>
</div>
<div id="view-coop" style="display:none;">
<div class="coop-trend">
<div class="coop-trend-head">
<span class="coop-trend-title" id="trend-title">The co-op over time</span>
</div>
<div class="coop-stats">
<div class="stat"><div class="num" id="coop-total">—</div><div class="lbl">co-op spend, all time</div></div>
<div class="stat"><div class="num" id="coop-own">—</div><div class="lbl">of which the co-op's own accounts</div></div>
</div>
<div class="coop-trend-controls">
<span class="trend-group">
<span class="board-note" style="margin:0;">Show</span>
<button class="mode-btn active" id="tm-members" onclick="setTrendMetric('members')">Members</button>
<button class="mode-btn" id="tm-requests" onclick="setTrendMetric('requests')">Requests</button>
<button class="mode-btn" id="tm-spend" onclick="setTrendMetric('spend')">Spend</button>
<button class="mode-btn" id="tm-energy" onclick="setTrendMetric('energy')">Energy</button>
<button class="mode-btn" id="tm-co2e" onclick="setTrendMetric('co2e')">Carbon</button>
</span>
<span class="trend-group">
<span class="board-note" style="margin:0;">Period</span>
<button class="mode-btn" id="tr-30" onclick="setTrendDays(30)">30 days</button>
<button class="mode-btn active" id="tr-90" onclick="setTrendDays(90)">90 days</button>
<button class="mode-btn" id="tr-all" onclick="setTrendDays(0)">All time</button>
</span>
</div>
<div id="trend-body" class="coop-trend-body"><div class="empty">Loading</div></div>
</div>
<div class="board-note">Usage across the co-op, including the co-op's own accounts, last 30 days</div>
<div style="display:flex; align-items:center; gap:10px; margin-bottom:10px;">
<span class="board-note" style="margin:0;">Sort by</span>
<button class="mode-btn active" id="sort-cost" onclick="setBoardSort('cost')">Cost</button>
<button class="mode-btn" id="sort-requests" onclick="setBoardSort('requests')">Requests</button>
</div>
<div class="board" id="coop-board"></div>
</div>
<a class="docs-link" href="https://docs.inference.coop/models/" target="_blank">About these models →</a>
<a class="docs-link" href="https://docs.inference.coop/energy/" target="_blank">How we estimate energy and carbon →</a>
</div>
<div class="card" id="keys-card">
<h2>API keys</h2>
<p class="hint">Keys let you use the co-op's AI from your own tools. They draw from the same balance as chat.</p>
<div class="keys" id="keys"><div class="empty">No API keys yet.</div></div>
<div class="key-chat" id="key-chat"></div>
<div class="new-key">
<input id="new-name" type="text" placeholder="Key name (e.g. my-script)" maxlength="64" />
<button class="primary" id="create-btn" onclick="createKey()">Create key</button>
</div>
<div class="flash" id="flash"></div>
<div class="key-reveal" id="key-reveal" style="display:none;">
<div class="key-reveal-title">Copy your key now — it won't be shown again</div>
<div class="key-reveal-name" id="key-reveal-name"></div>
<code class="key-reveal-value" id="key-reveal-value"></code>
<button class="ghost" onclick="$('key-reveal').style.display='none';">Dismiss</button>
</div>
</div>
<div class="card" id="matrix-card" style="display:none">
<h2>Matrix chat</h2>
<p class="hint">We use the Matrix chat protocol to collaborate. You can access our space with an inference.coop account or an account hosted elsewhere.</p>
<p class="hint" style="margin-bottom:6px;"><strong>Current Matrix ID:</strong></p>
<div class="key-reveal" id="mxid-registered">
<code class="key-reveal-value" id="mxid-registered-value">checking…</code>
<div class="new-key" id="mxid-actions" style="margin-top:12px;">
<button class="ghost" id="mxid-use-local" onclick="useLocalMxid()" style="display:none"></button>
<button class="ghost" id="mxid-use-external" onclick="showExternalField()">Use external account</button>
</div>
<div class="new-key" id="mxid-field-row" style="display:none; margin-top:12px;">
<input id="mxid-input" type="text" placeholder="@username:server.org" maxlength="255" />
<button class="primary" id="mxid-btn" onclick="saveMxid()">Save</button>
<button class="ghost" onclick="hideExternalField()">Cancel</button>
</div>
<div class="hint" id="mxid-status"></div>
</div>
</div>
<div class="card" id="guests-card" style="display:none">
<h2>Guest access</h2>
<p class="guest-hint" id="guest-hint">Give a friend $5 of AI credits for the co-op's chat and API — no membership needed. They get 60 days to try it. One guest per member every 30 days.</p>
<div class="new-key">
<input id="guest-email" type="email" placeholder="their@email.org" maxlength="254" />
<input id="guest-name" type="text" class="name-input" placeholder="Their name (optional)" maxlength="80" />
<button class="primary" id="guest-btn" onclick="sendGuestInvite()">Send request</button>
</div>
<div class="hint" id="guest-allowance"></div>
<div class="guest-trail" id="guest-trail"></div>
</div>
</div>
<footer>
<a href="https://docs.inference.coop/">Docs</a> ·
<a href="https://docs.inference.coop/terms-of-service/">Terms</a> ·
<a href="https://docs.inference.coop/privacy-policy/">Privacy</a>
<div style="margin-top:6px;">The Inference Cooperative · inference.coop</div>
</footer>
<script>
const $ = (id) => document.getElementById(id);
function flash(msg, ok) {
const f = $('flash');
f.textContent = msg;
f.className = 'flash show ' + (ok ? 'ok' : 'err');
setTimeout(() => { f.className = 'flash'; }, 6000);
}
function fmtMoney(n) { const v = Math.abs(Number(n)) < 0.005 ? 0 : (Number(n) || 0); return '$' + v.toFixed(2); }
// --- Guest self-service cancel (reveal → confirm → ended state) -----------
function revealCancelGuest() {
$('cancel-reveal').style.display = 'none';
$('cancel-confirm').style.display = '';
}
function hideCancelGuest() {
$('cancel-confirm').style.display = 'none';
$('cancel-reveal').style.display = '';
}
async function doCancelGuest() {
const btn = $('cancel-go');
btn.disabled = true;
btn.textContent = 'Ending…';
try {
const r = await fetch('/api/cancel-guest', { method: 'POST' });
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) {
flash(d.error || 'Cancelling failed — try again', false);
btn.disabled = false;
btn.textContent = 'Confirm — end my access';
return;
}
renderGuestEnded({
guest_status: d.guest_status || 'cancelled by recipient',
credits_returned: d.credits_returned || 0
});
} catch (e) {
flash('Cancelling failed — try again', false);
btn.disabled = false;
btn.textContent = 'Confirm — end my access';
}
}
// The ended state: access over, account and data kept, membership one
// contribution away. Replaces the usage card content.
function renderGuestEnded(g) {
const st = String(g.guest_status || '');
let line;
if (st === 'cancelled by recipient') {
line = 'You cancelled your guest access.';
if (Number(g.credits_returned) > 0) {
line += ' Unspent credit of ' + fmtMoney(g.credits_returned) + ' was returned to the co-op.';
}
} else if (st === 'expired') {
line = 'Guest access ran out of time.';
} else if (st === 'depleted') {
line = 'The guest credit was spent.';
} else {
line = 'Your guest access has ended.';
}
$('usage-header').style.display = 'none';
$('view-coop').style.display = 'none';
$('cancel-row').style.display = 'none';
$('view-mine').innerHTML =
'<div class="ended">' +
'<h3>Your guest access has ended</h3>' +
'<p class="hint">' + line + '</p>' +
'<p class="hint">Your account and data are kept. Become a member anytime with the same login — your account resumes as a full membership, and a member can re-invite you.</p>' +
'<a class="buy-btn" href="@@BECOME_MEMBER_URL@@" target="_blank" rel="noopener">Become a member</a>' +
'</div>';
const kc = document.getElementById('keys-card');
if (kc) kc.style.display = 'none';
}
// --- Member self-serve guest access ----------------------------------------
// One invitation per member per rolling 30 days (the portal owns the rule);
// under the trial gate a request waits for the co-op's approval before the
// friend's account is created. The trail is the member's own history only.
const GUEST_STATUS_LABELS = {
pending: ['pending approval', 'pending'],
rejected: ['not approved', 'bad'],
active: ['active guest', 'ok'],
converted: ['became a member', 'done'],
expired: ['ended — time ran out', 'done'],
depleted: ['ended — credit spent', 'done'],
'cancelled by recipient': ['ended — they cancelled', 'done'],
};
function guestStatusPill(status, kind) {
const [label, cls] = GUEST_STATUS_LABELS[status] ||
[(status || 'sent').replace(/^./, c => c.toUpperCase()), 'done'];
return '<span class="gpill ' + cls + '">' + escapeHtml(label) + '</span>';
}
function fmtDay(s) {
if (!s) return '';
const d = new Date(String(s).replace(' ', 'T') + (String(s).includes('Z') ? '' : 'Z'));
return isNaN(d) ? '' : d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}
async function loadGuests() {
try {
const r = await fetch('/api/guests');
if (r.status === 401) { location.reload(); return; }
const d = await r.json().catch(() => ({}));
renderGuests(d);
} catch (e) {
$('guest-allowance').textContent = '';
$('guest-trail').innerHTML = '<div class="empty">Could not load your guest invitations — try again later.</div>';
}
}
function renderGuests(d) {
if (d.error) {
$('guest-allowance').textContent = '';
$('guest-trail').innerHTML = '<div class="empty">' + escapeHtml(d.error) + '</div>';
return;
}
// The gate: with auto-approve on the invitation sends directly; under the
// trial it waits for the co-op's approval. The button says which.
const auto = !!d.auto_approve;
$('guest-btn').textContent = auto ? 'Send invite' : 'Send request';
if (auto) {
$('guest-hint').textContent = "Give a friend $5 of AI credits for the co-op's chat and API — no membership needed. They get 60 days to try it. One guest per member every 30 days.";
} else {
$('guest-hint').textContent = "Give a friend $5 of AI credits for the co-op's chat and API — no membership needed. They get 60 days to try it. One guest per member every 30 days. The co-op approves guest requests before the account is created.";
}
if (d.eligible) {
$('guest-allowance').textContent = 'You can send one guest invitation now.';
} else if (d.next_eligible_at) {
$('guest-allowance').textContent =
'One guest every ' + (d.per_inviter_days || 30) + ' days — your next invitation opens ' + fmtDay(d.next_eligible_at) + '.';
} else {
$('guest-allowance').textContent =
'One guest every ' + (d.per_inviter_days || 30) + ' days.';
}
const trail = d.trail || [];
if (!trail.length) {
$('guest-trail').innerHTML = '<div class="empty">No guest invitations yet.</div>';
return;
}
$('guest-trail').innerHTML = trail.map(t => {
const who = t.name ? escapeHtml(t.name) + ' · ' + escapeHtml(t.recipient) : escapeHtml(t.recipient);
const when = t.decided_at ? 'Decided ' + fmtDay(t.decided_at) : 'Sent ' + fmtDay(t.created_at);
return '<div class="guest-row">' +
'<div><div class="guest-who">' + who + '</div>' +
'<div class="guest-meta">' + when + '</div></div>' +
guestStatusPill(t.status, t.kind) +
'</div>';
}).join('');
}
async function sendGuestInvite() {
const email = ($('guest-email').value || '').trim();
const name = ($('guest-name').value || '').trim();
const btn = $('guest-btn');
const label = btn.textContent;
if (!email || email.indexOf('@') < 1) { flash('Enter their email address', false); return; }
btn.disabled = true;
btn.textContent = 'Sending…';
try {
const r = await fetch('/api/guests', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ email, name })
});
const d = await r.json().catch(() => ({}));
if (!r.ok || d.error) {
flash(d.detail || d.note || d.error || 'Could not send the request', false);
return;
}
$('guest-email').value = '';
$('guest-name').value = '';
flash(d.note || 'Request sent — waiting for approval.', true);
await loadGuests();
} catch (e) {
flash('Could not send the request: ' + e.message, false);
} finally {
btn.disabled = false;
btn.textContent = label;
}
}
async function load() {
try {
const r = await fetch('/api/usage');
if (r.status === 401) { location.reload(); return; }
const d = await r.json();
if (d.error) {
// A 403 can be an ENDED GUEST (cancelled, expired or spent out): the
// portal answers /api/guest-status for those, so the dashboard says
// plainly that access ended instead of flashing an error.
if (r.status === 403) {
try {
const gs = await fetch('/api/guest-status');
const g = await gs.json();
if (g && g.guest && g.ended) { renderGuestEnded(g); return; }
} catch (e) { /* fall through to the error flash */ }
}
flash(d.error, false);
return;
}
// Guest accounts (portal flag): no Matrix section — the card is hidden in
// the markup and only shown to members — and a Become-a-member button in
// place of the credit-pack buy path. Everything else stays.
const isGuest = !!d.guest;
$('matrix-card').style.display = isGuest ? 'none' : '';
$('guests-card').style.display = isGuest ? 'none' : '';
$('oc-note').style.display = isGuest ? 'none' : '';
if (isGuest) {
const b = $('buy-btn');
b.href = '@@BECOME_MEMBER_URL@@';
b.textContent = 'Become a member';
$('buy-credits').textContent = 'Your guest credit never expires · members get a monthly allowance';
$('meta').textContent = 'Guest access from a member — $5 of AI usage across chat and the API.';
$('cancel-row').style.display = '';
}
const balance = d.balance ?? 0;
const spend = d.spend ?? 0;
const remaining = d.remaining ?? Math.max(0, balance - spend);
const pct = balance > 0 ? Math.min(100, (spend / balance) * 100) : 0;
// Two buckets: monthly allowance (resets) + purchased credits (never expire).
// Balance view shows credits REMAINING (purchased minus what this cycle's
// overspend already drew); the all-time figure is d.credits (total bought).
const allowance = d.allowance ?? 15;
const creditsTotal = d.credits ?? 0;
const creditsLeft = d.credits_remaining ?? creditsTotal;
const spentThisCycle = Math.min(spend, allowance);
const allowanceLeft = Math.max(0, allowance - spentThisCycle);
$('spend').textContent = fmtMoney(spend);
$('of').textContent = 'of ' + fmtMoney(balance) + ' current balance used';
$('remaining').textContent = fmtMoney(remaining);
$('allowance').textContent = fmtMoney(allowanceLeft);
$('credits').textContent = fmtMoney(creditsLeft);
$('fill').style.width = pct + '%';
$('fill').className = 'fill' + (pct > 80 ? ' warn' : '');
// Reset date (when the monthly allowance renews)
if (d.reset_at) {
const d2 = new Date(d.reset_at);
const opts = { year: 'numeric', month: 'long', day: 'numeric' };
$('meta').textContent = 'Shared across chat and API · Allowance renews ' + d2.toLocaleDateString(undefined, opts) + '.';
}
// Credit status lives next to the buy button, not in the meta line: with a
// pack bought it reads the real all-time figure, otherwise it stays the
// static "credit packs never expire" line already in the markup.
if (creditsTotal > 0) {
$('buy-credits').textContent = 'Credits never expire (' + fmtMoney(creditsTotal) + ' purchased all-time)';
}
const calls = (d.models || []).reduce((s, m) => s + (m.calls || 0), 0);
$('alltime').textContent = fmtMoney(d.all_time_spend ?? 0);
$('calls').textContent = calls.toLocaleString();
renderModels(d.models || []);
renderBoard(d.coop_models || []);
renderKeys(d.keys || [], d.key_spend || []);
if (!isGuest) { loadMxid(); loadGuests(); }
} catch (e) {
flash('Could not load usage: ' + e.message, false);
}
}
let mxidLocal = ''; // @username:inference.coop, resolved by the portal
let mxidCurrent = ''; // what is registered right now (external or local)
function mxidValid(v) { return /^@[^\\s:]+:[^\\s]+\\.[^\\s]+$/.test(v); }
async function loadMxid() {
try {
const r = await fetch('/api/matrix-mxid');
if (r.status === 401) return;
const d = await r.json();
if (d.error) {
$('mxid-registered-value').textContent = 'unavailable';
$('mxid-status').textContent = 'Could not load: ' + d.error;
return;
}
mxidLocal = (d.local_mxid || '').trim();
mxidCurrent = (d.matrix_mxid || '').trim() || mxidLocal;
$('mxid-registered-value').textContent = mxidCurrent || 'pending — will use the inference.coop account once it exists';
const useLocalBtn = $('mxid-use-local');
if (mxidCurrent && mxidLocal && mxidCurrent !== mxidLocal) {
useLocalBtn.textContent = 'Use ' + mxidLocal;
useLocalBtn.style.display = '';
} else {
useLocalBtn.style.display = 'none';
}
} catch (e) {
$('mxid-registered-value').textContent = 'unavailable';
$('mxid-status').textContent = 'Could not load: ' + e.message;
}
}
function showExternalField() {
$('mxid-actions').style.display = 'none';
$('mxid-field-row').style.display = '';
$('mxid-input').value = (mxidCurrent && mxidCurrent !== mxidLocal) ? mxidCurrent : '';
$('mxid-status').textContent = '';
$('mxid-input').focus();
}
function hideExternalField() {
$('mxid-field-row').style.display = 'none';
$('mxid-actions').style.display = '';
$('mxid-status').textContent = '';
}
async function useLocalMxid() {
const btn = $('mxid-use-local');
btn.disabled = true;
try {
const r = await fetch('/api/matrix-mxid', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ matrix_mxid: '' })
});
const d = await r.json();
if (d.error) { $('mxid-status').textContent = d.error; }
else { $('mxid-status').textContent = ''; await loadMxid(); }
} catch (e) { $('mxid-status').textContent = 'Could not switch: ' + e.message; }
btn.disabled = false;
}
async function saveMxid() {
const mxid = $('mxid-input').value.trim();
if (!mxidValid(mxid)) {
$('mxid-status').textContent = 'Enter a Matrix ID like @username:server.org';
return;
}
const btn = $('mxid-btn');
btn.disabled = true;
try {
const r = await fetch('/api/matrix-mxid', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ matrix_mxid: mxid })
});
const d = await r.json();
if (d.error) { $('mxid-status').textContent = d.error; }
else {
hideExternalField();
await loadMxid();
$('mxid-status').textContent = d.invite_sent === false
? 'Saved — that account could not be reached right now; the nightly sync will retry automatically.'
: 'Saved — accept the invite from that account to join the space.';
}
} catch (e) { $('mxid-status').textContent = 'Could not save: ' + e.message; }
btn.disabled = false;
}
function renderModels(models) {
const el = $('models');
if (!models.length) { el.innerHTML = ''; return; }
const rows = [...models].sort((a, b) => (b.calls || 0) - (a.calls || 0));
el.innerHTML = rows.map(m => {
const sub = (m.calls || 0).toLocaleString() + ' requests · ' + (m.tokens || 0).toLocaleString() + ' tokens';
return '<div class="model-row">' +
'<div><div class="model-name">' + escapeHtml(m.model) + '</div>' +
'<div class="model-sub">' + escapeHtml(sub) + '</div></div>' +
'<div class="model-spend">' + fmtMoney(m.spend) + '</div>' +
'</div>';
}).join('');
}
// ---- The co-op over time (chart) ----
// Same series the admin panel charts; the portal owns the data and serves it
// through the broker as aggregate, non-personal numbers. Fetched once at the
// widest range; the toggles re-render client-side without refetching.
let trendsData = null;
let trendMetric = "members"; // members | requests | spend
let trendDays = 90; // 0 = all time
const TREND_CONF = {
members: { kind: "line", title: "The co-op over time" },
requests: { kind: "bar", title: "Requests the co-op served" },
spend: { kind: "bar", title: "What the co-op spent (members + the co-op's own accounts)" },
energy: { kind: "bar", title: "Energy the co-op used" },
co2e: { kind: "bar", title: "Carbon the co-op emitted" }
};
async function loadMetrics() {
if (trendsData) { renderCoopTotals(); renderTrends(); return; }
const host = $("trend-body");
try {
const r = await fetch("/api/metrics");
if (r.status === 401 || r.status === 403) { host.innerHTML = "<div class=empty>Sign in to see this.</div>"; return; }
const d = await r.json();
if (d.error) { host.innerHTML = "<div class=empty>" + d.error + "</div>"; return; }
trendsData = d.series || [];
renderCoopTotals();
renderTrends();
} catch (e) {
host.innerHTML = "<div class=empty>Could not load the co-op chart</div>";
}
}
// The co-op total spans the members AND the co-op's own (operator) accounts —
// spend_usd is the whole co-op. operator_spend_usd is the co-op's own share of
// it (NULL where a day was not measured, so it is skipped rather than counted
// as zero). Both summed over the widest range the series carries (all time).
function renderCoopTotals() {
let total = 0, own = 0;
(trendsData || []).forEach(row => {
if (typeof row.spend_usd === "number") total += row.spend_usd;
if (typeof row.operator_spend_usd === "number") own += row.operator_spend_usd;
});
$("coop-total").textContent = fmtMoney(total);
$("coop-own").textContent = fmtMoney(own);
}
function setTrendMetric(m) {
trendMetric = m;
$("tm-members").className = "mode-btn" + (m === "members" ? " active" : "");
$("tm-requests").className = "mode-btn" + (m === "requests" ? " active" : "");
$("tm-spend").className = "mode-btn" + (m === "spend" ? " active" : "");
$("tm-energy").className = "mode-btn" + (m === "energy" ? " active" : "");
$("tm-co2e").className = "mode-btn" + (m === "co2e" ? " active" : "");
renderTrends();
}
function setTrendDays(d) {
trendDays = d;
$("tr-30").className = "mode-btn" + (d === 30 ? " active" : "");
$("tr-90").className = "mode-btn" + (d === 90 ? " active" : "");
$("tr-all").className = "mode-btn" + (d === 0 ? " active" : "");
renderTrends();
}
function trendVal(row) {
if (trendMetric === "members") return row.members_total;
if (trendMetric === "spend") return row.spend_usd;
if (trendMetric === "energy") return row.energy_wh;
if (trendMetric === "co2e") return row.co2e_g;
return row.requests;
}
// Y-axis step: counts are people and things, so ticks stay whole numbers;
// money uses the 1/2/5 x 10^k rule so ticks read $10.00, not $4.92.
function niceStep(raw) {
if (trendMetric === "spend" || trendMetric === "energy" || trendMetric === "co2e") {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
}
function trendLabel(v) {
if (v === null || v === undefined) return "not measured";
if (trendMetric === "spend") return fmtMoney(v);
if (trendMetric === "energy") return Number(v).toLocaleString() + " Wh";
if (trendMetric === "co2e") return Number(v).toLocaleString() + " g";
return Number(v).toLocaleString();
}
function renderTrends() {
const host = $("trend-body");
if (!host || !trendsData) return;
const conf = TREND_CONF[trendMetric];
const rows = trendDays === 0 ? trendsData : trendsData.slice(-trendDays);
const vals = rows.map(trendVal);
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) {
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
return;
}
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
const top = step * 4;
const W = 1000, H = 250, padL = 62, padR = 14, padT = 14, padB = 30;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = vals.length;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + conf.title + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="var(--border, #e4e0d8)"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + trendLabel(step * g) + '</text>');
}
if (conf.kind === "bar") {
const bw = Math.max(1, plotW / n - 1);
for (let i = 0; i < n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = yAt(v);
parts.push('<rect x="' + (xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, baseY - yy) + '" fill="var(--green-mid)"><title>' + rows[i].day + ": " + trendLabel(v) + "</title></rect>");
}
} else {
// Contiguous measured runs: a day we never recorded stays a gap.
const runs = [];
let run = [];
for (let i = 0; i < n; i++) {
if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
for (let s = 0; s < runs.length; s++) {
const r0 = runs[s];
parts.push('<path d="M' + xAt(r0[0]) + "," + baseY + " L" + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" L") + " L" + xAt(r0[r0.length - 1]) + "," + baseY + ' Z" fill="var(--green-deep)" fill-opacity="0.10"/>');
parts.push('<polyline points="' + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" ") + '" fill="none" stroke="var(--green-deep)" stroke-width="2" stroke-linejoin="round"/>');
}
for (let i = 0; i < n; i++) {
if (vals[i] === null || vals[i] === undefined) continue;
parts.push('<circle cx="' + xAt(i) + '" cy="' + yAt(vals[i]) + '" r="7" fill="transparent"><title>' + rows[i].day + ": " + trendLabel(vals[i]) + "</title></circle>");
}
}
const marks = n > 2 ? [0, Math.floor((n - 1) / 2), n - 1] : [0, n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
parts.push('<text x="' + xAt(i) + '" y="' + (H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(rows[i].day).slice(5) + '</text>');
}
parts.push("</svg>");
host.innerHTML = parts.join("");
}
let usageMode = 'mine'; // 'mine' | 'coop'
function setUsageMode(mode) {
usageMode = mode;
$('mode-mine').className = 'mode-btn' + (mode === 'mine' ? ' active' : '');
$('mode-coop').className = 'mode-btn' + (mode === 'coop' ? ' active' : '');
$('view-mine').style.display = mode === 'mine' ? '' : 'none';
$('view-coop').style.display = mode === 'coop' ? '' : 'none';
// The co-op chart loads the first time someone opens the co-op view.
if (mode === 'coop') loadMetrics();
}
let boardSort = 'cost'; // default: rank by cost (requests made nomic-embed dominate)
let coopModels = [];
function setBoardSort(mode) {
boardSort = mode;
$('sort-cost').className = 'mode-btn' + (mode === 'cost' ? ' active' : '');
$('sort-requests').className = 'mode-btn' + (mode === 'requests' ? ' active' : '');
renderBoard();
}
function renderBoard(models) {
if (models !== undefined) coopModels = models || [];
const el = $('coop-board');
if (!coopModels.length) {
el.innerHTML = '<div class="empty">Not enough usage data yet — check back soon.</div>';
return;
}
// Descending by the selected metric; bar widths relative to the top.
const metric = (m) => (boardSort === 'cost' ? (m.spend || 0) : (m.requests || 0));
const rows = [...coopModels].sort((a, b) => metric(b) - metric(a));
const top = Math.max(...rows.map(metric), 1e-9);
el.innerHTML = rows.map((m, i) => {
const req = m.requests || 0;
const v = metric(m);
const pct = Math.max(2, Math.round((v / top) * 100));
return '<div class="board-row">' +
'<div class="board-rank">' + (i + 1) + '</div>' +
'<div class="board-main">' +
'<div class="board-line">' +
'<div class="board-name">' + escapeHtml(m.model) + '</div>' +
'<div class="board-cost">' + fmtMoney(m.spend || 0) + ' total</div>' +
'</div>' +
'<div class="board-bar"><div class="board-fill" style="width:' + pct + '%"></div></div>' +
'<div class="board-sub">' + req.toLocaleString() + ' requests</div>' +
'</div>' +
'</div>';
}).join('');
}
function renderKeys(keys, keySpend) {
const el = $('keys');
// Spend rows come from the portal, keyed by the member's key name; the chat
// key is carried separately (is_chat) and rendered on its own line.
const spendFor = {};
(keySpend || []).forEach(s => { if (!s.is_chat) spendFor[s.name] = s; });
if (!keys.length) {
el.innerHTML = '<div class="empty">No API keys yet. Create one below.</div>';
renderChatSpend(keySpend);
return;
}
el.innerHTML = keys.map(k => {
const fp = k.fingerprint || '';
const created = k.created_at ? ' · created ' + k.created_at.slice(0,10) : '';
const s = spendFor[k.name];
// Secondary detail: this key's all-time spend (server-side, from the spend
// logs — LiteLLM's own per-key counter is period-only).
const spent = ' · ' + fmtMoney(s ? s.spend : 0) + ' spent';
return '<div class="key-row">' +
'<div><div class="key-name">' + escapeHtml(k.name) + '</div>' +
'<div class="key-meta">' + escapeHtml(created) +
(fp ? ' · ends …' + escapeHtml(fp) : '') + escapeHtml(spent) + '</div>' +
'</div>' +
'<button class="ghost" data-name="' + escapeHtml(k.name) + '" onclick="revokeKey(this.dataset.name)">Revoke</button>' +
'</div>';
}).join('');
renderChatSpend(keySpend);
}
function renderChatSpend(keySpend) {
const el = $('key-chat');
if (!el) return;
const chat = (keySpend || []).find(s => s.is_chat);
if (!chat) { el.innerHTML = ''; return; }
// The built-in chat key is not one of the member's API keys, so its spend is
// shown on its own line rather than mixed into the list above.
el.innerHTML = '<span class="key-chat-name">Chat (built-in)</span> · ' +
'<span class="key-chat-num">' + fmtMoney(chat.spend) + '</span> spent' +
(chat.requests ? ' · ' + chat.requests.toLocaleString() + ' requests' : '');
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
}
async function createKey() {
const name = $('new-name').value.trim();
if (!name) { flash('Enter a name for the key', false); return; }
$('create-btn').disabled = true;
try {
const r = await fetch('/api/keys', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ name })
});
const d = await r.json();
if (d.error) { flash(d.error, false); }
else {
const token = d.sk_token || '';
if (token) {
// Reveal the key ONCE, inline, copyable. It is never shown again.
const box = $('key-reveal');
box.style.display = 'block';
$('key-reveal-value').textContent = token;
$('key-reveal-name').textContent = name;
navigator.clipboard?.writeText(token).catch(() => {});
}
$('new-name').value = '';
load();
}
} catch (e) { flash(e.message, false); }
$('create-btn').disabled = false;
}
async function revokeKey(name) {
if (!confirm('Revoke key "' + name + '"?')) return;
try {
const r = await fetch('/api/keys/' + encodeURIComponent(name), { method: 'DELETE' });
const d = await r.json();
if (d.error) { flash(d.error, false); }
else { flash('Key revoked.', true); load(); }
} catch (e) { flash(e.message, false); }
}
load();
</script>
</body>
</html>"""
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
if exc.status_code == 403:
return JSONResponse({"error": exc.detail}, status_code=403)
# The buy path below came from a member contribution: code/member-dashboard PR #1 by cag,
# who identified that members could not find how to add usage. Implemented with a
# configurable destination (see CREDIT_PACK_URL) rather than the hardcoded URL.
return JSONResponse({"error": exc.detail}, status_code=exc.status_code)