Files
ai-agent/backend/plugins/hubperf.py
gabrielvidalandClaude Opus 5.5 a459352850 refactor(plugins): the header's CPU and On-disk chips move to the performance plugin
The core carried the conversation header's two perf chips (PerfChip,
StorageChip) although they belong to the performance plugin, and since
plugin-links they linked to /dashboards/performance|storage, which no
longer exist. They are now the plugin's `conversation.header` slot:

- `conversation.header` (declared since v1, never drawn) is rendered:
  HeaderPluginSlots puts each slot inline at the end of the header's meta
  line, sized both ways by resize(h, w), update {sessionId,
  conversationId, running}. SinglePluginSlot gets `startEmpty` (hidden
  until the frame first sizes itself, so a chip never shows a blank
  300 px frame while it loads) and `emptyStyle` (a 0 x 0 inline box: the
  absolute EMPTY_SLOT_STYLE would start mid-line and overflow the page);
- removed: PerfCard.tsx / StorageCard.tsx, useConversationPerf /
  useConversationStorage, fmtPct, the *Performance* eye switch (`perf`)
  and its French hint;
- perf.read already serves both reads (conversation/{sid} without series,
  conversation/{sid}/storage); a bridge test now pins the fields the
  chips draw, and the retired-files test lists the two chip files;
- docs/plugins.md and CLAUDE.md say where the chips live now.

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

318 lines
12 KiB
Python

