The handoff link, the conversation menu's Hand off ▸, HandoffDialog, the
Continued from / Continued in banners and POST /api/handoff move to the
handoff live plugin (ai-agent-plugins). What the core keeps is generic:
- ui.menuItems (conversation.menu): a plugin row in the conversation menu
opening the plugin's sandboxed dialog; frame bridges close() and toast()
- slot places conversation.threadHeader / conversation.threadEnd, whose
update carries the plugin's own meta.plugins.<id> (pluginData)
- ConversationDetail.pluginData (owner only)
- conversations.data: GET|POST hub/conversations/{sid}/data, a plugin's
own data on a conversation (handler only, owner only, operator approval)
- runs.start takes test; hub/conversations rows carry model and harness
- carryover.handoffs moves the old meta.handoffFrom / handoffTo stamps
into meta.plugins.handoff once
Removed: runs/handoff.py, /api/handoff, SpawnBody.handoffFrom and the
spawn's handoff origin, meta.handoffFrom/handoffTo and their resolved refs,
Handoff.tsx, the Handoffs eye switch (the plugin's vis switch replaces it).
The CLI's --handoff-from and MCP handoff_from are left alone (inert) until
the CLI/MCP plugin-commands mechanism lands.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
228 lines
9.7 KiB
Python
228 lines
9.7 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
|
|
|
|
seen = deps.whats_new.seen_counts()
|
|
whats_new = [{"id": e["id"], "title": e["title"], "publishedAt": e["publishedAt"],
|
|
"seen": seen.get(e["id"], 0)}
|
|
for e in deps.whats_new.entries()][: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() -> 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). 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 = []
|
|
return _REGISTRY
|