Manifest: four new slot places (home.section, conversation.pinned, conversation.threadFooter, conversation.gizmos); optional ui.slots[] keys label / defaultStashed / vis / events and ui.toolCards[] match.hasField / vis / events, written only when set (approval fingerprints unchanged); provides "home.tiles". Backend: plugins/home_tiles.py + GET /api/plugins/home-tiles (app.read, sanitized arc/burn/stat/sparkline/bar tiles, 5 s cache dropped on plugin mutations); hub bridges hub/usage/home (usage.read) and hub/activity/daily (activity.read); limits/burn payloads factored out of usage/routes.py; HomeTilesResponse schema + regenerated openapi/orval. Frontend: PluginSandboxFrame gains a live update channel (no reload, replayed to late onUpdate), setEmpty / resize(h, w), forwarded SSE events (lib/sseTap) and host RPCs scrollTo / openMediaViewer / openPreview / mediaUrl (host-side fetch → blob URL). PluginSlots: usePluginSlots, SinglePluginSlot (zero-layout empty state, stays mounted), vis gating. Tool cards: hasField, vis, rich init + live update; a call an inThread plugin card claims makes the core widget stand down. Visibility popover: dynamic plugin:<pid>:<key> switches under "Plugins". Details drawer: one HoldEditable card per conversation.details slot with the compact live snapshot, DETAIL_CARD_RENAMES onto the plugin keys and claimed core cards hidden. Home: plugin tiles merged into the usage strip by id, home.section slots. Conversation: pinned / threadFooter / gizmos slots (core PinnedMovies / GenProgressStrip / DeployGizmo yield when claimed), thread bridge + conversation contexts, app-level PluginHostBridges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
234 lines
8.8 KiB
Python
234 lines
8.8 KiB
Python
"""Declarative home usage tiles contributed by live plugins
|
|
(``provides: {"home.tiles": "<action>"}``) — ``GET /api/plugins/home-tiles``.
|
|
|
|
Each enabled, approved plugin active for the caller that declares
|
|
``provides.home.tiles`` runs its action with::
|
|
|
|
{"trigger": "home.tiles", "scope", "profileScope", "composerHarness", "tzOffset"}
|
|
|
|
and answers ``{"tiles": [...]}``. Tiles are pure data the home strip
|
|
(``ProfileUsageCard``) draws natively — ``arc`` (an ``ArcGauge``), ``burn``
|
|
(``BurnGauge``), ``stat``, ``sparkline`` and ``bar`` — so nothing here is a
|
|
frame. Every field is sanitized: unknown kinds and keys are dropped, numbers
|
|
are clamped, strings cut, ``to`` must be an app path. A tile's ``id`` is the
|
|
key its saved ``listOrders["home-usage:<profile>"]`` slot uses, so the ids of
|
|
the core tiles a plugin takes over (``h5:<acct>``, ``week:<acct>``, ``spark``,
|
|
``today``…) must stay the same; the first tile of an id wins.
|
|
|
|
Answers are cached 5 s per caller + plugin fingerprint + config + query (+ the
|
|
summaries version, so a transcript write shows at once), and dropped on any
|
|
plugin mutation (:func:`invalidate`).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import math
|
|
import re
|
|
import threading
|
|
import time
|
|
from typing import Any
|
|
|
|
from plugins.store import OWNER_UID
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
PROVIDES = "home.tiles"
|
|
TTL_SECS = 5.0
|
|
MAX_TILES = 24
|
|
KINDS = frozenset({"arc", "burn", "stat", "sparkline", "bar"})
|
|
|
|
_ID_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_:.@-]{0,79}$")
|
|
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
|
|
_lock = threading.Lock()
|
|
_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}
|
|
|
|
|
|
def invalidate(pid: str | None = None) -> None:
|
|
"""Drop cached tiles (all, or for one plugin id)."""
|
|
with _lock:
|
|
if pid is None:
|
|
_cache.clear()
|
|
else:
|
|
prefix = f":{pid}@"
|
|
for k in [k for k in _cache if prefix in k]:
|
|
_cache.pop(k, None)
|
|
|
|
|
|
# ── sanitizing ───────────────────────────────────────────────────────────────
|
|
|
|
def _num(v: Any, lo: float = -1e12, hi: float = 1e12) -> float | None:
|
|
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
|
return None
|
|
f = float(v)
|
|
if math.isnan(f) or math.isinf(f):
|
|
return None
|
|
return max(lo, min(hi, f))
|
|
|
|
|
|
def _str(v: Any, n: int) -> str | None:
|
|
if not isinstance(v, str):
|
|
return None
|
|
s = v.strip()
|
|
return s[:n] if s else None
|
|
|
|
|
|
def _app_path(v: Any) -> str | None:
|
|
if not isinstance(v, str):
|
|
return None
|
|
p = v.strip()
|
|
if not p.startswith("/") or p.startswith("//") or "\\" in p or len(p) > 300:
|
|
return None
|
|
if re.search(r"[\x00-\x1f]", p):
|
|
return None
|
|
return p
|
|
|
|
|
|
def _put(out: dict[str, Any], key: str, val: Any) -> None:
|
|
if val is not None:
|
|
out[key] = val
|
|
|
|
|
|
def clean_tile(pid: str, raw: Any) -> dict[str, Any] | None:
|
|
"""One tile, sanitized, or None when it isn't a valid tile."""
|
|
if not isinstance(raw, dict):
|
|
return None
|
|
tid = raw.get("id")
|
|
kind = raw.get("kind")
|
|
if not isinstance(tid, str) or not _ID_RE.match(tid) or kind not in KINDS:
|
|
return None
|
|
label = _str(raw.get("label"), 48)
|
|
if not label:
|
|
return None
|
|
t: dict[str, Any] = {"id": tid, "pluginId": pid, "kind": kind, "label": label,
|
|
"fixed": bool(raw.get("fixed", False)),
|
|
"defaultBench": bool(raw.get("defaultBench", False)),
|
|
"stale": bool(raw.get("stale", False))}
|
|
_put(t, "to", _app_path(raw.get("to")))
|
|
_put(t, "title", _str(raw.get("title"), 120))
|
|
_put(t, "sub", _str(raw.get("sub"), 80))
|
|
if kind == "arc":
|
|
t["pct"] = _num(raw.get("pct"), 0, 1000)
|
|
_put(t, "resetsAt", _num(raw.get("resetsAt"), 0, 1e11))
|
|
_put(t, "goal", _num(raw.get("goal"), 0, 1000))
|
|
elif kind == "burn":
|
|
usd = _num(raw.get("usdPerHour"), 0, 1e6)
|
|
if usd is None:
|
|
return None
|
|
t["usdPerHour"] = usd
|
|
for k, hi in (("pctPerHour", 1000), ("neededUsdPerHour", 1e6),
|
|
("neededPctPerHour", 1000), ("projected", 10000), ("goal", 1000)):
|
|
_put(t, k, _num(raw.get(k), 0 if k != "projected" else -10000, hi))
|
|
wm = _num(raw.get("windowMinutes"), 1, 10080)
|
|
_put(t, "windowMinutes", int(wm) if wm is not None else None)
|
|
elif kind == "stat":
|
|
value = _str(raw.get("value"), 40)
|
|
usd = _num(raw.get("valueUsd"), -1e9, 1e9)
|
|
if value is None and usd is None:
|
|
return None
|
|
_put(t, "value", value)
|
|
_put(t, "valueUsd", usd)
|
|
_put(t, "subUsdPerDay", _num(raw.get("subUsdPerDay"), -1e9, 1e9))
|
|
elif kind == "sparkline":
|
|
days = raw.get("days")
|
|
if not isinstance(days, list):
|
|
return None
|
|
pts: list[dict[str, Any]] = []
|
|
for d in days[:120]:
|
|
if not isinstance(d, dict):
|
|
continue
|
|
date = d.get("date")
|
|
val = _num(d.get("value"), -1e12, 1e12)
|
|
if not isinstance(date, str) or not _DATE_RE.match(date) or val is None:
|
|
continue
|
|
pt: dict[str, Any] = {"date": date, "value": val}
|
|
_put(pt, "label", _str(d.get("label"), 40))
|
|
pts.append(pt)
|
|
t["days"] = pts
|
|
t["isCost"] = bool(raw.get("isCost", False))
|
|
elif kind == "bar":
|
|
value = _num(raw.get("value"), 0, 1e12)
|
|
mx = _num(raw.get("max"), 0, 1e12)
|
|
text = _str(raw.get("text"), 60)
|
|
if value is None or mx is None or text is None:
|
|
return None
|
|
t.update({"value": value, "max": mx, "text": text, "over": bool(raw.get("over", False))})
|
|
return t
|
|
|
|
|
|
def clean_tiles(pid: str, raw: Any) -> list[dict[str, Any]]:
|
|
items = raw.get("tiles") if isinstance(raw, dict) else None
|
|
if not isinstance(items, list):
|
|
return []
|
|
out: list[dict[str, Any]] = []
|
|
for it in items[:MAX_TILES]:
|
|
t = clean_tile(pid, it)
|
|
if t:
|
|
out.append(t)
|
|
return out
|
|
|
|
|
|
# ── collecting ───────────────────────────────────────────────────────────────
|
|
|
|
def _cache_key(uid: str, rec: dict[str, Any], grant: dict[str, Any] | None, q: dict, ver: Any) -> str:
|
|
cfg = json.dumps({"c": rec.get("config") or {}, "g": (grant or {}).get("config") or {},
|
|
"q": q, "v": ver}, sort_keys=True, default=str)
|
|
ch = hashlib.sha256(cfg.encode("utf-8")).hexdigest()[:16]
|
|
return f"{uid}:{rec['id']}@{rec.get('fingerprint') or ''}:{ch}"
|
|
|
|
|
|
def _run_one(deps, uid: str, rec: dict[str, Any], grant: dict[str, Any] | None,
|
|
payload: dict) -> list[dict[str, Any]]:
|
|
from plugins.runner import run_script
|
|
mf = rec["manifest"]
|
|
act = mf["actions"][mf["provides"][PROVIDES]]
|
|
try:
|
|
raw = run_script(
|
|
deps, deps.plugin_store, uid, rec, act["script"],
|
|
payload=payload,
|
|
timeout_sec=min(10, int(act.get("timeoutSec") or 10)),
|
|
grant=grant,
|
|
)
|
|
except Exception as e: # noqa: BLE001 — one broken plugin never hides the rest
|
|
log.warning("home.tiles plugin %s failed: %s", rec.get("id"), e)
|
|
return []
|
|
return clean_tiles(rec["id"], raw)
|
|
|
|
|
|
def tiles_for(deps, caller, scope: str = "all", profile_scope: str = "personal",
|
|
composer_harness: str = "", tz_offset: int = 0) -> list[dict[str, Any]]:
|
|
"""Every plugin tile active for ``caller``, deduplicated by ``id`` (the
|
|
first plugin, in id order, wins)."""
|
|
from plugins.waiting import _providers_for
|
|
uid = OWNER_UID if caller.is_owner else caller.id
|
|
q = {"scope": str(scope or "all")[:200], "profileScope": str(profile_scope or "")[:80],
|
|
"composerHarness": str(composer_harness or "")[:40],
|
|
"tzOffset": max(-960, min(960, int(tz_offset or 0)))}
|
|
payload = {"trigger": PROVIDES, **q}
|
|
store = getattr(deps, "store", None)
|
|
ver = getattr(store, "summaries_version", None)
|
|
out: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
now = time.monotonic()
|
|
for rec, grant in _providers_for(deps, uid, PROVIDES):
|
|
key = _cache_key(uid, rec, grant, q, ver)
|
|
with _lock:
|
|
hit = _cache.get(key)
|
|
if len(_cache) > 512:
|
|
for k in [k for k, (at, _) in _cache.items() if now - at >= TTL_SECS]:
|
|
_cache.pop(k, None)
|
|
if hit is not None and now - hit[0] < TTL_SECS:
|
|
items = hit[1]
|
|
else:
|
|
items = _run_one(deps, uid, rec, grant, payload)
|
|
with _lock:
|
|
_cache[key] = (now, items)
|
|
for t in items:
|
|
if t["id"] not in seen:
|
|
seen.add(t["id"])
|
|
out.append(t)
|
|
return out
|