Speed - seed_registry.effective() cached the "any provider plugin active?" check on the plugin store's version: it deep-copied all 46 manifests on every price lookup (9.4 ms → 8 µs per rates_for) — half the hub's CPU, and what made Graph / Goals / Plan usage bridges take 17–180 s. - GET /api/plugins/ui: the slim list every page reads (UI descriptors, provides, each active plugin's glyph + config), a few KB instead of the 253 KB full list, which is now for Settings → Plugins only. - Identical readOnly actions in flight share one handler run (plugins/singleflight.py). - composer.shortcuts / composer.mode are stale-while-revalidate (plugins/swr.py); inbox.waiting stays fresh but concurrent calls share one run, auto-archive reuses a ≤ 30 s answer; provider lookups copy only the matching records (store.active_providing / active_ids). - aiAgentPlugin.query(): host-kept reads — the last answer at once (own IndexedDB store, not busted per deploy), then the fresh one; learned preload starts a page's reads as its route mounts; UI documents kept the same way. UI - The page's subtitle, buttons and a refresh that spins while its reads run live in the app's header (setHeader / onHeaderAction / onRefresh); the frame is borderless across the content area; a skeleton (after 150 ms) holds its place until the frame painted, then it fades in. - A UI kit (aia-* classes, the app's font and tokens) injected into every plugin frame. - Dashboards / Files nav: plugin pages in the same rearrangeable list, with the plugin's description as subtitle. - Mock: a demo plugin page (/plugins/demo/board?mock=1). Docs: docs/plugins.md → "Pages that feel native: reads, header, kit". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
249 lines
9.4 KiB
Python
249 lines
9.4 KiB
Python
"""Host-level plugin providers for:
|
|
|
|
* ``provides: {"inbox.waiting": "<action>"}`` — pending questions surfaced in
|
|
*Waiting for feedback*, *FeedbackBell*, *ConversationWaiting*, and
|
|
*auto-archive* (``GET /api/inbox/waiting``). Enforces ``ownerOnly: true``
|
|
server-side so guests never receive owner-only items.
|
|
* ``provides: {"composer.mode": "<action>"}`` — composer mode descriptors
|
|
(e.g. *New project* toggle / guest picker entry) served at
|
|
``GET /api/plugins/composer-modes``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import threading
|
|
import time
|
|
from typing import Any
|
|
|
|
from plugins.store import OWNER_UID
|
|
from plugins.swr import SWRCache
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
WAITING_PROVIDES = "inbox.waiting"
|
|
MODE_PROVIDES = "composer.mode"
|
|
MODE_TTL_SECS = 30.0
|
|
# A mode past its TTL is still served while the plugin runs again behind it
|
|
# (its quota line may lag a few minutes; a plugin change drops it at once).
|
|
MODE_MAX_STALE_SECS = 600.0
|
|
# Auto-archive's sweep reads the waiting sessions this old at most (the
|
|
# inbox itself always asks the plugins: an answered question must go).
|
|
SESSIONS_MAX_AGE_SECS = 30.0
|
|
|
|
_lock = threading.Lock()
|
|
_mode_cache = SWRCache(MODE_TTL_SECS, MODE_MAX_STALE_SECS, name="composer-modes")
|
|
# uid → (lock held by the one run going, (monotonic, items) of the last run)
|
|
_waiting_locks: dict[str, threading.Lock] = {}
|
|
_waiting_last: dict[str, tuple[float, list[dict[str, Any]]]] = {}
|
|
|
|
|
|
def invalidate(pid: str | None = None) -> None:
|
|
if pid is None:
|
|
_mode_cache.clear()
|
|
else:
|
|
prefix = f":{pid}@"
|
|
_mode_cache.drop(lambda k: prefix in k)
|
|
with _lock:
|
|
_waiting_last.clear()
|
|
|
|
|
|
def _providers_for(deps, uid: str, key: str) -> list[tuple[dict[str, Any], dict[str, Any] | None]]:
|
|
store = getattr(deps, "plugin_store", None)
|
|
if store is None:
|
|
return []
|
|
try:
|
|
out: list[tuple[dict[str, Any], dict[str, Any] | None]] = [
|
|
(rec, None) for rec in store.active_providing(uid, key)]
|
|
except Exception:
|
|
out = []
|
|
seen = {rec["id"] for rec, _ in out}
|
|
if uid != OWNER_UID:
|
|
for rec in store.managed_plugins():
|
|
pid = rec["id"]
|
|
if pid in seen:
|
|
continue
|
|
mf = rec.get("manifest") or {}
|
|
act = (mf.get("provides") or {}).get(key)
|
|
if not (act and act in (mf.get("actions") or {})):
|
|
continue
|
|
grant = store.effective_grant(uid, pid, mf)
|
|
if grant.get("enabled"):
|
|
seen.add(pid)
|
|
out.append((rec, grant))
|
|
return out
|
|
|
|
|
|
def _clean_waiting_item(pid: str, raw: Any, is_owner: bool) -> dict[str, Any] | None:
|
|
if not isinstance(raw, dict):
|
|
return None
|
|
owner_only = bool(raw.get("ownerOnly", False))
|
|
if owner_only and not is_owner:
|
|
return None
|
|
iid = str(raw.get("id") or "").strip()[:120]
|
|
title = str(raw.get("title") or raw.get("question") or "").strip()[:240]
|
|
if not iid or not title:
|
|
return None
|
|
kind = str(raw.get("kind") or "askform")[:32]
|
|
entry: dict[str, Any] = {
|
|
"id": iid,
|
|
"pluginId": pid,
|
|
"kind": kind,
|
|
"title": title,
|
|
"detail": str(raw.get("detail") or raw.get("description") or "")[:400],
|
|
"type": str(raw.get("type") or "ai")[:24],
|
|
"at": str(raw.get("at") or raw.get("createdAt") or "") or None,
|
|
"sessionId": str(raw.get("sessionId") or ""),
|
|
"url": str(raw.get("url") or ""),
|
|
"formId": str(raw.get("formId") or ""),
|
|
"fieldCount": int(raw.get("fieldCount") or 0),
|
|
"ownerOnly": owner_only,
|
|
}
|
|
if isinstance(raw.get("embedOrigins"), list):
|
|
entry["embedOrigins"] = [str(o) for o in raw["embedOrigins"] if isinstance(o, str)]
|
|
if isinstance(raw.get("options"), list):
|
|
entry["options"] = [str(o)[:80] for o in raw["options"] if isinstance(o, str)][:8]
|
|
return entry
|
|
|
|
|
|
def waiting_for(deps, caller) -> list[dict[str, Any]]:
|
|
"""Collect pending inbox waiting items from all active plugins declaring
|
|
``provides.inbox.waiting``. Always asked fresh (an answered question must
|
|
leave the inbox at once), but concurrent calls for one person — the
|
|
badge, the inbox, a second tab — share the run that is going."""
|
|
uid = OWNER_UID if caller.is_owner else caller.id
|
|
with _lock:
|
|
lk = _waiting_locks.setdefault(uid, threading.Lock())
|
|
started = time.monotonic()
|
|
with lk:
|
|
with _lock:
|
|
last = _waiting_last.get(uid)
|
|
if last is not None and last[0] >= started:
|
|
# A run that began after this call arrived just finished: its
|
|
# answer is as fresh as ours would be.
|
|
return [dict(it) for it in last[1]]
|
|
began = time.monotonic()
|
|
items = _collect_waiting(deps, caller, uid)
|
|
with _lock:
|
|
_waiting_last[uid] = (began, items)
|
|
return [dict(it) for it in items]
|
|
|
|
|
|
def _collect_waiting(deps, caller, uid: str) -> list[dict[str, Any]]:
|
|
from plugins.runner import run_script
|
|
out: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
for rec, grant in _providers_for(deps, uid, WAITING_PROVIDES):
|
|
mf = rec["manifest"]
|
|
act = mf["actions"][mf["provides"][WAITING_PROVIDES]]
|
|
try:
|
|
res = run_script(
|
|
deps, deps.plugin_store, uid, rec, act["script"],
|
|
payload={"trigger": WAITING_PROVIDES},
|
|
timeout_sec=min(10, int(act.get("timeoutSec") or 10)),
|
|
grant=grant,
|
|
)
|
|
except Exception as e:
|
|
log.warning("inbox.waiting plugin %s failed: %s", rec.get("id"), e)
|
|
continue
|
|
items = res.get("items") if isinstance(res, dict) else None
|
|
if not isinstance(items, list):
|
|
continue
|
|
for raw in items[:100]:
|
|
cleaned = _clean_waiting_item(rec["id"], raw, caller.is_owner)
|
|
if cleaned and cleaned["id"] not in seen:
|
|
seen.add(cleaned["id"])
|
|
out.append(cleaned)
|
|
out.sort(key=lambda x: x.get("at") or "", reverse=True)
|
|
return out
|
|
|
|
|
|
def waiting_sessions(deps) -> set[str]:
|
|
"""Session ids with an open plugin waiting item (used by auto-archive) —
|
|
the owner's last inbox answer when it is under
|
|
:data:`SESSIONS_MAX_AGE_SECS` old, else a fresh one."""
|
|
from users.caller import OWNER
|
|
with _lock:
|
|
last = _waiting_last.get(OWNER_UID)
|
|
if last is not None and time.monotonic() - last[0] < SESSIONS_MAX_AGE_SECS:
|
|
items = last[1]
|
|
else:
|
|
try:
|
|
items = waiting_for(deps, OWNER)
|
|
except Exception:
|
|
return set()
|
|
return {it["sessionId"] for it in items if it.get("sessionId")}
|
|
|
|
|
|
def _mode_cache_key(uid: str, rec: dict[str, Any], grant: dict[str, Any] | None) -> str:
|
|
cfg = json.dumps({"c": rec.get("config") or {}, "g": (grant or {}).get("config") or {}}, sort_keys=True)
|
|
ch = hashlib.sha256(cfg.encode("utf-8")).hexdigest()[:12]
|
|
return f"{uid}:{rec['id']}@{rec.get('fingerprint') or ''}:{ch}"
|
|
|
|
|
|
def _clean_mode(pid: str, raw: Any) -> dict[str, Any] | None:
|
|
if not isinstance(raw, dict):
|
|
return None
|
|
mid = str(raw.get("id") or pid).strip()[:48]
|
|
label = str(raw.get("label") or "").strip()[:60]
|
|
if not mid or not label:
|
|
return None
|
|
out: dict[str, Any] = {
|
|
"id": mid,
|
|
"pluginId": pid,
|
|
"label": label,
|
|
"icon": str(raw.get("icon") or "FolderPlus")[:48],
|
|
"allowed": bool(raw.get("allowed", True)),
|
|
"reason": str(raw.get("reason") or "") or None,
|
|
"surface": str(raw.get("surface") or "both")[:24], # "toolbar" | "picker" | "both"
|
|
}
|
|
for k in ("placeholder", "hint", "stagingNote", "stagingCwd", "submitAction", "remaining", "bucket", "domain"):
|
|
if k in raw and raw[k] is not None:
|
|
out[k] = raw[k]
|
|
return out
|
|
|
|
|
|
def _run_modes(deps, uid: str, rec: dict[str, Any], grant: dict[str, Any] | None) -> list[dict[str, Any]]:
|
|
from plugins.runner import run_script
|
|
mf = rec["manifest"]
|
|
act = mf["actions"][mf["provides"][MODE_PROVIDES]]
|
|
modes: list[dict[str, Any]] = []
|
|
try:
|
|
res = run_script(
|
|
deps, deps.plugin_store, uid, rec, act["script"],
|
|
payload={"trigger": MODE_PROVIDES},
|
|
timeout_sec=min(10, int(act.get("timeoutSec") or 10)),
|
|
grant=grant,
|
|
)
|
|
raw_modes = res.get("modes") if isinstance(res, dict) else None
|
|
if isinstance(raw_modes, list):
|
|
for m in raw_modes[:8]:
|
|
cm = _clean_mode(rec["id"], m)
|
|
if cm:
|
|
modes.append(cm)
|
|
elif isinstance(res, dict) and res.get("label"):
|
|
cm = _clean_mode(rec["id"], res)
|
|
if cm:
|
|
modes.append(cm)
|
|
except Exception as e:
|
|
log.warning("composer.mode plugin %s failed: %s", rec.get("id"), e)
|
|
return modes
|
|
|
|
|
|
def composer_modes_for(deps, caller) -> list[dict[str, Any]]:
|
|
"""Collect composer mode descriptors from active plugins declaring
|
|
``provides.composer.mode`` (stale-while-revalidate: plugins/swr.py)."""
|
|
uid = OWNER_UID if caller.is_owner else caller.id
|
|
out: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
for rec, grant in _providers_for(deps, uid, MODE_PROVIDES):
|
|
key = _mode_cache_key(uid, rec, grant)
|
|
modes = _mode_cache.get(key, lambda rec=rec, grant=grant: _run_modes(deps, uid, rec, grant))
|
|
for m in modes:
|
|
if m["id"] not in seen:
|
|
seen.add(m["id"])
|
|
out.append(m)
|
|
return out
|