forked from code/member-dashboard
1748 lines
77 KiB
Python
1748 lines
77 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
|
|
from pathlib import Path
|
|
import re
|
|
|
|
import httpx
|
|
from fastapi import FastAPI, Request, HTTPException
|
|
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
|
|
|
|
from app import oidc
|
|
|
|
# The oidc module is SHARED (byte-identical copy of the canonical
|
|
# ops-docs: scripts/shared/oidc_client.py — see tests/test_oidc_sync.py);
|
|
# this app's identity (logger name, session cookie, session salt) is set
|
|
# here. The cookie name and salt are the app's historical values, so
|
|
# existing sessions survive the consolidation.
|
|
oidc.configure("member-dashboard", "member_oidc_session", "member-dashboard-oidc-session")
|
|
|
|
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,
|
|
)
|
|
# no-store: the page is one inline script with no validators, so a cached
|
|
# copy runs the PREVIOUS deploy's JS and makes a working app look broken
|
|
# (it did, 2026-11-13).
|
|
return HTMLResponse(render_page(identity), headers={"Cache-Control": "no-store"})
|
|
|
|
|
|
@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.get("/api/money-series")
|
|
async def api_money_series(request: Request):
|
|
"""Revenue / token-spend / OC-balance series, for the Co-op usage view.
|
|
|
|
Aggregate and non-personal, exactly like /api/metrics: cumulative revenue,
|
|
cumulative token spend, and the co-op's Open Collective balance — no member
|
|
identities. The co-op's finances are charted beside its other charts so
|
|
members and stewards see the same picture, from the same shared chart
|
|
definition (CoOpChart.CHART_METRICS "money").
|
|
"""
|
|
identity = get_user_identity(request)
|
|
if not identity:
|
|
return JSONResponse({"error": "unauthenticated"}, status_code=401)
|
|
try:
|
|
return await broker_get(identity, "/broker/money-series")
|
|
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,
|
|
counted from the guests ledger) 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 / manual account) and PROVISIONS
|
|
IMMEDIATELY on a valid request — the friend's account and invitation
|
|
email go out at once (the trial-approval gate was removed 2026-11-08).
|
|
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("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
|
|
|
|
|
|
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))
|
|
)
|
|
|
|
|
|
# The shared chart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
|
# byte-identical copy at app/coop_chart.js — tests/test_chart_sync.py pins it)
|
|
# is spliced into the page's single <script> block at import time, above the
|
|
# page JS, which destructures CoOpChart into bare function names.
|
|
CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()
|
|
|
|
PAGE_HTML = """<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<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; }
|
|
|
|
/* Shared chart module tooltip (same block as the admin panel's, so the
|
|
hover boxes read identically on both UIs). */
|
|
.chart-tip { position: fixed; display: none; z-index: 60; pointer-events: none; background: #fff; border: 1px solid var(--border, #e4e0d8); border-radius: 8px; box-shadow: 0 2px 10px rgba(45,51,39,0.16); padding: 7px 10px; font-size: 12px; max-width: 280px; }
|
|
.chart-tip .tip-day { color: var(--muted); font-size: 11px; margin-bottom: 3px; }
|
|
.chart-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
|
.chart-tip .tip-row span { color: var(--muted); }
|
|
.chart-tip .tip-row b { color: var(--ink); font-variant-numeric: tabular-nums; }
|
|
.mine-chart { margin-top: 18px; }
|
|
.mine-chart .coop-trend-body { margin-top: 10px; }
|
|
/* Usage mode switch */
|
|
|
|
.usage-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
|
|
.usage-header h2 { margin-bottom: 0; }
|
|
.mode-switch { display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
|
|
.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; }
|
|
.coop-legend { display: inline-flex; gap: 12px; flex-wrap: wrap; font-size: 12px; color: var(--muted); font-weight: 600; margin-left: auto; }
|
|
.coop-legend .key { display: inline-flex; align-items: center; gap: 5px; }
|
|
.coop-legend .sw { display: inline-block; width: 10px; height: 10px; border-radius: 3px; flex-shrink: 0; }
|
|
.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; }
|
|
/* Standard guest-invite form (shared with the admin panel): email required,
|
|
name optional. */
|
|
.guest-invite-title { font-size: 14px; font-weight: 700; margin: 0 0 8px; }
|
|
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
|
.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.ok { background: #eaf3ea; color: #2f5c30; }
|
|
.gpill.done { background: #f1e8da; color: #a97a4a; }
|
|
.gpill.bad { background: #f6e9e5; color: var(--danger); }
|
|
.gpill.invited { background: #e7edf5; color: #4a6a8a; }
|
|
|
|
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%; }
|
|
.new-key .name-input { max-width: none; } /* full-width in the stacked form */
|
|
.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 & 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="mine-chart" id="mine-chart" style="display:none;">
|
|
<div class="coop-trend-controls">
|
|
<span class="trend-group">
|
|
<span class="board-note" style="margin:0;">Show</span>
|
|
<button class="mode-btn active" id="mm-spend" onclick="setMineMetric('spend')">Spend</button>
|
|
<button class="mode-btn" id="mm-requests" onclick="setMineMetric('requests')">Requests</button>
|
|
</span>
|
|
<span class="trend-group">
|
|
<span class="board-note" style="margin:0;">Period</span>
|
|
<button class="mode-btn" id="md-30" onclick="setMineDays(30)">30 days</button>
|
|
<button class="mode-btn active" id="md-90" onclick="setMineDays(90)">90 days</button>
|
|
<button class="mode-btn" id="md-all" onclick="setMineDays(0)">All time</button>
|
|
</span>
|
|
</div>
|
|
<div id="mine-chart-body" class="coop-trend-body"></div>
|
|
</div>
|
|
<div class="models" id="models"></div>
|
|
</div>
|
|
|
|
<div id="view-coop" style="display:none;">
|
|
<div class="coop-trend">
|
|
<div class="coop-trend-head">
|
|
<span class="coop-trend-title" id="trend-title">Members</span>
|
|
<span id="trend-legend" class="coop-legend"></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" id="trend-metrics">
|
|
<span class="board-note" style="margin:0;">Show</span>
|
|
<!-- The metric buttons are rendered from CoOpChart.CHART_METRICS, so
|
|
this dashboard and the admin panel offer the same metrics, in the
|
|
same order, with the same titles. Do not hand-write them here. -->
|
|
</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 $2 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 id="guest-invite-wrap">
|
|
<h3 class="guest-invite-title">Invite a guest</h3>
|
|
<form class="new-key" id="guest-invite-form" onsubmit="sendGuestInvite(event)">
|
|
<label class="sr-only" for="guest-email">Their email</label>
|
|
<input id="guest-email" type="email" required placeholder="their@email.org" maxlength="254" autocomplete="off" inputmode="email" />
|
|
<label class="sr-only" for="guest-name">Their name (optional)</label>
|
|
<input id="guest-name" type="text" class="name-input" placeholder="Their name (optional)" maxlength="80" autocomplete="off" />
|
|
<button class="primary" id="guest-btn" type="submit">Send invite</button>
|
|
</form>
|
|
</div>
|
|
<!-- Guest feedback renders HERE, inside the guest card — never in the
|
|
API-key flash above, which is a different feature. -->
|
|
<div class="flash" id="guest-flash"></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>
|
|
/*@@CHART_MODULE@@*/
|
|
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);
|
|
}
|
|
|
|
// Guest-invite feedback stays INSIDE the guest access card. The #flash element
|
|
// lives in the API-keys card — a different feature — and a guest error landing
|
|
// there reads as an API-key problem (this replaces exactly that bug).
|
|
function guestFlash(msg, ok) {
|
|
const f = $('guest-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);
|
|
// an invitation provisions immediately — the friend's account and invitation
|
|
// email go out at once (the trial-approval gate was removed 2026-11-08).
|
|
// The trail is the member's own history only.
|
|
|
|
const GUEST_STATUS_LABELS = {
|
|
rejected: ['not approved', 'bad'],
|
|
invited: ['Invited — awaiting setup', 'invited'],
|
|
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;
|
|
}
|
|
// An invitation provisions immediately (the approval gate is gone) — the
|
|
// button and hint say what happens, with no approval step.
|
|
$('guest-btn').textContent = 'Send invite';
|
|
$('guest-hint').textContent = "Give a friend $2 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.";
|
|
if (d.eligible) {
|
|
// An invite is available: show the form.
|
|
$('guest-invite-wrap').style.display = '';
|
|
$('guest-allowance').textContent = 'You can send one guest invitation now.';
|
|
} else {
|
|
// The 30-day invite is used: the form GOES — there is nothing left to
|
|
// submit — and the next-open date (computed by the portal from the last
|
|
// invite) takes its place. This is UX only; the portal refuses direct
|
|
// over-limit calls server-side regardless of what the page shows.
|
|
$('guest-invite-wrap').style.display = 'none';
|
|
const next = d.next_eligible_at ? fmtDay(d.next_eligible_at) : '';
|
|
$('guest-allowance').textContent = next
|
|
? 'You have already invited a guest this month. Your next invite is available ' + next + '.'
|
|
: 'You have already invited a guest this month.';
|
|
}
|
|
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);
|
|
// `state` carries the portal's derived display state — the SINGLE
|
|
// derivation lives in the portal (tested there) and this page derives
|
|
// nothing: 'invited' while the guest has not accepted their setup invite
|
|
// (never 'active' before that), else the ledger status. Older payloads
|
|
// carry status only; fall back to it.
|
|
return '<div class="guest-row">' +
|
|
'<div><div class="guest-who">' + who + '</div>' +
|
|
'<div class="guest-meta">' + when + '</div></div>' +
|
|
guestStatusPill(t.state || t.status, t.kind) +
|
|
'</div>';
|
|
}).join('');
|
|
}
|
|
|
|
// The standard guest-invite form: the guest's email (required) plus an
|
|
// OPTIONAL display name. The inviter is the logged-in member — automatic, no
|
|
// field; the portal applies the member-side protections SERVER-SIDE (active
|
|
// member, one per 30 days, recipient checks) and a valid invitation
|
|
// provisions immediately — hiding this form is UX, not the gate. An empty
|
|
// name is never derived from the email. Every message from this flow renders
|
|
// in the guest card (guestFlash), never the API-key flash.
|
|
async function sendGuestInvite(ev) {
|
|
if (ev) ev.preventDefault();
|
|
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) { guestFlash('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) {
|
|
guestFlash(d.detail || d.note || d.error || 'Could not send the invitation', false);
|
|
return;
|
|
}
|
|
$('guest-email').value = '';
|
|
$('guest-name').value = '';
|
|
guestFlash(d.note || 'Invitation sent — your friend can set up their account now.', true);
|
|
await loadGuests();
|
|
} catch (e) {
|
|
guestFlash('Could not send the invitation: ' + 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 — $2 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();
|
|
|
|
mineData = d.daily || [];
|
|
renderMineChart();
|
|
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
|
|
|
|
// The chart definitions live in the shared module (CoOpChart.CHART_METRICS),
|
|
// which the admin panel reads too: same metrics, same order, same titles, same
|
|
// shapes. This page owns only which fetch feeds each metric (METRIC_SOURCE) and
|
|
// its own DOM. Hand-writing a metric list here is what let the two UIs drift.
|
|
const METRIC_SOURCE = {
|
|
members: "metrics", requests: "metrics", spend: "metrics",
|
|
energy: "metrics", co2e: "metrics",
|
|
money: "money"
|
|
};
|
|
|
|
function buildMetricButtons() {
|
|
const row = $("trend-metrics");
|
|
if (!row || row.getAttribute("data-built") === "1") return;
|
|
let html = "";
|
|
for (const def of CHART_METRICS) {
|
|
if (!METRIC_SOURCE[def.id]) continue; // a metric this page cannot fetch
|
|
html += '<button class="mode-btn" id="tm-' + def.id + '" data-metric="' + def.id + '">'
|
|
+ escapeHtml(def.title) + "</button>";
|
|
}
|
|
row.insertAdjacentHTML("beforeend", html);
|
|
row.setAttribute("data-built", "1");
|
|
// Delegated, not an inline handler: an inline onclick inside this
|
|
// Python triple-quoted string is exactly where a quote escape can
|
|
// silently break the whole page, and the escape that ships is not the
|
|
// one the raw source text shows.
|
|
if (!row.getAttribute("data-wired")) {
|
|
row.addEventListener("click", function (e) {
|
|
const b = e.target && e.target.closest ? e.target.closest("button[data-metric]") : null;
|
|
if (b) setTrendMetric(b.getAttribute("data-metric"));
|
|
});
|
|
row.setAttribute("data-wired", "1");
|
|
}
|
|
syncMetricButtons();
|
|
}
|
|
|
|
function syncMetricButtons() {
|
|
for (const def of CHART_METRICS) {
|
|
const b = $("tm-" + def.id);
|
|
if (b) b.className = "mode-btn" + (def.id === trendMetric ? " active" : "");
|
|
}
|
|
}
|
|
|
|
// The money metric's rows come from the broker (the co-op's finances are
|
|
// aggregate, non-personal — see the portal's /broker/money-series).
|
|
async function loadMoneySeries() {
|
|
if (moneyData) { renderTrends(); return; }
|
|
const host = $("trend-body");
|
|
try {
|
|
const r = await fetch("/api/money-series");
|
|
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; }
|
|
moneyData = d;
|
|
renderTrends();
|
|
} catch (e) {
|
|
host.innerHTML = "<div class=empty>Could not load the co-op money chart</div>";
|
|
}
|
|
}
|
|
|
|
function metricRows(id) {
|
|
const src = METRIC_SOURCE[id];
|
|
if (!src) return null;
|
|
if (src === "money") return moneyData ? (moneyData.series || []) : null;
|
|
return trendsData;
|
|
}
|
|
|
|
function loadForMetric() {
|
|
const src = METRIC_SOURCE[trendMetric];
|
|
if (src === "money") { if (moneyData) renderTrends(); else loadMoneySeries(); return; }
|
|
if (trendsData) renderTrends(); else loadMetrics();
|
|
}
|
|
|
|
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;
|
|
syncMetricButtons();
|
|
loadForMetric();
|
|
}
|
|
|
|
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();
|
|
}
|
|
|
|
// ---- Shared chart module ----
|
|
// Chart rendering + the exact-value hover tooltips come from the shared
|
|
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
|
// byte-identical copy shipped in this image and spliced in above). The full
|
|
// contract (stamp data-tip-host/i, then registerChartTips with the EXACT
|
|
// values; NULL renders as a gap, never a zero) is documented in the module
|
|
// header.
|
|
const {
|
|
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
|
|
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
|
|
drawLineRuns, hoverTargets,
|
|
CHART_METRICS, metricDef, fmtMetric, renderChart
|
|
} = CoOpChart;
|
|
// (fmtMoney is NOT destructured: this page already defines its own, byte-identical
|
|
// one. Two declarations of the same const is a page-blanking SyntaxError — the
|
|
// exact failure check-page-js.sh exists to catch, and it did.)
|
|
|
|
let moneyData = null; // the money metric's rows (a different endpoint)
|
|
|
|
function renderTrends() {
|
|
const host = $("trend-body");
|
|
if (!host) return;
|
|
hideChartTip();
|
|
const def = metricDef(trendMetric);
|
|
const legendEl = $("trend-legend");
|
|
$("trend-title").textContent = def.title;
|
|
const all = metricRows(trendMetric);
|
|
if (!all) {
|
|
// A metric this page has no source for, versus one it has not fetched yet.
|
|
host.innerHTML = METRIC_SOURCE[trendMetric]
|
|
? "<div class=empty>Loading</div>"
|
|
: "<div class=empty>Not available here.</div>";
|
|
if (legendEl) legendEl.innerHTML = "";
|
|
return;
|
|
}
|
|
const rows = trendDays === 0 ? all : all.slice(-trendDays);
|
|
// The shared renderer: it draws the chart, registers the exact tooltip values
|
|
// and hands back the legend, so this chart is the same chart the panel draws.
|
|
const out = renderChart({ host: "trend-body", def, rows, gridStroke: "var(--border, #e4e0d8)" });
|
|
if (out.empty) {
|
|
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
|
|
if (legendEl) legendEl.innerHTML = "";
|
|
return;
|
|
}
|
|
host.innerHTML = out.svg;
|
|
if (legendEl) {
|
|
legendEl.innerHTML = out.legend.map(it =>
|
|
'<span class="key"><span class="sw" style="background:' + it.color + '"></span>'
|
|
+ escapeHtml(it.name) + "</span>").join("");
|
|
}
|
|
}
|
|
|
|
// ---- My usage over time (chart) ----
|
|
// Per-day spend/requests for the signed-in member, from /api/usage's `daily`
|
|
// series (the portal builds it from the same spend logs the co-op charts read;
|
|
// interior zero days are explicit, so spacing is true). Fetched once at the
|
|
// widest range with the usage payload; the toggles re-render client-side.
|
|
let mineData = null; // [{day, spend, requests}]
|
|
let mineMetric = "spend"; // spend | requests
|
|
let mineDays = 90; // 0 = all time
|
|
|
|
const MINE_CONF = {
|
|
spend: { title: "What you used per day", cont: true, val: r => r.spend },
|
|
requests: { title: "Requests you made per day", cont: false, val: r => r.requests }
|
|
};
|
|
|
|
function mineLabel(v) {
|
|
if (v === null || v === undefined) return "not measured";
|
|
if (mineMetric === "spend") return fmtMoney(v);
|
|
return Number(v).toLocaleString();
|
|
}
|
|
|
|
function setMineMetric(m) {
|
|
mineMetric = m;
|
|
$("mm-spend").className = "mode-btn" + (m === "spend" ? " active" : "");
|
|
$("mm-requests").className = "mode-btn" + (m === "requests" ? " active" : "");
|
|
renderMineChart();
|
|
}
|
|
|
|
function setMineDays(d) {
|
|
mineDays = d;
|
|
$("md-30").className = "mode-btn" + (d === 30 ? " active" : "");
|
|
$("md-90").className = "mode-btn" + (d === 90 ? " active" : "");
|
|
$("md-all").className = "mode-btn" + (d === 0 ? " active" : "");
|
|
renderMineChart();
|
|
}
|
|
|
|
function renderMineChart() {
|
|
const block = $("mine-chart");
|
|
if (!block) return;
|
|
const all = mineData || [];
|
|
// No usage rows at all: no chart yet (the empty state would be noise).
|
|
if (!all.length) { block.style.display = "none"; return; }
|
|
block.style.display = "";
|
|
const rows = mineDays === 0 ? all : all.slice(-mineDays);
|
|
block.style.display = "";
|
|
const host = $("mine-chart-body");
|
|
const conf = MINE_CONF[mineMetric];
|
|
const vals = rows.map(conf.val);
|
|
// Exact-value hover tooltips, same contract as every other chart here.
|
|
registerChartTips("mine-chart-body", rows.map((row, i) => ({
|
|
label: row.day,
|
|
series: [[conf.title, mineLabel(vals[i])]]
|
|
})));
|
|
const have = vals.filter(v => v !== null && v !== undefined);
|
|
if (have.length < 2) {
|
|
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
|
|
return;
|
|
}
|
|
const maxV = Math.max.apply(null, have);
|
|
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, conf.cont);
|
|
const fr = chartFrame({
|
|
n: vals.length,
|
|
top: step * 4,
|
|
step,
|
|
tickLabel: mineLabel,
|
|
aria: conf.title,
|
|
gridStroke: "var(--border, #e4e0d8)"
|
|
});
|
|
drawBars(fr, vals, { color: "var(--green-mid)", host: "mine-chart-body" });
|
|
dateMarks(fr, rows.map(r => r.day));
|
|
fr.parts.push("</svg>");
|
|
host.innerHTML = fr.parts.join("");
|
|
}
|
|
|
|
let usageMode = 'mine'; // 'mine' | 'coop'
|
|
|
|
function setUsageMode(mode) {
|
|
usageMode = mode;
|
|
$('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 => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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); }
|
|
}
|
|
|
|
// The shared metric row (CHART_METRICS) is built here, at boot. It used to
|
|
// be missing entirely: a one-shot replace had put this call inside
|
|
// loadGuests()'s 401 branch, where it never ran.
|
|
buildMetricButtons();
|
|
load();
|
|
</script>
|
|
</body>
|
|
</html>"""
|
|
|
|
# Splice the shared chart module into the page's single <script> block. The
|
|
# placeholder is a JS comment, so the extracted-and-checked block stays valid
|
|
# even before the splice (check-page-js.sh performs the same splice when it
|
|
# runs the harnesses).
|
|
PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
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)
|