The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(whatsapp): unanswered /health and standalone sends respect session ownership
unsupportedpastelse1cc967c292d
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 8b2e06f3046..3dc040d26aa 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -57,6 +57,13 @@ def _safe_ints(tokens) -> list:return out+def _session_dir(extra) -> Path:+ """Absolute session dir: --session, bridge.pid and every /health ``session`` comparison (gateway and standalone+ sends) share this one string, or a gateway restarted from another cwd would see its own bridge as foreign."""+ return Path(os.path.abspath(os.path.expanduser(str((extra or {}).get(+ "session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session"))))))++def _windows_listener_pids(port: int) -> list:"""PIDs in LISTENING state on ``port`` via netstat (Windows)."""from hermes_cli._subprocess_compat import windows_hide_flags@@ -303,6 +310,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._profile_home = get_hermes_home()self._bridge_process: Optional[subprocess.Popen] = Noneself._foreign_bridge_session: Optional[str] = None # set by _reuse_running_bridge when /health names another profile's session+ self._bridge_probe_timed_out = False # set by _reuse_running_bridge when the port's holder gave no /health answerfrom .bridge_ownership import standalone_bridge_porttry:# Same resolution as out-of-process sends, so a profile that recorded a port while serving as a@@ -312,9 +320,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):logger.warning("[whatsapp] %s; using port 3000", exc)self._bridge_port = 3000self._bridge_script: str = extra.get("bridge_script", str(self._DEFAULT_BRIDGE_DIR / "bridge.js"))- # Absolute once: --session, bridge.pid and the /health ``session`` comparison share one string, or a- # gateway restarted from another cwd would see its own bridge as foreign.- self._session_path = Path(os.path.abspath(os.path.expanduser(str(extra.get("session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session"))))))+ self._session_path = _session_dir(extra)self._reply_prefix: Optional[str] = extra.get("reply_prefix")self._dm_policy = str(_extra_or_secret(extra, "dm_policy", "WHATSAPP_DM_POLICY", "pairing")).strip().lower()self._allow_from = self._coerce_allow_list(self._select_dm_allowlist(extra, ("WHATSAPP_ALLOWED_USERS",), _wenv))@@ -402,6 +408,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):async def _reuse_running_bridge(self, bridge_path: Path) -> bool:"""Adopt a connected bridge serving the on-disk bridge.js + same read-receipt config; else say why it restarts."""self._foreign_bridge_session = None+ self._bridge_probe_timed_out = Falsetry:ok, data = await self._probe_bridge_health()if not ok or data is None:@@ -427,6 +434,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):return Truestale_reason = f"running={running_hash or 'unversioned'}, disk={disk_hash}" if running_hash != disk_hash else "send_read_receipts config changed"print(f"[{self.name}] Running bridge is stale ({stale_reason}), restarting")+ except asyncio.TimeoutError:+ self._bridge_probe_timed_out = True # something holds the port but gave no identity; connect() leaves itexcept Exception:pass # Bridge not running, start a new onereturn False@@ -587,6 +596,20 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if not secondary or prior_bridge_is_ours:_kill_stale_bridge_by_pidfile(self._session_path)if not secondary:+ if self._bridge_probe_timed_out:+ # No /health answer is no ownership evidence (another profile's busy bridge looks the same), and+ # our own stale bridge was just reaped by its pidfile: a holder that remains is left running.+ await asyncio.sleep(1)+ if _listener_pids_on_port(self._bridge_port):+ self._set_fatal_error(+ "whatsapp_bridge_unresponsive",+ f"Port {self._bridge_port} is held by a process that did not answer /health in time, so "+ f"Hermes cannot tell whose WhatsApp bridge it is; nothing on port {self._bridge_port} was "+ "stopped. Stop that process, or give this profile its own port via "+ "platforms.whatsapp.extra.bridge_port.",+ retryable=True,+ )+ return False_kill_port_process(self._bridge_port)if not secondary or prior_bridge_is_ours:await asyncio.sleep(1)@@ -1014,6 +1037,7 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_fbridge_port = standalone_bridge_port(get_hermes_home(), (getattr(pconfig, "extra", {}) or {}).get("bridge_port"))+ own_session = str(_session_dir(getattr(pconfig, "extra", {}) or {}))normalized_chat_id = to_whatsapp_jid(chat_id)media = media_files or []# A caption only applies to a single media file — never repeat it across a multi-file send.@@ -1029,12 +1053,19 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_flast_message_id = Noneasync with aiohttp.ClientSession() as session:+ # Whose bridge holds the port is checked before anything is posted: on a shared port another profile's+ # bridge would deliver from that profile's WhatsApp account. A bridge without ``session`` predates the field.+ async with session.get(+ f"http://localhost:{bridge_port}/health",+ timeout=aiohttp.ClientTimeout(total=5),+ ) as resp:+ health = await resp.json() if resp.status == 200 else {}+ reported_session = health.get("session")+ if reported_session and reported_session != own_session:+ return send_error(+ f"WhatsApp bridge on port {bridge_port} serves another profile's session ({reported_session}); "+ "nothing was sent. Give each profile its own platforms.whatsapp.extra.bridge_port.")if pending_mentions:- async with session.get(- f"http://localhost:{bridge_port}/health",- timeout=aiohttp.ClientTimeout(total=5),- ) as resp:- health = await resp.json() if resp.status == 200 else {}if not (health.get("capabilities") or {}).get("outboundMentions"):return {"error": ("WhatsApp bridge does not support native mentions; "diff --git a/tests/gateway/test_whatsapp_stale_bridge.py b/tests/gateway/test_whatsapp_stale_bridge.pyindex d2b5161ab22..6137057c7f2 100644--- a/tests/gateway/test_whatsapp_stale_bridge.py+++ b/tests/gateway/test_whatsapp_stale_bridge.py@@ -18,6 +18,7 @@ package.json changes, not only when node_modules is missing.import asyncioimport os+from contextlib import nullcontextfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patch@@ -59,6 +60,7 @@ def _make_adapter(bridge_script: str = "/tmp/test-bridge.js",adapter._bridge_script = bridge_scriptadapter._session_path = Path(os.path.abspath(os.path.expanduser(str(session_path))))adapter._foreign_bridge_session = None # mirror __init__; harness builds via __new__+ adapter._bridge_probe_timed_out = Falseadapter._bridge_log_fh = Noneadapter._bridge_log = Noneadapter._bridge_process = None@@ -156,14 +158,16 @@ class TestStaleBridgeHandshake:mock_popen.assert_called_once()@pytest.mark.asyncio- @pytest.mark.parametrize("session,status,adopted", [- ("own", "connected", True),- ("other", "connected", False),- ("other", "disconnected", False),- ], ids=["own-session-adopted", "other-session-connected", "other-session-starting"])- async def test_bridge_is_adopted_or_left_running_by_its_session(self, tmp_path, session, status, adopted):- """Two profiles default to one bridge_port; only this profile's own session may be adopted, and another- profile's bridge is never killed, even while it reports ``disconnected`` (startup, reconnect, QR wait)."""+ @pytest.mark.parametrize("holder,status,fatal", [+ ("own", "connected", None),+ ("other", "connected", "whatsapp_bridge_foreign_session"),+ ("other", "disconnected", "whatsapp_bridge_foreign_session"),+ ("unanswered", None, "whatsapp_bridge_unresponsive"),+ ], ids=["own-session-adopted", "other-session-connected", "other-session-starting", "no-health-answer"])+ async def test_bridge_is_adopted_or_left_running_by_its_session(self, tmp_path, holder, status, fatal):+ """Two profiles default to one bridge_port; only this profile's own session may be adopted. Another profile's+ bridge is never killed, even while it reports ``disconnected`` (startup, reconnect, QR wait), and neither is a+ port holder that gives no /health answer, which proves no ownership."""from plugins.platforms.whatsapp.adapter import _file_content_hashbridge_dir = _setup_bridge_dir(tmp_path)@@ -172,7 +176,7 @@ class TestStaleBridgeHandshake:bridge_script=str(bridge_dir / "bridge.js"),session_path=tmp_path / "session",)- reported = tmp_path / ("session" if session == "own" else "other-profile-session")+ reported = tmp_path / ("session" if holder == "own" else "other-profile-session")mock_client = _mock_health({"status": status,@@ -181,24 +185,33 @@ class TestStaleBridgeHandshake:"session": str(reported),})-- with patch("plugins.platforms.whatsapp.adapter.check_whatsapp_requirements", return_value=True), \- patch("aiohttp.ClientSession", mock_client), \- patch("plugins.platforms.whatsapp.adapter.asyncio.sleep", new_callable=AsyncMock), \- patch("plugins.platforms.whatsapp.adapter._kill_stale_bridge_by_pidfile") as mock_kill_pidfile, \- patch("plugins.platforms.whatsapp.adapter._kill_port_process") as mock_kill_port, \- patch("subprocess.Popen", return_value=MagicMock()) as mock_popen, \- patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True):- assert await adapter.connect() is adopted+ unanswered = (patch.object(adapter, "_probe_bridge_health", AsyncMock(side_effect=asyncio.TimeoutError))+ if holder == "unanswered" else nullcontext())++ with (+ unanswered,+ patch("plugins.platforms.whatsapp.adapter.check_whatsapp_requirements", return_value=True),+ patch("aiohttp.ClientSession", mock_client),+ patch("plugins.platforms.whatsapp.adapter.asyncio.sleep", new_callable=AsyncMock),+ patch("plugins.platforms.whatsapp.adapter._kill_stale_bridge_by_pidfile") as mock_kill_pidfile,+ patch("plugins.platforms.whatsapp.adapter._kill_port_process") as mock_kill_port,+ patch("plugins.platforms.whatsapp.adapter._listener_pids_on_port", return_value=[4242]),+ patch("subprocess.Popen", return_value=MagicMock()) as mock_popen,+ patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True),+ ):+ assert await adapter.connect() is (fatal is None)mock_popen.assert_not_called()- mock_kill_pidfile.assert_not_called()mock_kill_port.assert_not_called()- if not adopted:- assert adapter._fatal_error_code == "whatsapp_bridge_foreign_session"- assert adapter._fatal_error_retryable is False- assert str(reported) in adapter._fatal_error_message+ # Reaping by this profile's own pidfile is identity-based; only a foreign verdict skips it.+ assert mock_kill_pidfile.called is (fatal == "whatsapp_bridge_unresponsive")+ if fatal:+ assert adapter._fatal_error_code == fatal+ assert adapter._fatal_error_retryable is (fatal == "whatsapp_bridge_unresponsive")+ assert f"nothing on port {adapter._bridge_port} was" in adapter._fatal_error_messageassert "bridge_port" in adapter._fatal_error_message+ if fatal == "whatsapp_bridge_foreign_session":+ assert str(reported) in adapter._fatal_error_messageclass TestDepRefreshStamp:diff --git a/tests/tools/test_whatsapp_send_message_media.py b/tests/tools/test_whatsapp_send_message_media.pyindex 024a6af8048..e20a82c7e6f 100644--- a/tests/tools/test_whatsapp_send_message_media.py+++ b/tests/tools/test_whatsapp_send_message_media.py@@ -66,9 +66,10 @@ def _resp(status, json_data=None, text_data=None):return r-def _session_with(responses):- """Build a mocked aiohttp.ClientSession that returns *responses* in order- and records every GET/POST (url, json_payload)."""+def _session_with(responses, health=None):+ """Build a mocked aiohttp.ClientSession: GET /health answers *health* (default an+ empty 200), POSTs return *responses* in order; every GET/POST is recorded as+ (url, json_payload)."""calls = []idx = [0]@@ -81,9 +82,16 @@ def _session_with(responses):ctx.__aexit__ = AsyncMock(return_value=False)return ctx+ def _get(url, **kwargs):+ calls.append((url, kwargs.get("json")))+ ctx = MagicMock()+ ctx.__aenter__ = AsyncMock(return_value=health or _resp(200))+ ctx.__aexit__ = AsyncMock(return_value=False)+ return ctx+session = MagicMock()session.post = MagicMock(side_effect=_post)- session.get = MagicMock(side_effect=_post)+ session.get = MagicMock(side_effect=_get)session_ctx = MagicMock()session_ctx.__aenter__ = AsyncMock(return_value=session)session_ctx.__aexit__ = AsyncMock(return_value=False)@@ -124,13 +132,14 @@ def test_text_plus_mixed_media_routes_native_types():))assert res["success"] is True- # text first, then three media uploads in order- assert calls[0][0].endswith("/send")- assert calls[0][1]["message"] == "hello"+ # health check, text first, then three media uploads in order+ assert calls[0][0].endswith("/health")+ assert calls[1][0].endswith("/send")+ assert calls[1][1]["message"] == "hello"media_types = [c[1]["mediaType"] for c in calls if c[0].endswith("/send-media")]assert media_types == ["image", "video", "audio"]# chat id normalized to a WhatsApp JID- assert "@" in calls[0][1]["chatId"]+ assert "@" in calls[1][1]["chatId"]finally:for p in (img, vid, voice):os.unlink(p)@@ -154,9 +163,8 @@ def test_missing_captioned_file_falls_back_to_text():assert "error" in resassert "not found" in res["error"]# ...but the caption text was delivered on its own first.- assert len(calls) == 1- assert calls[0][0].endswith("/send")- assert calls[0][1]["message"] == "floor plan"+ assert [url for url, _ in calls] == ["http://localhost:3000/health", "http://localhost:3000/send"]+ assert calls[1][1]["message"] == "floor plan"def test_standalone_send_uses_persisted_secondary_bridge_port(tmp_path, monkeypatch):@@ -170,7 +178,7 @@ def test_standalone_send_uses_persisted_secondary_bridge_port(tmp_path, monkeypawith patch("aiohttp.ClientSession", return_value=session_ctx):result = asyncio.run(_standalone_send(SimpleNamespace(token="", extra={}), "12345", "hello"))assert result["success"] is True- assert calls[0][0] == "http://localhost:3042/send"+ assert [url for url, _ in calls] == ["http://localhost:3042/health", "http://localhost:3042/send"]@pytest.mark.parametrize(@@ -197,11 +205,10 @@ def test_secondary_standalone_sends_use_active_profile_port_for_text_media_and_m(secondary_home, extra, expected_port),(launch_home, {}, 3000),):- session_ctx, calls = _session_with([- _resp(200, {"capabilities": {"outboundMentions": True}}),- _resp(200, {"messageId": "text"}),- _resp(200, {"messageId": "media"}),- ])+ session_ctx, calls = _session_with(+ [_resp(200, {"messageId": "text"}), _resp(200, {"messageId": "media"})],+ health=_resp(200, {"capabilities": {"outboundMentions": True}}),+ )override = set_hermes_home_override(home)try:with patch("aiohttp.ClientSession", return_value=session_ctx):@@ -224,3 +231,26 @@ def test_secondary_standalone_sends_use_active_profile_port_for_text_media_and_massert not record.exists()else:assert record.read_text(encoding="utf-8") == str(persisted_port)++[email protected]("reported", ["own", "other", None], ids=["own-session", "other-profile-session", "pre-session-bridge"])+def test_standalone_send_posts_only_through_this_profiles_bridge(tmp_path, reported):+ """Profiles sharing a bridge_port must not send from each other's WhatsApp account, text or media."""+ own = tmp_path / "b" / "session"+ media = tmp_path / "image.png"+ media.write_bytes(b"image")+ health = {"session": str(own if reported == "own" else tmp_path / "a" / "session")} if reported else {}+ session_ctx, calls = _session_with(+ [_resp(200, {"messageId": "text"}), _resp(200, {"messageId": "media"})], health=_resp(200, health))+ with patch("aiohttp.ClientSession", return_value=session_ctx):+ result = asyncio.run(_standalone_send(+ SimpleNamespace(token="", extra={"bridge_port": 3000, "session_path": str(own)}), "12345", "hello",+ media_files=[(str(media), False)],+ ))+ posted = [url for url, _ in calls if not url.endswith("/health")]+ if reported == "other":+ assert "another profile's session" in result["error"]+ assert posted == []+ else:+ assert result.get("success") is True, result+ assert posted == ["http://localhost:3000/send", "http://localhost:3000/send-media"]diff --git a/website/docs/user-guide/messaging/whatsapp.md b/website/docs/user-guide/messaging/whatsapp.mdindex 6b5f6e8f7cd..b1f8724d3cf 100644--- a/website/docs/user-guide/messaging/whatsapp.md+++ b/website/docs/user-guide/messaging/whatsapp.md@@ -70,7 +70,11 @@ platforms:A gateway identifies a running bridge by the session directory the bridgereports in `/health`. A bridge serving another profile's session is neveradopted and never stopped: the second profile's WhatsApp fails to start with-`whatsapp_bridge_foreign_session`, naming the port and the other session. If you+`whatsapp_bridge_foreign_session`, naming the port and the other session. On+Linux and macOS, a process that holds the port but does not answer `/health` in+time is left running too, and WhatsApp fails with the retryable+`whatsapp_bridge_unresponsive`. `hermes whatsapp send` and cron delivery check+the same field and refuse to send through another profile's bridge. If youoverride `session_path`, keep it distinct per profile, or the profiles share oneWhatsApp login. Bridges started by an older Hermes report no session directoryand are restarted once, as after a bridge update.