Files
gabrielvidalandClaude Opus 5.5 ce6382f03b feat(plugins): the core names no plugin page — each page brings its own links
The core still hard-coded links into plugin pages (Files → Goals / Skills /
Agents / Forms cards and drawer links, Dashboards → Performance, Settings →
What's new and its editor, the home Analytics icon, skill/agent pills) and
~25 old addresses that forwarded to them (/goals, /skills, /dashboards/plan,
/whats-new, /memories/<slug>…). On a hub without those plugins (raw-hub)
they opened 404 pages. Now every link to a plugin page comes from its
manifest:

- bottom-bar drawers: every `files` / `dashboards` plugin page joins its
  section's drawer (past five slots into the stash), key
  `<section>/p:<plugin>:<page>`; saved slots of the core's old links map to
  the plugins' (SUB_RENAMED);
- Files landing: the plugins' Files pages are its cards; Files panel: the
  hard-coded Goals row is gone;
- What's new + editor leave the settings registry (the plugin's own
  `nav: "settings"` pages);
- new optional page fields (written only when set — `ui` is in the approval
  fingerprint): `perm` (the page reaches its holders only), `header: "home"`
  (a button in the home page's head — Analytics), `tag` (the tag kind whose
  pills open the page at <page>/<slug> — skill, agent), `feature` (the App
  usage id its visits count under, so a former core page keeps its history;
  else plugin.<plugin>.<page>, in the frontend and telemetry/views.registry);
- the old addresses and their redirect components are dropped; the owner's
  usage rings, the burn gauge and the Stats redirect link nowhere into a
  plugin; the plan-usage and /tmp-full pushes open /dashboards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:14:14 +01:00

262 lines
11 KiB
Python

