Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

feat(stats): panel-internal dashboard (off public repo)

mrbizarro73769e9dfe2b
diff --git a/docs/STATE.md b/docs/STATE.md
index 8f81dd0..3a18456 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -338,6 +338,31 @@ phosphene-dev.git/
## 7. Known bugs / fixed bugs
+### 2026-05-22 (later) — stats dashboard moves INSIDE the panel (private)
+
+Mr Bizarro: "don't put it in the public repo." Pivoted the architecture
+from GitHub Pages + committed JSONL to entirely panel-internal:
+
+- **Dashboard URL is now `http://127.0.0.1:8199/stats`** (panel-served,
+ 127.0.0.1-only). Bookmark this; the panel must be running to view.
+- **Data lives at `state/stats-data.jsonl`** — gitignored, on the user's
+ Mac only, never on the public repo.
+- **`panel_assets/stats.html`** holds the dashboard template (still public
+ code — only the data is private).
+- **Panel background thread `stats_fetch_loop`** runs `scripts/fetch_repo_stats.py`
+ once at startup (if data file is missing/stale ≥ 6h) and daily thereafter.
+- **GitHub Action deleted** — no public cron, no GitHub Pages, no GitHub
+ push needed at all to keep the dashboard working.
+- **Token resolution** (first hit wins): `PHOSPHENE_REPO_STATS_TOKEN` →
+ `GH_STATS_TOKEN` → `GH_TOKEN` / `GITHUB_TOKEN` → `gh auth token`. Skipped
+ silently if none works (panel logs one warning + carries on).
+- The brief window where the data was on the public repo
+ (`151d0d2`..`827c5d8`) only contained one snapshot of public aggregate
+ counts — nothing private leaked. Door closed before it became a habit.
+
+Setup is now ZERO steps for the user (panel + token both already there);
+just open `/stats`. See `scripts/STATS_DASHBOARD.md` for the full guide.
+
### 2026-05-22 — ship-prep pass: GitHub-data dashboard + analytics ROLLED BACK
Mr Bizarro decision: opt-in telemetry won't be well-received in the OSS
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 216e115..02eb80a 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -141,6 +141,15 @@ COMFY_PATTERN = os.environ.get("LTX_COMFY_PATTERN", "pinokio/api/comfy.git.*main
STATE_DIR = Path(os.environ.get("LTX_STATE_DIR", str(ROOT / "state")))
QUEUE_FILE = STATE_DIR / "panel_queue.json"
HIDDEN_FILE = STATE_DIR / "panel_hidden.json"
+# Repo-stats dashboard (Mr Bizarro 2026-05-22: solo-maintainer signal,
+# stays on the user's Mac, never in the public repo). The HTML
+# template ships at panel_assets/stats.html and is served at /stats;
+# the JSONL data is appended daily by a background thread (see
+# stats_fetch_loop) and served at /stats/data. Both endpoints are
+# 127.0.0.1-only like the rest of the panel.
+STATS_DATA_FILE = STATE_DIR / "stats-data.jsonl"
+STATS_HTML_FILE = ROOT / "panel_assets" / "stats.html"
+STATS_FETCHER = ROOT / "scripts" / "fetch_repo_stats.py"
HELPER_IDLE_TIMEOUT = int(os.environ.get("LTX_HELPER_IDLE_TIMEOUT", "1800"))
HELPER_LOW_MEMORY = os.environ.get("LTX_HELPER_LOW_MEMORY", "true")
FPS = 24
@@ -2281,6 +2290,111 @@ def get_version_state() -> dict:
return dict(_VERSION_STATE)
+# ---------------------------------------------------------------------------
+# Repo-stats background fetcher (Mr Bizarro's solo-maintainer dashboard).
+# Runs the stdlib-only fetcher script as a subprocess once per 24h, appending
+# a JSON line to state/stats-data.jsonl. Dashboard at /stats reads this file.
+# 127.0.0.1-only by design (state/ is gitignored, file lives on the user's
+# Mac only). Skipped silently if no GitHub token is resolvable — no telemetry
+# is the floor, this is opt-in via "have a token configured".
+# ---------------------------------------------------------------------------
+
+_STATS_POLL_INTERVAL_SEC = 24 * 60 * 60 # daily
+_STATS_STARTUP_DELAY_SEC = 90 # let the panel finish booting first
+_STATS_MIN_REFETCH_SEC = 6 * 60 * 60 # don't re-fetch faster than every 6h
+
+
+def _resolve_github_token() -> str:
+ """Token resolution for the stats fetcher, in priority order:
+ 1. PHOSPHENE_REPO_STATS_TOKEN — explicit override for this purpose
+ 2. GH_STATS_TOKEN — fetcher's own preferred name
+ 3. GH_TOKEN / GITHUB_TOKEN — generic env vars
+ 4. `gh auth token` subprocess (when gh CLI is installed + authed)
+ Returns empty string if nothing works — caller logs once and skips."""
+ for name in ("PHOSPHENE_REPO_STATS_TOKEN", "GH_STATS_TOKEN",
+ "GH_TOKEN", "GITHUB_TOKEN"):
+ v = (os.environ.get(name) or "").strip()
+ if v:
+ return v
+ try:
+ out = subprocess.run(
+ ["gh", "auth", "token"], check=True, capture_output=True,
+ timeout=5, text=True,
+ )
+ return (out.stdout or "").strip()
+ except (FileNotFoundError, subprocess.SubprocessError):
+ return ""
+
+
+_STATS_WARNED_NO_TOKEN = False
+
+
+def _run_stats_fetch_once() -> None:
+ """Spawn scripts/fetch_repo_stats.py as a subprocess. Output to the
+ panel's `push()` log so the user can see what happened. Idempotent —
+ the fetcher itself replaces today's row on re-runs in the same UTC day."""
+ global _STATS_WARNED_NO_TOKEN
+ if not STATS_FETCHER.is_file():
+ return # repo install missing the script — fail silent
+ token = _resolve_github_token()
+ if not token:
+ if not _STATS_WARNED_NO_TOKEN:
+ push(
+ "stats: no GitHub token resolvable (tried "
+ "PHOSPHENE_REPO_STATS_TOKEN, GH_STATS_TOKEN, GH_TOKEN, "
+ "GITHUB_TOKEN, `gh auth token`). Dashboard will be empty "
+ "until you set one. See docs/stats-README.md."
+ )
+ _STATS_WARNED_NO_TOKEN = True
+ return
+ env = os.environ.copy()
+ env["GITHUB_TOKEN"] = token
+ try:
+ cp = subprocess.run(
+ [sys.executable, str(STATS_FETCHER)],
+ capture_output=True, text=True, timeout=120, env=env,
+ )
+ if cp.returncode != 0:
+ push(f"stats: fetch failed (exit {cp.returncode}): "
+ f"{(cp.stderr or cp.stdout or '').strip().splitlines()[-1][:200]}")
+ return
+ # Last stdout line is the human-readable summary the fetcher prints
+ # at exit. Forward to the panel log so /status surfaces it.
+ last_line = ""
+ for line in (cp.stdout or "").splitlines():
+ if line.strip():
+ last_line = line.strip()
+ if last_line:
+ push(f"stats: {last_line}")
+ except subprocess.TimeoutExpired:
+ push("stats: fetch timed out after 120s (rate limit? network?)")
+ except Exception as exc: # noqa: BLE001
+ push(f"stats: fetch raised {exc!r}")
+
+
+def stats_fetch_loop() -> None:
+ """Daemon thread entry: fetch repo stats once at startup (if the data
+ file is missing or stale), then daily on _STATS_POLL_INTERVAL_SEC.
+
+ The startup-fetch is gated by _STATS_MIN_REFETCH_SEC so multiple panel
+ restarts in a short window don't hammer the GitHub API for nothing."""
+ time.sleep(_STATS_STARTUP_DELAY_SEC)
+ # First-run / cold-start fetch — but only if it's been a while.
+ try:
+ last_age = (time.time() - STATS_DATA_FILE.stat().st_mtime
+ if STATS_DATA_FILE.exists() else float("inf"))
+ except OSError:
+ last_age = float("inf")
+ if last_age >= _STATS_MIN_REFETCH_SEC:
+ _run_stats_fetch_once()
+ while True:
+ time.sleep(_STATS_POLL_INTERVAL_SEC)
+ try:
+ _run_stats_fetch_once()
+ except Exception as exc: # noqa: BLE001 — belt + braces
+ sys.stderr.write(f"WARN: stats fetch loop raised: {exc}\n")
+
+
def parse_loras_from_form(form: dict) -> list[dict]:
"""Parse the loras=<JSON> form field that the UI submits with each job.
Shape on the wire is a JSON array of {id, path, strength}. We trust
@@ -7644,6 +7758,38 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/":
self._ok(page().encode())
return
+ # Repo-stats dashboard. HTML is a static file in panel_assets/;
+ # JSONL data lives in state/ and gets appended by stats_fetch_loop.
+ # Both 127.0.0.1-only via the early _is_local_request guard above.
+ if parsed.path in ("/stats", "/stats/"):
+ try:
+ html = STATS_HTML_FILE.read_bytes()
+ except FileNotFoundError:
+ self.send_error(404, "stats.html missing — repo install broken")
+ return
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Cache-Control", "no-cache")
+ self.send_header("Content-Length", str(len(html)))
+ self.end_headers()
+ try: self.wfile.write(html)
+ except (BrokenPipeError, ConnectionResetError): pass
+ return
+ if parsed.path == "/stats/data":
+ try:
+ body = STATS_DATA_FILE.read_bytes()
+ except FileNotFoundError:
+ # No snapshot yet — return an empty but valid JSONL so the
+ # dashboard's "no data yet" path renders cleanly.
+ body = b""
+ self.send_response(200)
+ self.send_header("Content-Type", "application/jsonl; charset=utf-8")
+ self.send_header("Cache-Control", "no-cache")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ try: self.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError): pass
+ return
if parsed.path == "/status":
qs = parse_qs(parsed.query)
include_hidden = qs.get("include_hidden", ["0"])[0] == "1"
@@ -28401,6 +28547,11 @@ if __name__ == "__main__":
threading.Thread(target=version_check_loop, daemon=True).start()
else:
_detect_local_install_state()
+ # Repo-stats fetcher — appends to state/stats-data.jsonl daily so
+ # the dashboard at /stats has historic data. Data stays on disk in
+ # state/ (gitignored), never on the public repo. Skipped silently
+ # when no GitHub token is resolvable.
+ threading.Thread(target=stats_fetch_loop, daemon=True).start()
# Pre-flight: bind in a try/except so a busy port surfaces an actionable
# one-liner instead of a 6-frame Python traceback. The bare OSError
# ("[Errno 48] Address already in use") was confusing users who'd closed
diff --git a/panel_assets/stats.html b/panel_assets/stats.html
new file mode 100644
index 0000000..91bf6f9
--- /dev/null
+++ b/panel_assets/stats.html
@@ -0,0 +1,1116 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Phosphene · stats</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="robots" content="noindex,nofollow">
+ <!--
+ Phosphene repo-stats dashboard.
+
+ Served BY THE PANEL at http://127.0.0.1:8199/stats. The HTML
+ template lives at panel_assets/stats.html and is read at request
+ time; the JSONL data is appended daily by the panel's
+ stats_fetch_loop background thread and persisted at
+ state/stats-data.jsonl (gitignored — never on the public repo).
+ Both endpoints are 127.0.0.1-only.
+
+ Pure vanilla — single file, no build, no framework. Chart.js from
+ CDN is the only outside dep.
+
+ Feature-detects optional fields the fetcher may add over time:
+ - clones_window: [{date,count,uniques}] — 15d rolling window
+ - views_window: [{date,count,uniques}] — 15d rolling window
+ - stars_timeline: [{date,count}] — cumulative per-day
+ Anything else unknown is ignored gracefully.
+ -->
+ <style>
+ /* Dark theme (default) */
+ :root, [data-theme="dark"] {
+ --bg: #0d1117;
+ --bg-card: #161b22;
+ --bg-card-2: #1f2630;
+ --bg-chip: #21262d;
+ --bg-chip-active: #1f6feb;
+ --border: #30363d;
+ --border-focus: #58a6ff;
+ --text: #c9d1d9;
+ --text-dim: #8b949e;
+ --text-faint:#6e7681;
+ --accent: #58a6ff;
+ --good: #3fb950;
+ --warn: #d29922;
+ --bad: #f85149;
+ --grid: #21262d;
+ --skel-1: #1f2630;
+ --skel-2: #2a323d;
+ --shadow: rgba(0,0,0,0.3);
+ }
+ [data-theme="light"] {
+ --bg: #ffffff;
+ --bg-card: #f6f8fa;
+ --bg-card-2: #ffffff;
+ --bg-chip: #eaeef2;
+ --bg-chip-active: #0969da;
+ --border: #d0d7de;
+ --border-focus: #0969da;
+ --text: #1f2328;
+ --text-dim: #59636e;
+ --text-faint:#818b98;
+ --accent: #0969da;
+ --good: #1a7f37;
+ --warn: #9a6700;
+ --bad: #cf222e;
+ --grid: #eaeef2;
+ --skel-1: #eaeef2;
+ --skel-2: #d0d7de;
+ --shadow: rgba(140,149,159,0.15);
+ }
+ * { box-sizing: border-box; }
+ html, body {
+ margin: 0; padding: 0;
+ background: var(--bg); color: var(--text);
+ font: 14px/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text",
+ "Segoe UI", system-ui, sans-serif;
+ min-height: 100vh;
+ transition: background 0.15s ease, color 0.15s ease;
+ }
+ a { color: var(--accent); text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ /* Visible focus ring everywhere */
+ :focus { outline: none; }
+ :focus-visible {
+ outline: 2px solid var(--border-focus);
+ outline-offset: 2px;
+ border-radius: 4px;
+ }
+ .wrap { max-width: 1100px; margin: 0 auto; padding: 28px 24px 80px; }
+ header {
+ display: flex; align-items: baseline; justify-content: space-between;
+ flex-wrap: wrap; gap: 12px; margin-bottom: 24px;
+ }
+ h1 {
+ font-size: 22px; font-weight: 600; margin: 0;
+ }
+ h1 .subtitle {
+ color: var(--text-dim); font-weight: 400; font-size: 14px;
+ margin-left: 10px;
+ }
+ .meta-row {
+ display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
+ }
+ .meta {
+ color: var(--text-dim); font-size: 13px;
+ }
+ .meta strong { color: var(--text); font-weight: 500; }
+ .header-actions {
+ display: flex; gap: 8px; align-items: center;
+ }
+ .icon-btn {
+ background: var(--bg-card);
+ border: 1px solid var(--border);
+ color: var(--text-dim);
+ font-size: 12px;
+ padding: 6px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
+ font-family: inherit;
+ line-height: 1;
+ }
+ .icon-btn:hover {
+ background: var(--bg-card-2);
+ color: var(--text);
+ border-color: var(--text-dim);
+ }
+ section {
+ background: var(--bg-card);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 20px;
+ margin-bottom: 18px;
+ }
+ h2 {
+ font-size: 13px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: 0.05em; color: var(--text-dim); margin: 0 0 14px;
+ }
+ .section-head {
+ display: flex; align-items: center; justify-content: space-between;
+ gap: 12px; flex-wrap: wrap; margin-bottom: 14px;
+ }
+ .section-head h2 { margin: 0; }
+ /* Period chips */
+ .chips {
+ display: inline-flex; gap: 4px;
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px; padding: 3px;
+ }
+ .chip {
+ background: transparent; border: 0;
+ color: var(--text-dim);
+ font: inherit; font-size: 12px; font-weight: 500;
+ padding: 4px 10px; border-radius: 4px;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+ }
+ .chip:hover { color: var(--text); }
+ .chip[aria-pressed="true"] {
+ background: var(--bg-chip-active);
+ color: white;
+ }
+ /* Cards row */
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
+ gap: 12px;
+ }
+ .card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 14px 16px;
+ position: relative;
+ overflow: hidden;
+ }
+ .card .label {
+ color: var(--text-dim);
+ font-size: 11px; text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+ .card .value {
+ font-size: 28px; font-weight: 600; line-height: 1.1;
+ margin-top: 6px;
+ font-variant-numeric: tabular-nums;
+ }
+ .card .deltas {
+ display: flex; gap: 8px; flex-wrap: wrap;
+ margin-top: 6px; font-size: 11px;
+ }
+ .card .delta { color: var(--text-faint); }
+ .card .delta.up { color: var(--good); }
+ .card .delta.down { color: var(--bad); }
+ .card .delta .lbl { color: var(--text-faint); margin-right: 2px; }
+ .card .spark {
+ height: 28px; margin-top: 8px;
+ width: 100%;
+ }
+ /* Chart blocks */
+ .chart-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 14px;
+ }
+ @media (max-width: 600px) {
+ .chart-row { grid-template-columns: 1fr; }
+ }
+ .chart-card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 14px 16px;
+ }
+ .chart-card h3 {
+ font-size: 12px; font-weight: 600; text-transform: uppercase;
+ letter-spacing: 0.05em; color: var(--text-dim);
+ margin: 0 0 8px;
+ }
+ .chart-card .chart-wrap {
+ position: relative; height: 180px;
+ }
+ /* Tables */
+ table {
+ width: 100%; border-collapse: collapse; font-size: 13px;
+ }
+ th, td {
+ text-align: left; padding: 7px 8px;
+ border-bottom: 1px solid var(--border);
+ }
+ th {
+ font-weight: 500; color: var(--text-dim);
+ text-transform: uppercase; font-size: 11px; letter-spacing: 0.05em;
+ position: sticky; top: 0;
+ background: var(--bg-card);
+ }
+ td.num { text-align: right; font-variant-numeric: tabular-nums; }
+ .table-wrap {
+ max-height: 360px; overflow-y: auto;
+ border: 1px solid var(--border); border-radius: 6px;
+ }
+ .table-wrap table th, .table-wrap table td { padding: 8px 10px; }
+ .table-wrap table th:first-child, .table-wrap table td:first-child { padding-left: 12px; }
+ .table-wrap table th:last-child, .table-wrap table td:last-child { padding-right: 12px; }
+ .table-wrap table tbody tr:last-child td { border-bottom: 0; }
+ .two-col {
+ display: grid; grid-template-columns: 1fr 1fr; gap: 14px;
+ }
+ @media (max-width: 600px) {
+ .two-col { grid-template-columns: 1fr; }
+ }
+ .empty {
+ color: var(--text-faint); font-style: italic; padding: 20px 0;
+ text-align: center;
+ }
+ code {
+ background: var(--bg-card-2); padding: 1px 5px; border-radius: 3px;
+ font-size: 12px; font-family: ui-monospace, SFMono-Regular, monospace;
+ }
+ footer {
+ color: var(--text-faint); font-size: 12px; text-align: center;
+ margin-top: 30px;
+ }
+ /* Skeletons */
+ @keyframes skel-pulse {
+ 0%, 100% { background-color: var(--skel-1); }
+ 50% { background-color: var(--skel-2); }
+ }
+ .skel {
+ animation: skel-pulse 1.4s ease-in-out infinite;
+ border-radius: 4px;
+ display: inline-block;
+ }
+ .skel-card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 14px 16px;
+ min-height: 92px;
+ }
+ .skel-card .skel.label { width: 60%; height: 10px; margin-bottom: 12px; }
+ .skel-card .skel.value { width: 50%; height: 24px; margin-bottom: 8px; }
+ .skel-card .skel.delta { width: 70%; height: 10px; }
+ .skel-chart { width: 100%; height: 180px; }
+ /* Error card */
+ .error-card {
+ background: var(--bg-card-2);
+ border: 1px solid var(--bad);
+ border-radius: 8px;
+ padding: 20px;
+ color: var(--text);
+ }
+ .error-card .err-title {
+ color: var(--bad);
+ font-weight: 600; font-size: 14px;
+ margin: 0 0 8px;
+ display: flex; align-items: center; gap: 8px;
+ }
+ .error-card .err-msg {
+ color: var(--text-dim); font-size: 13px;
+ font-family: ui-monospace, SFMono-Regular, monospace;
+ margin: 0 0 12px;
+ word-break: break-word;
+ }
+ .error-card .err-actions {
+ display: flex; gap: 8px; flex-wrap: wrap;
+ }
+ .btn {
+ background: var(--accent);
+ color: #fff; border: 0;
+ padding: 7px 14px; border-radius: 6px;
+ cursor: pointer; font: inherit; font-size: 13px; font-weight: 500;
+ }
+ .btn:hover { filter: brightness(1.1); }
+ .btn.ghost {
+ background: var(--bg-card);
+ color: var(--text);
+ border: 1px solid var(--border);
+ }
+ .btn.ghost:hover { background: var(--bg-card-2); }
+ .num-tip { cursor: help; border-bottom: 1px dashed var(--text-faint); }
+ /* Mobile tweaks */
+ @media (max-width: 600px) {
+ .wrap { padding: 20px 14px 60px; }
+ header { gap: 8px; }
+ h1 { font-size: 19px; }
+ h1 .subtitle { display: block; margin: 4px 0 0; }
+ section { padding: 16px 14px; }
+ .card .value { font-size: 24px; }
+ }
+ </style>
+</head>
+<body>
+ <div class="wrap">
+ <header>
+ <h1>Phosphene · stats <span class="subtitle">solo-maintainer dashboard</span></h1>
+ <div class="meta-row">
+ <div class="meta" id="meta" aria-live="polite">
+ <span class="skel" style="width:200px;height:13px"></span>
+ </div>
+ <div class="header-actions">
+ <a class="icon-btn" id="raw-link"
+ href="/stats/data"
+ target="_blank" rel="noopener"
+ title="View the raw JSONL data file (served locally — never on the public repo)">raw JSONL ↗</a>
+ <button class="icon-btn" id="theme-toggle"
+ type="button" aria-label="Toggle light / dark theme"
+ title="Toggle theme">◐</button>
+ </div>
+ </div>
+ </header>
+
+ <!-- Mount point for error state. Hidden unless fetch fails. -->
+ <div id="error-mount" hidden></div>
+
+ <!-- Big number cards: state TODAY (last snapshot) -->
+ <section id="sec-now">
+ <h2>Right now</h2>
+ <div class="cards" id="cards" aria-busy="true" aria-label="Current repository stats">
+ <!-- skeleton placeholders -->
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ <div class="skel-card"><span class="skel label"></span><br><span class="skel value"></span><br><span class="skel delta"></span></div>
+ </div>
+ </section>
+
+ <!-- Time-series charts: cumulative + daily counts -->
+ <section id="sec-over-time">
+ <div class="section-head">
+ <h2>Over time</h2>
+ <div class="chips" role="group" aria-label="Date range">
+ <button class="chip" type="button" data-period="7" aria-pressed="false">7d</button>
+ <button class="chip" type="button" data-period="30" aria-pressed="true">30d</button>
+ <button class="chip" type="button" data-period="90" aria-pressed="false">90d</button>
+ <button class="chip" type="button" data-period="all" aria-pressed="false">all</button>
+ </div>
+ </div>
+ <div class="chart-row">
+ <div class="chart-card">
+ <h3>Stars · cumulative</h3>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-stars"
+ aria-label="Line chart of cumulative star count over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ <div class="chart-card">
+ <h3>Forks · cumulative</h3>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-forks"
+ aria-label="Line chart of cumulative fork count over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ </div>
+ <div class="chart-row" style="margin-top:14px">
+ <div class="chart-card">
+ <h3>Clones per day</h3>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-clones"
+ aria-label="Bar chart of git clones per day over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ <div class="chart-card">
+ <h3>Repo page views per day</h3>
+ <div class="chart-wrap" data-skel="1">
+ <canvas id="chart-views"
+ aria-label="Bar chart of repository page views per day over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ </div>
+ <!-- Stars-gained section, only inserted if stars_timeline is present -->
+ <div id="stars-timeline-row" hidden style="margin-top:14px">
+ <div class="chart-row">
+ <div class="chart-card">
+ <h3>New stars per day</h3>
+ <div class="chart-wrap">
+ <canvas id="chart-stars-gained"
+ aria-label="Bar chart of new stars gained per day over the selected date range"
+ role="img"></canvas>
+ </div>
+ </div>
+ <div class="chart-card">
+ <h3>Cumulative stars from history</h3>
+ <div class="chart-wrap">
+ <canvas id="chart-stars-history"
+ aria-label="Line chart of cumulative star count derived from full stargazer history"
+ role="img"></canvas>
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- 14-day rolling snapshots from latest fetch -->
+ <section id="sec-traffic">
+ <h2>Where traffic comes from (last 14 days)</h2>
+ <div class="two-col">
+ <div>
+ <h3 style="font-size:12px;color:var(--text-dim);margin:0 0 6px">Top referrers</h3>
+ <div class="table-wrap">
+ <table id="referrers-table"><thead><tr>
+ <th>Source</th><th class="num">Views</th><th class="num">Uniques</th>
+ </tr></thead><tbody>
+ <tr><td colspan="3" class="empty">loading…</td></tr>
+ </tbody></table>
+ </div>
+ </div>
+ <div>
+ <h3 style="font-size:12px;color:var(--text-dim);margin:0 0 6px">Top paths</h3>
+ <div class="table-wrap">
+ <table id="paths-table"><thead><tr>
+ <th>Path</th><th class="num">Views</th><th class="num">Uniques</th>
+ </tr></thead><tbody>
+ <tr><td colspan="3" class="empty">loading…</td></tr>
+ </tbody></table>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <footer>
+ Data lives at <code>state/stats-data.jsonl</code> on your Mac —
+ never on the public repo. The panel refreshes it once a day in
+ the background via <code>scripts/fetch_repo_stats.py</code>.
+ <br>
+ The GitHub Traffic API only retains 14 days; this archive is how
+ we keep the history.
+ </footer>
+ </div>
+
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
+ <script>
+ // ====================================================================
+ // Phosphene stats dashboard — vanilla JS, single file, no build step.
+ // Loads docs/stats-data.jsonl, renders cards/charts/tables.
+ //
+ // State is held in module-scope vars, charts are created/destroyed
+ // on period change. Period selection + theme persist in localStorage.
+ // ====================================================================
+
+ const LS_PERIOD = 'phosphene.stats.period';
+ const LS_THEME = 'phosphene.stats.theme';
+ const REPO_URL = 'https://github.com/mrbizarro/phosphene';
+ // Served by the panel at /stats/data — JSONL lives in state/ on the
+ // user's Mac, never in the public repo (Mr Bizarro 2026-05-22).
+ const JSONL_URL = '/stats/data';
+ const RAW_URL = '/stats/data';
+
+ let allRows = []; // every row from JSONL, sorted ascending
+ let currentPeriod = '30'; // '7' | '30' | '90' | 'all'
+ const charts = {}; // id -> Chart instance (so we can destroy & redraw)
+ const sparkCharts = {}; // card-label -> mini Chart
+ const intersectObservers = new Map();
+
+ // ---- theme ---------------------------------------------------------
+ function initTheme() {
+ const saved = localStorage.getItem(LS_THEME);
+ const theme = saved === 'light' ? 'light' : 'dark';
+ document.documentElement.setAttribute('data-theme', theme);
+ const btn = document.getElementById('theme-toggle');
+ btn.textContent = theme === 'light' ? '☀' : '◐';
+ btn.setAttribute('aria-label',
+ theme === 'light' ? 'Switch to dark theme' : 'Switch to light theme');
+ btn.addEventListener('click', toggleTheme);
+ }
+ function toggleTheme() {
+ const cur = document.documentElement.getAttribute('data-theme') || 'dark';
+ const next = cur === 'dark' ? 'light' : 'dark';
+ document.documentElement.setAttribute('data-theme', next);
+ localStorage.setItem(LS_THEME, next);
+ const btn = document.getElementById('theme-toggle');
+ btn.textContent = next === 'light' ? '☀' : '◐';
+ btn.setAttribute('aria-label',
+ next === 'light' ? 'Switch to dark theme' : 'Switch to light theme');
+ // Chart colors come from CSS-var-tinted JS literals; rerender so they pick up.
+ if (allRows.length) {
+ destroyAllCharts();
+ renderCharts(sliceByPeriod(allRows, currentPeriod));
+ renderCards(allRows); // sparklines too
+ }
+ }
+
+ // ---- load + parse the JSONL ----------------------------------------
+ async function loadRows() {
+ const r = await fetch(JSONL_URL, {cache: 'no-store'});
+ if (!r.ok) throw new Error('HTTP ' + r.status + ' on ' + JSONL_URL);
+ const text = await r.text();
+ const rows = text.split(/\n+/).filter(Boolean).map(l => {
+ try { return JSON.parse(l); }
+ catch (e) { console.warn('skipping bad row', e); return null; }
+ }).filter(Boolean);
+ rows.sort((a, b) => (a.date || '') < (b.date || '') ? -1 : 1);
+ return rows;
+ }
+
+ // ---- helpers --------------------------------------------------------
+ function fmt(n) {
+ return (n == null || Number.isNaN(n)) ? '—' : Number(n).toLocaleString();
+ }
+ /** Format big numbers with K/M shortening (>9999). */
+ function fmtShort(n) {
+ if (n == null || Number.isNaN(n)) return '—';
+ const abs = Math.abs(n);
+ if (abs < 10000) return Number(n).toLocaleString();
+ if (abs < 1e6) return (n / 1e3).toFixed(n % 1e3 === 0 ? 0 : 1).replace(/\.0$/, '') + 'K';
+ if (abs < 1e9) return (n / 1e6).toFixed(n % 1e6 === 0 ? 0 : 1).replace(/\.0$/, '') + 'M';
+ return (n / 1e9).toFixed(1).replace(/\.0$/, '') + 'B';
+ }
+ function dayAgo(iso) {
+ const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return '—';
+ const ms = Date.now() - t;
+ if (ms < 60_000) return 'just now';
+ if (ms < 3_600_000) return Math.floor(ms / 60_000) + 'm ago';
+ if (ms < 86_400_000) return Math.floor(ms / 3_600_000) + 'h ago';
+ const d = Math.floor(ms / 86_400_000);
+ if (d === 1) return 'yesterday';
+ if (d < 7) return d + 'd ago';
+ return Math.floor(d / 7) + 'w ago';
+ }
+ function escapeHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, c =>
+ ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c])
+ );
+ }
+ function escapeAttr(s) { return escapeHtml(s); }
+
+ /** Read a CSS variable from :root so charts respect the active theme. */
+ function cssVar(name) {
+ return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ }
+
+ /** Slice rows by period. period ∈ {'7','30','90','all'}. */
+ function sliceByPeriod(rows, period) {
+ if (period === 'all' || !period) return rows;
+ const n = parseInt(period, 10);
+ if (!Number.isFinite(n) || n <= 0) return rows;
+ return rows.slice(-n);
+ }
+
+ /** Two-line delta span (yday + week-over-week). */
+ function deltaSpan(today, yesterday, weekAgo) {
+ const out = [];
+ if (today != null && yesterday != null) {
+ out.push(deltaPart(today - yesterday, 'yday'));
+ }
+ // w/w only when we have a value 7+ snapshots back
+ if (today != null && weekAgo != null && weekAgo !== yesterday) {
+ out.push(deltaPart(today - weekAgo, 'w/w'));
+ }
+ if (!out.length) return '';
+ return `<div class="deltas">${out.join('')}</div>`;
+ }
+ function deltaPart(diff, label) {
+ if (diff === 0) return `<span class="delta"><span class="lbl">${label}</span>±0</span>`;
+ const sign = diff > 0 ? '+' : '';
+ const cls = diff > 0 ? 'up' : 'down';
+ return `<span class="delta ${cls}"><span class="lbl">${label}</span>${sign}${diff.toLocaleString()}</span>`;
+ }
+
+ // ---- cards + sparklines --------------------------------------------
+ /**
+ * Build the card row. We always source values from allRows so the
+ * "Right now" snapshot is the true latest (period slider only affects
+ * the charts), and sparklines reflect the last 14 days of history.
+ */
+ function renderCards(rows) {
+ const mount = document.getElementById('cards');
+ mount.setAttribute('aria-busy', 'false');
+ if (!rows.length) {
+ mount.innerHTML = '<div class="empty">no snapshots yet — panel will fetch one shortly</div>';
+ return;
+ }
+ const last = rows[rows.length - 1];
+ const prev = rows.length > 1 ? rows[rows.length - 2] : {};
+ // For week-over-week: prefer rows[len-8] (7 days back). If we don't
+ // have 8 rows, fall back to prev so yday is the only signal.
+ const wkIdx = rows.length - 8;
+ const week = wkIdx >= 0 ? rows[wkIdx] : null;
+
+ // 14-day spark series. (Use full history if fewer than 14 rows exist.)
+ const sparkRows = rows.slice(-14);
+ const sparkOf = pick => sparkRows.map(pick);
+
+ const cards = [
+ {
+ key:'stars', label:'Stars', value:last.stars,
+ yday:prev.stars, wk:week?.stars,
+ spark:sparkOf(r => r.stars), color:'#58a6ff',
+ },
+ {
+ key:'forks', label:'Forks', value:last.forks,
+ yday:prev.forks, wk:week?.forks,
+ spark:sparkOf(r => r.forks), color:'#8957e5',
+ },
+ {
+ key:'watchers', label:'Watchers', value:last.subscribers,
+ yday:prev.subscribers, wk:week?.subscribers,
+ spark:sparkOf(r => r.subscribers), color:'#39c5cf',
+ },
+ {
+ key:'clones', label:'Clones · today',
+ value:last.clones?.count,
+ yday:prev.clones?.count, wk:week?.clones?.count,
+ spark:sparkOf(r => r.clones?.count ?? 0), color:'#3fb950',
+ },
+ {
+ key:'views', label:'Views · today',
+ value:last.views?.count,
+ yday:prev.views?.count, wk:week?.views?.count,
+ spark:sparkOf(r => r.views?.count ?? 0), color:'#d29922',
+ },
+ {
+ key:'issues', label:'Open issues',
+ value:last.open_issues,
+ yday:prev.open_issues, wk:week?.open_issues,
+ spark:sparkOf(r => r.open_issues), color:'#f85149',
+ },
+ {
+ key:'prs', label:'Open PRs',
+ value:last.open_prs,
+ yday:prev.open_prs, wk:week?.open_prs,
+ spark:sparkOf(r => r.open_prs), color:'#a371f7',
+ },
+ ];
+
+ // Growth card — the headline "is this growing?" number.
+ // Daily growth = (today_clones - yday_clones) / max(yday,1)
+ // Weekly growth = avg(last 7 clones) vs avg(prev 7 clones).
+ const growth = computeGrowth(rows);
+ cards.push({
+ key:'growth', label:'Clone growth',
+ custom: renderGrowthCard(growth),
+ });
+
+ const total_dl = last.releases?.total ?? null;
+ if (total_dl != null && total_dl > 0) {
+ cards.push({
+ key:'dl', label:'Release downloads',
+ value:total_dl, yday:prev.releases?.total, wk:week?.releases?.total,
+ spark:sparkOf(r => r.releases?.total ?? 0), color:'#58a6ff',
+ });
+ }
+
+ mount.innerHTML = cards.map(c => {
+ if (c.custom) {
+ return `<div class="card" data-key="${c.key}" tabindex="0">${c.custom}</div>`;
+ }
+ const isBig = c.value != null && Math.abs(c.value) > 9999;
+ const valHtml = isBig
+ ? `<div class="value"><span class="num-tip" title="${escapeAttr(fmt(c.value))}">${escapeHtml(fmtShort(c.value))}</span></div>`
+ : `<div class="value">${fmt(c.value)}</div>`;
+ const sparkOk = c.spark && c.spark.length >= 2 &&
+ c.spark.some(v => v != null && v !== 0);
+ return `
+ <div class="card" data-key="${c.key}" tabindex="0">
+ <div class="label">${escapeHtml(c.label)}</div>
+ ${valHtml}
+ ${deltaSpan(c.value, c.yday, c.wk)}
+ ${sparkOk ? `<canvas class="spark" id="spark-${c.key}" aria-hidden="true"></canvas>` : ''}
+ </div>`;
+ }).join('');
+
+ // Now draw sparklines (after cards are in DOM).
+ cards.forEach(c => {
+ if (!c.spark) return;
+ const sparkOk = c.spark.length >= 2 &&
+ c.spark.some(v => v != null && v !== 0);
+ if (!sparkOk) return;
+ drawSparkline('spark-' + c.key, c.spark, c.color);
+ });
+ }
+
+ function computeGrowth(rows) {
+ // Daily growth rate from clone counts.
+ const counts = rows.map(r => r.clones?.count ?? 0);
+ const today = counts[counts.length - 1] ?? null;
+ const yday = counts[counts.length - 2] ?? null;
+ let daily = null;
+ if (today != null && yday != null) {
+ if (yday === 0) daily = today > 0 ? Infinity : 0;
+ else daily = ((today - yday) / yday) * 100;
+ }
+ // Weekly: last 7 vs prior 7 (if we have 14+ rows).
+ let weekly = null;
+ if (counts.length >= 14) {
+ const cur = counts.slice(-7).reduce((a,b) => a+b, 0);
+ const prev = counts.slice(-14, -7).reduce((a,b) => a+b, 0);
+ if (prev === 0) weekly = cur > 0 ? Infinity : 0;
+ else weekly = ((cur - prev) / prev) * 100;
+ }
+ return { daily, weekly };
+ }
+
+ function renderGrowthCard(g) {
+ // Build {text, cls} for a percent value (or null / Infinity).
+ const pct = v => {
+ if (v == null) return { text: '—', cls: '' };
+ if (v === Infinity) return { text: 'new', cls: 'up' };
+ if (v === 0) return { text: '0.0%', cls: '' };
+ const sign = v > 0 ? '+' : '';
+ return { text: sign + v.toFixed(1) + '%', cls: v > 0 ? 'up' : 'down' };
+ };
+ const day = pct(g.daily);
+ const week = pct(g.weekly);
+ // Big number prefers weekly (smoother signal), falls back to daily.
+ const big = g.weekly != null ? week : day;
+ const bigColor = big.cls === 'up' ? 'color:var(--good)'
+ : big.cls === 'down' ? 'color:var(--bad)'
+ : '';
+ return `
+ <div class="label" title="Daily and weekly clone growth — the simplest 'is this app catching on?' signal.">Clone growth</div>
+ <div class="value" style="${bigColor}">${escapeHtml(big.text)}</div>
+ <div class="deltas" style="margin-top:8px">
+ <span class="delta ${day.cls}"><span class="lbl">day</span>${escapeHtml(day.text)}</span>
+ <span class="delta ${week.cls}"><span class="lbl">week</span>${escapeHtml(week.text)}</span>
+ </div>`;
+ }
+
+ function drawSparkline(canvasId, data, color) {
+ const el = document.getElementById(canvasId);
+ if (!el) return;
+ if (sparkCharts[canvasId]) { sparkCharts[canvasId].destroy(); }
+ sparkCharts[canvasId] = new Chart(el.getContext('2d'), {
+ type: 'line',
+ data: {
+ labels: data.map((_, i) => i),
+ datasets: [{
+ data,
+ borderColor: color,
+ backgroundColor: color + '22',
+ fill: true, tension: 0.3,
+ pointRadius: 0, pointHoverRadius: 3,
+ borderWidth: 1.5,
+ }]
+ },
+ options: {
+ responsive: true, maintainAspectRatio: false,
+ plugins: { legend: { display: false }, tooltip: { enabled: false } },
+ scales: { x: { display: false }, y: { display: false } },
+ animation: false,
+ }
+ });
+ }
+
+ // ---- main charts ---------------------------------------------------
+ Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, system-ui, sans-serif';
+ Chart.defaults.font.size = 11;
+ Chart.defaults.plugins.legend.display = false;
+
+ function commonOpts() {
+ // Pull colors fresh each render so theme switching works.
+ Chart.defaults.color = cssVar('--text-dim') || '#8b949e';
+ Chart.defaults.borderColor = cssVar('--border') || '#30363d';
+ const grid = cssVar('--grid') || '#21262d';
+ return {
+ responsive: true, maintainAspectRatio: false,
+ scales: {
+ x: { grid: { color: grid }, ticks: { maxRotation: 0, autoSkip: true, maxTicksLimit: 8 } },
+ y: { grid: { color: grid }, beginAtZero: true, ticks: { precision: 0 } },
+ },
+ plugins: { tooltip: { intersect: false, mode: 'index' } },
+ };
+ }
+
+ function lineChart(canvasId, labels, data, color) {
+ const el = document.getElementById(canvasId);
+ if (!el) return;
+ if (charts[canvasId]) { charts[canvasId].destroy(); }
+ charts[canvasId] = new Chart(el.getContext('2d'), {
+ type: 'line',
+ data: {
+ labels,
+ datasets: [{
+ data,
+ borderColor: color,
+ backgroundColor: color + '33',
+ fill: true, tension: 0.25, pointRadius: 2,
+ pointHoverRadius: 4, borderWidth: 2,
+ }]
+ },
+ options: commonOpts(),
+ });
+ }
+
+ function barChart(canvasId, labels, data, color) {
+ const el = document.getElementById(canvasId);
+ if (!el) return;
+ if (charts[canvasId]) { charts[canvasId].destroy(); }
+ charts[canvasId] = new Chart(el.getContext('2d'), {
+ type: 'bar',
+ data: {
+ labels,
+ datasets: [{ data, backgroundColor: color, borderWidth: 0 }]
+ },
+ options: commonOpts(),
+ });
+ }
+
+ function destroyAllCharts() {
+ Object.values(charts).forEach(c => c?.destroy?.());
+ for (const k in charts) delete charts[k];
+ }
+
+ /**
+ * Render the four "Over time" charts for the given slice.
+ *
+ * For clones+views, we prefer the freshest `clones_window` / `views_window`
+ * array on the LATEST row (if present), because the daily snapshot files
+ * record only a single per-day number, while the GH API actually gives us
+ * a 15-day rolling window each fetch. Using the window on day 1 means we
+ * already see 15 days of granularity instead of one point.
+ */
+ function renderCharts(slice) {
+ if (!slice.length) return;
+ const last = slice[slice.length - 1];
+ const labels = slice.map(r => r.date?.slice(5) || '');
+
+ lineChart('chart-stars', labels, slice.map(r => r.stars ?? null), '#58a6ff');
+ lineChart('chart-forks', labels, slice.map(r => r.forks ?? null), '#8957e5');
+
+ // Clones: prefer the rolling window if present + we'd otherwise show 1 dot.
+ const useClonesWindow = Array.isArray(last.clones_window) && last.clones_window.length > 1
+ && slice.length < last.clones_window.length;
+ if (useClonesWindow) {
+ const w = last.clones_window;
+ barChart('chart-clones',
+ w.map(p => (p.date || '').slice(5)),
+ w.map(p => p.count ?? 0),
+ '#3fb950');
+ } else {
+ barChart('chart-clones', labels, slice.map(r => r.clones?.count ?? 0), '#3fb950');
+ }
+
+ const useViewsWindow = Array.isArray(last.views_window) && last.views_window.length > 1
+ && slice.length < last.views_window.length;
+ if (useViewsWindow) {
+ const w = last.views_window;
+ barChart('chart-views',
+ w.map(p => (p.date || '').slice(5)),
+ w.map(p => p.count ?? 0),
+ '#d29922');
+ } else {
+ barChart('chart-views', labels, slice.map(r => r.views?.count ?? 0), '#d29922');
+ }
+
+ renderStarsTimeline(last, slice);
+ }
+
+ /**
+ * stars_timeline (optional): list of {starred_at, login_hash}.
+ * If present on the latest row, draw a per-day stars-gained bar chart
+ * and a cumulative line derived from the FULL history (not just the
+ * fetcher's daily snapshot). Feature-detect; silent skip if absent.
+ */
+ function renderStarsTimeline(last, slice) {
+ const row = document.getElementById('stars-timeline-row');
+ const tl = Array.isArray(last.stars_timeline) ? last.stars_timeline : null;
+ if (!tl || tl.length === 0) { row.hidden = true; return; }
+ row.hidden = false;
+
+ // Group by date (UTC yyyy-mm-dd) → count.
+ const byDay = new Map();
+ for (const ev of tl) {
+ const d = (ev.starred_at || '').slice(0, 10);
+ if (!d) continue;
+ byDay.set(d, (byDay.get(d) || 0) + 1);
+ }
+ const sortedDays = [...byDay.keys()].sort();
+ if (!sortedDays.length) { row.hidden = true; return; }
+
+ // Limit timeline to the current period (matches the chip selection).
+ let days = sortedDays;
+ if (currentPeriod !== 'all') {
+ const n = parseInt(currentPeriod, 10);
+ if (Number.isFinite(n)) days = sortedDays.slice(-n);
+ }
+
+ const labels = days.map(d => d.slice(5));
+ const gained = days.map(d => byDay.get(d) || 0);
+
+ // Cumulative from the START of full history (so the line is meaningful
+ // even when sliced).
+ const cum = [];
+ let total = 0;
+ for (const d of sortedDays) {
+ total += byDay.get(d) || 0;
+ if (days.includes(d)) cum.push(total);
+ }
+
+ barChart ('chart-stars-gained', labels, gained, '#58a6ff');
+ lineChart('chart-stars-history', labels, cum, '#58a6ff');
+ }
+
+ // ---- tables --------------------------------------------------------
+ /** Turn a referrer string (e.g. "reddit.com" or "Google") into a URL
+ * if we can confidently link it. Returns null for opaque search-engine
+ * names like "Google" / "DuckDuckGo" / "Bing" where the real URL is
+ * hidden by GitHub. */
+ function referrerHref(name) {
+ if (!name) return null;
+ const SEARCH_ENGINES = new Set(['google','bing','duckduckgo','yahoo','baidu','yandex']);
+ if (SEARCH_ENGINES.has(name.toLowerCase())) return null;
+ // Heuristic: looks like a domain if it contains a dot and no spaces.
+ if (/\s/.test(name)) return null;
+ if (!/\./.test(name)) return null;
+ // Strip stray protocol if present.
+ const host = name.replace(/^https?:\/\//, '').replace(/\/.*$/, '');
+ if (!host) return null;
+ return 'https://' + host;
+ }
+
+ function renderTables(rows) {
+ const last = rows[rows.length - 1] || {};
+ const refs = last.referrers || [];
+ const paths = last.paths || [];
+ const refBody = document.querySelector('#referrers-table tbody');
+ const pathBody = document.querySelector('#paths-table tbody');
+ if (refs.length === 0) {
+ refBody.innerHTML = '<tr><td colspan="3" class="empty">no referrer data yet</td></tr>';
+ } else {
+ refBody.innerHTML = refs.map(r => {
+ const href = referrerHref(r.referrer);
+ const name = href
+ ? `<a href="${escapeAttr(href)}" target="_blank" rel="noopener noreferrer">${escapeHtml(r.referrer)}</a>`
+ : escapeHtml(r.referrer);
+ return `<tr>
+ <td>${name}</td>
+ <td class="num" title="${escapeAttr(fmt(r.count))}">${escapeHtml(fmtShort(r.count))}</td>
+ <td class="num" title="${escapeAttr(fmt(r.uniques))}">${escapeHtml(fmtShort(r.uniques))}</td>
+ </tr>`;
+ }).join('');
+ }
+ if (paths.length === 0) {
+ pathBody.innerHTML = '<tr><td colspan="3" class="empty">no path data yet</td></tr>';
+ } else {
+ pathBody.innerHTML = paths.map(p => `
+ <tr><td><a href="https://github.com${escapeAttr(p.path)}"
+ target="_blank" rel="noopener">${escapeHtml(p.path)}</a></td>
+ <td class="num" title="${escapeAttr(fmt(p.count))}">${escapeHtml(fmtShort(p.count))}</td>
+ <td class="num" title="${escapeAttr(fmt(p.uniques))}">${escapeHtml(fmtShort(p.uniques))}</td></tr>
+ `).join('');
+ }
+ }
+
+ function renderMeta(rows) {
+ const last = rows[rows.length - 1];
+ const meta = document.getElementById('meta');
+ if (!last) {
+ meta.textContent = 'no data yet — panel will fetch one shortly';
+ return;
+ }
+ const local = new Date(last.fetched_at);
+ const localStr = Number.isFinite(local.getTime()) ? local.toString() : last.fetched_at;
+ meta.innerHTML = `
+ <strong>${rows.length}</strong> ${rows.length === 1 ? 'snapshot' : 'daily snapshots'} ·
+ last refresh <span title="${escapeAttr(last.fetched_at)} (UTC)&#10;${escapeAttr(localStr)} (local)"><strong>${escapeHtml(dayAgo(last.fetched_at))}</strong></span> ·
+ <a href="${REPO_URL}" target="_blank" rel="noopener">repo ↗</a>
+ `;
+ }
+
+ // ---- period chips --------------------------------------------------
+ function initChips() {
+ const saved = localStorage.getItem(LS_PERIOD);
+ if (saved && ['7','30','90','all'].includes(saved)) currentPeriod = saved;
+ document.querySelectorAll('.chip').forEach(b => {
+ b.setAttribute('aria-pressed', String(b.dataset.period === currentPeriod));
+ b.addEventListener('click', () => {
+ currentPeriod = b.dataset.period;
+ localStorage.setItem(LS_PERIOD, currentPeriod);
+ document.querySelectorAll('.chip').forEach(x =>
+ x.setAttribute('aria-pressed', String(x === b)));
+ renderCharts(sliceByPeriod(allRows, currentPeriod));
+ });
+ });
+ }
+
+ // ---- error state ---------------------------------------------------
+ function showError(err) {
+ // Hide the loading/skeleton sections.
+ document.getElementById('sec-now').hidden = true;
+ document.getElementById('sec-over-time').hidden = true;
+ document.getElementById('sec-traffic').hidden = true;
+
+ const meta = document.getElementById('meta');
+ meta.innerHTML = `<span style="color:var(--bad)">could not load stats</span>`;
+
+ const mount = document.getElementById('error-mount');
+ mount.hidden = false;
+ mount.innerHTML = `
+ <div class="error-card" role="alert">
+ <p class="err-title">Could not load /stats/data</p>
+ <p class="err-msg">${escapeHtml(err.message || String(err))}</p>
+ <p style="color:var(--text-dim);font-size:12px;margin:0 0 12px">
+ URL: <a href="${JSONL_URL}" target="_blank" rel="noopener">${JSONL_URL}</a>
+ (relative to this page)
+ </p>
+ <div class="err-actions">
+ <button class="btn" id="retry-btn" type="button">Try again</button>
+ <a class="btn ghost" href="${RAW_URL}" target="_blank" rel="noopener">View on GitHub ↗</a>
+ </div>
+ </div>`;
+ document.getElementById('retry-btn').addEventListener('click', () => {
+ mount.hidden = true;
+ document.getElementById('sec-now').hidden = false;
+ document.getElementById('sec-over-time').hidden = false;
+ document.getElementById('sec-traffic').hidden = false;
+ main();
+ });
+ }
+
+ // ---- lazy chart init via IntersectionObserver ----------------------
+ /**
+ * Defers main-section chart rendering until the section scrolls into
+ * view. The "Right now" cards (+ their sparklines) draw immediately,
+ * since they're above the fold and small.
+ */
+ function lazyMountCharts() {
+ const section = document.getElementById('sec-over-time');
+ if (!section) return;
+ let drawn = false;
+ const draw = () => {
+ if (drawn) return;
+ drawn = true;
+ renderCharts(sliceByPeriod(allRows, currentPeriod));
+ };
+ if (!('IntersectionObserver' in window)) {
+ // Fallback for very old browsers.
+ draw();
+ return;
+ }
+ const io = new IntersectionObserver(entries => {
+ for (const e of entries) {
+ if (e.isIntersecting) {
+ draw();
+ io.disconnect();
+ return;
+ }
+ }
+ }, { rootMargin: '200px' });
+ io.observe(section);
+ // Also redraw on chip change after initial paint.
+ }
+
+ // ---- main flow -----------------------------------------------------
+ async function main() {
+ try {
+ allRows = await loadRows();
+ renderMeta(allRows);
+ if (!allRows.length) {
+ // Render empty cards row with a friendly message.
+ document.getElementById('cards').setAttribute('aria-busy', 'false');
+ document.getElementById('cards').innerHTML =
+ '<div class="empty" style="grid-column:1 / -1">no snapshots yet — panel will fetch one shortly</div>';
+ return;
+ }
+ renderCards(allRows);
+ renderTables(allRows);
+ lazyMountCharts();
+ } catch (e) {
+ console.error(e);
+ showError(e);
+ }
+ }
+
+ // ---- boot ----------------------------------------------------------
+ initTheme();
+ initChips();
+ main();
+ </script>
+</body>
+</html>
diff --git a/scripts/STATS_DASHBOARD.md b/scripts/STATS_DASHBOARD.md
new file mode 100644
index 0000000..b8a9b59
--- /dev/null
+++ b/scripts/STATS_DASHBOARD.md
@@ -0,0 +1,126 @@
+# Phosphene repo stats — maintainer guide
+
+A tiny, stdlib-only pipeline that snapshots GitHub repo metrics into a local
+JSONL on the maintainer's Mac and serves a dashboard through the Phosphene
+panel itself. Nothing public, no GitHub Pages, no telemetry, no cloud.
+
+**Open the dashboard:** the Phosphene panel must be running, then visit
+**<http://127.0.0.1:8199/stats>**.
+
+## The pieces
+
+| Path | Role | In public repo? |
+|---|---|---|
+| `scripts/fetch_repo_stats.py` | Stdlib-only fetcher. Hits GitHub's REST API, writes one JSON row per UTC day. | yes (code only, no data) |
+| `panel_assets/stats.html` | Dashboard. Loads the JSONL at page load, renders cards + Chart.js charts client-side. No build step. | yes (template only, no data) |
+| `state/stats-data.jsonl` | Append-only data store on the maintainer's Mac. | **NO** — gitignored, never leaves your machine |
+| Panel routes `/stats` + `/stats/data` | Serve the dashboard + data file. Both 127.0.0.1-only via the panel's standard local-only guard. | n/a |
+| Panel `stats_fetch_loop` background thread | Runs the fetcher once a day (and once at startup if the data file is stale or missing). | n/a |
+
+## What you actually need to do
+
+**Once:** make sure a GitHub token is resolvable. The panel checks these in
+order, first hit wins:
+
+1. `PHOSPHENE_REPO_STATS_TOKEN` env var (explicit, recommended for Pinokio)
+2. `GH_STATS_TOKEN` env var
+3. `GH_TOKEN` / `GITHUB_TOKEN` env var
+4. `gh auth token` subprocess (when the gh CLI is installed + logged in)
+
+The token needs the `repo` scope (the GitHub Traffic API requires push
+access). `gh auth login` gives you that by default.
+
+**Then:** restart the panel. Within 90 seconds the background thread runs
+the first fetch. Open `/stats` — done.
+
+## Run the fetcher manually (debug / catch-up)
+
+```bash
+GITHUB_TOKEN=$(gh auth token) python3 scripts/fetch_repo_stats.py
+```
+
+Useful flags:
+
+```bash
+python3 scripts/fetch_repo_stats.py --dry-run # don't write JSONL
+python3 scripts/fetch_repo_stats.py --repo OWNER/NAME # different repo
+```
+
+The fetcher is idempotent — re-running on the same UTC day REPLACES today's
+row rather than appending a duplicate.
+
+## What's collected
+
+One JSON object per UTC day. Top-level fields (see the fetcher's docstring
+for the canonical schema):
+
+- `date`, `fetched_at`
+- `stars`, `forks`, `watchers`, `subscribers`, `open_issues`, `open_prs`
+- `clones` (today), `views` (today)
+- `clones_window` / `views_window` — full 15-day Traffic API arrays
+- `stars_timeline` — cumulative `[{date, count}]`. Logins are dropped, not
+ stored — privacy by construction.
+- `referrers` — top 10 with `{referrer, count, uniques}`, 14-day aggregate
+- `paths` — top 10 with `{path, title, count, uniques}`
+- `releases` — `{total, by_release}` (empty for Phosphene, which ships via
+ Pinokio clone, not release binaries)
+
+## What's deliberately NOT collected
+
+GitHub's API cannot give you any of these no matter how hard you mine it:
+
+- Apple Silicon tier of installs (M1 / M2 / M3 / M4 family/variant)
+- Unified RAM per install
+- macOS version
+- Whether `pinokio install` actually completed
+- Which modes get used (Character vs Base, Q4 vs Q8 HQ, Fast vs Exact)
+- Render wall-times in the wild
+- Error frequency / crash signatures
+- Active vs lapsed users
+
+If you ever want any of those you'd have to ship client-side telemetry,
+which we explicitly decided against (the brief 2026-05-21 opt-in experiment
+was rolled back the next day). GitHub-data signal is the floor and the
+ceiling.
+
+## Pinokio notes
+
+Pinokio publishes NO install / activation stats per app. The only signal
+you have that a Pinokio user installed Phosphene is the `clone` count
+spike on the repo — indistinguishable from a `git clone` from a human, a
+`git pull` in CI, or a researcher poking at the source. Don't read too
+much into day-level fluctuations.
+
+## Troubleshooting
+
+| Symptom | Likely cause | Fix |
+|---|---|---|
+| Dashboard at /stats is blank | No data yet (first fetch hasn't run) | Wait 90 s after panel boot or run fetcher manually |
+| Panel log: `stats: no GitHub token resolvable` | No token configured anywhere | `gh auth login`, or set `GITHUB_TOKEN` / `PHOSPHENE_REPO_STATS_TOKEN` |
+| Panel log: `stats: fetch failed (exit 1)` | Token lacks `repo` scope | `gh auth refresh -s repo` |
+| `/stats/data` returns empty body | `state/stats-data.jsonl` doesn't exist yet | Same as "blank" above |
+| Charts blank but cards filled | Only one snapshot so far — charts need ≥2 points | Wait for tomorrow's fetch or change system date for testing |
+| Dashboard ships data into a public commit | Should be impossible after the 2026-05-22 rewrite — `state/` is gitignored | If you see this, file an issue immediately |
+
+## FAQ
+
+**Why no client-side telemetry?** Mr Bizarro's call on 2026-05-22: "not
+going to be well accepted in the open source world." We stand on what
+GitHub already publishes about the repo. Stays private; stays simple.
+
+**Why is the data file local and not in the repo?** Daily clone / view
+counts + referrer breakdowns are private business signal. If you want a
+public dashboard down the road, that's a deliberate later decision — the
+machinery is here.
+
+**How long is the history?** Forever, in `state/stats-data.jsonl`. The
+GitHub Traffic API only retains 14 days; this file is exactly how we
+keep older days from disappearing.
+
+**Can I rebuild old data?** No. The Traffic API's 15-day window is hard;
+anything older than today − 14 days is unrecoverable. So don't delete
+the JSONL.
+
+**Can a teammate see this?** Only if they have access to your Mac and the
+panel is running. The panel binds 127.0.0.1 with no auth — same posture
+as the rest of Phosphene.