Shared hooks for templates, memories, desk-phone, activity, project-env, ship and blue-green-deploy, with no legacy module removed: - manifest: owner-only templates.read / memories.read / projects.env / activity.read / ship.run (one _OPERATOR_CAPS set); provides memories.index, notify.audio, app.banner - runner: AIA_TEMPLATES_DIR / AIA_MEMORIES_DIR / AIA_PROJECTS_DIR for the owner's runs; requester_context() carries sessionId for runAs: owner - /api/plugins (+ ui): active provides keys (no app.banner for guests) - hub/conversations: memories=1 (memoriesRead, model), memory=<slug> - hub/activity (plugins/activitydata.py now holds the rollup; dashboards/activity.py is a shim; dashboards/timebins.py helpers) - /api/usage/daily (owner, lab.read); Home's usage card reads it - memories_bridge.py (plans_bridge twin), Graph prefers it - banner.py + /api/app-banner + StatusBanner.tsx; webhook/action of the provider invalidates and publishes SSE banner; is_maintenance pauses guest-job delivery - hubbridge: inline scaffold template list; ship/deploy, ship/audit, ship/scan bridges - project.detail slot on Project.tsx; aiAgentPlugin.copy(text) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
150 lines
5.7 KiB
Python
150 lines
5.7 KiB
Python
"""``analytics.read`` — how many conversations, and how long they ran, for the
|
|
Analytics plugin (the cost-focused Conversations analytics page left the core
|
|
on 2026-11-25 and came back as a page about usage; cost stays in the core's
|
|
cost dashboards and cards).
|
|
|
|
One row per **top-level** conversation in a profile scope and date range:
|
|
when it started and ended, its **working time** — the distinct 5-minute bins
|
|
it (and its subagents) produced a turn in, the same measure as the guests'
|
|
Stats and the Activity dashboard — its wall-clock span, user turns, and the
|
|
keys the page breaks it down by: model, harness, projects, machine, person,
|
|
origin. Working time is also given per local day (``byDay``, the browser's
|
|
``tzOffset``), so a conversation spanning midnight counts on both days.
|
|
|
|
Children another conversation started (``spawnedBy``) are always left out;
|
|
cron and test runs only with ``cron=1``. No cost, ever. Owner only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
from typing import Any
|
|
|
|
from plugins.footprintdata import RANGE_DAYS, RANGES, _cards, _ts, profiles, subscription_start
|
|
|
|
|
|
def model_label(model: str | None) -> str:
|
|
"""A Claude id → its family (``opus``…); anything else → its own id
|
|
(``gpt-6-sol``, ``gemini-4-neon``, ``ggml-org/qwen3.8-27b``)."""
|
|
m = (model or "").strip()
|
|
low = m.lower()
|
|
for fam in ("opus", "sonnet", "haiku", "fable"):
|
|
if fam in low:
|
|
return fam
|
|
if "mythos" in low:
|
|
return "fable"
|
|
return m or "unknown"
|
|
|
|
|
|
def _bins_by_session(deps) -> dict[str, set[int]]:
|
|
out: dict[str, set[int]] = {}
|
|
for _path, s in deps.store.all_summaries():
|
|
sid = s.get("sessionId")
|
|
if not sid:
|
|
continue
|
|
for bins in (s.get("activeBins") or {}).values():
|
|
if bins:
|
|
out.setdefault(sid, set()).update(b for b in bins if isinstance(b, int))
|
|
return out
|
|
|
|
|
|
def _runners(deps) -> dict[str, str]:
|
|
names = {"local": "Homelab"}
|
|
try:
|
|
for w in deps.worker_store.list():
|
|
if w.get("id"):
|
|
names[w["id"]] = w.get("name") or w["id"]
|
|
except Exception: # noqa: BLE001 — no worker store (tests)
|
|
pass
|
|
return names
|
|
|
|
|
|
def _people(deps) -> dict[str, str]:
|
|
from users.caller import OWNER_ID, OWNER_NAME
|
|
names = {OWNER_ID: OWNER_NAME}
|
|
try:
|
|
for u in deps.users.all():
|
|
names[u["id"]] = u.get("name") or u["id"]
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
return names
|
|
|
|
|
|
def build(deps, account: str | None = None, range_key: str | None = None,
|
|
tz_offset: int = 0, cron: bool = False, now: float | None = None) -> dict[str, Any]:
|
|
from conversations import BIN_MINUTES
|
|
from dashboards.timebins import _local_day_and_slot
|
|
from profiles.store import guest_owner
|
|
from telemetry.views import run_origin
|
|
from users.caller import OWNER_ID
|
|
|
|
scope = (account or "").strip().lower() or f"profile:{deps.profile_store.default()['id']}"
|
|
rk = range_key if range_key in RANGES else "30d"
|
|
now = now if now is not None else dt.datetime.now(dt.timezone.utc).timestamp()
|
|
sub = subscription_start(deps, scope)
|
|
since: float | None = None
|
|
if rk in RANGE_DAYS:
|
|
since = now - RANGE_DAYS[rk] * 86400
|
|
elif rk == "sub" and sub:
|
|
try:
|
|
since = dt.datetime.fromisoformat(sub).replace(tzinfo=dt.timezone.utc).timestamp()
|
|
except ValueError:
|
|
since = None
|
|
off_ms = int(tz_offset) * 60 * 1000
|
|
sel = deps.profile_store.selector(scope)
|
|
bins = _bins_by_session(deps)
|
|
runners = _runners(deps)
|
|
people = _people(deps)
|
|
rows = []
|
|
for c in _cards(deps):
|
|
m = c.get("meta") or {}
|
|
if m.get("spawnedBy"):
|
|
continue
|
|
if not cron and (m.get("cron") or m.get("test") or m.get("agentRun")):
|
|
continue
|
|
acct = m.get("account")
|
|
guest = guest_owner(m, acct)
|
|
if not sel(acct, m.get("profile"), guest):
|
|
continue
|
|
t = _ts(c)
|
|
if since is not None and (t is None or t < since):
|
|
continue
|
|
start = c.get("startedAt")
|
|
t0 = _ts({"startedAt": start}) if start else None
|
|
mine = bins.get(c.get("sessionId") or "", set())
|
|
by_day: dict[str, int] = {}
|
|
for b in mine:
|
|
d, _ = _local_day_and_slot(b, off_ms)
|
|
by_day[d] = by_day.get(d, 0) + BIN_MINUTES
|
|
runner = m.get("worker") or m.get("workerSource") or "local"
|
|
person = guest or OWNER_ID
|
|
rows.append({
|
|
"id": c.get("id"),
|
|
"title": (m.get("title") or c.get("title") or "")[:140],
|
|
"start": int(t0 * 1000) if t0 is not None else None,
|
|
"t": int(t * 1000) if t is not None else None,
|
|
"workMin": len(mine) * BIN_MINUTES,
|
|
"wallSec": max(0, int(t - t0)) if t is not None and t0 is not None else 0,
|
|
"turns": int(c.get("userTurns") or 0),
|
|
"byDay": by_day,
|
|
"model": model_label((c.get("models") or [None])[0] or c.get("model")),
|
|
"harness": m.get("harness") or "claude",
|
|
"projects": [p for p in (m.get("projects") or []) if isinstance(p, str)],
|
|
# an unpaired machine keeps no name: say so rather than show an id
|
|
"machine": runners.get(runner) or f"Unpaired machine · {runner[:6]}",
|
|
"person": people.get(person, person),
|
|
"guest": bool(guest),
|
|
"origin": run_origin(m),
|
|
})
|
|
rows.sort(key=lambda r: r["t"] or 0, reverse=True)
|
|
return {
|
|
"scope": scope,
|
|
"range": rk,
|
|
"since": int(since * 1000) if since is not None else None,
|
|
"subscriptionStart": sub,
|
|
"binMinutes": BIN_MINUTES,
|
|
"cron": bool(cron),
|
|
"profiles": profiles(deps),
|
|
"conversations": rows,
|
|
}
|