Callers parked on the per-person lock behind a slow provider run, each holding a worker thread, while the ask-form provider's script called back into the hub for a thread of its own: the pool filled up (2026-11-27). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
273 lines
11 KiB
Python
273 lines
11 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 re
|
|
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"
|
|
# A push id as hub/notify mints one for a push with buttons.
|
|
_NOTIFY_ID = re.compile(r"ntf_[0-9a-f]{12}")
|
|
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
|
|
# How long a call waits for the same person's run already going before it
|
|
# answers with the previous result instead (``waiting_for``).
|
|
WAIT_FOR_RUN_SECS = 1.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]
|
|
# The plugin's push this question is (hub/notify with ``actions``: auto-
|
|
# ship's Merge & deploy): the card's buttons answer that push
|
|
# (/api/notify/{id}/action, owner only) — the tap the phone would send.
|
|
nid = str(raw.get("notifyId") or "").strip()
|
|
if is_owner and _NOTIFY_ID.fullmatch(nid):
|
|
entry["notifyId"] = nid
|
|
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()
|
|
last = _waiting_last.get(uid)
|
|
# Wait for the run that is going only briefly when there is an earlier
|
|
# answer to fall back on: each waiter holds one of the 40 pool threads,
|
|
# and a provider's script calls back into this hub (ask-form's reads
|
|
# its forms through the bridge) — 2026-11-27, waiters parked behind a
|
|
# slow run filled the pool and every request in the app waited 30 s.
|
|
if not lk.acquire(timeout=WAIT_FOR_RUN_SECS if last is not None else -1):
|
|
with _lock:
|
|
last = _waiting_last.get(uid, last)
|
|
return [dict(it) for it in last[1]]
|
|
try:
|
|
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]
|
|
finally:
|
|
lk.release()
|
|
|
|
|
|
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
|