Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(android): Wave 12 B1 — move broadcast into nodes/android/_events.py
trohitg7e4ff7b7f589
diff --git a/server/nodes/android/__init__.py b/server/nodes/android/__init__.pyindex 3aee870b..54fb3799 100644--- a/server/nodes/android/__init__.py+++ b/server/nodes/android/__init__.py@@ -17,6 +17,7 @@ from services.ws_handler_registry import ()from . import _router+from ._events import broadcast_android_status # noqa: F401 — re-exportfrom ._handlers import WS_HANDLERSfrom ._option_loaders import load_service_actionsfrom ._refresh import refresh_android_statusdiff --git a/server/nodes/android/_events.py b/server/nodes/android/_events.pynew file mode 100644index 00000000..e7f0a496--- /dev/null+++ b/server/nodes/android/_events.py@@ -0,0 +1,161 @@+"""Wave 12 B1: CloudEvents factories + broadcaster wrappers for android.++Plugin-specific event emission — replaces the+``StatusBroadcaster.update_android_status`` method (deleted in this+commit) and the direct ``broadcaster._status["android"]`` mutations+inside ``_refresh.py`` / ``_relay/broadcaster.py``.++Per RFC plugin_authoring_rfc.md §6.4: plugin-specific factories live in+the plugin folder. The cross-cutting ``WorkflowEvent.connection_status``+factory in ``services/events/envelope.py`` is borderline (parametrized+by plugin but each plugin's payload differs) — Phase B moves the+plugin-specific shape into per-plugin factories.++Wire format unchanged from X4 (the dual-emit transition pattern):+ - Legacy raw frame: ``{type: "android_status", data: <raw dict>}``+ - Typed CloudEvents sibling: ``{type: "plugin_connection_status",+ data: <WorkflowEvent envelope>}``++Caller pattern (from ``_refresh.py`` / ``_relay/broadcaster.py``):+ from nodes.android import broadcast_android_status+ await broadcast_android_status(connected=True, device_id="...", ...)+"""++from __future__ import annotations++from typing import Any, Dict, List, Optional++from services.events.envelope import WorkflowEvent+++# Wire-routing keys are the OUTER ``type`` field on the WS frame, which+# the FE switches on. Unchanged from X4 so FE listeners keep working.+_LEGACY_WIRE_KEY = "android_status"+_TYPED_WIRE_KEY = "plugin_connection_status"++# Module-level cache mirror — kept in sync with+# ``StatusBroadcaster._status["android"]`` until the framework's+# ``get_status()`` snapshot path migrates to a per-plugin getter+# registry. The plugin owns the SHAPE of this dict; the broadcaster+# stores it.+_DEFAULT_STATUS: Dict[str, Any] = {+ "connected": False,+ "paired": False,+ "device_id": None,+ "device_name": None,+ "connected_devices": [],+ "connection_type": None,+ "qr_data": None,+ "session_token": None,+}+++# ---- Typed factory ---------------------------------------------------------+++def android_connection_status(+ *,+ connected: bool,+ paired: bool = False,+ device_id: Optional[str] = None,+ device_name: Optional[str] = None,+ connected_devices: Optional[List[str]] = None,+ connection_type: Optional[str] = None,+ qr_data: Optional[str] = None,+ session_token: Optional[str] = None,+) -> WorkflowEvent:+ """Build a typed CloudEvents envelope describing the android relay+ connection state.++ ``subject`` is the device id so the FE can route per-device updates.+ ``data`` carries the full android status payload (mirrors+ ``_DEFAULT_STATUS`` shape).+ """+ return WorkflowEvent(+ source="machinaos://nodes/android",+ type=(+ "com.machinaos.android.connection.opened"+ if connected+ else "com.machinaos.android.connection.closed"+ ),+ subject=device_id,+ data={+ "connected": connected,+ "paired": paired,+ "device_id": device_id,+ "device_name": device_name,+ "connected_devices": list(connected_devices or []),+ "connection_type": connection_type,+ "qr_data": qr_data,+ "session_token": session_token,+ },+ )+++# ---- Broadcaster wrapper ---------------------------------------------------+++async def broadcast_android_status(+ *,+ connected: bool,+ paired: bool = False,+ device_id: Optional[str] = None,+ device_name: Optional[str] = None,+ connected_devices: Optional[List[str]] = None,+ connection_type: Optional[str] = None,+ qr_data: Optional[str] = None,+ session_token: Optional[str] = None,+) -> None:+ """Update the android status cache + emit both the legacy raw+ ``android_status`` frame AND the typed ``plugin_connection_status``+ CloudEvents sibling.++ Replaces ``StatusBroadcaster.update_android_status``. Same wire shape+ on both channels — FE consumers see no change.+ """+ from services.status_broadcaster import get_status_broadcaster++ broadcaster = get_status_broadcaster()++ # Status cache lives on the broadcaster (still consumed by+ # ``StatusBroadcaster.get_android_status()`` + the WS-connect+ # initial-status snapshot). Plugin owns the SHAPE of the cache.+ payload: Dict[str, Any] = {+ "connected": connected,+ "paired": paired,+ "device_id": device_id,+ "device_name": device_name,+ "connected_devices": list(connected_devices or []),+ "connection_type": connection_type,+ "qr_data": qr_data,+ "session_token": session_token,+ }+ broadcaster._status["android"] = payload++ # Legacy raw frame (FE back-compat).+ await broadcaster.broadcast({+ "type": _LEGACY_WIRE_KEY,+ "data": payload,+ })++ # Typed CloudEvents sibling — X4 dual-emit pattern.+ event = android_connection_status(+ connected=connected,+ paired=paired,+ device_id=device_id,+ device_name=device_name,+ connected_devices=connected_devices,+ connection_type=connection_type,+ qr_data=qr_data,+ session_token=session_token,+ )+ await broadcaster.broadcast({+ "type": _TYPED_WIRE_KEY,+ "data": event.model_dump(mode="json"),+ })+++__all__ = [+ "android_connection_status",+ "broadcast_android_status",+]diff --git a/server/nodes/android/_refresh.py b/server/nodes/android/_refresh.pyindex 171163e7..cdb0b22b 100644--- a/server/nodes/android/_refresh.py+++ b/server/nodes/android/_refresh.py@@ -37,27 +37,27 @@ async def refresh_android_status(broadcaster: "StatusBroadcaster") -> None:async def _auto_reconnect_body(broadcaster: "StatusBroadcaster", span) -> None:+ # Single source of truth for android status emission — owns both+ # the cache update + the dual-emit (legacy raw + typed sibling).+ from ._events import broadcast_android_status+try:# Already connected? Refresh the cached snapshot and stop.from ._relay.manager import get_current_relay_clientexisting = get_current_relay_client()if existing and existing.is_connected():- broadcaster._status["android"] = {- "connected": True,- "paired": existing.is_paired(),- "device_id": existing.paired_device_id,- "device_name": existing.paired_device_name,- "connected_devices": list(existing.get_connected_devices()),- "connection_type": "relay",- "qr_data": existing.qr_data,- "session_token": existing.session_token,- }+ await broadcast_android_status(+ connected=True,+ paired=existing.is_paired(),+ device_id=existing.paired_device_id,+ device_name=existing.paired_device_name,+ connected_devices=list(existing.get_connected_devices()),+ connection_type="relay",+ qr_data=existing.qr_data,+ session_token=existing.session_token,+ )logger.debug("[StatusBroadcaster] Android relay already connected")- await broadcaster.broadcast({- "type": "android_status",- "data": broadcaster._status["android"],- })span.set_attribute("path", "already_connected")return@@ -98,20 +98,16 @@ async def _auto_reconnect_body(broadcaster: "StatusBroadcaster", span) -> None:# The relay server creates a new session on each connect, so# pairing may be lost -- mirror whatever the new client# reports.- broadcaster._status["android"] = {- "connected": True,- "paired": client.is_paired(),- "device_id": client.paired_device_id,- "device_name": client.paired_device_name,- "connected_devices": list(client.get_connected_devices()),- "connection_type": "relay",- "qr_data": client.qr_data,- "session_token": client.session_token,- }- await broadcaster.broadcast({- "type": "android_status",- "data": broadcaster._status["android"],- })+ await broadcast_android_status(+ connected=True,+ paired=client.is_paired(),+ device_id=client.paired_device_id,+ device_name=client.paired_device_name,+ connected_devices=list(client.get_connected_devices()),+ connection_type="relay",+ qr_data=client.qr_data,+ session_token=client.session_token,+ )span.set_attribute("reconnect_ok", True)else:span.set_attribute("reconnect_ok", False)diff --git a/server/nodes/android/_relay/broadcaster.py b/server/nodes/android/_relay/broadcaster.pyindex 9da152e8..aeb0423e 100644--- a/server/nodes/android/_relay/broadcaster.py+++ b/server/nodes/android/_relay/broadcaster.py@@ -1,7 +1,12 @@"""Android Status Broadcaster-Broadcasts Android relay connection status changes to frontend WebSocket clients.+Relay-specific helpers that translate relay-shaped arguments+(``devices: Set[str]``, derived ``connection_type="relay"``) into the+canonical :func:`nodes.android.broadcast_android_status` shape. Wave 12+B1 — the actual broadcast emission moved into+:mod:`nodes.android._events` (plugin-owned). This file just adapts+relay-state to that shape."""from typing import Optional, Setimport structlog@@ -9,7 +14,7 @@ import structloglogger = structlog.get_logger()-async def broadcast_android_status(+async def _emit_relay_status(connected: bool,paired: bool = False,device_id: Optional[str] = None,@@ -18,22 +23,14 @@ async def broadcast_android_status(qr_data: Optional[str] = None,session_token: Optional[str] = None):- """- Broadcast Android relay status changes to frontend WebSocket clients.-- Args:- connected: Whether connected to relay server- paired: Whether paired with Android device- device_id: Paired device ID (if any)- device_name: Paired device name (if any)- devices: Set of all connected device IDs- qr_data: QR code data for pairing (app://pair?token=...)- session_token: Relay session token- """+ """Translate relay-shaped args and route to the canonical+ plugin-owned broadcaster (``nodes.android._events``)."""try:- from services.status_broadcaster import get_status_broadcaster- broadcaster = get_status_broadcaster()- await broadcaster.update_android_status(+ # Import from the plugin package — single source of truth+ # for the android status wire format (Wave 12 B1).+ from nodes.android import broadcast_android_status++ await broadcast_android_status(connected=connected,paired=paired,device_id=device_id,@@ -41,7 +38,7 @@ async def broadcast_android_status(connected_devices=list(devices) if devices else [],connection_type="relay" if connected else None,qr_data=qr_data,- session_token=session_token+ session_token=session_token,)except Exception as e:logger.warning("[Android] Failed to broadcast status", error=str(e))@@ -49,7 +46,7 @@ async def broadcast_android_status(async def broadcast_connected(device_id: str, device_name: Optional[str] = None):"""Broadcast that Android device is paired"""- await broadcast_android_status(+ await _emit_relay_status(connected=True,paired=True,device_id=device_id,@@ -73,7 +70,7 @@ async def broadcast_device_disconnected(qr_data: QR code data for re-pairingsession_token: Current session token"""- await broadcast_android_status(+ await _emit_relay_status(connected=relay_connected, # Relay may still be connectedpaired=False, # Device is disconnecteddevice_id=None,@@ -86,7 +83,7 @@ async def broadcast_device_disconnected(async def broadcast_relay_disconnected():"""Broadcast that relay connection is closed (fully disconnected)"""- await broadcast_android_status(+ await _emit_relay_status(connected=False,paired=False,device_id=None,@@ -103,7 +100,7 @@ async def broadcast_disconnected():async def broadcast_qr_code(qr_data: str, session_token: Optional[str] = None):"""Broadcast QR code for pairing"""- await broadcast_android_status(+ await _emit_relay_status(connected=True, # Connected to relay but not pairedpaired=False,device_id=None,diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.pyindex 4a5080dd..c62da6bf 100644--- a/server/services/status_broadcaster.py+++ b/server/services/status_broadcaster.py@@ -578,44 +578,13 @@ class StatusBroadcaster:"data": event.model_dump(mode="json"),})- async def update_android_status(- self,- connected: bool,- paired: bool = False,- device_id: Optional[str] = None,- device_name: Optional[str] = None,- connected_devices: Optional[List[str]] = None,- connection_type: Optional[str] = None,- qr_data: Optional[str] = None,- session_token: Optional[str] = None- ):- """Update Android relay connection status and broadcast.-- Emits both the legacy ``android_status`` raw frame (FE- back-compat) and a CloudEvents-typed sibling via- :meth:`_emit_connection_typed` (Wave 11.I, X4).- """- self._status["android"] = {- "connected": connected,- "paired": paired,- "device_id": device_id,- "device_name": device_name,- "connected_devices": connected_devices or [],- "connection_type": connection_type,- "qr_data": qr_data,- "session_token": session_token- }-- await self.broadcast({- "type": "android_status",- "data": self._status["android"]- })- await self._emit_connection_typed(- plugin="android",- connected=connected,- subject=device_id,- data=self._status["android"],- )+ # Wave 12 B1: ``update_android_status`` MOVED to+ # ``nodes/android/_events.py:broadcast_android_status``. Plugin+ # owns its broadcast shape + the dual-emit (legacy raw ++ # typed CloudEvents sibling). Status cache still lives in+ # ``self._status["android"]`` — the plugin's wrapper mutates it+ # so ``get_android_status()`` + the WS-connect initial-status+ # snapshot keep working unchanged.# =========================================================================# Status updates -- per-service refresh bodies live in their plugindiff --git a/server/tests/test_status_broadcasts.py b/server/tests/test_status_broadcasts.pyindex 85877135..bf39aee7 100644--- a/server/tests/test_status_broadcasts.py+++ b/server/tests/test_status_broadcasts.py@@ -77,7 +77,8 @@ _TELEMETRY_CARVE_OUT: FrozenSet[str] = frozenset({# envelope is a frontend change too. Migration is per-plugin, not# included in milestone U scope._LEGACY_RAW_DICT_BROADCASTS: FrozenSet[str] = frozenset({- "update_android_status", # FE: AndroidStatusPanel reads `android_status` wire-frame+ # Wave 12 B1: ``update_android_status`` retired; moved to+ # ``nodes/android/_events.py:broadcast_android_status``."update_whatsapp_status", # FE: WhatsAppStatusPanel reads `whatsapp_status` wire-frame"update_telegram_status", # FE: TelegramStatusPanel reads `telegram_status` wire-frame})