Skip to content

Self-improving AI Employees for everyone

fix(events): scope chat messages to their workflow - stop cross-workflow trigger firing

trohitgd139439546c0
diff --git a/docs-internal/event_framework.md b/docs-internal/event_framework.md
index e974294f..92c30e3f 100644
--- a/docs-internal/event_framework.md
+++ b/docs-internal/event_framework.md
@@ -89,6 +89,20 @@ services/events/dispatch.py:emit(event: WorkflowEvent)
└─→ status_broadcaster.broadcast() — direct in-process WS fan-out
```
+**Workflow-scoped delivery** (core dispatch rule, July 2026): an envelope
+whose `workflow_id` field is set by its producer's call site reaches ONLY
+that workflow's consumers — `_signal_running_consumers` appends
+`AND EventWorkflowId='<id>'` to both the listener clause and the controller
+clause of the Visibility query (every consumer shape carries that Search
+Attribute). Unscoped envelopes (telegram / webhook / gmail — genuinely
+broadcast semantics) are unchanged. First producer: chat — the panel is
+bound to one workflow (`session_id` IS its workflow id), and without the
+scope one workflow's chat message fired every deployed workflow's
+chatTrigger. The scoping DECISION lives in the core call site
+(`routers/websocket.py:handle_send_chat_message`; the legacy `"default"`
+session stays unscoped) and the narrowing in core dispatch — plugin
+`_events.py` factories only plumb the field of their own wire shape.
+
Worker is embedded in the FastAPI process (`main.py:211-292`
`TemporalWorkerManager.start()` runs as `asyncio.create_task()`). Activities
and the WebSocket connection pool share memory + event loop, so the fan-out
diff --git a/server/nodes/trigger/chat_trigger/_events.py b/server/nodes/trigger/chat_trigger/_events.py
index fa95dba1..752fcbf2 100644
--- a/server/nodes/trigger/chat_trigger/_events.py
+++ b/server/nodes/trigger/chat_trigger/_events.py
@@ -13,7 +13,7 @@ so the deployment manager skips ``setup_event_trigger`` and the legacy
from __future__ import annotations
-from typing import Any, Mapping
+from typing import Any, Mapping, Optional
from services.events.envelope import WorkflowEvent
@@ -24,25 +24,40 @@ from services.events.envelope import WorkflowEvent
_WIRE_ROUTING_KEY = "chat_message_received"
-def chat_message_received(event_data: Mapping[str, Any]) -> WorkflowEvent:
+def chat_message_received(
+ event_data: Mapping[str, Any],
+ *,
+ workflow_id: Optional[str] = None,
+) -> WorkflowEvent:
"""Incoming chat message envelope. ``subject`` is the session_id so
- consumers can route per-conversation."""
+ consumers can route per-conversation.
+
+ ``workflow_id`` is carried verbatim onto the envelope — the scoping
+ DECISION belongs to the core call site (routers/websocket.py) and
+ the scoped-delivery rule to core dispatch; this factory only plumbs
+ the field of its own wire shape.
+ """
payload = dict(event_data)
session_id = payload.get("session_id")
return WorkflowEvent(
source="opencompany://nodes/chat_trigger",
type="com.opencompany.chat.message.received",
subject=str(session_id) if session_id else None,
+ workflow_id=workflow_id,
data=payload,
)
-async def dispatch_chat_message_received(event_data: Mapping[str, Any]) -> None:
+async def dispatch_chat_message_received(
+ event_data: Mapping[str, Any],
+ *,
+ workflow_id: Optional[str] = None,
+) -> None:
"""Dispatch an incoming chat message via the canary CloudEvents path."""
from services.events.dispatch import emit
await emit(
- chat_message_received(dict(event_data)),
+ chat_message_received(dict(event_data), workflow_id=workflow_id),
wire_routing_key=_WIRE_ROUTING_KEY,
)
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 3f5735ce..6ed58488 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -1071,10 +1071,21 @@ async def handle_send_chat_message(data: Dict[str, Any], websocket: WebSocket) -
# Build event data matching chatTrigger output schema
event_data = {"message": message, "timestamp": timestamp, "session_id": session_id}
+ # Chat is inherently workflow-scoped: the panel is bound to ONE
+ # workflow and its ``session_id`` IS that workflow's id ("default"
+ # only when no workflow is open — that legacy session keeps broadcast
+ # semantics). The scope rides the envelope's ``workflow_id`` so
+ # ``dispatch.emit`` signals only this workflow's consumers via the
+ # EventWorkflowId Search Attribute; without it, one workflow's chat
+ # message fired EVERY deployed workflow's chatTrigger. The scoping
+ # decision lives here (core router) and the narrowing in core
+ # dispatch — the plugin factory only carries the field.
+ workflow_scope = session_id if session_id and session_id != "default" else None
+
# Dispatch via canary CloudEvents path — Visibility-query Signal
# fan-out to running TriggerListenerWorkflow consumers + in-process
# WS broadcast on ``chat_message_received``.
- await dispatch_chat_message_received(event_data)
+ await dispatch_chat_message_received(event_data, workflow_id=workflow_scope)
logger.info(f"[ChatMessage] Dispatched canary event for session={session_id}")
diff --git a/server/services/events/dispatch.py b/server/services/events/dispatch.py
index b3edcda3..04356e79 100644
--- a/server/services/events/dispatch.py
+++ b/server/services/events/dispatch.py
@@ -126,11 +126,26 @@ async def _signal_running_consumers(event: WorkflowEvent) -> None:
clauses = " OR ".join(f"EventType='{event_type}'" for event_type in event_types)
query = _RUNNING_COMPAT_CONSUMERS_QUERY.format(event_type_clauses=clauses)
+ # Workflow-scoped delivery (core dispatch rule, not per-plugin code):
+ # an envelope whose ``workflow_id`` is set by its producer's call site
+ # reaches ONLY that workflow's consumers. Every consumer shape carries
+ # the EventWorkflowId Search Attribute (controllers via
+ # _start_controller, canary listeners via the deployment manager,
+ # direct-exec MachinaWorkflow via the executor), so the narrowing is
+ # uniform. Unscoped envelopes (telegram / webhook / gmail — genuinely
+ # broadcast semantics) are unchanged. Without this, one workflow's
+ # chat message fired every deployed workflow's chatTrigger.
+ scope_clause = ""
+ scoped_workflow_id = getattr(event, "workflow_id", None)
+ if scoped_workflow_id:
+ literal = str(scoped_workflow_id).replace("'", "''")
+ scope_clause = f" AND EventWorkflowId='{literal}'"
+
try:
# Controlled deployments keep trigger definitions in their controller
# history. Controllers filter the event against those definitions, so
# no TriggerListenerWorkflow/ PollingTriggerWorkflow execution exists.
- query = f"({query}) OR ({_RUNNING_CONTROLLERS_QUERY})"
+ query = f"({query}{scope_clause}) OR ({_RUNNING_CONTROLLERS_QUERY}{scope_clause})"
consumers = []
async for wf in client.list_workflows(query=query):
consumers.append(wf)
diff --git a/server/tests/test_chat_trigger_canary_producer.py b/server/tests/test_chat_trigger_canary_producer.py
index 15ae05c5..082df41e 100644
--- a/server/tests/test_chat_trigger_canary_producer.py
+++ b/server/tests/test_chat_trigger_canary_producer.py
@@ -99,3 +99,48 @@ class TestChatTriggerProducerCanaryEmit:
assert event.type == "com.opencompany.chat.message.received"
assert event.subject == "sess-1"
assert emit_calls[0]["wire_routing_key"] == "chat_message_received"
+ # No scope passed -> unscoped envelope (broadcast semantics).
+ assert event.workflow_id is None
+
+ @pytest.mark.asyncio
+ async def test_workflow_scope_rides_the_envelope_verbatim(self, monkeypatch):
+ """The factory plumbs ``workflow_id`` onto the envelope without
+ any decision logic — the scoping RULE lives at the core call
+ site (routers/websocket.py) and the scoped-delivery narrowing in
+ core dispatch. Without the scope, one workflow's chat message
+ fired every deployed workflow's chatTrigger."""
+ from nodes.trigger.chat_trigger import _events
+ from services.events import dispatch as dispatch_mod
+
+ emit_calls: List[Any] = []
+
+ async def fake_emit(event, **kwargs):
+ emit_calls.append({"event": event, **kwargs})
+ return event
+
+ monkeypatch.setattr(dispatch_mod, "emit", fake_emit)
+
+ await _events.dispatch_chat_message_received(
+ {"message": "hi", "session_id": "wf-1", "timestamp": "t"},
+ workflow_id="wf-1",
+ )
+
+ assert emit_calls[0]["event"].workflow_id == "wf-1"
+
+ def test_router_decides_the_scope_not_the_plugin(self):
+ """The chat WS handler (core) derives the workflow scope from the
+ session and the plugin factory carries it verbatim — execution
+ logic stays out of the node folder."""
+ from nodes.trigger.chat_trigger import _events
+ from routers import websocket as ws_router
+
+ factory_src = inspect.getsource(_events.chat_message_received)
+ assert '"default"' not in factory_src, (
+ "The plugin factory must not embed the session!='default' "
+ "scoping decision — that rule lives in "
+ "routers/websocket.py:handle_send_chat_message."
+ )
+
+ handler_src = inspect.getsource(ws_router.handle_send_chat_message)
+ assert "workflow_id=workflow_scope" in handler_src
+ assert 'session_id != "default"' in handler_src