Files
gabrielvidalandClaude Opus 5.5 b42063f3a1 refactor(deploy): drop the core deploy banner — the blue-green-deploy plugin's app.banner replaces it
- delete backend/deploy_status.py (DeployWatcher's 1 s file poll), GET
  /api/deploy-status, the DeployStep/DeployStatus schemas, the authz/usage
  entries and guests._deploying (guest-job delivery now waits on
  banner.is_maintenance alone)
- _attach_conversation moves to plugins/routes.py (only /api/app-banner uses
  it); its test becomes test_banner_conversation.py
- delete DeployBanner.tsx, fetchDeployStatus/useDeployStatus, the SSE
  `deploy` handler and the French strings only it used; the mock seeds its
  mid-flight deploy as an app.banner instead
- useAppBanner polls while a banner shows (6 s done/failed, 1 min running),
  so a provider's expired snapshot goes away without a webhook

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

187 lines
6.4 KiB
Python

"""The owner's floating status banner, from a live plugin
(``provides: {"app.banner": "<action>"}``).
A plugin (``blue-green-deploy`` for the hub's own deploys; later backups,
container updates…) answers what the host draws as a generic draggable corner
banner (``frontend/src/technical/StatusBanner.tsx``):
{"active": bool, "title", "label", "status": "running"|"done"|"failed"|"info",
"phaseNum", "totalPhases", "phase", "steps": [{"n", "label", "state"?}],
"startedAt", "updatedAt", "sessionId"?, "maintenance"?: bool}
Owner only: the action runs as the owner and ``GET /api/app-banner`` is
``lab.read`` (never a guest's). The answer is cached :data:`TTL_SECS`;
:func:`invalidate` drops it — called when the providing plugin's webhook or
action runs (:func:`touched`, which also publishes SSE ``{"type": "banner"}``).
:func:`is_maintenance` is what pauses guest-job push delivery
(``cron/guests.py``) while a provider says a maintenance window is on.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Any
from plugins.store import OWNER_UID
log = logging.getLogger(__name__)
PROVIDES = "app.banner"
TTL_SECS = 5.0
_STATUSES = frozenset({"running", "done", "failed", "info"})
_STEP_STATES = frozenset({"pending", "active", "done", "failed"})
_lock = threading.Lock()
_cache: tuple[float, dict[str, Any] | None] | None = None
def invalidate() -> None:
global _cache
with _lock:
_cache = None
def provides_banner(rec: dict[str, Any] | None) -> bool:
return PROVIDES in (((rec or {}).get("manifest") or {}).get("provides") or {})
def touched(deps, rec: dict[str, Any] | None) -> None:
"""The plugin ``rec`` just ran a webhook or an action: when it provides
``app.banner``, drop the cache and tell the app to refetch."""
if not provides_banner(rec):
return
invalidate()
try:
deps.hub.publish({"type": "banner"})
except Exception: # noqa: BLE001 — no hub (tests)
pass
def _provider(deps) -> tuple[dict[str, Any], str] | None:
from plugins.waiting import _providers_for
try:
found = _providers_for(deps, OWNER_UID, PROVIDES)
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
return None
for rec, _grant in found:
mf = rec.get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
if act in (mf.get("actions") or {}):
return rec, act
return None
def has_provider(deps) -> bool:
return _provider(deps) is not None
def _int(v: Any, default: int = 0) -> int:
try:
return int(v)
except (TypeError, ValueError):
return default
def _str(v: Any, n: int = 200) -> str | None:
return str(v)[:n] if isinstance(v, (str, int, float)) and str(v) else None
def _steps(raw: Any, phase_num: int, status: str) -> list[dict[str, Any]]:
"""Each step with a ``state`` — the plugin's own when valid, else derived
from ``phaseNum`` + ``status``: before it done, at it active (failed when
the job failed), after it pending; all done once the job is."""
out: list[dict[str, Any]] = []
for i, s in enumerate(raw if isinstance(raw, list) else []):
if not isinstance(s, dict):
continue
n = _int(s.get("n"), i + 1)
state = s.get("state")
if state not in _STEP_STATES:
if status == "done":
state = "done"
elif status == "failed":
state = "done" if n < phase_num else ("failed" if n == phase_num else "pending")
else:
state = "done" if n < phase_num else ("active" if n == phase_num else "pending")
out.append({"n": n, "label": str(s.get("label") or "")[:120], "state": state})
if len(out) >= 24:
break
return out
def normalize(raw: Any) -> dict[str, Any] | None:
"""The provider's answer as ``BannerStatus``, or ``None`` when it has
nothing to show."""
if not isinstance(raw, dict):
return None
if isinstance(raw.get("banner"), dict): # {"banner": {...}} is accepted too
raw = raw["banner"]
if raw.get("active") is None and not raw.get("status"):
return None
status = raw.get("status") if raw.get("status") in _STATUSES else "info"
phase_num = _int(raw.get("phaseNum"))
steps = _steps(raw.get("steps"), phase_num, status)
return {
"active": bool(raw.get("active", True)),
"title": _str(raw.get("title"), 120),
"label": _str(raw.get("label"), 120),
"status": status,
"phaseNum": phase_num,
"totalPhases": _int(raw.get("totalPhases"), len(steps)),
"phase": _str(raw.get("phase"), 300),
"steps": steps,
"startedAt": _int(raw.get("startedAt")) or None,
"updatedAt": _int(raw.get("updatedAt")) or None,
"sessionId": _str(raw.get("sessionId"), 80),
"conversationId": None,
"convTitle": _str(raw.get("convTitle"), 200),
"convUrl": None,
"maintenance": bool(raw.get("maintenance")),
}
def _fetch(deps) -> dict[str, Any] | None:
hit = _provider(deps)
if hit is None:
return None
rec, action = hit
from plugins.runner import run_script
act = (rec.get("manifest") or {}).get("actions", {}).get(action) or {}
try:
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
payload={"trigger": "banner"},
timeout_sec=min(10, int(act.get("timeoutSec") or 10)))
except Exception as e: # noqa: BLE001 — a broken plugin never breaks the hub
log.warning("app.banner via %s failed: %s", rec.get("id"), e)
return None
return normalize(res)
def status(deps) -> dict[str, Any] | None:
"""The cached banner (a copy), or ``None``."""
global _cache
now = time.monotonic()
with _lock:
c = _cache
if c is not None and now - c[0] < TTL_SECS:
return dict(c[1]) if c[1] else None
snap = _fetch(deps)
with _lock:
_cache = (time.monotonic(), snap)
return dict(snap) if snap else None
def is_maintenance(deps) -> bool:
"""A provider says a maintenance window is on (``maintenance: true``) or
its job is still running."""
if not has_provider(deps):
return False
snap = status(deps)
return bool(snap and snap.get("active")
and (snap.get("maintenance") or snap.get("status") == "running"))