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(analytics): opt-in anonymous telemetry — OFF by default

mrbizarrod94c72f4fbaf
diff --git a/README.md b/README.md
index 4e27104..5b16097 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@
## Overview
-Phosphene is a local generative-media panel for Apple Silicon. It runs [LTX-Video 2.3](https://github.com/Lightricks/LTX-Video) (MLX port) for joint audio-and-video synthesis, [Qwen-Image-Edit-2511](https://huggingface.co/Qwen/Qwen-Image-Edit-2511) and an MLX port of [HiDream-O1-Image-Dev](https://huggingface.co/HiDream-ai/HiDream-O1-Image-Dev) for stills, and ships an in-panel LoRA training pipeline for character identity (face + optional voice from a single dataset). Everything runs on-device. No cloud, no API keys, no telemetry.
+Phosphene is a local generative-media panel for Apple Silicon. It runs [LTX-Video 2.3](https://github.com/Lightricks/LTX-Video) (MLX port) for joint audio-and-video synthesis, [Qwen-Image-Edit-2511](https://huggingface.co/Qwen/Qwen-Image-Edit-2511) and an MLX port of [HiDream-O1-Image-Dev](https://huggingface.co/HiDream-ai/HiDream-O1-Image-Dev) for stills, and ships an in-panel LoRA training pipeline for character identity (face + optional voice from a single dataset). Everything runs on-device. No cloud, no API keys. Anonymous usage analytics are opt-in and OFF by default — see [TELEMETRY.md](TELEMETRY.md).
3.0 introduces in-panel character training (face + voice LoRA from one dataset), the Audio-to-Video workflow, the Image Studio tab with two MLX-native engines, hardware capability tiering, and an agentic prompt enhancer / shot planner driven by the same local Gemma 3 12B used for auto-captioning.
@@ -248,4 +248,6 @@ Phosphene is free and open source.
## Network note
-Phosphene runs locally. No telemetry. A clean production install checks GitHub every 30 minutes for an update badge, and only touches Hugging Face or CivitAI when you download models or LoRAs. Disable the update check with `PHOSPHENE_DISABLE_VERSION_CHECK=1`. The panel binds to `127.0.0.1` with no auth. It's not designed for LAN exposure or tunneling.
+Phosphene runs locally. A clean production install checks GitHub every 30 minutes for an update badge, and only touches Hugging Face or CivitAI when you download models or LoRAs. Disable the update check with `PHOSPHENE_DISABLE_VERSION_CHECK=1`. The panel binds to `127.0.0.1` with no auth. It's not designed for LAN exposure or tunneling.
+
+**Telemetry.** OFF by default. If you opt in under **Settings → Anonymous analytics**, the panel sends a small JSON event per render — type, duration, hardware tier, error category. Never prompts, image bytes, filenames, paths, or hostname. Full schema and rationale: [TELEMETRY.md](TELEMETRY.md). Point at a self-hosted endpoint with `PHOSPHENE_ANALYTICS_ENDPOINT`.
diff --git a/TELEMETRY.md b/TELEMETRY.md
new file mode 100644
index 0000000..efd38be
--- /dev/null
+++ b/TELEMETRY.md
@@ -0,0 +1,182 @@
+# Phosphene anonymous telemetry
+
+## TL;DR
+
+- **OFF by default.** Enable it in **Settings → Anonymous analytics**.
+- Sends a small JSON event per render boundary. No prompts. No image
+ bytes. No filenames. No paths. No hostname. No IP-in-payload.
+- A single anonymous install id (32-char hex) is generated the first
+ time you opt in. Click **forget me** to rotate it.
+- All HTTP is non-blocking and best-effort. A flaky endpoint will never
+ stall a render.
+- Endpoint configurable via `PHOSPHENE_ANALYTICS_ENDPOINT` env var.
+ Default: `https://analytics.phosphene.ai/v1/event` (run by Mr Bizarro).
+
+## Why
+
+Phosphene is a young open-source project. GitHub release-download stats
+only show a 14-day window, and Pinokio installs aren't counted at all.
+Without **opt-in** telemetry we have no way to tell:
+
+- which Apple Silicon tiers people actually run on (M2, M3, M4 Max,
+ Ultra…) so we can prioritize the right perf wins;
+- which modes (T2V, I2V, A2V, FFLF, Extend, Character) get used most
+ vs. which are gathering dust;
+- what's breaking in the field — OOMs, missing models, helper crashes,
+ bad LoRA combos — so we can ship fixes rather than wait for an issue
+ to land;
+- whether a release regressed render time on real hardware.
+
+If you'd rather not share any of this, leave the toggle OFF — Phosphene
+works identically. We mean it.
+
+## What we collect
+
+Every event carries:
+
+| Field | Example | Notes |
+|---------------|----------------------|------------------------------------------|
+| `event` | `render_done` | The event type — see list below. |
+| `ts` | `2026-05-21T19:42:11Z` | ISO 8601 UTC, second precision. |
+| `install_id` | `a1b2c3…` | Anonymous 32-char hex. Generated locally on first opt-in; you can rotate it. |
+
+Plus, **per event type**:
+
+### `panel_boot` — fires once at panel startup
+
+| Field | Example | Why |
+|-----------------|------------------------|--------------------------------------|
+| `version` | `0.10.3` | Phosphene release tag if known. |
+| `sha` | `ec1437f` | Short commit if you're on dev. |
+| `branch` | `dev` | `main` or `dev`. |
+| `tier` | `M4 Max 64 GB` | Hardware tier label. |
+| `allows_q8` | `true` | Whether the machine can run Q8 HQ. |
+| `os` | `macOS 26.4` | OS family + major.minor only. |
+| `machine` | `arm64` | CPU architecture. |
+| `python` | `3.11` | Major.minor. |
+| `ram_gb_bucket` | `64` | Snapped to nearest bucket (16/32/48/64/96/128/192/256). Raw GB would near-uniquely identify users. |
+| `cpu_brand` | `Apple M4 Max` | Truncated to 64 chars. |
+
+### `render_start` / `render_done` / `render_failed` / `render_cancelled`
+
+| Field | Example | Notes |
+|------------------|---------------|---------------------------------------------|
+| `mode` | `i2v` | One of: t2v, i2v, a2v, character, fflf, extend, image, audio. |
+| `quality` | `q8_hq` | Pipeline tier picked. |
+| `width` | `1280` | Output width in pixels. |
+| `height` | `704` | Output height. |
+| `frames` | `97` | Frame count requested. |
+| `has_character` | `true` | Whether a Phosphene character LoRA is loaded — not which one. |
+| `lora_count` | `2` | Number of user LoRAs (count only, no names).|
+| `hdr` | `false` | HDR IC-LoRA pipeline? |
+| `enhance` | `true` | Gemma prompt-enhance step run? |
+| `upscale` | `false` | Post-upscale step run? |
+| `accel` | `exact` | Fast / Exact pill. |
+| `engine` | `mlx` | Pipeline engine (mlx / comfy). |
+| `elapsed_sec` | `306.5` | End-to-end seconds. Only on `_done`/`_failed`/`_cancelled`. |
+| `error_category` | `oom` | Only on `_failed`. Coarse bucket — see list below. |
+
+Error categories: `oom`, `hf_auth`, `hf_gated`, `wrong_backend`,
+`missing_model`, `q8_missing`, `missing_deps`, `character_error`,
+`file_missing`, `helper_pipe`, `runtime`.
+
+### `helper_crash` — fires when the helper subprocess exits unexpectedly
+
+| Field | Example | Notes |
+|-----------------|--------------|----------------------------------------|
+| `exit_code` | `-9` | OS exit code. |
+| `last_action` | `generate` | What the helper was doing. |
+| `mode` | `i2v` | Same shape as above. |
+
+### `settings_opt_in` / `settings_opt_out`
+
+| Field | Example | Notes |
+|-----------|---------|---------------------------------------------|
+| `version` | `0.10.3`| Phosphene release tag at the moment of the flip. |
+
+`settings_opt_out` is the **last event** sent before silence. After
+that we send nothing until you opt in again.
+
+## What we **never** collect
+
+The wire sanitizer drops any field with these keys, even if a caller
+accidentally tries to attach one:
+
+```
+prompt, negative_prompt, image, image_path, audio_path,
+output, output_path, path, filename,
+hostname, username, user
+```
+
+Beyond that:
+
+- **No URL parameters** — events are POSTed as JSON bodies.
+- **No IP in payload** — your IP is visible to the receiving server at
+ the TCP layer (same as any HTTP request) but it's not stored or
+ attached to the install_id.
+- **No reference image bytes / no rendered frames / no audio.**
+- **No GitHub username, no machine name, no email, no API tokens.**
+- **No LoRA filenames** — we only count how many you used.
+
+## Defense in depth
+
+Even if a future code change tried to ship more data than the schema
+above, `analytics.py` enforces hard limits:
+
+- **4 KB max payload.** Anything over gets dropped, not truncated.
+- **200-char max per string value.** Runaway error strings get cut.
+- **512-event in-memory queue.** When the endpoint is unreachable,
+ oldest events drop first — never unbounded growth.
+- **4 s socket timeout.** A flaky endpoint can't stall a render.
+- **Daemon thread.** The flusher dies with the process; it never holds
+ shutdown open.
+
+The full implementation lives in `analytics.py` — 350 lines, readable
+top-to-bottom in under 10 minutes. Audit before you opt in.
+
+## Controlling it
+
+### Opt in / opt out
+
+**Settings → Anonymous analytics → Enable / Disable.**
+
+Takes effect immediately. No restart, no helper kick.
+
+### Rotate your anonymous id ("forget me")
+
+**Settings → Anonymous analytics → forget me** (button next to the id).
+
+Generates a fresh 32-char hex. Past events from your old id stay in
+the receiver's logs but can no longer be correlated to your new
+events.
+
+### Self-host the endpoint
+
+Set `PHOSPHENE_ANALYTICS_ENDPOINT` in the panel's environment:
+
+```bash
+export PHOSPHENE_ANALYTICS_ENDPOINT="https://my-receiver.example.com/event"
+```
+
+If both the env var and the saved endpoint are unset, telemetry is a
+no-op even when the toggle is ON (fail-safe for forks).
+
+### Disable entirely at build time
+
+Leave the toggle OFF. Done. The code path is a no-op — `emit()` short-
+circuits inside `Analytics.emit` when `is_enabled()` returns False.
+
+## Receiver
+
+The default endpoint at `analytics.phosphene.ai` accepts POST JSON,
+returns `204 No Content`, retains events for 90 days, and drops any
+field outside the schema above on ingest. Source for the receiver is
+not yet public — happy to publish it once the schema stabilizes. File
+an issue if you'd like to see it sooner.
+
+## Questions?
+
+Open an issue at <https://github.com/mrbizarro/phosphene/issues> with
+the `telemetry` label. The privacy posture is intentionally
+conservative — if any of it makes you uncomfortable, please tell us so
+we can fix it.
diff --git a/analytics.py b/analytics.py
new file mode 100644
index 0000000..d59e408
--- /dev/null
+++ b/analytics.py
@@ -0,0 +1,359 @@
+"""Phosphene anonymous telemetry.
+
+Strictly opt-in. Default OFF. When the user enables it via Settings,
+the panel sends a tiny event payload to a configurable endpoint
+(``PHOSPHENE_ANALYTICS_ENDPOINT`` env var, falls back to the public
+ingest URL Mr Bizarro hosts).
+
+Privacy guarantees:
+- Never sends prompts, image bytes, output filenames, audio waveforms,
+ LoRA filenames (only counts), absolute paths, hostnames, IP, or any
+ user-content.
+- Anonymous install UUID generated once on first opt-in. Rotating
+ ``analytics_install_id`` in settings resets identity (forget-me).
+- All HTTP calls are non-blocking (daemon thread, 4 s socket timeout) so
+ a slow endpoint never stalls a render.
+- Endpoint failures are logged to the panel log but never raised — the
+ user's render is the priority, telemetry is best-effort.
+
+Full event schema:
+ See TELEMETRY.md alongside this file.
+
+Events emitted today:
+ panel_boot — every panel startup (version, branch, tier, RAM)
+ render_start — every job enters the worker
+ render_done — every successful job (with elapsed_sec, mode, quality)
+ render_failed — every error / cancellation (with categorized error)
+ helper_crash — every unexpected helper subprocess exit
+ settings_opt_in — when the user flips analytics_enabled on
+ settings_opt_out — when the user flips analytics_enabled off (last
+ event before silence)
+"""
+from __future__ import annotations
+
+import json
+import os
+import platform
+import queue
+import sys
+import threading
+import time
+import urllib.error
+import urllib.request
+import uuid
+from typing import Any
+
+
+# Default public ingest. Mr Bizarro can swap this via env. If neither
+# env nor saved settings provide an endpoint, telemetry is a no-op
+# even when analytics_enabled=True — fail-safe for forks.
+DEFAULT_ENDPOINT = os.environ.get(
+ "PHOSPHENE_ANALYTICS_ENDPOINT",
+ "https://analytics.phosphene.ai/v1/event",
+).strip()
+
+# Hard limit on payload size — defense-in-depth. Any single event over
+# this gets dropped without sending (prevents accidental large blobs).
+_MAX_PAYLOAD_BYTES = 4 * 1024
+
+# Hard limit on the in-memory event queue. Older events get dropped if
+# the endpoint is unreachable and events pile up. Prevents unbounded
+# memory growth across a long session.
+_QUEUE_MAX = 512
+
+# Socket timeout per request. Keep tight so a flaky endpoint never
+# stalls the render path.
+_SOCKET_TIMEOUT_SEC = 4
+
+# How long to wait between background-flush ticks. Most events are
+# already triggered by user actions (render boundaries), so the
+# background loop is really just retry / drain.
+_FLUSH_INTERVAL_SEC = 5
+
+
+# Module-level singleton — the ``Analytics`` class is a thread that
+# owns the event queue + background flusher. We construct it once at
+# panel startup and write through the module-level helpers below.
+_INSTANCE: "Analytics | None" = None
+_INSTANCE_LOCK = threading.Lock()
+
+
+def _now_iso() -> str:
+ """ISO 8601 UTC timestamp, second precision (sub-second isn't useful
+ for cross-machine event correlation and adds noise)."""
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+
+
+class Analytics:
+ """Background-thread event sender.
+
+ Construct once at panel startup. The constructor does NOT start the
+ thread — call ``start()`` after the settings layer is wired up so
+ we can read the opt-in flag.
+ """
+
+ def __init__(
+ self,
+ *,
+ is_enabled: callable,
+ get_install_id: callable,
+ get_endpoint: callable,
+ log: callable | None = None,
+ ) -> None:
+ self._is_enabled = is_enabled
+ self._get_install_id = get_install_id
+ self._get_endpoint = get_endpoint
+ # ``log`` should be the panel's ``push()`` (or any function that
+ # accepts a single string). When None, errors go to stderr only.
+ self._log = log or (lambda s: sys.stderr.write(s + "\n"))
+ self._queue: "queue.Queue[dict[str, Any]]" = queue.Queue(maxsize=_QUEUE_MAX)
+ self._stop_event = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ # ------------------------------------------------------------------
+ # Thread lifecycle
+ # ------------------------------------------------------------------
+
+ def start(self) -> None:
+ """Start the background flush thread. Idempotent."""
+ if self._thread and self._thread.is_alive():
+ return
+ self._stop_event.clear()
+ self._thread = threading.Thread(
+ target=self._run, name="phosphene-analytics", daemon=True
+ )
+ self._thread.start()
+
+ def stop(self) -> None:
+ """Signal the background thread to exit and join briefly. Called
+ at process shutdown (best-effort — daemon thread will die with
+ the process anyway)."""
+ self._stop_event.set()
+ if self._thread:
+ self._thread.join(timeout=2.0)
+
+ # ------------------------------------------------------------------
+ # Event entry points
+ # ------------------------------------------------------------------
+
+ def emit(self, event_type: str, fields: dict[str, Any] | None = None) -> None:
+ """Queue an event. No-op if analytics is disabled. Safe to call
+ from any thread; never raises."""
+ try:
+ if not self._is_enabled():
+ return
+ payload = self._build_event(event_type, fields or {})
+ if payload is None:
+ return # event was dropped by validation
+ try:
+ self._queue.put_nowait(payload)
+ except queue.Full:
+ # Drop the OLDEST item, queue the new one. Recent events
+ # are more useful than ancient ones when we're behind.
+ try:
+ self._queue.get_nowait()
+ except queue.Empty:
+ pass
+ try:
+ self._queue.put_nowait(payload)
+ except queue.Full:
+ pass
+ except Exception as exc: # noqa: BLE001 — never crash the caller
+ try:
+ self._log(f"analytics: emit failed silently: {exc}")
+ except Exception:
+ pass
+
+ # ------------------------------------------------------------------
+ # Internal
+ # ------------------------------------------------------------------
+
+ def _build_event(self, event_type: str, fields: dict[str, Any]) -> dict[str, Any] | None:
+ """Compose the final event dict + run privacy validation.
+
+ Returns ``None`` if the event should be silently dropped (e.g.
+ oversize payload or a forbidden field name leaked in).
+ """
+ # Strip any fields whose key looks like it could carry user
+ # content. Defense in depth — even if a caller violates the
+ # rule, the sanitizer keeps the wire clean.
+ BANNED = {"prompt", "image", "image_path", "audio_path",
+ "output_path", "output", "path", "hostname",
+ "username", "user", "negative_prompt", "filename"}
+ clean: dict[str, Any] = {}
+ for k, v in fields.items():
+ if k in BANNED:
+ continue
+ # Truncate stringy values to 200 chars. Some fields are
+ # legitimately stringy (e.g., error category) but a runaway
+ # value should never make it to wire.
+ if isinstance(v, str) and len(v) > 200:
+ v = v[:200] + "…"
+ clean[k] = v
+ event = {
+ "event": str(event_type)[:64],
+ "ts": _now_iso(),
+ "install_id": self._get_install_id(),
+ **clean,
+ }
+ # Size check
+ try:
+ payload_bytes = json.dumps(event).encode("utf-8")
+ except (TypeError, ValueError) as exc:
+ self._log(f"analytics: event {event_type!r} not JSON-serializable: {exc}")
+ return None
+ if len(payload_bytes) > _MAX_PAYLOAD_BYTES:
+ self._log(
+ f"analytics: dropping oversize {event_type} event "
+ f"({len(payload_bytes)} > {_MAX_PAYLOAD_BYTES} bytes)"
+ )
+ return None
+ return event
+
+ def _run(self) -> None:
+ """Background loop. Drains the queue, POSTs each event with a
+ short timeout. Failures are logged once per minute (silent
+ otherwise) to avoid log spam from a flaky endpoint."""
+ last_warn_ts = 0.0
+ while not self._stop_event.is_set():
+ try:
+ event = self._queue.get(timeout=_FLUSH_INTERVAL_SEC)
+ except queue.Empty:
+ continue
+ try:
+ self._post(event)
+ except Exception as exc: # noqa: BLE001
+ now = time.time()
+ if now - last_warn_ts > 60:
+ last_warn_ts = now
+ try:
+ self._log(f"analytics: post failed ({exc}); will retry")
+ except Exception:
+ pass
+ # Put it back? Decision: NO — accept the drop. Otherwise
+ # a permanently-down endpoint makes us cycle forever.
+ # The settings_opt_out event is the one drop we'd hate
+ # to lose; we accept that loss for simplicity.
+
+ def _post(self, event: dict[str, Any]) -> None:
+ endpoint = self._get_endpoint()
+ if not endpoint:
+ return # no endpoint configured; silent no-op
+ body = json.dumps(event).encode("utf-8")
+ req = urllib.request.Request(
+ endpoint,
+ data=body,
+ method="POST",
+ headers={
+ "Content-Type": "application/json",
+ "User-Agent": "phosphene-panel-analytics",
+ },
+ )
+ with urllib.request.urlopen(req, timeout=_SOCKET_TIMEOUT_SEC) as resp:
+ # We don't care about the response body; just consume so
+ # the connection can close cleanly.
+ try:
+ resp.read(64)
+ except Exception: # noqa: BLE001
+ pass
+
+
+# ---------------------------------------------------------------------
+# Module-level helpers — the panel calls these directly
+# ---------------------------------------------------------------------
+
+def install(
+ *,
+ is_enabled: callable,
+ get_install_id: callable,
+ get_endpoint: callable,
+ log: callable | None = None,
+) -> None:
+ """Wire up the singleton. Call once at panel boot before any emit().
+ Idempotent — subsequent calls are no-ops."""
+ global _INSTANCE
+ with _INSTANCE_LOCK:
+ if _INSTANCE is not None:
+ return
+ _INSTANCE = Analytics(
+ is_enabled=is_enabled,
+ get_install_id=get_install_id,
+ get_endpoint=get_endpoint,
+ log=log,
+ )
+ _INSTANCE.start()
+
+
+def emit(event_type: str, fields: dict[str, Any] | None = None) -> None:
+ """Queue an event. No-op if analytics is disabled or not installed."""
+ inst = _INSTANCE
+ if inst is not None:
+ inst.emit(event_type, fields)
+
+
+def shutdown() -> None:
+ """Stop the background thread. Best-effort; daemon thread dies
+ with the process anyway."""
+ inst = _INSTANCE
+ if inst is not None:
+ inst.stop()
+
+
+def new_install_id() -> str:
+ """Generate a fresh anonymous install UUID. Called by the settings
+ layer the first time analytics_enabled flips ON (or when the user
+ rotates the id via the 'forget me' button)."""
+ return uuid.uuid4().hex
+
+
+def system_fingerprint() -> dict[str, Any]:
+ """Anonymized hardware / software fingerprint. Sent with panel_boot
+ so we can correlate bugs to hardware tier + OS version without
+ learning anything user-identifying.
+
+ What's collected:
+ os — "macOS 26.4" etc., no patch level
+ machine — "arm64"
+ python — "3.11"
+ ram_gb_bucket — bucketed: 16/32/48/64/96/128/192/256+
+ (raw value would near-uniquely identify
+ a user across the install pool)
+ cpu_brand — "Apple M4 Max" etc. when available
+ """
+ info: dict[str, Any] = {}
+ try:
+ sys_name = platform.system()
+ if sys_name == "Darwin":
+ # "26.4.1" → "26.4" — patch level doesn't add bug-correlation
+ # value and slightly increases per-user uniqueness.
+ mac = (platform.mac_ver()[0] or "").split(".")
+ major_minor = ".".join(mac[:2]) if mac and mac[0] else ""
+ info["os"] = f"macOS {major_minor}".strip()
+ else:
+ info["os"] = sys_name or "?"
+ except Exception:
+ info["os"] = "?"
+ info["machine"] = platform.machine() or "?"
+ info["python"] = ".".join(platform.python_version().split(".")[:2])
+ try:
+ # psutil is already a Phosphene dep
+ import psutil # noqa: PLC0415
+ ram_gb = psutil.virtual_memory().total / (1024**3)
+ for bucket in (16, 32, 48, 64, 96, 128, 192, 256):
+ if ram_gb <= bucket + 4: # snap to bucket within ±4 GB
+ info["ram_gb_bucket"] = bucket
+ break
+ else:
+ info["ram_gb_bucket"] = 256
+ except Exception:
+ info["ram_gb_bucket"] = 0
+ try:
+ import subprocess # noqa: PLC0415
+ out = subprocess.check_output(
+ ["sysctl", "-n", "machdep.cpu.brand_string"],
+ timeout=2, stderr=subprocess.DEVNULL,
+ ).decode().strip()
+ info["cpu_brand"] = out[:64]
+ except Exception:
+ info["cpu_brand"] = "?"
+ return info
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index c98d41a..ca441f5 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -319,6 +319,21 @@ def _settings_defaults() -> dict:
# Memory/speed policy. Defaults to Auto so 5 s clips keep the fast
# full-decode path while long/high-pressure renders stay protected.
"memory_policy": DEFAULT_MEMORY_POLICY,
+ # Anonymous telemetry — OPT-IN. Default OFF. When enabled, the
+ # panel sends a tiny event payload (no prompts, no image bytes,
+ # no paths, no hostnames) for every render start/done/failed, the
+ # panel boot itself, and helper crashes. Used to understand
+ # version regressions, hardware-tier feature usage, and bug
+ # frequency over time — github clone-counts only retain 14 days.
+ # Full event schema lives in TELEMETRY.md alongside this file.
+ # Endpoint configurable via PHOSPHENE_ANALYTICS_ENDPOINT env var.
+ "analytics_enabled": False,
+ # Anonymous install UUID — generated once on first opt-in and
+ # written here. Lets us count unique installs without correlating
+ # with any user identity. Rotating this field resets the install
+ # identity (useful if a user wants to "forget me" before
+ # re-enabling).
+ "analytics_install_id": "",
}
@@ -532,6 +547,31 @@ def _validate_settings_patch(patch: dict) -> tuple[dict, str | None]:
return {}, f"unknown memory_policy: {policy}"
out["memory_policy"] = policy
+ if "analytics_enabled" in patch:
+ # urlencoded-bool coercion. When flipping ON, generate a fresh
+ # anonymous install_id if one isn't already saved — that's the
+ # only stable identifier we ever attach to events. Rotating it
+ # via the panel "Forget me" button (which clears
+ # analytics_install_id) is how the user resets identity.
+ v = patch["analytics_enabled"]
+ if isinstance(v, bool):
+ new_val = v
+ else:
+ new_val = str(v).strip().lower() in ("1", "true", "yes", "on")
+ out["analytics_enabled"] = new_val
+
+ if "analytics_install_id" in patch:
+ v = str(patch["analytics_install_id"]).strip()
+ # Allow only an empty string (forget-me) OR a 32-char hex UUID.
+ # Anything else is rejected to avoid the field becoming a free-
+ # form data sink the user could put PII in.
+ if v == "":
+ out["analytics_install_id"] = ""
+ elif len(v) == 32 and all(c in "0123456789abcdefABCDEF" for c in v):
+ out["analytics_install_id"] = v.lower()
+ else:
+ return {}, "analytics_install_id must be empty or 32-char hex"
+
return out, None
@@ -575,6 +615,11 @@ def get_settings_public() -> dict:
"models_card_dismissed": bool(s.get("models_card_dismissed", False)),
"spicy_mode": bool(s.get("spicy_mode", False)),
"memory_policy": s.get("memory_policy", DEFAULT_MEMORY_POLICY),
+ # Anonymous opt-in telemetry. The install_id itself is fine to
+ # expose — it's not a secret, the user can rotate it from the
+ # UI ("forget me"). The flag drives the Settings UI toggle.
+ "analytics_enabled": bool(s.get("analytics_enabled", False)),
+ "analytics_install_id": str(s.get("analytics_install_id", "")),
}
@@ -6868,6 +6913,28 @@ def worker_loop() -> None:
STATE["log"] = []
caffeinate_on()
persist_queue()
+ # ANALYTICS — render_start. Sanitized: no prompt, no paths, no
+ # filenames. Just shape (mode/quality/dims/frames). Safe-call:
+ # any failure inside emit() is swallowed silently.
+ try:
+ import analytics as _ph_analytics # type: ignore
+ _p = job.get("params", {}) or {}
+ _ph_analytics.emit("render_start", {
+ "mode": _p.get("mode"),
+ "quality": _p.get("quality"),
+ "width": _p.get("width"),
+ "height": _p.get("height"),
+ "frames": _p.get("frames"),
+ "has_character": bool(_p.get("character_id")),
+ "lora_count": len(_p.get("loras") or []),
+ "hdr": bool(_p.get("hdr")),
+ "enhance": bool(_p.get("enhance")),
+ "upscale": _p.get("upscale"),
+ "accel": _p.get("accel"),
+ "engine": _p.get("engine_override") if _p.get("mode") == "image" else None,
+ })
+ except Exception: # noqa: BLE001
+ pass
try:
run_job_inner(job)
@@ -6892,6 +6959,53 @@ def worker_loop() -> None:
STATE["pid"] = None
STATE["pgid"] = None
persist_queue()
+ # ANALYTICS — render_done / render_failed / render_cancelled.
+ # The error_category bucketing is coarse on purpose: keep the
+ # cardinality low so the same kind of bug across users
+ # aggregates cleanly. Full error STRINGS would leak filesystem
+ # paths and prompt fragments.
+ try:
+ import analytics as _ph_analytics # type: ignore
+ _p = job.get("params", {}) or {}
+ _status = job.get("status", "?")
+ _ev = {
+ "done": "render_done",
+ "failed": "render_failed",
+ "cancelled": "render_cancelled",
+ }.get(_status, "render_unknown")
+ _evt: dict = {
+ "mode": _p.get("mode"),
+ "quality": _p.get("quality"),
+ "elapsed_sec": job.get("elapsed_sec"),
+ "frames": _p.get("frames"),
+ }
+ if _status == "failed":
+ # Categorize the error so the wire stays small + private.
+ _err = (job.get("error") or "")
+ _cat = "other"
+ for needle, name in (
+ ("out of memory", "oom"),
+ ("OOM", "oom"),
+ ("jetsam", "oom"),
+ ("HF", "hf_auth"),
+ ("gated", "hf_gated"),
+ ("401", "hf_auth"),
+ ("CUDA", "wrong_backend"),
+ ("model_dir", "missing_model"),
+ ("Q8", "q8_missing"),
+ ("not installed", "missing_deps"),
+ ("character", "character_error"),
+ ("FileNotFoundError", "file_missing"),
+ ("BrokenPipeError", "helper_pipe"),
+ ("RuntimeError", "runtime"),
+ ):
+ if needle.lower() in _err.lower():
+ _cat = name
+ break
+ _evt["error_category"] = _cat
+ _ph_analytics.emit(_ev, _evt)
+ except Exception: # noqa: BLE001
+ pass
# ---- Image Studio + characters integration ----------------------------------
@@ -10750,6 +10864,56 @@ class Handler(BaseHTTPRequestHandler):
prev.get("memory_policy", DEFAULT_MEMORY_POLICY) !=
current.get("memory_policy", DEFAULT_MEMORY_POLICY)
)
+ # Analytics opt-in lifecycle. When flipping ON, generate a
+ # fresh anonymous install_id if one isn't already saved, and
+ # fire a single settings_opt_in event so we count adoption.
+ # When flipping OFF, fire settings_opt_out as the LAST event
+ # before silence (gives us the offboarding signal without
+ # tracking the user afterward).
+ analytics_was = bool(prev.get("analytics_enabled", False))
+ analytics_now = bool(current.get("analytics_enabled", False))
+ if analytics_now and not analytics_was:
+ if not current.get("analytics_install_id"):
+ try:
+ import analytics as _ph_a # type: ignore
+ new_id = _ph_a.new_install_id()
+ update_settings({"analytics_install_id": new_id})
+ current = get_settings()
+ push("settings: analytics ON (anonymous install id generated)")
+ except Exception as _e: # noqa: BLE001
+ push(f"settings: analytics ON but install_id gen failed: {_e}")
+ try:
+ import analytics as _ph_a # type: ignore
+ _ph_a.emit("settings_opt_in", {
+ "version": _read_local_version() or "unknown",
+ })
+ except Exception: # noqa: BLE001
+ pass
+ elif analytics_was and not analytics_now:
+ # Last gasp before silence.
+ try:
+ import analytics as _ph_a # type: ignore
+ _ph_a.emit("settings_opt_out", {
+ "version": _read_local_version() or "unknown",
+ })
+ except Exception: # noqa: BLE001
+ pass
+ elif analytics_now and analytics_was:
+ # Forget-me path — user blanked install_id while still
+ # opted in. Regenerate immediately so the next event
+ # uses a fresh anonymous identity (anyone correlating
+ # events on the ingest side sees this as a new user).
+ prev_id = (prev.get("analytics_install_id") or "").strip()
+ cur_id = (current.get("analytics_install_id") or "").strip()
+ if prev_id and not cur_id:
+ try:
+ import analytics as _ph_a # type: ignore
+ new_id = _ph_a.new_install_id()
+ update_settings({"analytics_install_id": new_id})
+ current = get_settings()
+ push("settings: analytics identity rotated")
+ except Exception as _e: # noqa: BLE001
+ push(f"settings: analytics rotate failed: {_e}")
if codec_changed:
push(
f"settings: output codec → {current['output_pix_fmt']} "
@@ -19187,6 +19351,36 @@ HTML = r"""<!doctype html>
<div class="hint" id="spicyHint" style="margin-top:8px; display:none"></div>
</div>
+ <!-- Anonymous opt-in telemetry. Strictly OFF by default. When ON,
+ a tiny event payload (no prompts, no image bytes, no paths) is
+ sent per render so we can spot bugs + understand how Phosphene
+ is actually used. The "What's collected?" link opens the
+ TELEMETRY.md doc shipping in the repo so the user can audit
+ every field before opting in. -->
+ <div class="settings-section">
+ <h3>Anonymous analytics <span class="hint" style="font-weight:400">(help improve Phosphene)</span></h3>
+ <div class="hint" style="margin-bottom:10px">
+ OFF by default. When ON, Phosphene sends a tiny anonymous event
+ per render — render type, duration, model tier, error category.
+ Never sends prompts, image data, file paths, or your hostname.
+ <a href="https://github.com/mrbizarro/phosphene/blob/main/TELEMETRY.md"
+ target="_blank" rel="noopener">What's collected?</a>
+ </div>
+ <div class="spicy-row">
+ <span class="spicy-state" id="analyticsStateBadge">OFF</span>
+ <button type="button" class="ghost-btn" id="analyticsToggleBtn"
+ onclick="toggleAnalytics()" style="margin-left:auto">
+ Enable anonymous analytics
+ </button>
+ </div>
+ <div class="hint" id="analyticsHint" style="margin-top:8px; display:none"></div>
+ <div class="hint" id="analyticsForgetRow" style="margin-top:8px; display:none">
+ Anonymous install id: <code id="analyticsInstallId" style="font-size:11px"></code>
+ <button type="button" class="ghost-btn" onclick="rotateAnalyticsId()"
+ style="margin-left:8px; padding:2px 8px; font-size:11px">forget me</button>
+ </div>
+ </div>
+
<div class="settings-section" id="settingsCustomSection" style="display:none">
<h3>Custom (advanced)</h3>
<div class="settings-row" style="margin-bottom:10px">
@@ -25547,6 +25741,9 @@ async function openSettingsModal() {
// on the JS side; only ON/OFF gets persisted.
_spicyArmed = false;
renderSpicyState(!!cur.spicy_mode);
+
+ // Anonymous analytics toggle — single click, no two-step confirm.
+ renderAnalyticsState(!!cur.analytics_enabled, cur.analytics_install_id || '');
}
function renderMemoryPolicyHint() {
@@ -25648,6 +25845,103 @@ async function _persistSpicyMode(target) {
}
}
+// Anonymous analytics — single-click toggle (no two-click confirm; this
+// is opt-IN, not destructive). The install_id is generated server-side
+// the first time the flag flips ON; the UI just shows the bare boolean.
+function renderAnalyticsState(isOn, installId) {
+ const badge = document.getElementById('analyticsStateBadge');
+ const btn = document.getElementById('analyticsToggleBtn');
+ const hint = document.getElementById('analyticsHint');
+ const forgetRow = document.getElementById('analyticsForgetRow');
+ const idEl = document.getElementById('analyticsInstallId');
+ if (!badge || !btn) return;
+ badge.classList.remove('on', 'armed');
+ if (isOn) {
+ badge.textContent = 'ON';
+ badge.classList.add('on');
+ btn.textContent = 'Disable';
+ btn.classList.remove('primary-btn');
+ btn.classList.add('ghost-btn');
+ if (hint) {
+ hint.style.display = '';
+ hint.textContent = 'Thanks — anonymous render events are flowing. Toggle OFF to stop instantly.';
+ }
+ if (forgetRow && installId) {
+ forgetRow.style.display = '';
+ if (idEl) idEl.textContent = installId.slice(0, 8) + '…';
+ } else if (forgetRow) {
+ forgetRow.style.display = 'none';
+ }
+ } else {
+ badge.textContent = 'OFF';
+ btn.textContent = 'Enable anonymous analytics';
+ btn.classList.remove('primary-btn');
+ btn.classList.add('ghost-btn');
+ if (hint) { hint.style.display = 'none'; hint.textContent = ''; }
+ if (forgetRow) forgetRow.style.display = 'none';
+ }
+}
+
+async function toggleAnalytics() {
+ const cur = (_settingsCache && _settingsCache.settings) || {};
+ const target = !cur.analytics_enabled;
+ const status = document.getElementById('settingsStatus');
+ try {
+ const fd = new URLSearchParams();
+ fd.set('analytics_enabled', target ? 'true' : 'false');
+ const r = await fetch('/settings', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (j.error) throw new Error(j.error);
+ if (_settingsCache && _settingsCache.settings) {
+ _settingsCache.settings.analytics_enabled = !!target;
+ if (j.settings && j.settings.analytics_install_id) {
+ _settingsCache.settings.analytics_install_id = j.settings.analytics_install_id;
+ }
+ }
+ const id = (_settingsCache?.settings?.analytics_install_id) || '';
+ renderAnalyticsState(!!target, id);
+ if (status) {
+ status.textContent = target ? 'Anonymous analytics ON · thanks for helping' : 'Anonymous analytics OFF';
+ status.className = 'settings-status ok';
+ }
+ } catch (e) {
+ if (status) {
+ status.textContent = 'Could not change analytics: ' + (e.message || e);
+ status.className = 'settings-status err';
+ }
+ }
+}
+
+async function rotateAnalyticsId() {
+ // Clear the saved id; server regenerates a fresh one on next opt-in
+ // (or on the next emit if still enabled). Sends one settings_opt_out
+ // + one settings_opt_in with the new id, which is the right wire
+ // shape — anyone correlating events sees a new identity from now on.
+ const status = document.getElementById('settingsStatus');
+ try {
+ const fd = new URLSearchParams();
+ fd.set('analytics_install_id', '');
+ const r = await fetch('/settings', { method: 'POST', body: fd });
+ const j = await r.json();
+ if (j.error) throw new Error(j.error);
+ if (_settingsCache && _settingsCache.settings) {
+ _settingsCache.settings.analytics_install_id =
+ (j.settings && j.settings.analytics_install_id) || '';
+ }
+ const id = _settingsCache?.settings?.analytics_install_id || '';
+ renderAnalyticsState(!!(_settingsCache?.settings?.analytics_enabled), id);
+ if (status) {
+ status.textContent = 'Analytics identity reset — future events use a fresh anonymous id';
+ status.className = 'settings-status ok';
+ }
+ } catch (e) {
+ if (status) {
+ status.textContent = 'Could not reset analytics id: ' + (e.message || e);
+ status.className = 'settings-status err';
+ }
+ }
+}
+
function setTokenStatus(prefix, isSet, dirty) {
const el = document.getElementById(prefix + 'Status');
if (!el) return;
@@ -28147,6 +28441,31 @@ if __name__ == "__main__":
threading.Thread(target=version_check_loop, daemon=True).start()
else:
_detect_local_install_state()
+ # ---- Anonymous telemetry — strictly opt-in (default OFF) ------------
+ # Wire the analytics module to read settings live so the user can
+ # flip the toggle without restarting. The install_id is generated
+ # lazily the first time the user opts in (see /settings handler).
+ try:
+ import analytics as _ph_analytics # type: ignore
+ _ph_analytics.install(
+ is_enabled=lambda: bool(get_settings().get("analytics_enabled", False)),
+ get_install_id=lambda: str(get_settings().get("analytics_install_id", "")),
+ get_endpoint=lambda: (os.environ.get("PHOSPHENE_ANALYTICS_ENDPOINT", "").strip()
+ or _ph_analytics.DEFAULT_ENDPOINT),
+ log=push,
+ )
+ # Boot event. Carries anonymized fingerprint so we can correlate
+ # bugs to hardware tier + OS without per-user identifiers.
+ _ph_analytics.emit("panel_boot", {
+ "version": _read_local_version() or "unknown",
+ "sha": (_VERSION_STATE.get("local_short") or ""),
+ "branch": (_VERSION_STATE.get("local_branch") or "?"),
+ "tier": SYSTEM_CAPS.get("label", "?"),
+ "allows_q8": bool(SYSTEM_CAPS.get("allows_q8", False)),
+ **_ph_analytics.system_fingerprint(),
+ })
+ except Exception as _exc: # noqa: BLE001 — telemetry must never crash the panel
+ sys.stderr.write(f"WARN: analytics setup failed silently: {_exc}\n")
# 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
@@ -28169,3 +28488,11 @@ if __name__ == "__main__":
finally:
HELPER.kill()
caffeinate_off()
+ # Telemetry is best-effort; daemon thread will die with the
+ # process anyway, but a clean stop lets queued events flush
+ # if the user closes the panel gracefully.
+ try:
+ import analytics as _ph_a # type: ignore
+ _ph_a.shutdown()
+ except Exception:
+ pass