Files
ai-agent/backend/core/routes.py
gabrielvidalandClaude Opus 5.5 0e68e98795 feat(scheduled): Send later leaves the core for the scheduled-conversations plugin
Generic hooks the plugin builds on: the conversations.drawer, composer.send and
app.modal slot places (openModal / modal.setResult / modal.close, ?modal=
links), runs.start taking the composer's whole payload (auto routing,
account, projects, cwd, meta.scheduled) and hub/runs/resolve, a turn's knobs
on conversations.send, push buttons answered as the notify.action event,
hub/changed (SSE plugin-data), hub/title (conversations.title), the
runs.schedule provider behind /api/scheduled, the week's budget and the
stopped-run card, providers in /api/plugins/ui, carryover.scheduled.

backend/scheduled/ and frontend/src/business/scheduled/ are gone.

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

142 lines
5.6 KiB
Python

"""App-level routes: the SSE event stream, live-run progress and health."""
import asyncio
import json
import time
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, StreamingResponse
import schemas
from telemetry import metrics as tm
from core.http import _r
from core.state import State
from runs import genprogress
from users import access
from users.caller import CallerDep
router = APIRouter()
# What a guest's stream carries: the pings about conversations they can see
# (and the cross-cutting ones that only make a client refetch a filtered list).
# (`usage` is a bare ping — new /usage % points — that refetches their own
# gauges, `/api/me/usage`.)
_GUEST_PASS = {"users", "accounts", "whats-new", "usage"}
def _visible_progress(deps, caller, progress: dict) -> dict:
return {sid: p for sid, p in progress.items() if access.visible(deps, caller, sid)}
def _guest_filter(deps, caller):
def flt(ev: dict):
kind = ev.get("type")
if kind in _GUEST_PASS:
return ev
if kind == "transcript":
ids = [i for i in ev.get("ids") or []
if access.visible(deps, caller, i)]
if not ids:
return None
out = {**ev, "ids": ids}
if ev.get("roots"):
out["roots"] = {k: v for k, v in ev["roots"].items() if k in ids}
if ev.get("cards"):
out["cards"] = {k: v for k, v in ev["cards"].items()
if access.visible(deps, caller, k)}
return out
if kind == "meta":
cid = ev.get("id")
return ev if not cid or access.visible(deps, caller, cid) else None
if kind == "drafts":
# their own composer drafts only
return ev if ev.get("user") == caller.id else None
if kind == "short-title":
return ev if access.visible(deps, caller, ev.get("id") or "") else None
if kind in ("form", "askform"):
sid = ev.get("sessionId")
return ev if sid and access.visible(deps, caller, sid) else None
if kind == "gen-progress":
return {**ev, "progress": _visible_progress(deps, caller, ev.get("progress") or {})}
if kind == "notification":
return ev # an id only; the feed it refetches is filtered
if kind == "plugins":
return {"type": "plugins", **({"id": ev["id"]} if ev.get("id") else {})} \
if ev.get("uid") in (None, caller.id) else None
if kind == "plugin-data":
# a plugin's handler wrote its installer's data (hub/changed)
return {"type": "plugin-data", "id": ev.get("id")} \
if ev.get("uid") == caller.id else None
if kind == "workers" and set(ev) == {"type"}:
# A bare "something changed" ping — their computers list
# (/api/me/computers, filtered) refetches on it.
return ev
return None
return flt
# Traefik's `writeTimeout` (600 s) cuts any response that long, SSE included;
# ending the stream ourselves first makes the browser reconnect cleanly with
# `Last-Event-ID`, and the hub replays what it missed in between — no gap,
# no catch-up refetch.
SSE_MAX_S = 540
@router.get("/api/events")
async def events(request: Request, deps: State, caller: CallerDep):
"""Server-Sent Events: ``meta`` / ``transcript`` change pings for the UI.
Every event carries an ``id``; a reconnect with ``Last-Event-ID`` gets the
events published since (the hub keeps a ring of recent ones). When that id
is unknown — too old, or from a previous backend process — the stream
opens with a ``resync`` event, and the client refetches instead."""
flt = None if caller.is_owner else _guest_filter(deps, caller)
loop = asyncio.get_running_loop()
aq = deps.hub.subscribe_async(loop, flt)
last = request.headers.get("last-event-id")
backlog: list[tuple[str, str]] = []
resync = False
if last is not None:
replay = deps.hub.replay_since(last, flt)
if replay is None:
resync = True
else:
backlog = replay
tm.SSE_RESUMES.labels("resync" if resync else "replay").inc()
async def gen():
try:
yield "retry: 1000\n\n"
if resync:
yield f"id: {deps.hub.last_id}\ndata: {json.dumps({'type': 'resync'})}\n\n"
for sq, data in backlog:
yield f"id: {sq}\ndata: {data}\n\n"
deadline = time.monotonic() + SSE_MAX_S
while time.monotonic() < deadline:
try:
sq, data = await asyncio.wait_for(aq.get(), timeout=15.0)
yield f"id: {sq}\ndata: {data}\n\n"
except asyncio.TimeoutError:
yield ": ping\n\n" # keep proxies from closing the stream
finally:
deps.hub.unsubscribe_async(aq)
return StreamingResponse(
gen(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no",
"Connection": "keep-alive"})
@router.get("/api/gen-progress", responses=_r(schemas.GenProgressSnapshot))
def gen_progress(deps: State, caller: CallerDep):
"""Every live local-model run's llm-server reading (``runs/genprogress.py``),
the conversations the caller can see only. The ``gen-progress`` SSE event
carries the same map whenever it moves."""
return {"progress": _visible_progress(deps, caller, genprogress.snapshot())}
@router.get("/api/health")
async def health():
return JSONResponse({"ok": True})