"""What the two pages read: the Hub card (``/dashboards/performance``) and the
Usage dashboard (``/dashboards/usage``). Plain dicts, shaped by
``schemas/telemetry.py``."""
from __future__ import annotations
import time
from conversations.ids import uid_time
from users.caller import OWNER_ID, OWNER_NAME
from .middleware import Hist
from .store import _hist_from, _quantile
#: range → (span, bucket) in seconds.
HUB_RANGES = {"24h": (86400, 300), "7d": (7 * 86400, 3600), "30d": (30 * 86400, 4 * 3600)}
USAGE_RANGES = {"7d": 7, "30d": 30, "90d": 90}
#: Where a conversation came from (:func:`run_origin`), in display order.
ORIGINS = ("app", "script", "cron", "scheduled", "child", "mcp", "handoff", "fork",
"newProject", "unknown")
def _iso_day(t: float) -> str:
return time.strftime("%Y-%m-%d", time.localtime(t))
# ── the Hub card ─────────────────────────────────────────────────────────────
def hub(deps, rng: str, now: float | None = None) -> dict:
now = now or time.time()
span, step = HUB_RANGES[rng]
since = now - span
st = deps.telemetry
buckets: dict[int, dict] = {}
total = Hist()
minute_lags: list[float] = []
lag_max = 0.0
for (t, n, err, sum_ms, max_ms, b, lag_p95, lag_mx, sse, busy, rss, cpu) in st.query(
"SELECT t, n, err, sum_ms, max_ms, b, lag_p95, lag_max, sse, busy, rss, cpu "
"FROM hub_minutes WHERE t >= ? ORDER BY t", (since,)):
k = int(t // step * step)
e = buckets.setdefault(k, {"h": Hist(), "lag": [], "lagMax": 0.0, "sse": 0,
"rss": 0, "cpu": []})
if n:
h = _hist_from(b, n, err, sum_ms, max_ms)
e["h"].merge(h)
total.merge(h)
if lag_p95 is not None:
e["lag"].append(lag_p95)
minute_lags.append(lag_p95)
if lag_mx is not None:
e["lagMax"] = max(e["lagMax"], lag_mx)
lag_max = max(lag_max, lag_mx)
e["sse"] = max(e["sse"], sse or 0)
e["rss"] = max(e["rss"], rss or 0)
if cpu is not None:
e["cpu"].append(cpu)
series = [{
"t": k, "n": e["h"].n, "err": e["h"].err,
"p50": e["h"].quantile(.5), "p95": e["h"].quantile(.95),
"lagP95": _quantile(e["lag"], .95), "lagMax": round(e["lagMax"], 1),
"sse": e["sse"], "rss": e["rss"] or None,
"cpu": round(sum(e["cpu"]) / len(e["cpu"]), 1) if e["cpu"] else None,
} for k, e in sorted(buckets.items())]
per_route: dict[str, Hist] = {}
for route, n, err, sum_ms, max_ms, b in st.query(
"SELECT route, n, err, sum_ms, max_ms, b FROM hub_routes WHERE t >= ?",
(since - 3600,)):
per_route.setdefault(route, Hist()).merge(_hist_from(b, n, err, sum_ms, max_ms))
routes = sorted(({
"route": r, "n": h.n, "err": h.err, "p50": h.quantile(.5), "p95": h.quantile(.95),
"max": round(h.max, 1), "sumMs": round(h.sum),
} for r, h in per_route.items() if h.n), key=lambda x: -x["sumMs"])[:25]
vitals: dict[tuple[str, str], list[float]] = {}
for name, device, value in st.query(
"SELECT name, device, value FROM web_vitals WHERE t >= ?", (since,)):
vitals.setdefault((name, device), []).append(value)
vitals.setdefault((name, "all"), []).append(value)
web = [{"name": name, "device": device, "n": len(v), "p75": _quantile(v, .75)}
for (name, device), v in sorted(vitals.items())]
errors = [{"message": m, "page": p, "n": n, "last": last, "source": src}
for m, p, n, last, src in st.query(
"SELECT message, page, SUM(n), MAX(last), MAX(source) FROM web_errors "
"WHERE day >= ? GROUP BY message, page ORDER BY SUM(n) DESC LIMIT 10",
(_iso_day(since),))]
return {
"range": rng, "step": step, "series": series,
"totals": {"n": total.n, "err": total.err, "p50": total.quantile(.5),
"p95": total.quantile(.95), "max": round(total.max, 1),
"lagP95": _quantile(minute_lags, .95), "lagMax": round(lag_max, 1)},
"routes": routes, "web": web, "errors": errors,
"now": {"sse": deps.hub.subscriber_count()},
}
# ── the Usage dashboard ──────────────────────────────────────────────────────
def run_origin(m: dict) -> str:
"""Where a conversation was started from, read off its meta. ``app`` /
``script`` are stamped by ``/api/spawn`` since telemetry began; before
that, and for a session started in a terminal, it is ``unknown``."""
if m.get("cron"):
return "cron"
if m.get("scheduled"):
return "scheduled"
if m.get("spawnedBy"):
return "child"
via = m.get("via")
if isinstance(via, dict) and via.get("kind") == "mcp":
return "mcp"
if m.get("forkedFrom"):
return "fork"
if m.get("newProject"):
return "newProject"
o = m.get("origin")
# ``handoff``: stamped by /api/spawn from 2026-11-24 until handoffs left the
# core for the handoff plugin (2026-11-26) — its successors are ``script``s now.
return o if o in ("app", "script", "handoff") else "unknown"
def _who(deps, who: str) -> set[str] | None:
"""``all`` → None (everyone); ``owner``; ``guests``; ``guest:<uid>``."""
if who == "owner":
return {OWNER_ID}
guests = {u["id"] for u in deps.users.all()}
if who == "guests":
return guests
if who.startswith("guest:"):
uid = who[6:]
return {uid} if uid in guests else set()
return None
def usage(deps, rng: str, who: str = "all", now: float | None = None) -> dict:
now = now or time.time()
days = USAGE_RANGES[rng]
since_t = now - days * 86400
since = _iso_day(since_t)
uids = _who(deps, who)
st = deps.telemetry
feats: dict[tuple[str, str], dict] = {}
for kind, name, uid, device, n in st.query(
"SELECT kind, name, uid, device, SUM(n) FROM usage_daily WHERE day >= ? "
"GROUP BY kind, name, uid, device", (since,)):
if uids is not None and uid not in uids:
continue
f = feats.setdefault((kind, name), {"kind": kind, "name": name, "n": 0,
"byUser": {}, "byDevice": {}})
f["n"] += n
f["byUser"][uid] = f["byUser"].get(uid, 0) + n
f["byDevice"][device] = f["byDevice"].get(device, 0) + n
# First and last use ever, per person: adoption after a What's new entry.
first: dict[tuple[str, str], dict[str, list[str]]] = {}
for kind, name, uid, d0, d1 in st.query(
"SELECT kind, name, uid, MIN(day), MAX(day) FROM usage_daily "
"WHERE kind != 'api' GROUP BY kind, name, uid"):
if uids is not None and uid not in uids:
continue
first.setdefault((kind, name), {})[uid] = [d0, d1]
for key, f in feats.items():
f["users"] = len(f["byUser"])
f["firstUse"] = {u: v[0] for u, v in first.get(key, {}).items()}
f["lastDay"] = max((v[1] for v in first.get(key, {}).values()), default=None)
features = sorted(feats.values(), key=lambda f: -f["n"])
devices: dict[str, int] = {}
for f in features:
if f["kind"] == "api":
continue
for d, n in f["byDevice"].items():
devices[d] = devices.get(d, 0) + n
# The guests' What's new entries and who saw each — the whats-new plugin's
# (plugins/whatsnew_bridge.py; none without it).
from plugins import whatsnew_bridge
whats_new = whatsnew_bridge.entries(deps)[:12]
runs: dict[str, dict] = {}
for cid, m in deps.meta_store.items():
t = uid_time(cid)
if t is None or t < since_t:
continue
if m.get("test"):
continue
uid = m.get("owner") or OWNER_ID
if uids is not None and uid not in uids:
continue
o = run_origin(m)
r = runs.setdefault(o, {"origin": o, "n": 0, "byUser": {}})
r["n"] += 1
r["byUser"][uid] = r["byUser"].get(uid, 0) + 1
origins = sorted(runs.values(), key=lambda r: ORIGINS.index(r["origin"]))
people = [{"id": OWNER_ID, "name": OWNER_NAME, "guest": False}] + [
{"id": u["id"], "name": u.get("name") or u.get("email") or u["id"], "guest": True}
for u in deps.users.all() if not u.get("disabled")]
span = st.query("SELECT MIN(day) FROM usage_daily")
return {"range": rng, "who": who, "features": features, "devices": devices,
"whatsNew": whats_new, "runs": origins, "people": people,
"trackedSince": span[0][0] if span and span[0][0] else None}
# ── the feature registry ─────────────────────────────────────────────────────
_REGISTRY: list | None = None
def registry(deps=None) -> list[dict]:
"""The app's feature registry (lib/telemetry/features.ts — every page and
client feature it knows by name), as ``features.json`` beside this module:
generated from the TypeScript, which ``src/lib/telemetry/features.test.ts``
keeps in step (``UPDATE_FEATURES=1 npx vitest run`` rewrites it) — plus,
given ``deps``, every installed plugin's pages (``plugin_features``). The
App usage plugin joins it with the counts to label rows and list what goes
unused."""
global _REGISTRY
if _REGISTRY is None:
import json
import pathlib
try:
data = json.loads((pathlib.Path(__file__).with_name("features.json")).read_text(encoding="utf-8"))
_REGISTRY = [f for f in data if isinstance(f, dict) and isinstance(f.get("id"), str)]
except (OSError, ValueError):
_REGISTRY = []
if deps is None:
return _REGISTRY
known = {f["id"] for f in _REGISTRY}
return _REGISTRY + [f for f in plugin_features(deps) if f["id"] not in known]
# A plugin page's App usage area, by the section its ``nav`` puts it in.
_PLUGIN_AREAS = {"files": "Lab", "settings": "Settings"}
def plugin_features(deps) -> list[dict]:
"""One view feature per page of every installed plugin (anyone's, once
per id): its id the page's ``feature`` — the one it counted under before
it was a plugin's, so its history carries on — else
``plugin.<plugin>.<page>``. The frontend records the same id
(lib/telemetry ``pageOf``)."""
out: dict[str, dict] = {}
try:
installed = deps.plugin_store.all_installed()
except Exception: # noqa: BLE001 — no store, no plugin pages
return []
for _uid, rec in installed:
mf = rec.get("manifest") or {}
pid = rec.get("id") or mf.get("id") or ""
for pg in (mf.get("ui") or {}).get("pages") or []:
if pg.get("nav") == "none" or not pid:
continue
fid = pg.get("feature") or f"plugin.{pid}.{pg['id']}"
if fid in out:
continue
out[fid] = {"id": fid, "label": pg.get("label") or pg["id"],
"area": _PLUGIN_AREAS.get(pg.get("nav") or "", "Dashboards"),
"kind": "view", **({"ownerOnly": True} if pg.get("perm") else {})}
return list(out.values())