# -*- coding: utf-8 -*- """X2 extension WebSocket hub — push jobs to online Chrome helpers.""" from __future__ import annotations import asyncio import json import logging from dataclasses import dataclass from typing import Any, Optional from fastapi import WebSocket log = logging.getLogger("x2_ws") @dataclass class ExtClient: ws: WebSocket agent_id: str label: str = "dylive Helper" busy: bool = False connected_at: float = 0.0 class ExtensionHub: def __init__(self) -> None: self._clients: list[ExtClient] = [] self._lock = asyncio.Lock() @property def online_count(self) -> int: return len(self._clients) async def register(self, client: ExtClient) -> None: async with self._lock: # drop dead duplicates for same agent (single helper expected) stale = [c for c in self._clients if c.agent_id == client.agent_id] self._clients = [c for c in self._clients if c.agent_id != client.agent_id] self._clients.append(client) for old in stale: try: await old.ws.close(code=4000) except Exception: pass log.info("x2 ws register agent=%s total=%s", client.agent_id, len(self._clients)) async def unregister(self, client: ExtClient) -> None: async with self._lock: self._clients = [c for c in self._clients if c is not client] log.info("x2 ws unregister agent=%s total=%s", client.agent_id, len(self._clients)) async def set_busy(self, client: ExtClient, busy: bool) -> None: client.busy = bool(busy) async def send_json(self, client: ExtClient, payload: dict[str, Any]) -> bool: try: await client.ws.send_text(json.dumps(payload, ensure_ascii=False, default=str)) return True except Exception as exc: log.warning("x2 ws send fail agent=%s: %s", client.agent_id, exc) return False async def broadcast(self, payload: dict[str, Any], *, agent_id: str = "") -> int: async with self._lock: targets = list(self._clients) if agent_id: targets = [c for c in targets if c.agent_id == agent_id] n = 0 for c in targets: if await self.send_json(c, payload): n += 1 return n async def notify_cancel(self, job_id: str, *, agent_id: str = "") -> None: jid = str(job_id or "").strip() if not jid: return await self.broadcast({"type": "job.cancel", "ids": [jid]}, agent_id=agent_id) async def dispatch_queued(self) -> int: """Claim queued jobs and push to idle websocket clients. Returns jobs sent.""" from . import x2_db sent = 0 async with self._lock: idle = [c for c in self._clients if not c.busy] for client in idle: # claim in threadpool via sync db loop = asyncio.get_running_loop() job = await loop.run_in_executor(None, x2_db.claim_next_job, client.agent_id) if not job: break client.busy = True ok = await self.send_json(client, {"type": "job.exec", "job": job}) if ok: sent += 1 else: client.busy = False # best-effort: leave job running in DB; extension reconnect may not re-claim return sent hub = ExtensionHub()