Skip to content

Self-improving AI Employees for everyone

refactor(Wave 13.8 + 13.9): extract 3 pricing handlers + 1 android status straggler

trohitgdf2c0c0a3023
diff --git a/server/main.py b/server/main.py
index 56a40194..22159324 100644
--- a/server/main.py
+++ b/server/main.py
@@ -37,26 +37,28 @@ _startup_log("Importing FastAPI...")
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
-_startup_log("Importing DI container + all services...")
-from core.container import container
+# Configure logging FIRST — before any imports that may trigger
+# ``logger.debug(...)`` calls (DI container, routers, plugin
+# self-registration). Otherwise structlog's *default* processor chain
+# wins on first use, which includes ``TimeStamper`` and produces
+# double-time output (``[10:51:08.157] server | 2026-05-15 10:51:08
+# [debug] ...``) because the supervisor already prepends
+# ``[HH:MM:SS.fff]`` to every aggregated line.
_startup_log("Importing settings + logging...")
from core.config import Settings
from core.logging import configure_logging, get_logger, setup_websocket_logging, shutdown_websocket_logging
from core.tracing import init_tracing
-_startup_log("Importing routers...")
-from routers import workflow, database, nodejs_compat, websocket, webhook, auth, credentials, schemas
-_startup_log("All imports complete")
-
-# Initialize settings, logging, and tracing.
-# init_tracing() registers the OpenTelemetry TracerProvider with a
-# ConsoleSpanExporter so every span emitted via
-# ``trace.get_tracer(__name__).start_as_current_span(...)`` shows up in
-# stdout for cold-start benchmarking.
settings = Settings()
configure_logging(settings)
init_tracing()
logger = get_logger(__name__)
+_startup_log("Importing DI container + all services...")
+from core.container import container
+_startup_log("Importing routers...")
+from routers import workflow, database, nodejs_compat, websocket, webhook, auth, credentials, schemas
+_startup_log("All imports complete")
+
# Suppress noisy loggers
import logging
logging.getLogger("apscheduler").setLevel(logging.WARNING)
@@ -108,7 +110,11 @@ async def lifespan(app: FastAPI):
# get_workflow / get_all_workflows / delete_workflow).
import services.workflow_storage # noqa: F401
- # Wire dependency injection
+ # Wave 13.8: services/pricing_handlers.py self-registers the 3
+ # pricing handlers (get_pricing_config / save_pricing_config /
+ # get_api_usage_summary). Flat module (sibling to services/pricing.py)
+ # to avoid renaming the existing `services.pricing` import path.
+ import services.pricing_handlers # noqa: F401
container.wire(modules=[
"routers.workflow",
"routers.database",
diff --git a/server/nodes/android/_handlers.py b/server/nodes/android/_handlers.py
index 374b1671..06ec2adf 100644
--- a/server/nodes/android/_handlers.py
+++ b/server/nodes/android/_handlers.py
@@ -29,6 +29,12 @@ from services.status_broadcaster import get_status_broadcaster
logger = get_logger(__name__)
+async def handle_get_android_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Get Android connection status (Wave 13.9 — moved from routers/websocket.py)."""
+ broadcaster = get_status_broadcaster()
+ return {"type": "android_status", "data": broadcaster.get_android_status()}
+
+
async def handle_get_android_devices(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Get list of connected Android devices."""
from services.plugin.deps import get_android_service
@@ -146,6 +152,7 @@ async def handle_android_relay_reconnect(data: Dict[str, Any], websocket: WebSoc
WS_HANDLERS = {
+ "get_android_status": handle_get_android_status,
"get_android_devices": handle_get_android_devices,
"execute_android_action": handle_execute_android_action,
"android_relay_connect": handle_android_relay_connect,
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index d607465b..462a6ec0 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -96,10 +96,7 @@ async def handle_get_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[
return {"type": "full_status", "data": broadcaster.get_status()}
-async def handle_get_android_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Get Android connection status."""
- broadcaster = get_status_broadcaster()
- return {"type": "android_status", "data": broadcaster.get_android_status()}
+# handle_get_android_status moved to nodes/android/_handlers.py (Wave 13.9).
async def handle_get_node_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
@@ -1210,29 +1207,10 @@ async def handle_process_send_input(data: Dict[str, Any], websocket: WebSocket)
# ============================================================================
-# Pricing Config Handlers
+# Pricing Config Handlers — extracted to services/pricing_handlers.py (Wave 13.8)
# ============================================================================
-
-@ws_handler()
-async def handle_get_pricing_config(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Get full pricing configuration for display/editing."""
- from services.pricing import get_pricing_service
- pricing = get_pricing_service()
- return {"success": True, "config": pricing.get_config()}
-
-
-@ws_handler()
-async def handle_save_pricing_config(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Save updated pricing configuration."""
- from services.pricing import get_pricing_service
-
- config = data.get('config')
- if not config:
- return {"success": False, "error": "No config provided"}
-
- pricing = get_pricing_service()
- success = pricing.save_config(config)
- return {"success": success}
+# 3 handlers (get_pricing_config / save_pricing_config / get_api_usage_summary)
+# self-register on services/pricing_handlers.py import.
@ws_handler()
@@ -1242,15 +1220,6 @@ async def handle_get_node_allowlist(data: Dict[str, Any], websocket: WebSocket)
return get_node_allowlist_service().get_config()
-@ws_handler()
-async def handle_get_api_usage_summary(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Get aggregated API usage and cost by service (Twitter, etc.)."""
- database = container.database()
- service = data.get('service') # Optional filter by service
- services = await database.get_api_usage_summary(service)
- return {"success": True, "services": services}
-
-
# ============================================================================
# Compaction Handlers — extracted to services/settings/handlers.py (Wave 13.3)
# ============================================================================
@@ -1325,7 +1294,7 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
# Status/ping
"ping": handle_ping,
"get_status": handle_get_status,
- "get_android_status": handle_get_android_status,
+ # get_android_status moved to nodes/android/_handlers.py (Wave 13.9)
"get_node_status": handle_get_node_status,
"get_variable": handle_get_variable,
@@ -1444,10 +1413,8 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
# — extracted to services/settings/handlers.py (Wave 13.3); register
# via ws_handler_registry on package import.
- # Pricing Config
- "get_pricing_config": handle_get_pricing_config,
- "save_pricing_config": handle_save_pricing_config,
- "get_api_usage_summary": handle_get_api_usage_summary,
+ # Pricing Config — extracted to services/pricing_handlers.py (Wave 13.8);
+ # registered via ws_handler_registry on package import.
# Node Allowlist (UI palette filter)
"get_node_allowlist": handle_get_node_allowlist,
diff --git a/server/services/pricing_handlers.py b/server/services/pricing_handlers.py
new file mode 100644
index 00000000..2ed39d09
--- /dev/null
+++ b/server/services/pricing_handlers.py
@@ -0,0 +1,87 @@
+"""Pricing-domain WS handlers — Wave 13.8 extraction.
+
+Sibling module to ``services/pricing.py`` (the PricingService singleton);
+kept flat instead of a subpackage to avoid renaming the existing
+``services.pricing`` import path used across handlers.
+
+Side-effect import (from ``main.py``) registers the 3 handlers below
+into ``ws_handler_registry``:
+ - ``get_pricing_config`` — return full pricing config for the
+ Settings panel.
+ - ``save_pricing_config`` — persist edits.
+ - ``get_api_usage_summary`` — aggregated API usage / cost by service.
+
+Note: ``get_provider_usage_summary`` (token-pricing summary, per
+provider) moved into ``services/settings/handlers.py`` (Wave 13.3) —
+kept there because it's surfaced in the Credentials Modal alongside
+the provider-defaults panel.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from fastapi import WebSocket
+
+from core.container import container
+from core.logging import get_logger
+from services.ws_handler_registry import register_ws_handlers, ws_handler
+
+logger = get_logger(__name__)
+
+
+@ws_handler()
+async def handle_get_pricing_config(
+ data: Dict[str, Any], websocket: WebSocket,
+) -> Dict[str, Any]:
+ """Get full pricing configuration for display/editing."""
+ from services.pricing import get_pricing_service
+
+ pricing = get_pricing_service()
+ return {"success": True, "config": pricing.get_config()}
+
+
+@ws_handler()
+async def handle_save_pricing_config(
+ data: Dict[str, Any], websocket: WebSocket,
+) -> Dict[str, Any]:
+ """Save updated pricing configuration."""
+ from services.pricing import get_pricing_service
+
+ config = data.get("config")
+ if not config:
+ return {"success": False, "error": "No config provided"}
+
+ pricing = get_pricing_service()
+ success = pricing.save_config(config)
+ return {"success": success}
+
+
+@ws_handler()
+async def handle_get_api_usage_summary(
+ data: Dict[str, Any], websocket: WebSocket,
+) -> Dict[str, Any]:
+ """Get aggregated API usage and cost by service (Twitter, Maps, etc.)."""
+ database = container.database()
+ service = data.get("service") # Optional filter by service
+ services = await database.get_api_usage_summary(service)
+ return {"success": True, "services": services}
+
+
+WS_HANDLERS: Dict[str, Any] = {
+ "get_pricing_config": handle_get_pricing_config,
+ "save_pricing_config": handle_save_pricing_config,
+ "get_api_usage_summary": handle_get_api_usage_summary,
+}
+
+# Self-register on import — ``main.py`` triggers via
+# ``import services.pricing_handlers``.
+register_ws_handlers(WS_HANDLERS)
+
+
+__all__ = [
+ "WS_HANDLERS",
+ "handle_get_api_usage_summary",
+ "handle_get_pricing_config",
+ "handle_save_pricing_config",
+]