Skip to content

Self-improving AI Employees for everyone

fix(events): stop broadcasting inbound messages to every socket

trohitg7745ca14d677
diff --git a/CLAUDE.md b/CLAUDE.md
index accdc145..488828e8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2824,7 +2824,7 @@ This function:
- **`configure_logging(settings)` must run BEFORE plugin self-registration imports**: in `main.py`, `Settings()` + `configure_logging(settings)` + `init_tracing()` + `get_logger(__name__)` happen ahead of `from core.container import container` and `from routers import …`. Otherwise plugin folders that register on import call `logger.debug(...)` while structlog is still on its default processor chain (which includes `TimeStamper` + no `filter_by_level`) — symptom is double timestamps + debug records leaking despite `LOG_LEVEL=INFO`.
- **Plugin-identifier shape validator (`services/plugin/identifiers.py`)** (`7700f87`): `NODE_TYPE_PATTERN = r"^[A-Za-z_][A-Za-z0-9_]*$"` + `is_valid_node_type(value)`. Single source of truth used by FastAPI URL routes (`Path(pattern=NODE_TYPE_PATTERN)` in `routers/schemas.py`) AND internal helpers (`nodes/_visuals.py::get_plugin_meta` / `get_plugin_icon_path`). Hardens the icon-resolution endpoints: the registry lookup `get_node_class(node_type)` already gates the taint in practice, but CodeQL can't follow registry-mediated sanitization, so `fullmatch` at the function boundary states the constraint explicitly. **It does NOT close the CodeQL `py/path-injection` alerts, despite what this line used to claim.** Verified against the live SARIF (2026-07-26): `_visuals.py:217`, `_visuals.py:239` and `schemas.py:144` are still reported on every scan and were closed by *manual dismissal*, not by the regex. The reason is structural and worth knowing before you attempt a fix: the flagged sink is the path-construction/`resolve()` call itself, so no guard placed after it can clear the taint, and an interprocedural `fullmatch` in a helper is not treated as a barrier either. **`py/path-injection` on a containment helper is dismissed here, not coded around** — see `nodes/filesystem/_backend.py::resolve_within` and alerts #29-33, #39, #140, #142, #154-157. **The one shape the query does accept** is normalise-then-prefix-check performed *before* the path is used: `core/approot.py::resolve_static_asset` joins the request path onto the real base dir, runs `os.path.normpath`, and returns `None` unless the result starts with that base plus a separator. `main.py`'s SPA fallback was rewritten onto it in September 2026 (alerts #158-160) because that route can take a `None` and fall through to the SPA shell. Reach for that shape when the call site tolerates a miss; keep the dismissal route for helpers whose flagged sink IS the `resolve()`. Contract test (`tests/services/test_identifiers.py`, 47 cases) locks the regex against `../etc/passwd`, `..\windows\system32`, `foo\x00bar`, `%2e%2e%2fetc`, `foo;bar`, `${HOME}`, `` foo`bar ``, CRLF, and non-string input.
- **CLI recovery-resilience invariants** (May 2026): `python -m cli clean` must run end-to-end on a system Python with no third-party deps. Achieved by: (a) every verb in [`cli/cli.py`](./cli/cli.py) is a lazy stub that imports its impl inside the function body — `import cli.cli` does NOT pull in `anyio` / `psutil` / `cli.supervisor` / sibling verb modules (300 → 131 modules at boot). (b) [`cli/_common.py`](./cli/_common.py) defers `cli.supervisor` imports inside `build_backend_spec` so importing `cli._common` (and therefore `clean.py`) doesn't drag in rich. (c) [`cli/platform_.py`](./cli/platform_.py) lazy-imports `platformdirs` inside the four `user_*_dir` helpers — module loads without the wheel. (d) [`cli/commands/clean.py`](./cli/commands/clean.py) uses stdlib `print()` (no rich) + lazy `cli.ports` import inside `_kill_running_processes` wrapped in `try/except ImportError` (skip-with-warning if psutil is missing). (e)+(f) retired July 2026: the CLI no longer supervises Temporal at all — the backend lifespan owns the dev server via `services.temporal._runtime.ensure_started()` (`cli/commands/_temporal_specs.py` and the `_supervised_runtime.py` shim were deleted; long-running specs spawn the server venv interpreter directly via `cli.platform_.server_venv_python`, no resident `uv run` parents). (g) `daemon` is now a verb-per-file package ([`cli/commands/daemon/`](./cli/commands/daemon/) — `_state.py` + `start.py` + `stop.py` + `status.py` + `restart.py`) following pdm's `commands/venv/` shape; PID-file resolution is a function (`pid_dir()`) not a module-level attribute so platformdirs only loads at call time.
-- **Wave 13 canary fixes** — six load-bearing corrections to the Wave 12 event framework. See [docs-internal/event_framework.md → Wave 13 fixes](./docs-internal/event_framework.md#wave-13-fixes) for the full breakdown. Key invariants to remember when working on canary triggers: (1) `register_canary_trigger_type(node_type, cloudevent_type)` requires the CloudEvents reverse-DNS string as second arg — must match the producer's `WorkflowEvent.type` exactly or the deployment manager's `EventType` SA won't match `dispatch.emit`'s Visibility query (silent firing failure). Diverging re-registration raises `ValueError` so plugin upgrades surface loudly. (2) Plugin `_events.py` for canary-registered triggers is canary-only — no `event_waiter.dispatch` / `send_custom_event` calls (those have zero consumers in canary-on mode). `dispatch.emit(envelope, wire_routing_key=...)` handles BOTH Temporal Signal fan-out AND in-process WS broadcast. (3) `TriggerListenerWorkflow` + `PollingTriggerWorkflow` call `broadcast_trigger_status_activity` before/after each child spawn for firing-pulse UX (matches legacy `triggers.py` collector/processor). (4) `PollingTriggerNode.as_poll_activity` returns `seen_ids: list(current)` — NOT `list(prior_seen | current)` (the latter grows unboundedly; Gmail at ~100/day hit ~36K entries in a year). The legacy `_build_poll_coroutine` does `seen = set(current)` at end of cycle for the same reason. Visibility-filtered providers (Gmail-unread) re-emit on re-surface, which is correct. (5) Canary trigger output persistence: `MachinaWorkflow.run`'s pre-executed loop schedules `store_node_output_activity` for every firing trigger so `ParameterResolver` can resolve `{{triggerNode.field}}` in downstream nodes (the legacy `_execute_from_trigger` did this via `_store_output(trigger_node_id, "output_0", ...)`; canary skipped it pre-fix). Skips non-firing siblings (`_trigger_output={"not_triggered": True}`). (6) `DeploymentManager.cancel` sweeps stuck node statuses via `_clear_stuck_node_statuses(workflow_id, include_waiting=True)` + emits terminal `update_workflow_status(executing=False, workflow_id=...)`. Without these the FE leaves downstream nodes glowing forever after deployment cancel and the toolbar Start/Stop indicator stays at `executing=True`. The delegation guard inside `_clear_stuck_node_statuses` still protects in-flight fire-and-forget child agents.
+- **Wave 13 canary fixes** — six load-bearing corrections to the Wave 12 event framework. See [docs-internal/event_framework.md → Wave 13 fixes](./docs-internal/event_framework.md#wave-13-fixes) for the full breakdown. Key invariants to remember when working on canary triggers: (1) `register_canary_trigger_type(node_type, cloudevent_type)` requires the CloudEvents reverse-DNS string as second arg — must match the producer's `WorkflowEvent.type` exactly or the deployment manager's `EventType` SA won't match `dispatch.emit`'s Visibility query (silent firing failure). Diverging re-registration raises `ValueError` so plugin upgrades surface loudly. (2) Plugin `_events.py` for canary-registered triggers is canary-only — no `event_waiter.dispatch` / `send_custom_event` calls (those have zero consumers in canary-on mode). `dispatch.emit(envelope, wire_routing_key=..., broadcast=...)` handles BOTH Temporal Signal fan-out AND, when `broadcast=True`, the in-process WS broadcast; `broadcast` has no default, and a producer whose payload is someone's content passes `False` (RFC-0005 Phase 0.9). (3) `TriggerListenerWorkflow` + `PollingTriggerWorkflow` call `broadcast_trigger_status_activity` before/after each child spawn for firing-pulse UX (matches legacy `triggers.py` collector/processor). (4) `PollingTriggerNode.as_poll_activity` returns `seen_ids: list(current)` — NOT `list(prior_seen | current)` (the latter grows unboundedly; Gmail at ~100/day hit ~36K entries in a year). The legacy `_build_poll_coroutine` does `seen = set(current)` at end of cycle for the same reason. Visibility-filtered providers (Gmail-unread) re-emit on re-surface, which is correct. (5) Canary trigger output persistence: `MachinaWorkflow.run`'s pre-executed loop schedules `store_node_output_activity` for every firing trigger so `ParameterResolver` can resolve `{{triggerNode.field}}` in downstream nodes (the legacy `_execute_from_trigger` did this via `_store_output(trigger_node_id, "output_0", ...)`; canary skipped it pre-fix). Skips non-firing siblings (`_trigger_output={"not_triggered": True}`). (6) `DeploymentManager.cancel` sweeps stuck node statuses via `_clear_stuck_node_statuses(workflow_id, include_waiting=True)` + emits terminal `update_workflow_status(executing=False, workflow_id=...)`. Without these the FE leaves downstream nodes glowing forever after deployment cancel and the toolbar Start/Stop indicator stays at `executing=True`. The delegation guard inside `_clear_stuck_node_statuses` still protects in-flight fire-and-forget child agents.
- **Deployment reconcile snapshot on WS connect** (de8df87): a stale FE `deploymentStatus.isRunning=true` used to survive a backend restart because the in-memory `DeploymentManager._deployments` dict was wiped (no recovery wiring — the `RecoverySweeper.set_recovery_callback` extension point exists but is intentionally unwired; see the "workflow status not properly recognized" investigation). The Start button therefore stayed showing "Stop" forever. Fix: new `WorkflowEvent.deployment_snapshot(running_workflow_ids)` typed factory (`source = opencompany://services/workflow`, `type = workflow.deployment.snapshot`) + `broadcaster._send_deployment_snapshot(websocket)` that runs at the tail of `broadcaster.connect()` (single-target, NOT fan-out — only the just-connecting client needs to reconcile). FE `case 'deployment_snapshot'` in `WebSocketContext.tsx` iterates `useAppStore.workflowUIStates` and clears `isExecuting=true` on any workflow NOT in the snapshot's running set (empty list is meaningful — this is the load-bearing reset). Also reconciles `deploymentStatus.isRunning` for the active workflow. Distinct from `workflow_lifecycle("deployment.started")` (state-transition edge event) — the snapshot is an idempotent state dump tied to client connect, not a transition.
- **Agent progress badge — defensive status invariant** (15b8d9d): `AIAgentNode`'s "N / max" iteration badge is gated on `isExecuting && typeof iteration === 'number' && typeof maxIterations === 'number'` where `isExecuting = nodeStatus?.status === 'executing'`. The `agent_progress` handler USED to only set `data.iteration` / `data.max_iterations`, relying on a prior `node_status='executing'` broadcast to have already stamped the status. If agent_progress arrived first (race, single-step agent completion, out-of-order Temporal activity delivery), `status` stayed undefined and the badge was hidden even though the iteration data was populated. Fix: the agent_progress handler now defensively sets `status='executing'` on the slot — but preserves `'success'` / `'error'` if a later terminal broadcast already flipped the slot (terminal states win over the resurrection).
- **Temporal Worker tuner exclusivity** (Wave 16.4, 190c896): `Worker.__init__` rejects `tuner` alongside ANY of `max_concurrent_workflow_tasks` / `max_concurrent_activities` / `max_concurrent_local_activities` / `max_concurrent_nexus_tasks` — the tuner OWNS every slot supplier via its `WorkerTuner.create_composite(workflow_supplier, activity_supplier, local_activity_supplier, nexus_supplier)` and cannot coexist with the individual max-count kwargs. In `TemporalWorkerPool.start`, ALL FOUR max-count kwargs must be pulled from the base `worker_kwargs` when `tuner=` is added; the ai-heavy / browser queues use the tuner and preserve their 10-workflow-slot ceiling via `_tuner_for -> FixedSizeSlotSupplier(10)` on the workflow_supplier slot. The framework worker at `worker.py:282` does NOT use a tuner, so it keeps the plain `max_concurrent_workflow_tasks=10` + `max_concurrent_activities=self.pool_size` kwargs directly. `TEMPORAL_WORKER_POOL_ENABLED` defaulted to True in the same commit (`test_task_queue_coverage.py::TestWorkerPoolDefaultOn` locks the default via source-introspection so the flip survives a hasty revert).
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 5597fbee..2fed721a 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -425,27 +425,6 @@ export interface TerminalLogEntry {
details?: any;
}
-// WhatsApp received message structure (from Go service via whatsapp_message_received event)
-export interface WhatsAppMessage {
- message_id: string;
- sender: string;
- chat_id: string;
- type: 'text' | 'image' | 'video' | 'audio' | 'document' | 'location' | 'contact' | 'sticker';
- text?: string;
- timestamp: number;
- is_group: boolean;
- push_name?: string;
- media_url?: string;
- media_data?: string; // Base64 if includeMediaData is enabled
- caption?: string;
- // Location message fields
- latitude?: number;
- longitude?: number;
- // Contact message fields
- contact_name?: string;
- vcard?: string;
-}
-
export interface NodeParameters {
parameters: Record<string, any>;
version: number;
@@ -491,8 +470,6 @@ interface WebSocketContextValue {
twitterStatus: TwitterStatus;
googleStatus: GoogleStatus;
telegramStatus: TelegramStatus;
- whatsappMessages: WhatsAppMessage[]; // History of received messages
- lastWhatsAppMessage: WhatsAppMessage | null; // Most recent message
apiKeyStatuses: Record<string, ApiKeyStatus>;
consoleLogs: ConsoleLogEntry[]; // Console node output logs
terminalLogs: TerminalLogEntry[]; // Server/terminal logs
@@ -515,7 +492,6 @@ interface WebSocketContextValue {
updateCompactionStats: (workflowId: string, sessionId: string, stats: CompactionStats) => void;
requestStatus: () => void;
clearNodeStatus: (nodeId: string) => Promise<void>;
- clearWhatsAppMessages: () => void;
clearConsoleLogs: () => void;
clearTerminalLogs: () => void;
@@ -819,9 +795,6 @@ const getWebSocketUrl = () => {
return `${wsUrl}/ws/status`;
};
-// Max number of WhatsApp messages to keep in history
-const MAX_WHATSAPP_MESSAGE_HISTORY = 100;
-
export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
// Get authentication state - only connect WebSocket when authenticated
const { isAuthenticated, isLoading: authLoading } = useAuth();
@@ -841,8 +814,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
const [twitterStatus, setTwitterStatus] = useState<TwitterStatus>(defaultTwitterStatus);
const [googleStatus, setGoogleStatus] = useState<GoogleStatus>(defaultGoogleStatus);
const [telegramStatus, setTelegramStatus] = useState<TelegramStatus>(defaultTelegramStatus);
- const [whatsappMessages, setWhatsappMessages] = useState<WhatsAppMessage[]>([]);
- const [lastWhatsAppMessage, setLastWhatsAppMessage] = useState<WhatsAppMessage | null>(null);
const [apiKeyStatuses, setApiKeyStatuses] = useState<Record<string, ApiKeyStatus>>({});
const [consoleLogs, setConsoleLogs] = useState<ConsoleLogEntry[]>([]);
const [terminalLogs, setTerminalLogs] = useState<TerminalLogEntry[]>([]);
@@ -1396,39 +1367,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
break;
- case 'whatsapp_message_received':
- // Handle incoming WhatsApp message from Go service
- if (data) {
- const message: WhatsAppMessage = {
- message_id: data.message_id || data.id || '',
- sender: data.sender || data.from || '',
- chat_id: data.chat_id || data.chat || '',
- type: data.type || 'text',
- text: data.text || data.message || data.body || '',
- timestamp: data.timestamp || Date.now(),
- is_group: data.is_group || data.isGroup || false,
- push_name: data.push_name || data.pushName || data.name,
- media_url: data.media_url || data.mediaUrl,
- media_data: data.media_data || data.mediaData,
- caption: data.caption,
- latitude: data.latitude,
- longitude: data.longitude,
- contact_name: data.contact_name || data.contactName,
- vcard: data.vcard
- };
-
- // Update last message
- setLastWhatsAppMessage(message);
-
- // Add to message history (newest first, limit size)
- setWhatsappMessages(prev => {
- const updated = [message, ...prev];
- return updated.slice(0, MAX_WHATSAPP_MESSAGE_HISTORY);
- });
-
- }
- break;
-
case 'node_status':
// Per-workflow node status storage (n8n pattern)
// Store status under workflow_id -> node_id structure
@@ -2417,12 +2355,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
}, []);
- // Clear WhatsApp message history
- const clearWhatsAppMessages = useCallback(() => {
- setWhatsappMessages([]);
- setLastWhatsAppMessage(null);
- }, []);
-
// Clear console logs (both local state and database). Scoped to
// the currently-open workflow so other workflows' history survives.
const clearConsoleLogs = useCallback(() => {
@@ -3770,8 +3702,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
twitterStatus,
googleStatus,
telegramStatus,
- whatsappMessages,
- lastWhatsAppMessage,
apiKeyStatuses,
consoleLogs,
terminalLogs,
@@ -3794,7 +3724,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
getVariable,
requestStatus,
clearNodeStatus,
- clearWhatsAppMessages,
clearConsoleLogs,
clearTerminalLogs,
@@ -3872,7 +3801,6 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
isConnected, isReady, reconnecting,
androidStatus, setAndroidStatus,
whatsappStatus, twitterStatus, googleStatus, telegramStatus,
- whatsappMessages, lastWhatsAppMessage,
apiKeyStatuses,
consoleLogs, terminalLogs,
nodeStatuses, nodeParameters,
@@ -3880,7 +3808,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
compactionStats, updateCompactionStats,
getNodeStatus, getApiKeyStatus, getVariable,
requestStatus, clearNodeStatus,
- clearWhatsAppMessages, clearConsoleLogs, clearTerminalLogs,
+ clearConsoleLogs, clearTerminalLogs,
sendRequest, addEventListener,
getNodeParametersAsync, getAllNodeParametersAsync,
saveNodeParametersAsync, deleteNodeParametersAsync,
@@ -3996,20 +3924,6 @@ export const useWorkflowLock = (): WorkflowLock => {
return workflowLock;
};
-// Hook specifically for WhatsApp messages (for trigger nodes)
-export const useWhatsAppMessages = (): {
- messages: WhatsAppMessage[];
- lastMessage: WhatsAppMessage | null;
- clearMessages: () => void;
-} => {
- const { whatsappMessages, lastWhatsAppMessage, clearWhatsAppMessages } = useWebSocket();
- return {
- messages: whatsappMessages,
- lastMessage: lastWhatsAppMessage,
- clearMessages: clearWhatsAppMessages
- };
-};
-
// Hook to check if a tool is currently being executed by any AI Agent
// Used by tool nodes to show spinning indicator when they're being used
export const useIsToolExecuting = (toolName: string): boolean => {
diff --git a/docs-internal/event_framework.md b/docs-internal/event_framework.md
index 62d877eb..21bb5e21 100644
--- a/docs-internal/event_framework.md
+++ b/docs-internal/event_framework.md
@@ -104,10 +104,16 @@ what actually arrives is the limit. `WebhookSource.handle` no longer puts
each event on the source's queue, which nothing read.
**Private payloads skip the broadcast.** The broadcast reaches every
-connected socket. An event whose payload is one owner's content passes
-`broadcast=False` and reaches only the signalled workflows: chat does, since
-its envelope carries the owner's message text (clients learn of a new
-message from the identity-only `chat.updated`).
+connected socket, so `emit` has no default for `broadcast`: every producer
+states whether a client reads the frame (RFC-0005 Phase 0.9). An event whose
+payload is someone's content passes `broadcast=False` and reaches only the
+signalled workflows: owner chat (clients learn of a new message from the
+identity-only `chat.updated`), webhooks, Stripe, Dodo Payments, WhatsApp,
+WhatsApp Business, Telegram, Discord, email and Twitter. No client read any
+of those frames. Delegated-task completion broadcasts a separate
+identity-only envelope (the Task Manager panel refreshes on it), and
+`todos_updated` broadcasts because the checklist reads it. The WhatsApp
+bridge's outbound `event.message_sent` is no longer relayed at all.
**Workflow-scoped delivery** (core dispatch rule, July 2026): an envelope
whose `workflow_id` field is set by its producer's call site reaches ONLY
diff --git a/server/nodes/discord/_events.py b/server/nodes/discord/_events.py
index 51fe2ae4..45cebde5 100644
--- a/server/nodes/discord/_events.py
+++ b/server/nodes/discord/_events.py
@@ -92,20 +92,21 @@ async def broadcast_discord_status(
async def dispatch_discord_message_received(event_data: Mapping[str, Any]) -> None:
- """Single delivery path: Temporal listeners and the in-process socket.
+ """Single delivery path: Temporal listeners. Not broadcast: a message is
+ someone's content and no client reads it.
``emit`` is a no-op unless ``Settings.event_framework_enabled``, so the
legacy path stays the default.
"""
from services.events.dispatch import emit
- await emit(discord_message_received(event_data), wire_routing_key=MESSAGE_WIRE_KEY)
+ await emit(discord_message_received(event_data), wire_routing_key=MESSAGE_WIRE_KEY, broadcast=False)
async def dispatch_discord_interaction_created(event_data: Mapping[str, Any]) -> None:
from services.events.dispatch import emit
- await emit(discord_interaction_created(event_data), wire_routing_key=INTERACTION_WIRE_KEY)
+ await emit(discord_interaction_created(event_data), wire_routing_key=INTERACTION_WIRE_KEY, broadcast=False)
__all__ = [
diff --git a/server/nodes/email/_events.py b/server/nodes/email/_events.py
index be160e91..cd5707e6 100644
--- a/server/nodes/email/_events.py
+++ b/server/nodes/email/_events.py
@@ -4,8 +4,8 @@ Per RFC plugin_authoring_rfc.md §6.4: plugin-specific factories live in
the plugin folder.
Delivery: single ``dispatch.emit`` call routes events to running
-:class:`TriggerListenerWorkflow` consumers via Temporal Visibility AND
-broadcasts the envelope to FE on the ``email_received`` wire key.
+:class:`TriggerListenerWorkflow` consumers via Temporal Visibility. Not
+broadcast: an email is someone's content and no client reads it.
emailReceive is canary-registered (see ``nodes/email/__init__.py``) so
the deployment manager skips ``setup_event_trigger`` and the legacy
``event_waiter.dispatch`` path has zero consumers — removed.
@@ -45,6 +45,7 @@ async def dispatch_email_received(email_data: Mapping[str, Any]) -> None:
await emit(
email_message_received(dict(email_data)),
wire_routing_key=_WIRE_ROUTING_KEY,
+ broadcast=False,
)
diff --git a/server/nodes/stripe/_events.py b/server/nodes/stripe/_events.py
index 362e36ad..90d67079 100644
--- a/server/nodes/stripe/_events.py
+++ b/server/nodes/stripe/_events.py
@@ -26,7 +26,8 @@ from services.events.envelope import WorkflowEvent
# The exact string ``register_canary_trigger_type`` records for stripeReceive.
STRIPE_EVENT_RECEIVED_TYPE = "com.opencompany.stripe.event.received"
-# Outer WS wire key for the in-process broadcast half of ``emit``.
+# Outer wire key ``emit`` names the event with. Not broadcast: a Stripe
+# event carries customer details and no client reads it.
_WIRE_KEY = "stripe_event_received"
@@ -57,7 +58,7 @@ def stripe_event_received(
async def emit_stripe_event(event: WorkflowEvent) -> None:
from services.events.dispatch import emit
- await emit(event, wire_routing_key=_WIRE_KEY)
+ await emit(event, wire_routing_key=_WIRE_KEY, broadcast=False)
__all__ = [
diff --git a/server/nodes/telegram/_events.py b/server/nodes/telegram/_events.py
index dd989508..99217d75 100644
--- a/server/nodes/telegram/_events.py
+++ b/server/nodes/telegram/_events.py
@@ -150,16 +150,17 @@ async def dispatch_telegram_message_received(event_data: Mapping[str, Any]) -> N
"""Dispatch an incoming Telegram message via the canary CloudEvents path.
Single delivery: :func:`services.events.dispatch.emit` Signals running
- :class:`TriggerListenerWorkflow` consumers via Temporal Visibility AND
- broadcasts the envelope to FE on the ``telegram_message_received``
- wire key. telegramReceive is canary-registered so no legacy
- ``event_waiter`` waiter is ever registered for it.
+ :class:`TriggerListenerWorkflow` consumers via Temporal Visibility. Not
+ broadcast: the message is someone's content and no client reads it.
+ telegramReceive is canary-registered so no legacy ``event_waiter``
+ waiter is ever registered for it.
"""
from services.events.dispatch import emit
await emit(
telegram_message_received(dict(event_data)),
wire_routing_key=_MESSAGE_LEGACY_EVENT_TYPE,
+ broadcast=False,
)
diff --git a/server/nodes/tool/write_todos/_events.py b/server/nodes/tool/write_todos/_events.py
index 52f0b934..d5d7f226 100644
--- a/server/nodes/tool/write_todos/_events.py
+++ b/server/nodes/tool/write_todos/_events.py
@@ -68,6 +68,7 @@ async def dispatch_todos_updated(
workflow_id=workflow_id,
),
wire_routing_key=_TODOS_UPDATED_WIRE_KEY,
+ broadcast=True,
)
diff --git a/server/nodes/twitter/_events.py b/server/nodes/twitter/_events.py
index 9a2d49fd..18080243 100644
--- a/server/nodes/twitter/_events.py
+++ b/server/nodes/twitter/_events.py
@@ -90,6 +90,7 @@ async def dispatch_twitter_event_received(event_data: Mapping[str, Any]) -> int:
await emit(
twitter_event_received(payload),
wire_routing_key=_LEGACY_EVENT_TYPE,
+ broadcast=False,
)
return resolved
diff --git a/server/nodes/whatsapp/__init__.py b/server/nodes/whatsapp/__init__.py
index 40be784e..e0d31994 100644
--- a/server/nodes/whatsapp/__init__.py
+++ b/server/nodes/whatsapp/__init__.py
@@ -32,9 +32,9 @@ from services.ws_handler_registry import (
from ._credentials import WhatsAppCredential # noqa: F401 — side-effect register
from ._events import ( # noqa: F401 — re-exported for callers
broadcast_whatsapp_history_synced,
- broadcast_whatsapp_message,
broadcast_whatsapp_newsletter,
broadcast_whatsapp_status,
+ emit_whatsapp_message_received,
)
from ._filters import build_filter as build_whatsapp_filter
from ._handlers import WS_HANDLERS
@@ -71,7 +71,7 @@ register_option_loader("whatsappGroupMembers", load_group_members)
# Wave 12 C1 rollout #4: opt whatsappReceive into the
# TriggerListenerWorkflow consumer path. Producer side:
-# broadcast_whatsapp_message(direction="received", ...) in ._events.py
+# emit_whatsapp_message_received in ._events.py
# fans out via services.events.dispatch.emit; emit() is gated by
# Settings.event_framework_enabled so the legacy path stays default.
# See services/deployment/canary_registry.py.
diff --git a/server/nodes/whatsapp/_events.py b/server/nodes/whatsapp/_events.py
index 424cee55..19a4e58a 100644
--- a/server/nodes/whatsapp/_events.py
+++ b/server/nodes/whatsapp/_events.py
@@ -42,7 +42,6 @@ from services.events.envelope import WorkflowEvent
_STATUS_TYPED_WIRE_KEY = "plugin_connection_status" # shared cross-plugin channel
-_MESSAGE_SENT_WIRE_KEY = "whatsapp_message_sent"
_MESSAGE_RECEIVED_WIRE_KEY = "whatsapp_message_received"
_NEWSLETTER_WIRE_KEYS: Dict[str, str] = {
@@ -182,53 +181,20 @@ async def broadcast_whatsapp_status(
)
-async def broadcast_whatsapp_message(
- direction: Literal["sent", "received"],
- params: Mapping[str, Any],
-) -> None:
- """Emit a message event (sent or received).
+async def emit_whatsapp_message_received(params: Mapping[str, Any]) -> None:
+ """Deliver an inbound message to the deployed ``whatsappReceive``
+ triggers through :func:`services.events.dispatch.emit`.
- Inbound (``received``) routes via :func:`services.events.dispatch.emit`
- — the canary CloudEvents path Signals running
- :class:`TriggerListenerWorkflow` consumers AND broadcasts the
- envelope on the ``whatsapp_message_received`` wire key.
-
- Outbound (``sent``) is observation-only: no trigger consumer
- exists, so it bypasses ``dispatch.emit`` and goes out as a raw
- legacy frame on ``whatsapp_message_sent`` for the FE message-list
- UI.
+ Not broadcast: the message is a customer's content, and every
+ connected socket would receive it, while no client reads it.
"""
- from services.status_broadcaster import get_status_broadcaster
+ from services.events.dispatch import emit
- broadcaster = get_status_broadcaster()
- payload = dict(params)
-
- if direction == "received":
- # Canary path — single ``emit`` call delivers to Temporal
- # listeners + FE WS. The FE message-list handler at
- # WebSocketContext.tsx still reads ``data.*`` for back-compat,
- # so we also broadcast the legacy raw frame until that handler
- # migrates to envelope-shape (Wave 12 D4 follow-up).
- from services.events.dispatch import emit
-
- await broadcaster.broadcast(
- {
- "type": _MESSAGE_RECEIVED_WIRE_KEY,
- "data": payload,
- }
- )
- await emit(
- whatsapp_message_event("received", payload),
- wire_routing_key=_MESSAGE_RECEIVED_WIRE_KEY,
- )
- else:
- # Outbound observation only — direct legacy raw broadcast.
- await broadcaster.broadcast(
- {
- "type": _MESSAGE_SENT_WIRE_KEY,
- "data": payload,
- }
- )
+ await emit(
+ whatsapp_message_event("received", dict(params)),
+ wire_routing_key=_MESSAGE_RECEIVED_WIRE_KEY,
+ broadcast=False,
+ )
async def broadcast_whatsapp_newsletter(
@@ -239,8 +205,7 @@ async def broadcast_whatsapp_newsletter(
Not a trigger event — no canary consumer. Direct raw broadcast on
the legacy wire key until the FE newsletter UI migrates to read
- the envelope shape, at which point this becomes a ``dispatch.emit``
- call like :func:`broadcast_whatsapp_message`.
+ the envelope shape.
"""
from services.status_broadcaster import get_status_broadcaster
@@ -271,9 +236,9 @@ async def broadcast_whatsapp_history_synced(params: Mapping[str, Any]) -> None:
__all__ = [
"broadcast_whatsapp_history_synced",
- "broadcast_whatsapp_message",
"broadcast_whatsapp_newsletter",
"broadcast_whatsapp_status",
+ "emit_whatsapp_message_received",
"whatsapp_connection_status",
"whatsapp_history_synced",
"whatsapp_message_event",
diff --git a/server/nodes/whatsapp/_service.py b/server/nodes/whatsapp/_service.py
index 0d2ef81f..c7a31a07 100644
--- a/server/nodes/whatsapp/_service.py
+++ b/server/nodes/whatsapp/_service.py
@@ -148,9 +148,9 @@ class RPCClient:
# shape. No more direct broadcaster.* reaches into framework.
from . import (
broadcast_whatsapp_history_synced,
- broadcast_whatsapp_message,
broadcast_whatsapp_newsletter,
broadcast_whatsapp_status,
+ emit_whatsapp_message_received,
)
if method == "event.status":
@@ -235,12 +235,9 @@ class RPCClient:
qr=qr_image,
)
- elif method == "event.message_sent":
- await broadcast_whatsapp_message("sent", params)
-
elif method == "event.message_received":
# Includes newsletter messages with newsletter_meta field.
- await broadcast_whatsapp_message("received", params)
+ await emit_whatsapp_message_received(params)
elif method == "event.newsletter_join":
await broadcast_whatsapp_newsletter("joined", params)
diff --git a/server/nodes/whatsapp_business/_events.py b/server/nodes/whatsapp_business/_events.py
index 2cce8bb8..8c084e3e 100644
--- a/server/nodes/whatsapp_business/_events.py
+++ b/server/nodes/whatsapp_business/_events.py
@@ -75,13 +75,13 @@ def status_updated(data: Mapping[str, Any], *, event_id: str) -> WorkflowEvent:
async def emit_message_received(data: Mapping[str, Any], *, event_id: str) -> None:
from services.events.dispatch import emit
- await emit(message_received(data, event_id=event_id), wire_routing_key=_MESSAGE_WIRE_KEY)
+ await emit(message_received(data, event_id=event_id), wire_routing_key=_MESSAGE_WIRE_KEY, broadcast=False)
async def emit_status_updated(data: Mapping[str, Any], *, event_id: str) -> None:
from services.events.dispatch import emit
- await emit(status_updated(data, event_id=event_id), wire_routing_key=_STATUS_WIRE_KEY)
+ await emit(status_updated(data, event_id=event_id), wire_routing_key=_STATUS_WIRE_KEY, broadcast=False)
__all__ = [
diff --git a/server/services/events/dispatch.py b/server/services/events/dispatch.py
index 5520e0ba..5af530a2 100644
--- a/server/services/events/dispatch.py
+++ b/server/services/events/dispatch.py
@@ -64,7 +64,7 @@ async def emit(
event: WorkflowEvent,
*,
wire_routing_key: Optional[str] = None,
- broadcast: bool = True,
+ broadcast: bool,
) -> WorkflowEvent:
"""Route ``event`` to running consumer workflows + in-process WS clients.
@@ -76,10 +76,11 @@ async def emit(
field on the WS frame). Defaults to the generic
``cloudevent`` channel; plugin emitters override per their
existing wire key (e.g. ``"telegram_message_received"``).
- broadcast: ``False`` skips the WebSocket fan-out. The broadcast
- reaches every connected socket, so an event whose payload is
- one owner's content (a chat message) must not ride it; its
- consumers are the workflows signalled here.
+ broadcast: Whether the envelope also goes to every connected
+ socket. Required, so every producer decides: an event whose
+ payload is someone's content (a chat or channel message, a
+ webhook body) passes ``False``; its consumers are the workflows
+ signalled here. ``True`` only for a frame a client reads.
Returns:
The envelope unchanged — callers may chain.
diff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.py
index 201571a1..a4e3db53 100644
--- a/server/services/temporal/activities.py
+++ b/server/services/temporal/activities.py
@@ -417,7 +417,7 @@ async def emit_event_activity(event_payload: Dict[str, Any]) -> Dict[str, Any]:
"error": f"{type(exc).__name__}: {exc}",
}
- await emit(event)
+ await emit(event, broadcast=False)
return {
"delivered": True,
"event_id": event.id,
diff --git a/server/tests/nodes/test_stripe_plugin.py b/server/tests/nodes/test_stripe_plugin.py
index 02fb4d22..34d9c771 100644
--- a/server/tests/nodes/test_stripe_plugin.py
+++ b/server/tests/nodes/test_stripe_plugin.py
@@ -134,7 +134,8 @@ class TestStripeWebhookShape:
# by emit alone, which the base WebhookSource.handle never calls.
emit.assert_awaited_once()
assert emit.await_args.args == (ev,)
- assert emit.await_args.kwargs == {"wire_routing_key": "stripe_event_received"}
+ # Stripe events carry customer details and no client reads them.
+ assert emit.await_args.kwargs == {"wire_routing_key": "stripe_event_received", "broadcast": False}
def test_handle_rejects_tampered_signature(self):
from fastapi import HTTPException
diff --git a/server/tests/test_event_framework_phase_a.py b/server/tests/test_event_framework_phase_a.py
index 640a6c3f..8a38cac2 100644
--- a/server/tests/test_event_framework_phase_a.py
+++ b/server/tests/test_event_framework_phase_a.py
@@ -244,9 +244,19 @@ class TestA6DispatchEmitFeatureFlag:
source="opencompany://services/test",
type="com.opencompany.test.disabled",
)
- returned = await emit(event)
+ returned = await emit(event, broadcast=False)
assert returned is event
+ @pytest.mark.asyncio
+ async def test_every_emit_names_its_audience(self):
+ """``broadcast`` has no default, so no producer sends someone's
+ content to every socket by leaving it out (RFC-0005 Phase 0.9)."""
+ from services.events.dispatch import emit
+
+ event = WorkflowEvent(source="opencompany://services/test", type="com.opencompany.test.audience")
+ with pytest.raises(TypeError):
+ await emit(event)
+
@pytest.mark.asyncio
async def test_enabled_emit_calls_both_paths(self, monkeypatch):
"""When the flag is on, both signal-fanout and in-process
@@ -274,7 +284,7 @@ class TestA6DispatchEmitFeatureFlag:
source="opencompany://services/test",
type="com.opencompany.test.enabled",
)
- await dispatch.emit(event, wire_routing_key="custom_wire_key")
+ await dispatch.emit(event, wire_routing_key="custom_wire_key", broadcast=True)
assert len(signal_calls) == 1
assert signal_calls[0] is event
diff --git a/server/tests/test_whatsapp_trigger_canary_producer.py b/server/tests/test_whatsapp_trigger_canary_producer.py
index 854cfb9a..d9916c56 100644
--- a/server/tests/test_whatsapp_trigger_canary_producer.py
+++ b/server/tests/test_whatsapp_trigger_canary_producer.py
@@ -1,12 +1,10 @@
-"""Wave 12 C1 rollout #4: whatsappReceive producer dual-emit invariant.
+"""Wave 12 C1 rollout #4: whatsappReceive producer invariant.
-Locks the contract: ``nodes.whatsapp._events.broadcast_whatsapp_message``
-must fan out incoming (``direction="received"``) messages to the
-Temporal-durable ``services.events.dispatch.emit`` path so canary
-listeners can consume them. Outbound (``direction="sent"``) messages
-are pure observation — no trigger node consumes them, so the
-``dispatch.emit`` call is gated on direction == "received" inside
-the broadcaster.
+Locks the contract: ``nodes.whatsapp._events.emit_whatsapp_message_received``
+sends incoming messages through the Temporal-durable
+``services.events.dispatch.emit`` path so canary listeners can consume
+them, without broadcasting them to every socket. Outbound messages are
+not emitted or broadcast at all: nothing consumes them.
Same regex-introspection + runtime smoke pattern used for
webhookTrigger / chatTrigger / taskTrigger / telegramReceive
@@ -16,7 +14,6 @@ producers in this series.
from __future__ import annotations
import inspect
-import re
import sys
import types
from typing import Any, Dict, List
@@ -34,12 +31,8 @@ if "cli" not in sys.modules:
sys.modules["cli.tcp"] = _opencompany_tcp
-_EVENTS_EMIT_PATTERN = re.compile(r"\bemit\s*\(")
-_DIRECTION_GUARD_PATTERN = re.compile(r"direction\s*==\s*[\"']received[\"']")
-
-
class TestWhatsappProducerDualEmit:
- """Producer wrapper fans out received messages to the canary path."""
+ """Producer wrapper sends received messages to the canary path."""
def test_redelivery_keeps_the_id_scoped_to_chat_and_direction(self):
from nodes.whatsapp._events import whatsapp_message_event
@@ -60,31 +53,15 @@ class TestWhatsappProducerDualEmit:
assert whatsapp_message_event("received", payload).id != whatsapp_message_event("received", payload).id
- def test_broadcaster_is_async(self):
- from nodes.whatsapp._events import broadcast_whatsapp_message
-
- assert inspect.iscoroutinefunction(broadcast_whatsapp_message)
-
- def test_broadcaster_calls_dispatch_emit_for_received(self):
- from nodes.whatsapp import _events
-
- src = inspect.getsource(_events.broadcast_whatsapp_message)
-
- assert _EVENTS_EMIT_PATTERN.search(src), (
- "broadcast_whatsapp_message must call "
- "services.events.dispatch.emit(...) so canary "
- "TriggerListenerWorkflow consumers receive incoming "
- "WhatsApp messages."
- )
+ def test_emitter_is_async(self):
+ from nodes.whatsapp._events import emit_whatsapp_message_received
- assert _DIRECTION_GUARD_PATTERN.search(src), (
- "broadcast_whatsapp_message must gate the dispatch.emit "
- "call on direction == 'received' — outbound 'sent' events "
- "are pure observation and have no trigger consumers."
- )
+ assert inspect.iscoroutinefunction(emit_whatsapp_message_received)
@pytest.mark.asyncio
- async def test_received_message_fires_dispatch_emit(self, monkeypatch):
+ async def test_received_message_reaches_triggers_and_is_not_broadcast(self, monkeypatch):
+ """The message is a customer's content: it goes to the deployed
+ triggers only, never to every connected socket (RFC-0005 Phase 0.9)."""
from nodes.whatsapp import _events
from services.events import dispatch as dispatch_mod
from services import status_broadcaster as sb
@@ -101,8 +78,7 @@ class TestWhatsappProducerDualEmit:
monkeypatch.setattr(sb, "get_status_broadcaster", lambda: broadcaster)
monkeypatch.setattr(dispatch_mod, "emit", fake_emit)
- await _events.broadcast_whatsapp_message(
- "received",
+ await _events.emit_whatsapp_message_received(
{
"chat_id": "[email protected]",
"text": "hello",
@@ -111,58 +87,22 @@ class TestWhatsappProducerDualEmit:
},
)
- # Legacy raw frame still goes out so the existing FE message-list
- # handler at WebSocketContext.tsx (which reads ``data.*``)
- # keeps working until the Wave 12 D4 follow-up migrates it to
- # envelope-shape. The duplicate typed-envelope WS broadcast was
- # dropped in Wave 13 — dispatch.emit broadcasts the envelope on
- # the same wire key once.
- assert broadcaster.broadcast.await_count == 1
-
- # And the canary path fires exactly once.
+ broadcaster.broadcast.assert_not_awaited()
assert len(emit_calls) == 1
envelope = emit_calls[0]["event"]
assert envelope.type == "com.opencompany.whatsapp.message.received"
assert envelope.subject == "[email protected]"
assert emit_calls[0]["wire_routing_key"] == "whatsapp_message_received"
+ assert emit_calls[0]["broadcast"] is False
- @pytest.mark.asyncio
- async def test_sent_message_does_not_fire_dispatch_emit(self, monkeypatch):
- """Outbound message — observation only, no trigger consumer.
-
- Skipping the canary fan-out here keeps the Visibility query +
- signal load proportional to actual trigger demand. Without the
- guard, every outbound message would query Temporal Visibility
- with zero matches every time.
- """
- from nodes.whatsapp import _events
- from services.events import dispatch as dispatch_mod
- from services import status_broadcaster as sb
-
- emit_calls: List[Any] = []
-
- async def fake_emit(event, **kwargs):
- emit_calls.append(event)
- return event
-
- broadcaster = MagicMock()
- broadcaster.broadcast = AsyncMock()
-
- monkeypatch.setattr(sb, "get_status_broadcaster", lambda: broadcaster)
- monkeypatch.setattr(dispatch_mod, "emit", fake_emit)
-
- await _events.broadcast_whatsapp_message(
- "sent",
- {"chat_id": "[email protected]", "text": "hi"},
- )
-
- # Single legacy raw broadcast for the FE message-list
- # observation channel — duplicate typed-envelope sibling dropped
- # in Wave 13.
- assert broadcaster.broadcast.await_count == 1
+ def test_outbound_messages_are_not_broadcast(self):
+ """The bridge's message_sent events used to carry each outbound
+ message to every socket, and no client read them."""
+ from nodes.whatsapp import _events, _service
- # No canary fan-out (no trigger consumes outbound).
- assert emit_calls == []
+ assert not hasattr(_events, "broadcast_whatsapp_message")
+ assert "whatsapp_message_sent" not in inspect.getsource(_events)
+ assert 'method == "event.message_sent"' not in inspect.getsource(_service)
class TestWhatsappPluginSelfRegistersCanary: