Skip to content

Self-improving AI Employees for everyone

refactor(android): move option loader + retire services/node_option_loaders/ (Wave 11.I, M.3)

trohitg633694635d7d
diff --git a/server/nodes/android/__init__.py b/server/nodes/android/__init__.py
index a2067e4e..3aee870b 100644
--- a/server/nodes/android/__init__.py
+++ b/server/nodes/android/__init__.py
@@ -10,12 +10,22 @@ Wiring is body-free; both registrations are idempotent.
"""
from services.status_broadcaster import register_service_refresh
-from services.ws_handler_registry import register_router, register_ws_handlers
+from services.ws_handler_registry import (
+ register_option_loader,
+ register_router,
+ register_ws_handlers,
+)
from . import _router
from ._handlers import WS_HANDLERS
+from ._option_loaders import load_service_actions
from ._refresh import refresh_android_status
register_ws_handlers(WS_HANDLERS)
register_router(_router.router, name="android")
register_service_refresh(refresh_android_status)
+
+# loadOptionsMethod loader (Wave 11.I, milestone M.3) -- last entry to
+# leave services/node_option_loaders/, which is deleted at the same
+# commit.
+register_option_loader("getAndroidServiceActions", load_service_actions)
diff --git a/server/nodes/android/_option_loaders.py b/server/nodes/android/_option_loaders.py
new file mode 100644
index 00000000..fe2915f0
--- /dev/null
+++ b/server/nodes/android/_option_loaders.py
@@ -0,0 +1,44 @@
+"""Android ``loadOptionsMethod`` loaders.
+
+Wave 11.I, milestone M.3. Returns the list of actions supported by each
+Android service node. The frontend passes ``node_type`` in params; the
+loader maps it to the service's ``action`` enum advertised by the
+running Android bridge.
+
+``SERVICE_ID_MAP`` is the single source of truth -- imported from
+``_base.py`` instead of being duplicated here (the pre-Wave-11.I
+``services/node_option_loaders/android_loaders.py`` carried its own
+copy under a different name; that copy is gone now).
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, List
+
+from ._base import SERVICE_ID_MAP
+
+
+async def load_service_actions(params: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Return ``[{value, label}]`` for the given Android service node.
+
+ Each service's ``execute_action`` endpoint validates the action at
+ call time; the dropdown is convenience UX, not a correctness
+ boundary. The frontend falls back to a free-text input if the
+ loader returns an empty list (service offline / discovery failed).
+ """
+ node_type = params.get("node_type") or ""
+ service_id = SERVICE_ID_MAP.get(node_type)
+ if not service_id:
+ return []
+
+ try:
+ from core.container import container
+
+ android_svc = container.android_service()
+ actions = await android_svc.list_actions(service_id) # type: ignore[attr-defined]
+ return [
+ {"value": a, "label": a.replace("_", " ").title()}
+ for a in actions or []
+ ]
+ except Exception:
+ return []
diff --git a/server/nodes/whatsapp/__init__.py b/server/nodes/whatsapp/__init__.py
index 604dc547..3445d65f 100644
--- a/server/nodes/whatsapp/__init__.py
+++ b/server/nodes/whatsapp/__init__.py
@@ -51,9 +51,9 @@ register_service_refresh(refresh_whatsapp_status)
# carries no plugin-specific code.
register_filter_builder("whatsappReceive", build_whatsapp_filter)
-# loadOptionsMethod loaders (Wave 11.I, milestone M.1) -- moved out
-# of services/node_option_loaders/ so the central LOAD_OPTIONS_REGISTRY
-# carries no plugin-specific code.
+# loadOptionsMethod loaders (Wave 11.I, milestone M.1) -- self-register
+# into services.ws_handler_registry's option-loader registry, sibling to
+# the WS-handler / router registries.
register_option_loader("whatsappGroups", load_groups)
register_option_loader("whatsappChannels", load_channels)
register_option_loader("whatsappGroupMembers", load_group_members)
diff --git a/server/nodes/whatsapp/_option_loaders.py b/server/nodes/whatsapp/_option_loaders.py
index 1889bc72..6f7c64b8 100644
--- a/server/nodes/whatsapp/_option_loaders.py
+++ b/server/nodes/whatsapp/_option_loaders.py
@@ -2,9 +2,8 @@
Wave 11.I, milestone M.1. Each function is registered with
``services.ws_handler_registry.register_option_loader`` from
-``__init__.py`` so the central dispatcher in
-``services/node_option_loaders/__init__.py`` picks them up without a
-plugin-specific import.
+``__init__.py`` so the central ``dispatch_load_options`` picks them
+up without a plugin-specific import.
Adapter shape: turn the existing WS-handler responses
(``handle_whatsapp_groups`` / ``handle_whatsapp_newsletters`` /
diff --git a/server/routers/schemas.py b/server/routers/schemas.py
index 0ca84bea..42650bdf 100644
--- a/server/routers/schemas.py
+++ b/server/routers/schemas.py
@@ -100,7 +100,7 @@ async def load_options(method: str, body: dict | None = None):
parameter map (e.g. ``{"group_id": "..."}`` for
whatsappGroupMembers).
"""
- from services.node_option_loaders import dispatch_load_options
+ from services.ws_handler_registry import dispatch_load_options
params = (body or {}).get("params", body or {}) if isinstance(body, dict) else {}
options = await dispatch_load_options(method, params)
@@ -111,7 +111,7 @@ async def load_options(method: str, body: dict | None = None):
async def list_load_options():
"""Registered loadOptionsMethod names. Editor probes this on boot
to know which dynamic-option loaders are wired backend-side."""
- from services.node_option_loaders import list_load_options_methods
+ from services.ws_handler_registry import list_load_options_methods
return {"methods": list_load_options_methods()}
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 9cf7c1da..17912c6a 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -300,7 +300,7 @@ async def handle_load_options(
Body: ``{"method": "...", "params": {...}}``
Response: ``{"options": [{"value": ..., "label": ...}]}``
"""
- from services.node_option_loaders import dispatch_load_options
+ from services.ws_handler_registry import dispatch_load_options
options = await dispatch_load_options(data["method"], data.get("params", {}))
return {"method": data["method"], "options": options}
@@ -312,7 +312,7 @@ async def handle_list_load_options_methods(
) -> Dict[str, Any]:
"""Return registered loadOptionsMethod names. Editor uses this to
know which dynamic-option loaders are wired."""
- from services.node_option_loaders import list_load_options_methods
+ from services.ws_handler_registry import list_load_options_methods
return {"methods": list_load_options_methods()}
diff --git a/server/services/node_option_loaders/__init__.py b/server/services/node_option_loaders/__init__.py
deleted file mode 100644
index 9e7067fc..00000000
--- a/server/services/node_option_loaders/__init__.py
+++ /dev/null
@@ -1,66 +0,0 @@
-"""Generic loadOptionsMethod dispatch.
-
-Wave 6 Phase 4 introduced this as a central registry. Wave 11.I,
-milestone M relocates the per-plugin loaders into their plugin folders
-(``nodes/<plugin>/_option_loaders.py``) and routes lookups through
-``services.ws_handler_registry.register_option_loader`` -- the same
-``IdempotentRegistry``-backed sibling of ``register_ws_handlers`` /
-``register_router``.
-
-While milestone M is in flight we keep a small legacy dict for plugins
-that haven't migrated yet; the dispatcher consults the plugin registry
-first and falls back to the legacy table. After M.3 the legacy table is
-empty and this module retires alongside the rest of
-``services/node_option_loaders/``.
-"""
-
-from typing import Any, Awaitable, Callable, Optional
-
-from services.ws_handler_registry import get_option_loader
-
-from .android_loaders import load_android_service_actions
-
-
-# Async loader signature: (params: dict) -> list of {value, label, ...}
-LoadOptionsFn = Callable[[dict[str, Any]], Awaitable[list[dict[str, Any]]]]
-
-
-# Legacy table for not-yet-migrated plugins. Shrinks one entry per M.x
-# commit; deleted entirely at the end of M.3.
-LEGACY_LOAD_OPTIONS_REGISTRY: dict[str, LoadOptionsFn] = {
- "getAndroidServiceActions": load_android_service_actions,
-}
-
-
-# Backwards-compat alias for the previous public name. Tests and
-# ``list_load_options_methods`` still read it; updates land per M.x.
-LOAD_OPTIONS_REGISTRY = LEGACY_LOAD_OPTIONS_REGISTRY
-
-
-async def dispatch_load_options(
- method: str, params: Optional[dict[str, Any]] = None
-) -> list[dict[str, Any]]:
- """Look up and invoke a registered loader.
-
- Plugin-registry lookup wins; legacy table is the fallback. Returns
- an empty list when the method isn't registered (matches n8n's
- tolerant fallback -- the dropdown stays empty rather than erroring
- out).
- """
-
- loader = get_option_loader(method) or LEGACY_LOAD_OPTIONS_REGISTRY.get(method)
- if loader is None:
- return []
- return await loader(params or {})
-
-
-def list_load_options_methods() -> list[str]:
- """Stable alphabetised list of registered method names. The editor
- prefetches this once on boot so it knows which ``loadOptionsMethod``
- values are wired."""
-
- from services.ws_handler_registry import list_registered_option_methods
-
- plugin_methods = set(list_registered_option_methods())
- legacy_methods = set(LEGACY_LOAD_OPTIONS_REGISTRY.keys())
- return sorted(plugin_methods | legacy_methods)
diff --git a/server/services/node_option_loaders/android_loaders.py b/server/services/node_option_loaders/android_loaders.py
deleted file mode 100644
index 9ff26875..00000000
--- a/server/services/node_option_loaders/android_loaders.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Android dynamic option loaders.
-
-Returns the list of actions supported by each Android service node.
-The frontend passes ``node_type`` in params; the loader maps it to the
-service's ``action`` enum advertised by the running Android bridge.
-"""
-
-from __future__ import annotations
-
-from typing import Any
-
-
-async def load_android_service_actions(params: dict[str, Any]) -> list[dict[str, Any]]:
- """Return ``[{value, label}]`` for the given Android service node.
-
- Kept minimal — each service's `execute_action` endpoint validates
- the action at call time; the dropdown is convenience UX, not a
- correctness boundary. The frontend falls back to a free-text input
- if the loader returns an empty list.
- """
- node_type = params.get("node_type") or ""
- service_id = _ANDROID_SERVICE_MAP.get(node_type)
- if not service_id:
- return []
-
- try:
- from core.container import container
-
- android_svc = container.android_service()
- actions = await android_svc.list_actions(service_id) # type: ignore[attr-defined]
- return [{"value": a, "label": a.replace("_", " ").title()} for a in actions or []]
- except Exception:
- # Service offline / discovery failed — dropdown stays empty, user
- # can still type the action name manually.
- return []
-
-
-_ANDROID_SERVICE_MAP = {
- "batteryMonitor": "battery",
- "networkMonitor": "network",
- "systemInfo": "system_info",
- "location": "location",
- "appLauncher": "app_launcher",
- "appList": "app_list",
- "wifiAutomation": "wifi_automation",
- "bluetoothAutomation": "bluetooth_automation",
- "audioAutomation": "audio_automation",
- "deviceStateAutomation": "device_state",
- "screenControlAutomation": "screen_control",
- "airplaneModeControl": "airplane_mode",
- "motionDetection": "motion_detection",
- "environmentalSensors": "environmental_sensors",
- "cameraControl": "camera_control",
- "mediaControl": "media_control",
-}
diff --git a/server/services/ws_handler_registry.py b/server/services/ws_handler_registry.py
index 21c17ffb..dcc4fae0 100644
--- a/server/services/ws_handler_registry.py
+++ b/server/services/ws_handler_registry.py
@@ -17,8 +17,8 @@ Three sibling concerns share this file because they're the same pattern
3. **Option loaders** — ``register_option_loader(method_name, fn)`` for
dynamic-options dropdowns wired through the
``loadOptionsMethod`` Pydantic field metadata. Read by
- ``services.node_option_loaders.dispatch_load_options`` and the
- matching WS handler in ``routers/websocket.py``.
+ :func:`dispatch_load_options` (here in this module) and the matching
+ WS handler in ``routers/websocket.py``.
No hardcoded plugin names anywhere in the central router or main.py.
Adding a new plugin's WS / HTTP / option-loader surface is one
@@ -120,3 +120,25 @@ def get_option_loader(method_name: str) -> LoadOptionsFn | None:
def list_registered_option_methods() -> List[str]:
"""For diagnostics / startup logging."""
return sorted(_OPTION_LOADER_REGISTRY.keys())
+
+
+async def dispatch_load_options(
+ method: str, params: Dict[str, Any] | None = None
+) -> List[Dict[str, Any]]:
+ """Look up and invoke a registered loader.
+
+ Returns an empty list when the method isn't registered (matches
+ n8n's tolerant fallback -- the dropdown stays empty rather than
+ erroring out).
+ """
+ loader = _OPTION_LOADER_REGISTRY.get(method)
+ if loader is None:
+ return []
+ return await loader(params or {})
+
+
+def list_load_options_methods() -> List[str]:
+ """Stable alphabetised list of registered method names. The editor
+ prefetches this once on boot so it knows which ``loadOptionsMethod``
+ values are wired."""
+ return list_registered_option_methods()
diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.py
index 6a906437..31ccc151 100644
--- a/server/tests/test_node_spec.py
+++ b/server/tests/test_node_spec.py
@@ -1,9 +1,10 @@
"""Wave 6 NodeSpec contract tests.
Locks in the public shape emitted by services/node_input_schemas.py,
-services/node_spec.py, services/node_option_loaders, and the
-/api/schemas/nodes/*/spec.json + /api/schemas/nodes/options/* endpoints.
-Mirrors the Wave 3 test posture for node_output_schemas.
+services/node_spec.py, services/ws_handler_registry (option-loader
+registry, post-Wave-11.I M.3), and the /api/schemas/nodes/*/spec.json +
+/api/schemas/nodes/options/* endpoints. Mirrors the Wave 3 test posture
+for node_output_schemas.
"""
import pytest # noqa: F401 (used by @pytest.mark.asyncio on Phase 4 tests)
@@ -386,33 +387,33 @@ class TestPhase4LoadOptions:
"""Wave 6 Phase 4: unified loadOptionsMethod dispatch registry."""
def test_registry_has_whatsapp_methods(self):
- from services.node_option_loaders import list_load_options_methods
+ from services.ws_handler_registry import list_load_options_methods
methods = list_load_options_methods()
for method in ["whatsappGroups", "whatsappChannels", "whatsappGroupMembers"]:
assert method in methods
def test_registry_has_google_methods(self):
- from services.node_option_loaders import list_load_options_methods
+ from services.ws_handler_registry import list_load_options_methods
methods = list_load_options_methods()
for method in ["gmailLabels", "googleCalendarList", "googleDriveFolders", "googleTasklists"]:
assert method in methods
def test_list_methods_sorted(self):
- from services.node_option_loaders import list_load_options_methods
+ from services.ws_handler_registry import list_load_options_methods
methods = list_load_options_methods()
assert methods == sorted(methods)
assert len(methods) >= 7
@pytest.mark.asyncio
async def test_unknown_method_returns_empty(self):
- from services.node_option_loaders import dispatch_load_options
+ from services.ws_handler_registry import dispatch_load_options
result = await dispatch_load_options("nonExistentMethodXyz", {})
assert result == []
@pytest.mark.asyncio
async def test_dispatch_passes_params(self):
# Smoke test: unknown method tolerates arbitrary params, doesn't crash
- from services.node_option_loaders import dispatch_load_options
+ from services.ws_handler_registry import dispatch_load_options
result = await dispatch_load_options("unknown", {"group_id": "abc"})
assert result == []
@@ -750,7 +751,7 @@ class TestNodeSpecContractInvariants:
plugin's ``register_option_loader`` call. Catches typos and
forgotten loader registrations."""
from services.node_input_schemas import get_node_input_schema, NODE_INPUT_MODELS
- from services.node_option_loaders import list_load_options_methods
+ from services.ws_handler_registry import list_load_options_methods
methods = set(list_load_options_methods())
for t in NODE_INPUT_MODELS:
schema = get_node_input_schema(t)