- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage) - hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench) - android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive - protocol: architecture, MCP schema, and WebSocket protocol specs
278 lines
10 KiB
Python
278 lines
10 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import uuid
|
|
from typing import Any
|
|
|
|
import httpx
|
|
from fastapi import WebSocket
|
|
|
|
from app.storage.db import PulseWallDB, now_ms
|
|
|
|
|
|
class DeviceBridgeManager:
|
|
"""Manages active Android WebSocket sessions, pending render futures, and reverse event fan-out."""
|
|
|
|
def __init__(self, db: PulseWallDB) -> None:
|
|
self.db = db
|
|
self._connections: dict[str, WebSocket] = {}
|
|
self._pending_renders: dict[str, asyncio.Future[dict[str, Any]]] = {}
|
|
self._sse_subscribers: set[asyncio.Queue[dict[str, Any]]] = set()
|
|
|
|
def is_connected(self, device_id: str) -> bool:
|
|
return device_id in self._connections
|
|
|
|
def connected_device_ids(self) -> list[str]:
|
|
return list(self._connections.keys())
|
|
|
|
async def register(self, device_id: str, ws: WebSocket) -> None:
|
|
old = self._connections.get(device_id)
|
|
if old and old is not ws:
|
|
try:
|
|
await old.close(code=1001, reason="Replaced by new connection")
|
|
except Exception:
|
|
pass
|
|
self._connections[device_id] = ws
|
|
self.db.set_device_online(device_id, True)
|
|
self.db.add_audit("ws", device_id, "Device connected")
|
|
await self.push_config(device_id)
|
|
|
|
def unregister(self, device_id: str, ws: WebSocket) -> None:
|
|
if self._connections.get(device_id) is ws:
|
|
del self._connections[device_id]
|
|
self.db.set_device_online(device_id, False)
|
|
self.db.add_audit("ws", device_id, "Device disconnected")
|
|
|
|
async def close_all(self) -> None:
|
|
items = list(self._connections.items())
|
|
self._connections.clear()
|
|
for dev_id, ws in items:
|
|
self.db.set_device_online(dev_id, False)
|
|
try:
|
|
await ws.close(code=1001, reason="Hub shutting down")
|
|
except Exception:
|
|
pass
|
|
|
|
async def send_frame(self, device_id: str, msg_type: str, payload: dict[str, Any]) -> bool:
|
|
ws = self._connections.get(device_id)
|
|
if not ws:
|
|
return False
|
|
frame = {
|
|
"type": msg_type,
|
|
"msg_id": str(uuid.uuid4()),
|
|
"ts": now_ms(),
|
|
"payload": payload,
|
|
}
|
|
try:
|
|
await ws.send_text(json.dumps(frame, ensure_ascii=False))
|
|
return True
|
|
except Exception:
|
|
self.unregister(device_id, ws)
|
|
return False
|
|
|
|
async def push_config(self, device_id: str | None = None) -> int:
|
|
cfg = self.db.get_config()
|
|
targets = [device_id] if device_id else list(self._connections.keys())
|
|
sent = 0
|
|
for tid in targets:
|
|
effective_ai = self.db.get_effective_repair_ai(tid)
|
|
payload = {
|
|
"repair_ai": effective_ai.model_dump(),
|
|
"telemetry_interval_sec": cfg.telemetry_interval_sec,
|
|
"theme": cfg.theme,
|
|
}
|
|
if await self.send_frame(tid, "config.push", payload):
|
|
sent += 1
|
|
return sent
|
|
|
|
async def handle_incoming(self, device_id: str, raw_text: str) -> None:
|
|
try:
|
|
frame = json.loads(raw_text)
|
|
except json.JSONDecodeError:
|
|
return
|
|
msg_type = frame.get("type", "")
|
|
payload = frame.get("payload") or {}
|
|
|
|
if msg_type == "device.hello":
|
|
self.db.upsert_device_hello(device_id, payload)
|
|
await self.push_config(device_id)
|
|
await self._emit_event(device_id, "device_online", {"device_id": device_id, "model": payload.get("model", "")}, persist=False)
|
|
|
|
elif msg_type == "device.telemetry":
|
|
self.db.update_device_telemetry(device_id, payload)
|
|
|
|
elif msg_type == "render.result":
|
|
task_id = str(payload.get("task_id", ""))
|
|
snapshot_id = str(payload.get("snapshot_id", ""))
|
|
status = str(payload.get("status", "failed_rolled_back"))
|
|
final_html = payload.get("final_html")
|
|
fix_summary = str(payload.get("local_fix_summary", ""))
|
|
if snapshot_id:
|
|
self.db.update_snapshot_result(snapshot_id, status, final_html=final_html, local_fix_summary=fix_summary)
|
|
|
|
self.db.add_audit(
|
|
"render_result",
|
|
device_id,
|
|
f"Render {status} (task={task_id}, trigger={payload.get('trigger', 'initial_render')})",
|
|
{
|
|
"task_id": task_id,
|
|
"snapshot_id": snapshot_id,
|
|
"status": status,
|
|
"attempts": payload.get("attempts", 0),
|
|
"local_fix_summary": fix_summary,
|
|
"errors": payload.get("errors", []),
|
|
},
|
|
)
|
|
|
|
# Resolve synchronous MCP waiter if present
|
|
fut = self._pending_renders.pop(task_id, None)
|
|
if fut and not fut.done():
|
|
fut.set_result(payload)
|
|
|
|
# If end-side Repair AI needs upstream data clarification, ALWAYS emit a reverse event too
|
|
if status == "needs_clarification" or payload.get("clarification_questions"):
|
|
await self._emit_event(device_id, "repair_data_clarification", payload, persist=True)
|
|
|
|
elif msg_type == "interaction.reply":
|
|
self.db.add_audit(
|
|
"interaction",
|
|
device_id,
|
|
f"User replied: {payload.get('selected_label') or payload.get('custom_text')}",
|
|
payload,
|
|
)
|
|
await self._emit_event(device_id, "user_interaction_reply", payload, persist=True)
|
|
|
|
elif msg_type == "console.error_report":
|
|
self.db.add_audit(
|
|
"console_error",
|
|
device_id,
|
|
f"Runtime console error: {payload.get('message', '')[:120]}",
|
|
payload,
|
|
)
|
|
await self._emit_event(device_id, "console_error", payload, persist=True)
|
|
|
|
async def send_render_and_wait(
|
|
self,
|
|
device_id: str,
|
|
html: str,
|
|
mode: str = "full",
|
|
title: str = "",
|
|
data_context: dict[str, Any] | None = None,
|
|
wait_validation_sec: int = 15,
|
|
) -> dict[str, Any]:
|
|
task_id = f"task_{uuid.uuid4().hex[:10]}"
|
|
snapshot_id = self.db.create_snapshot(
|
|
device_id=device_id,
|
|
task_id=task_id,
|
|
html=html,
|
|
mode=mode,
|
|
title=title,
|
|
data_context=data_context,
|
|
status="pending",
|
|
)
|
|
if not self.is_connected(device_id):
|
|
self.db.update_snapshot_result(snapshot_id, "queued_offline")
|
|
return {
|
|
"status": "queued_offline",
|
|
"task_id": task_id,
|
|
"snapshot_id": snapshot_id,
|
|
"message": f"Device '{device_id}' is currently offline. Snapshot saved.",
|
|
}
|
|
|
|
loop = asyncio.get_running_loop()
|
|
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
|
self._pending_renders[task_id] = fut
|
|
|
|
sent = await self.send_frame(
|
|
device_id,
|
|
"render.apply",
|
|
{
|
|
"task_id": task_id,
|
|
"snapshot_id": snapshot_id,
|
|
"mode": mode,
|
|
"title": title,
|
|
"html": html,
|
|
"data_context": data_context or {},
|
|
},
|
|
)
|
|
if not sent:
|
|
self._pending_renders.pop(task_id, None)
|
|
self.db.update_snapshot_result(snapshot_id, "queued_offline")
|
|
return {
|
|
"status": "queued_offline",
|
|
"task_id": task_id,
|
|
"snapshot_id": snapshot_id,
|
|
"message": f"Failed to send frame to '{device_id}'.",
|
|
}
|
|
|
|
self.db.add_audit("render_push", device_id, f"Dispatched render task {task_id} ({mode})", {"snapshot_id": snapshot_id})
|
|
|
|
if wait_validation_sec <= 0:
|
|
return {"status": "dispatched", "task_id": task_id, "snapshot_id": snapshot_id}
|
|
|
|
try:
|
|
result = await asyncio.wait_for(fut, timeout=float(wait_validation_sec))
|
|
result.setdefault("task_id", task_id)
|
|
result.setdefault("snapshot_id", snapshot_id)
|
|
return result
|
|
except asyncio.TimeoutError:
|
|
self._pending_renders.pop(task_id, None)
|
|
return {
|
|
"status": "validation_timeout",
|
|
"task_id": task_id,
|
|
"snapshot_id": snapshot_id,
|
|
"message": f"Device did not finish validation/repair within {wait_validation_sec}s; check pending events later.",
|
|
}
|
|
|
|
# ---- SSE / Webhook Event Bus ----
|
|
def subscribe_sse(self) -> asyncio.Queue[dict[str, Any]]:
|
|
q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=100)
|
|
self._sse_subscribers.add(q)
|
|
return q
|
|
|
|
def unsubscribe_sse(self, q: asyncio.Queue[dict[str, Any]]) -> None:
|
|
self._sse_subscribers.discard(q)
|
|
|
|
async def _emit_event(
|
|
self,
|
|
device_id: str,
|
|
event_type: str,
|
|
payload: dict[str, Any],
|
|
persist: bool = True,
|
|
) -> dict[str, Any]:
|
|
if persist:
|
|
event = self.db.create_event(device_id, event_type, payload)
|
|
else:
|
|
event = {
|
|
"event_id": f"evt_{uuid.uuid4().hex[:10]}",
|
|
"device_id": device_id,
|
|
"event_type": event_type,
|
|
"payload": payload,
|
|
"acked": False,
|
|
"created_at_ms": now_ms(),
|
|
}
|
|
|
|
for q in list(self._sse_subscribers):
|
|
try:
|
|
q.put_nowait(event)
|
|
except asyncio.QueueFull:
|
|
pass
|
|
|
|
if persist:
|
|
webhooks = self.db.list_webhooks()
|
|
if webhooks:
|
|
asyncio.create_task(self._dispatch_webhooks(webhooks, event))
|
|
return event
|
|
|
|
async def _dispatch_webhooks(self, webhooks: list[dict[str, Any]], event: dict[str, Any]) -> None:
|
|
async with httpx.AsyncClient(timeout=8.0) as client:
|
|
for wh in webhooks:
|
|
headers = {"Content-Type": "application/json"}
|
|
if wh.get("secret"):
|
|
headers["X-PulseWall-Secret"] = wh["secret"]
|
|
try:
|
|
await client.post(wh["url"], json=event, headers=headers)
|
|
except Exception:
|
|
pass
|