"""``perf.read`` / ``perf.act`` — the Performance and Storage dashboards'
data, read and acted on by the ``performance`` live plugin
(``ai-agent-plugins/plugins/performance``, since 2026-11-26 it replaced core's
``/dashboards/performance`` and ``/dashboards/storage`` pages and the
conversation's CPU / RAM and *On disk* Details cards; since 2026-11-27 the
conversation header's CPU and On-disk chips too, its ``conversation.header``
slot).
Everything stays in ``perf/`` — the poller thread, the store, the storage
records, every ``/api/perf/*`` route (the Bash cards' cost strip and the guest
Stats still read them); these bridges only hand the plugin's handlers the same
answers. Owner only, operator approval. Each route is served at ``…/hub/…``
(the bridges' convention).
``perf.read`` (GET, the owner's handler or caller token):
* ``hub/perf/live?account=`` — ``/api/perf/live`` plus ``profiles`` (the
scope switch's segments) and ``guestNames`` (uid → name, for the pills);
* ``hub/perf/history?range=&runner=&account=``,
``hub/perf/conversations?range=&account=``,
``hub/perf/commands?range=&kind=&account=`` — as ``/api/perf/…``;
* ``hub/perf/conversation/{sid}?series=10m,life`` — ``{perf, series}``: the
conversation's numbers (``/api/perf/conversation/{sid}``) and, per window
asked, its CPU / RSS series (``…/series?window=``) — one call per refresh of
its Details card; without ``series`` (``series: {}``) it is the header CPU
chip's read (``live``, ``cpuSeconds``, ``peakRss``, ``peakProcs``);
* ``hub/perf/conversation/{sid}/storage`` — what it keeps on disk (the Details
card and the header On-disk chip: ``left``, ``items``);
* ``hub/perf/storage?account=`` (+ ``profiles``, ``guestNames``),
``hub/perf/storage/history?runner=&mount=&range=``,
``hub/perf/storage/writers?range=&account=``,
``hub/perf/storage/config?runner=``, ``hub/perf/settings``.
``telemetry.read`` (GET): ``hub/telemetry/hub?range=`` — ``/api/telemetry/hub``
(the hub's own API latency, loop lag, routes, web vitals and JS errors: the
Performance page's *The hub itself*). ``hub/telemetry/usage`` is
``plugins/proxyroutes.py``'s.
``perf.act`` (POST, the plugin's **own handlers** only, run for the owner):
``hub/perf/kill`` · ``hub/perf/keep`` · ``hub/perf/settings`` (the auto-kill
settings, a partial patch) · ``hub/perf/storage/rm`` · ``hub/perf/storage/scan``
· ``hub/perf/storage/config`` — the bodies of their ``/api/perf/…`` twins.
Refusals carry ``{"error": {message, kind}, "detail": {message, kind}}``.
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from starlette.concurrency import run_in_threadpool
from plugins.hubmachines import _refuse
from plugins.proxyroutes import _active_plugin, _who
router = APIRouter(include_in_schema=False)
BASE = "/proxy/tools/plugins/{pid}/hub"
READ, ACT, TELEMETRY = "perf.read", "perf.act", "telemetry.read"
SERIES_WINDOWS = ("10m", "life")
def _gate(request: Request, pid: str, cap: str, *, handler_only: bool = False):
"""(deps, None) for the owner's active plugin holding ``cap`` (its own
handler's token when ``handler_only``), else (None, a refusal)."""
who, err = _who(request, pid)
if err:
return None, err
if handler_only and who.handler != pid:
return None, _refuse(403, f"{cap} is only available to the plugin's own handlers",
"handler_only")
if not who.is_owner:
return None, _refuse(403, f"{cap} is owner-only", "capability")
deps = request.app.state.ai
_, rec, _, _, err = _active_plugin(deps, who, pid)
if err:
return None, err
if cap not in (rec["manifest"].get("capabilities") or []):
return None, _refuse(403, f"plugin lacks {cap} capability", "capability")
return deps, None
def _body_of(out: Any) -> Any:
"""A route's answer as plain JSON data (``@_json_in_worker`` routes hand
back a ready ``JSONResponse``)."""
if isinstance(out, JSONResponse):
import json
return json.loads(out.body)
return out
async def _run(fn, *args):
"""Run a sync perf view off the loop; its ``HTTPException`` (a bad range)
becomes the bridges' refusal shape."""
try:
return JSONResponse(_body_of(await run_in_threadpool(fn, *args)))
except HTTPException as e:
d = e.detail if isinstance(e.detail, str) else str(e.detail)
return _refuse(e.status_code, d[:300], "bad_request")
def guest_names(deps) -> dict[str, str]:
"""uid → display name of every guest (the dashboards' pills)."""
out: dict[str, str] = {}
try:
for u in deps.users.all() or ():
uid = u.get("id")
if uid:
out[uid] = u.get("name") or uid
except Exception: # noqa: BLE001 — names are a nicety
pass
return out
def with_scope_meta(deps, out: Any) -> Any:
"""``out`` plus the scope switch's ``profiles`` and the ``guestNames``."""
from plugins.footprintdata import profiles
out = _body_of(out)
if isinstance(out, dict):
out = {**out, "profiles": profiles(deps), "guestNames": guest_names(deps)}
return out
# ── perf.read ────────────────────────────────────────────────────────────────
@router.get(BASE + "/perf/live")
async def perf_live(pid: str, request: Request, account: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import views
from perf.scope import Scope
return await _run(lambda: with_scope_meta(deps, views.live(deps, Scope(deps, account or None))))
@router.get(BASE + "/perf/history")
async def perf_history(pid: str, request: Request, range: str = "24h", runner: str = "",
account: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import routes
return await _run(routes.perf_history, deps, None, range, runner or None, account or None)
@router.get(BASE + "/perf/conversations")
async def perf_conversations(pid: str, request: Request, range: str = "7d", account: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import routes
return await _run(routes.perf_conversations, deps, None, range, account or None)
@router.get(BASE + "/perf/commands")
async def perf_commands(pid: str, request: Request, range: str = "7d", kind: str = "tool",
account: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import routes
return await _run(routes.perf_commands, deps, None, range, kind, account or None)
def conversation_payload(deps, sid: str, series: str = "") -> dict:
"""One conversation's numbers and the series windows asked for."""
from perf import conversation as conv_view
wants = [w for w in dict.fromkeys(x.strip() for x in (series or "").split(","))
if w in SERIES_WINDOWS]
return {"sessionId": sid, "perf": conv_view.conversation(deps, sid),
"series": {w: conv_view.series(deps, sid, w) for w in wants}}
@router.get(BASE + "/perf/conversation/{sid}")
async def perf_conversation(pid: str, sid: str, request: Request, series: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
return await _run(conversation_payload, deps, sid, series)
@router.get(BASE + "/perf/conversation/{sid}/storage")
async def perf_conversation_storage(pid: str, sid: str, request: Request):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import storage_routes
return await _run(storage_routes.perf_conversation_storage, deps, None, sid)
@router.get(BASE + "/perf/storage")
async def perf_storage(pid: str, request: Request, account: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import storage_routes
return await _run(lambda: with_scope_meta(
deps, storage_routes.perf_storage(deps, None, account or None)))
@router.get(BASE + "/perf/storage/history")
async def perf_storage_history(pid: str, request: Request, runner: str = "lab", mount: str = "/",
range: str = "7d"):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import storage_routes
return await _run(storage_routes.perf_storage_history, deps, None, runner, mount, range)
@router.get(BASE + "/perf/storage/writers")
async def perf_storage_writers(pid: str, request: Request, range: str = "7d", account: str = ""):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import storage_routes
return await _run(storage_routes.perf_storage_writers, deps, None, range, account or None)
@router.get(BASE + "/perf/storage/config")
async def perf_storage_config(pid: str, request: Request, runner: str = "lab"):
deps, err = _gate(request, pid, READ)
if err:
return err
from perf import storage_routes
return await _run(storage_routes.perf_storage_config, deps, None, runner)
@router.get(BASE + "/perf/settings")
async def perf_settings(pid: str, request: Request):
deps, err = _gate(request, pid, READ)
if err:
return err
return await _run(deps.perf_settings.get)
# ── telemetry.read: the hub's own performance ────────────────────────────────
@router.get(BASE + "/telemetry/hub")
async def telemetry_hub(pid: str, request: Request, range: str = "24h"):
deps, err = _gate(request, pid, TELEMETRY)
if err:
return err
from telemetry import views
if range not in views.HUB_RANGES:
return _refuse(400, f"range must be one of {', '.join(views.HUB_RANGES)}", "bad_request")
return await _run(views.hub, deps, range)
# ── perf.act ─────────────────────────────────────────────────────────────────
async def _json(request: Request) -> dict | None:
try:
body = await request.json()
except Exception: # noqa: BLE001
return None
return body if isinstance(body, dict) else None
def _model(cls, body: dict | None):
"""``body`` validated as the twin route's pydantic body, else None."""
if body is None:
return None
try:
return cls(**body)
except Exception: # noqa: BLE001 — pydantic's ValidationError and friends
return None
async def _act(request: Request, pid: str, cls, fn):
deps, err = _gate(request, pid, ACT, handler_only=True)
if err:
return err
body = _model(cls, await _json(request)) if cls else await _json(request)
if body is None:
return _refuse(400, "a JSON object body, please (see the /api/perf twin route)",
"bad_request")
return await _run(fn, deps, None, body)
@router.post(BASE + "/perf/kill")
async def perf_kill(pid: str, request: Request):
from perf import routes
return await _act(request, pid, routes.KillBody, routes.perf_kill)
@router.post(BASE + "/perf/keep")
async def perf_keep(pid: str, request: Request):
from perf import routes
return await _act(request, pid, routes.KeepBody, routes.perf_keep)
@router.post(BASE + "/perf/settings")
async def perf_settings_set(pid: str, request: Request):
from perf import routes
return await _act(request, pid, None, routes.perf_settings_put)
@router.post(BASE + "/perf/storage/rm")
async def perf_storage_rm(pid: str, request: Request):
from perf import storage_routes
return await _act(request, pid, storage_routes.RemoveBody, storage_routes.perf_storage_rm)
@router.post(BASE + "/perf/storage/scan")
async def perf_storage_scan(pid: str, request: Request):
from perf import storage_routes
return await _act(request, pid, storage_routes.ScanBody, storage_routes.perf_storage_scan)
@router.post(BASE + "/perf/storage/config")
async def perf_storage_config_set(pid: str, request: Request):
from perf import storage_routes
return await _act(request, pid, storage_routes.ConfigBody,
storage_routes.perf_storage_config_set)