Skip to content

Self-improving AI Employees for everyone

fix: close out remaining 28 pre-existing failures -- 531 -> 559 passing

trohitg9726aba774ee
diff --git a/server/nodes/android/_base.py b/server/nodes/android/_base.py
index d9ee0efd..fc32ecb0 100644
--- a/server/nodes/android/_base.py
+++ b/server/nodes/android/_base.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import json
from typing import Any, Dict, Optional
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from core.logging import get_logger
from services.plugin import ActionNode, NodeContext, Operation, TaskQueue
@@ -55,6 +55,32 @@ class AndroidServiceParams(BaseModel):
model_config = ConfigDict(extra="allow")
+ @field_validator("parameters", mode="before")
+ @classmethod
+ def _coerce_parameters(cls, value: Any) -> Dict[str, Any]:
+ """Accept a JSON-encoded string in the ``parameters`` slot.
+
+ Pre-refactor handlers sometimes receive ``parameters`` as a raw
+ JSON string when the node is wired from an upstream template.
+ Malformed JSON silently becomes an empty dict rather than
+ failing validation — matches the pre-refactor tolerance
+ (see tests/nodes/test_android.py::TestParameterHandling).
+ """
+ if value is None:
+ return {}
+ if isinstance(value, dict):
+ return value
+ if isinstance(value, str):
+ stripped = value.strip()
+ if not stripped:
+ return {}
+ try:
+ parsed = json.loads(stripped)
+ return parsed if isinstance(parsed, dict) else {}
+ except (ValueError, TypeError):
+ return {}
+ return {}
+
class AndroidServiceOutput(BaseModel):
success: Optional[bool] = None
diff --git a/server/nodes/social/_base.py b/server/nodes/social/_base.py
index b26be680..edf85217 100644
--- a/server/nodes/social/_base.py
+++ b/server/nodes/social/_base.py
@@ -153,17 +153,17 @@ def _apply_filters(
True if message passes all filters
"""
# Channel filter
- channel_filter = parameters.get('channelFilter', 'all')
+ channel_filter = parameters.get('channel_filter', 'all')
if channel_filter != 'all' and message.get('channel') != channel_filter:
return False
# Message type filter
- type_filter = parameters.get('messageTypeFilter', 'all')
+ type_filter = parameters.get('message_type_filter', 'all')
if type_filter != 'all' and message.get('message_type') != type_filter:
return False
# Sender filter
- sender_filter = parameters.get('senderFilter', 'all')
+ sender_filter = parameters.get('sender_filter', 'all')
if sender_filter == 'any_contact':
# Non-group messages only
@@ -172,13 +172,13 @@ def _apply_filters(
elif sender_filter == 'contact':
# Specific contact
- contact_phone = parameters.get('contactPhone', '')
+ contact_phone = parameters.get('contact_phone', '')
if contact_phone and message.get('sender_phone') != contact_phone:
return False
elif sender_filter == 'group':
# Specific group
- group_id = parameters.get('groupId', '')
+ group_id = parameters.get('group_id', '')
if group_id and message.get('chat_id') != group_id:
return False
@@ -192,11 +192,11 @@ def _apply_filters(
return False
# Ignore own messages
- if parameters.get('ignoreOwnMessages', True) and message.get('is_from_me'):
+ if parameters.get('ignore_own_messages', True) and message.get('is_from_me'):
return False
# Ignore bots
- if parameters.get('ignoreBots', False) and message.get('is_bot'):
+ if parameters.get('ignore_bots', False) and message.get('is_bot'):
return False
return True
diff --git a/server/nodes/social/social_receive.py b/server/nodes/social/social_receive.py
index 890489b4..df53d6fc 100644
--- a/server/nodes/social/social_receive.py
+++ b/server/nodes/social/social_receive.py
@@ -10,7 +10,7 @@ delegates the per-platform unwrap to the existing handler.
from __future__ import annotations
-from typing import Any, Literal, Optional
+from typing import Any, Dict, Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
@@ -115,19 +115,42 @@ class SocialReceiveNode(ActionNode):
Params = SocialReceiveParams
Output = SocialReceiveOutput
- @Operation("normalize")
- async def normalize(self, ctx: NodeContext, params: SocialReceiveParams) -> Any:
+ async def execute(
+ self,
+ node_id: str,
+ parameters: Dict[str, Any],
+ context,
+ ) -> Dict[str, Any]:
+ """Override the base envelope wrap so the ``filtered`` metadata
+ flag the handler emits survives to the top-level result dict.
+ Without this override, BaseNode._wrap_success would re-wrap
+ ``response.get("result")`` and drop every sibling key, including
+ ``filtered`` and ``reason``.
+ """
+ import time
+
from ._base import handle_social_receive
- outputs = ctx.raw.get("connected_outputs") or {}
- source_nodes = ctx.raw.get("source_nodes") or []
+
+ start_time = time.time()
+ try:
+ params_obj = self._validate_params(parameters)
+ except Exception as e:
+ return self._wrap_error(start_time=start_time, error=f"Invalid parameters: {e}")
+
+ outputs = context.raw.get("connected_outputs") or {}
+ source_nodes = context.raw.get("source_nodes") or []
response = await handle_social_receive(
- node_id=ctx.node_id, node_type=self.type,
- parameters=params.model_dump(), context=ctx.raw,
- connected_outputs=outputs, source_nodes=source_nodes,
+ node_id=node_id, node_type=self.type,
+ parameters=params_obj.model_dump(), context=context.raw,
+ outputs=outputs, source_nodes=source_nodes,
)
- if response.get("success") is False:
- raise RuntimeError(response.get("error") or "social receive failed")
- return response.get("result") or {}
+ return response
+
+ @Operation("normalize")
+ async def normalize(self, ctx: NodeContext, params: SocialReceiveParams) -> Any:
+ # Kept for the contract invariant that every plugin declares an
+ # @Operation. Real dispatch goes through :meth:`execute` above.
+ raise NotImplementedError("socialReceive uses execute() override")
# socialReceive needs the executor's connected_outputs injection
diff --git a/server/nodes/telegram/telegram_receive.py b/server/nodes/telegram/telegram_receive.py
index a839d871..b0cbe31c 100644
--- a/server/nodes/telegram/telegram_receive.py
+++ b/server/nodes/telegram/telegram_receive.py
@@ -120,6 +120,30 @@ class TelegramReceiveNode(TriggerNode):
from services.event_waiter import build_telegram_filter
return build_telegram_filter(params.model_dump())
+ async def execute(
+ self,
+ node_id: str,
+ parameters: Dict[str, Any],
+ context,
+ ) -> Dict[str, Any]:
+ # Pre-flight: refuse to register a waiter if the bot isn't
+ # connected. Matches the pre-refactor handler contract where a
+ # disconnected bot short-circuits before event_waiter.register
+ # and returns an error envelope.
+ import time
+
+ from services.telegram_service import get_telegram_service
+
+ svc = get_telegram_service()
+ if not getattr(svc, "connected", False):
+ return self._wrap_error(
+ start_time=time.time(),
+ error=(
+ "Telegram bot not connected. Add bot token in Credentials."
+ ),
+ )
+ return await super().execute(node_id, parameters, context)
+
@Operation("wait")
async def wait(self, ctx: NodeContext, params: TelegramReceiveParams) -> TelegramReceiveOutput:
raise NotImplementedError(
diff --git a/server/nodes/telegram/telegram_send.py b/server/nodes/telegram/telegram_send.py
index ab4d02d8..9a794843 100644
--- a/server/nodes/telegram/telegram_send.py
+++ b/server/nodes/telegram/telegram_send.py
@@ -71,15 +71,19 @@ class TelegramSendParams(BaseModel):
)
# ===== LOCATION =====
- latitude: float = Field(
- default=0.0,
+ # Optional[float] with default None so the handler can tell the
+ # "user omitted the field" case apart from "user set 0.0 deliberately"
+ # (Null Island is a real place). The matching handler check is
+ # ``if params.latitude is None or params.longitude is None: raise``.
+ latitude: Optional[float] = Field(
+ default=None,
description="Location latitude (-90 to 90)",
json_schema_extra={
"displayOptions": {"show": {"message_type": ["location"]}},
},
)
- longitude: float = Field(
- default=0.0,
+ longitude: Optional[float] = Field(
+ default=None,
description="Location longitude (-180 to 180)",
json_schema_extra={
"displayOptions": {"show": {"message_type": ["location"]}},
diff --git a/server/nodes/text/file_handler.py b/server/nodes/text/file_handler.py
index bc693872..78a7678f 100644
--- a/server/nodes/text/file_handler.py
+++ b/server/nodes/text/file_handler.py
@@ -1,4 +1,10 @@
-"""File Handler — Wave 11.C migration. Read/write/process files."""
+"""File Handler — Wave 11.C migration.
+
+Content-metadata wrapper (NOT file I/O). Takes a text content blob plus
+file-type / file-name metadata and returns a wrapped ``{type: "file",
+data: {...}}`` envelope for downstream nodes. Actual file I/O lives in
+``nodes/filesystem/file_read`` / ``file_modify``.
+"""
from __future__ import annotations
@@ -10,18 +16,30 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueue
class FileHandlerParams(BaseModel):
- operation: Literal["read", "write", "append", "delete"] = "read"
- file_path: str = Field(...)
- content: str = Field(default="")
- encoding: str = Field(default="utf-8")
+ file_type: Literal[
+ "generic", "markdown", "text", "json", "csv", "html", "xml",
+ ] = Field(
+ default="generic",
+ description="Content type tag used for downstream processing hints.",
+ )
+ file_name: str = Field(
+ default="untitled.txt",
+ description="Filename label attached to the wrapped content.",
+ )
+ content: str = Field(
+ default="",
+ description="Text content to wrap.",
+ json_schema_extra={"rows": 8},
+ )
model_config = ConfigDict(extra="ignore")
class FileHandlerOutput(BaseModel):
- operation: Optional[str] = None
- content: Optional[str] = None
- success: Optional[bool] = None
+ type: Optional[str] = None
+ data: Optional[dict] = None
+ node_id: Optional[str] = None
+ timestamp: Optional[str] = None
model_config = ConfigDict(extra="allow")
@@ -29,29 +47,38 @@ class FileHandlerOutput(BaseModel):
class FileHandlerNode(ActionNode):
type = "fileHandler"
display_name = "File Handler"
- subtitle = "Read/Write Files"
+ subtitle = "Wrap Content Metadata"
icon = "📁"
color = "#bd93f9"
group = ("text",)
- description = "Read, write, and process files"
+ description = "Wrap text content with file-type / file-name metadata"
component_kind = "square"
handles = (
{"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
{"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
)
- annotations = {"destructive": True, "readonly": False, "open_world": False}
+ annotations = {"destructive": False, "readonly": True, "open_world": False}
task_queue = TaskQueue.DEFAULT
Params = FileHandlerParams
Output = FileHandlerOutput
- @Operation("dispatch")
- async def dispatch(self, ctx: NodeContext, params: FileHandlerParams) -> Any:
+ @Operation("wrap")
+ async def wrap(self, ctx: NodeContext, params: FileHandlerParams) -> Any:
from core.container import container
text_service = container.text_service()
+ # TextService.execute_file_handler uses camelCase keys by
+ # historical contract (the result dict it emits is served to
+ # the frontend with camelCase field names too). Translate our
+ # snake_case Params to the service's expected shape.
response = await text_service.execute_file_handler(
- ctx.node_id, params.model_dump(),
+ ctx.node_id,
+ {
+ "fileType": params.file_type,
+ "fileName": params.file_name,
+ "content": params.content,
+ },
)
if response.get("success"):
return response.get("result") or response
diff --git a/server/nodes/utility/process_manager.py b/server/nodes/utility/process_manager.py
index 7bc9c082..1219e848 100644
--- a/server/nodes/utility/process_manager.py
+++ b/server/nodes/utility/process_manager.py
@@ -72,23 +72,32 @@ class ProcessManagerNode(ActionNode):
op = params.operation
name = _clean(params.name)
+ def _unwrap(response: Any) -> Any:
+ """Raise on service-level failure envelopes so the plugin
+ wrapper returns success=False instead of burying a
+ ``{"success": False, "error": "..."}`` inside the result dict.
+ """
+ if isinstance(response, dict) and response.get("success") is False:
+ raise RuntimeError(response.get("error") or "process operation failed")
+ return response
+
if op == "start":
- return await svc.start(
+ return _unwrap(await svc.start(
name=name,
command=_clean(params.command),
workflow_id=workflow_id,
working_directory=_clean(params.cwd) or agent_dir,
- )
+ ))
if op == "stop":
- return await svc.stop(name, workflow_id)
+ return _unwrap(await svc.stop(name, workflow_id))
if op == "restart":
- return await svc.restart(name, workflow_id)
+ return _unwrap(await svc.restart(name, workflow_id))
if op == "send_input":
- return await svc.send_input(name, workflow_id, _clean(params.input_text))
+ return _unwrap(await svc.send_input(name, workflow_id, _clean(params.input_text)))
if op == "list":
return {"processes": svc.list_processes(workflow_id)}
if op == "get_output":
- return svc.get_output(name, workflow_id, params.stream, params.tail, 0)
+ return _unwrap(svc.get_output(name, workflow_id, params.stream, params.tail, 0))
raise RuntimeError(f"Unknown operation: {op}")
diff --git a/server/services/plugin/trigger.py b/server/services/plugin/trigger.py
index adf12243..02cfd631 100644
--- a/server/services/plugin/trigger.py
+++ b/server/services/plugin/trigger.py
@@ -91,6 +91,15 @@ class TriggerNode(BaseNode, abstract=True):
return self._wrap_error(start_time=start_time, error=f"Invalid parameters: {e}")
if self.mode == "event":
+ # Pre-flight: refuse to register a waiter if event_waiter
+ # doesn't recognise this trigger type. Pre-refactor handler
+ # contract — keeps Run-button feedback honest when the trigger
+ # config registry is missing the event_type entry.
+ if event_waiter.get_trigger_config(self.type) is None:
+ return self._wrap_error(
+ start_time=start_time,
+ error=f"Unknown trigger type: {self.type}",
+ )
waiter = await event_waiter.register(
node_type=self.type,
node_id=node_id,
diff --git a/server/tests/nodes/test_chat_utility.py b/server/tests/nodes/test_chat_utility.py
index 30993ede..592f3f02 100644
--- a/server/tests/nodes/test_chat_utility.py
+++ b/server/tests/nodes/test_chat_utility.py
@@ -371,27 +371,33 @@ class TestTextGenerator:
class TestFileHandler:
async def test_happy_path_wraps_content_metadata(self, harness):
+ # Nest a fresh patched_container so container.text_service() is
+ # wired to the real TextService (plugin resolves text_service via
+ # container, not the NodeExecutor-injected one).
from services.text import TextService
from services.node_executor import NodeExecutor
+ from tests.nodes._mocks import patched_container
- harness.text_service = TextService()
+ real_text = TextService()
+ harness.text_service = real_text
harness.executor = NodeExecutor(
database=harness.database,
ai_service=harness.ai_service,
maps_service=harness.maps_service,
- text_service=harness.text_service,
+ text_service=real_text,
android_service=harness.android_service,
settings=harness.settings,
output_store=harness._record_output,
)
- result = await harness.execute(
- "fileHandler",
- {
- "fileType": "markdown",
- "content": "# hello",
- "fileName": "note.md",
- },
- )
+ with patched_container(text_service=real_text):
+ result = await harness.execute(
+ "fileHandler",
+ {
+ "file_type": "markdown",
+ "content": "# hello",
+ "file_name": "note.md",
+ },
+ )
harness.assert_envelope(result, success=True)
payload = result["result"]
assert payload["type"] == "file"
@@ -405,18 +411,21 @@ class TestFileHandler:
async def test_defaults_applied(self, harness):
from services.text import TextService
from services.node_executor import NodeExecutor
+ from tests.nodes._mocks import patched_container
- harness.text_service = TextService()
+ real_text = TextService()
+ harness.text_service = real_text
harness.executor = NodeExecutor(
database=harness.database,
ai_service=harness.ai_service,
maps_service=harness.maps_service,
- text_service=harness.text_service,
+ text_service=real_text,
android_service=harness.android_service,
settings=harness.settings,
output_store=harness._record_output,
)
- result = await harness.execute("fileHandler", {})
+ with patched_container(text_service=real_text):
+ result = await harness.execute("fileHandler", {})
harness.assert_envelope(result, success=True)
assert result["result"]["data"]["fileName"] == "untitled.txt"
assert result["result"]["data"]["fileType"] == "generic"
diff --git a/server/tests/nodes/test_telegram_social.py b/server/tests/nodes/test_telegram_social.py
index 7150ed46..5190ffe7 100644
--- a/server/tests/nodes/test_telegram_social.py
+++ b/server/tests/nodes/test_telegram_social.py
@@ -20,6 +20,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+# Force import so unittest.mock.patch("services.telegram_service.X") can
+# resolve the attribute path. Without this the module is never loaded at
+# test-collection time and patch raises AttributeError.
+import services.telegram_service # noqa: F401
+
from tests.nodes._mocks import patched_broadcaster, patched_container
diff --git a/server/tests/nodes/test_workflow_triggers.py b/server/tests/nodes/test_workflow_triggers.py
index 34a3af02..5c72240d 100644
--- a/server/tests/nodes/test_workflow_triggers.py
+++ b/server/tests/nodes/test_workflow_triggers.py
@@ -390,9 +390,9 @@ class TestWebhookResponse:
result = await harness.execute(
"webhookResponse",
{
- "statusCode": 201,
- "responseBody": '{"ok": true}',
- "contentType": "application/json",
+ "status_code": 201,
+ "body": '{"ok": true}',
+ "content_type": "application/json",
},
)
harness.assert_envelope(result, success=True)
@@ -436,9 +436,9 @@ class TestWebhookResponse:
await harness.execute(
"webhookResponse",
{
- "statusCode": 200,
- "responseBody": "echo {{input.status}} and {{httpRequest.data}}",
- "contentType": "text/plain",
+ "status_code": 200,
+ "body": "echo {{input.status}} and {{httpRequest.data}}",
+ "content_type": "text/plain",
},
node_id="resp-node",
nodes=nodes,
@@ -473,7 +473,7 @@ class TestWebhookResponse:
with _patched_resolve_webhook_response() as resolve:
await harness.execute(
"webhookResponse",
- {"statusCode": 200, "responseBody": "", "contentType": "application/json"},
+ {"status_code": 200, "body": "", "content_type": "application/json"},
node_id="resp-node",
nodes=nodes,
edges=edges,