Spaces:
Paused
Paused
File size: 8,191 Bytes
042f4ed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | # Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""Live activity feed via Server-Sent Events."""
import asyncio
import json
import logging
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from sqlalchemy import desc
from sqlalchemy.future import select
from uuid import UUID
from src.core.auth import get_current_user, resolve_db_user_id
from src.database import async_session
from sqlalchemy.orm import selectinload
from sqlalchemy import or_
from src.models.account import Account
from src.models.agent import Agent
from src.models.task import Task
from src.models.transaction import Transaction
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/activity", tags=["activity"])
SSE_POLL_INTERVAL = 2 # seconds
SSE_MAX_DURATION = 300 # 5 minutes
@router.get("/stream")
async def activity_stream(
current_user: dict = Depends(get_current_user),
user_id: UUID = Depends(resolve_db_user_id),
) -> StreamingResponse:
"""Stream platform activity events via SSE.
Requires Bearer token in the Authorization header.
For browser EventSource clients that cannot set headers,
use a polyfill library like event-source-polyfill or
fetch-event-source which supports custom headers.
Emits events for new tasks, completed tasks, failed tasks,
new agent registrations, and credit transactions.
"""
async def event_stream():
last_seen: dict[str, datetime] = {}
elapsed = 0
lookback = timedelta(minutes=5)
while elapsed < SSE_MAX_DURATION:
try:
async with async_session() as db:
now = datetime.now(timezone.utc)
since = now - lookback
# New tasks (scoped to current user)
task_since = last_seen.get("task", since)
stmt = (
select(Task)
.options(selectinload(Task.provider_agent))
.where(Task.created_at > task_since)
.where(Task.creator_user_id == user_id)
.order_by(desc(Task.created_at))
.limit(10)
)
result = await db.execute(stmt)
tasks = result.scalars().all()
for task in reversed(tasks):
status = task.status.value if hasattr(task.status, "value") else task.status
if status == "completed":
event_type = "task_completed"
elif status == "failed":
event_type = "task_failed"
else:
event_type = "task_created"
# Extract first user message as preview
msg_preview = None
if task.messages:
for m in task.messages:
msg = m if isinstance(m, dict) else m.__dict__
if msg.get("role") == "user":
parts = msg.get("parts", [])
if parts:
p = parts[0] if isinstance(parts[0], dict) else parts[0].__dict__
text = p.get("content", "")
if text:
msg_preview = text[:100]
break
agent_name = task.provider_agent.name if task.provider_agent else None
event = {
"type": event_type,
"task_id": str(task.id),
"status": status,
"provider_agent_id": str(task.provider_agent_id) if task.provider_agent_id else None,
"agent_name": agent_name,
"message_preview": msg_preview,
"created_at": task.created_at.isoformat(),
}
yield f"event: {event_type}\ndata: {json.dumps(event)}\n\n"
if not last_seen.get("task") or task.created_at > last_seen["task"]:
last_seen["task"] = task.created_at
# New agents
agent_since = last_seen.get("agent", since)
stmt = (
select(Agent)
.where(Agent.created_at > agent_since)
.order_by(desc(Agent.created_at))
.limit(5)
)
result = await db.execute(stmt)
agents = result.scalars().all()
for agent in reversed(agents):
event = {
"type": "agent_registered",
"agent_id": str(agent.id),
"name": agent.name,
"category": agent.category,
"created_at": agent.created_at.isoformat(),
}
yield f"event: agent_registered\ndata: {json.dumps(event)}\n\n"
if not last_seen.get("agent") or agent.created_at > last_seen["agent"]:
last_seen["agent"] = agent.created_at
# Credit transactions (scoped to current user via account)
tx_since = last_seen.get("tx", since)
acct_result = await db.execute(
select(Account.id).where(Account.owner_id == user_id)
)
account_id = acct_result.scalar_one_or_none()
stmt = (
select(Transaction)
.where(Transaction.created_at > tx_since)
.where(
or_(
Transaction.from_account_id == account_id,
Transaction.to_account_id == account_id,
)
)
.order_by(desc(Transaction.created_at))
.limit(5)
) if account_id else None
txns = []
if stmt is not None:
result = await db.execute(stmt)
txns = result.scalars().all()
for tx in reversed(txns):
tx_type_val = tx.type.value if hasattr(tx.type, "value") else tx.type
event = {
"type": "credit_transaction",
"transaction_id": str(tx.id),
"tx_type": tx_type_val,
"amount": str(tx.amount),
"created_at": tx.created_at.isoformat(),
}
yield f"event: credit_transaction\ndata: {json.dumps(event)}\n\n"
if not last_seen.get("tx") or tx.created_at > last_seen["tx"]:
last_seen["tx"] = tx.created_at
except Exception:
logger.exception("Activity stream error")
yield f"event: error\ndata: {json.dumps({'message': 'Internal error'})}\n\n"
return
# After first poll, only look at new data
lookback = timedelta(seconds=SSE_POLL_INTERVAL + 1)
await asyncio.sleep(SSE_POLL_INTERVAL)
elapsed += SSE_POLL_INTERVAL
yield f"event: timeout\ndata: {json.dumps({'message': 'Stream max duration reached'})}\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
|