The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(whatsapp): adopt only the bridge that serves this profile's session
Victor Kyriazakosff32607c6f3d
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 37a086c2c35..fa5003fdf77 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -302,6 +302,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):from hermes_constants import get_hermes_homeself._profile_home = get_hermes_home()self._bridge_process: Optional[subprocess.Popen] = None+ self._foreign_bridge_session: Optional[str] = None # set by _reuse_running_bridge when /health names another profile's sessionfrom .bridge_ownership import standalone_bridge_porttry:# Same resolution as out-of-process sends, so a profile that recorded a port while serving as a@@ -311,7 +312,10 @@ 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"))- self._session_path = Path(extra.get("session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")))+ # F4: normalized ONCE here — the --session argv, the pidfile check and+ # the /health comparison all use one absolute string, so a gateway+ # restarted from a different cwd does not 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._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))@@ -398,10 +402,31 @@ 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."""+ # F2: reset the sentinel FIRST, before the probe — a failed probe or an+ # exception path must never leave a stale value from an earlier call.+ self._foreign_bridge_session = Nonetry:ok, data = await self._probe_bridge_health()if not ok or data is None:return False+ # Session handshake: /health reports the bridge's own session dir.+ # A bridge serving a DIFFERENT profile's session must be left+ # alone entirely — adopting it would cross wire two profiles, and+ # falling through to the kill path would kill the other profile's+ # bridge. connect() turns this into a fatal error telling the user+ # to give each profile its own bridge_port. A bridge that predates+ # the handshake reports no session and is treated as stale.+ # F1: this check runs BEFORE the connected-status check — bridge.js+ # reports only 'connected' or 'disconnected', so a foreign bridge+ # during startup/reconnect/QR-wait reports 'disconnected' and would+ # otherwise fall through to the kill path unmarked.+ reported_session = data.get("session")+ if reported_session and reported_session != str(self._session_path):+ self._foreign_bridge_session = reported_session+ return False+ if not reported_session:+ print(f"[{self.name}] Running bridge predates the session handshake, restarting")+ return Falsebridge_status = data.get("status", "unknown")if bridge_status != "connected":print(f"[{self.name}] Bridge found but not connected (status: {bridge_status}), restarting")@@ -560,6 +585,18 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):# the default keeps its historical adopt-or-clear-the-port path.if (not secondary or prior_bridge_is_ours) and await self._reuse_running_bridge(bridge_path):return True+ if self._foreign_bridge_session:+ # The port is served by another profile's bridge. Never adopt+ # it and never kill it: it belongs to a live session.+ foreign = self._foreign_bridge_session+ self._set_fatal_error(+ "whatsapp_bridge_foreign_session",+ f"Port {self._bridge_port} is already served by a WhatsApp bridge for a different session "+ f"({foreign}). Give this profile its own port via platforms.whatsapp.extra.bridge_port "+ f"(one distinct bridge_port per profile); nothing on port {self._bridge_port} was stopped.",+ retryable=False,+ )+ return Falseif not secondary or prior_bridge_is_ours:_kill_stale_bridge_by_pidfile(self._session_path)if not secondary:diff --git a/scripts/whatsapp-bridge/bridge.js b/scripts/whatsapp-bridge/bridge.jsindex 68569ec5bc7..a18b4183658 100644--- a/scripts/whatsapp-bridge/bridge.js+++ b/scripts/whatsapp-bridge/bridge.js@@ -51,6 +51,7 @@ import {normalizeWhatsAppId,pollCreationMessageFromPayload,pollUpdateForAggregation,+ sessionIdentity,writeJsonLine,} from './bridge_helpers.js';@@ -1132,6 +1133,7 @@ app.get('/health', (req, res) => {uptime: process.uptime(),scriptHash: SCRIPT_HASH,sendReadReceipts: SEND_READ_RECEIPTS,+ session: sessionIdentity(SESSION_DIR),capabilities: { outboundMentions: true },});});diff --git a/scripts/whatsapp-bridge/bridge_helpers.js b/scripts/whatsapp-bridge/bridge_helpers.jsindex d8f78cb8b3d..77ed482a201 100644--- a/scripts/whatsapp-bridge/bridge_helpers.js+++ b/scripts/whatsapp-bridge/bridge_helpers.js@@ -3,6 +3,18 @@ import { mkdirSync, writeFileSync } from 'fs';import { randomBytes } from 'crypto';import { format } from 'util';+/**+ * Normalized absolute identity of a bridge's session directory, reported in+ * /health as `session`. Uses path.resolve (NOT realpath) so both sides+ * normalize `..` and make the path absolute without resolving symlinks —+ * Python's os.path.abspath behaves the same way, and asymmetric symlink+ * resolution (e.g. macOS /tmp -> /private/tmp) would produce false+ * foreign-session verdicts.+ */+export function sessionIdentity(sessionDir) {+ return path.resolve(sessionDir);+}+export const MIME_MAP = {jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png',webp: 'image/webp', gif: 'image/gif',diff --git a/scripts/whatsapp-bridge/session_identity.test.mjs b/scripts/whatsapp-bridge/session_identity.test.mjsnew file mode 100644index 00000000000..30d0190f2d1--- /dev/null+++ b/scripts/whatsapp-bridge/session_identity.test.mjs@@ -0,0 +1,41 @@+/**+ * Unit tests for sessionIdentity(): the /health `session` field the+ * WhatsApp adapter compares against its own session path to tell its own+ * bridge from a foreign profile's bridge on the same port.+ *+ * bridge.js itself is NOT imported here (it starts a server at module+ * load); the helper must stay pure — see bridge.native.test.mjs.+ */++import { strict as assert } from 'node:assert';+import { mkdirSync, mkdtempSync, symlinkSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { sessionIdentity } from './bridge_helpers.js';++// -- relative input becomes absolute ---------------------------------------+{+ const resolved = sessionIdentity('relative/session');+ assert.ok(path.isAbsolute(resolved), 'sessionIdentity must return an absolute path');+}++// -- `..` segments are normalized ------------------------------------------+{+ const resolved = sessionIdentity('a/../b');+ assert.strictEqual(resolved, path.resolve('b'));+}++// -- symlinks are NOT resolved (path.resolve, not realpath) -----------------+{+ const root = mkdtempSync(path.join(tmpdir(), 'wa-session-identity-'));+ const realDir = path.join(root, 'real');+ const linkDir = path.join(root, 'link');+ mkdirSync(realDir);+ symlinkSync(realDir, linkDir, 'dir');+ const resolved = sessionIdentity(linkDir);+ assert.ok(+ resolved.includes('link') && !resolved.includes('real'),+ `symlink must not be resolved, got: ${resolved}`+ );+}diff --git a/tests/gateway/test_whatsapp_stale_bridge.py b/tests/gateway/test_whatsapp_stale_bridge.pyindex 3ad226de143..8111bc0f876 100644--- a/tests/gateway/test_whatsapp_stale_bridge.py+++ b/tests/gateway/test_whatsapp_stale_bridge.py@@ -17,6 +17,7 @@ package.json changes, not only when node_modules is missing."""import asyncio+import osfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMock, patch@@ -56,7 +57,8 @@ def _make_adapter(bridge_script: str = "/tmp/test-bridge.js",adapter.config = MagicMock()adapter._bridge_port = 19876adapter._bridge_script = bridge_script- adapter._session_path = session_path+ adapter._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_log_fh = Noneadapter._bridge_log = Noneadapter._bridge_process = None@@ -152,6 +154,160 @@ class TestStaleBridgeHandshake:mock_popen.assert_called_once()+ @pytest.mark.asyncio+ async def test_adopts_bridge_serving_same_session(self, tmp_path):+ from plugins.platforms.whatsapp.adapter import _file_content_hash++ bridge_dir = _setup_bridge_dir(tmp_path)+ _fresh_node_modules(bridge_dir)+ adapter = _make_adapter(+ bridge_script=str(bridge_dir / "bridge.js"),+ session_path=tmp_path / "session",+ )+ disk_hash = _file_content_hash(bridge_dir / "bridge.js")+ mock_client = _mock_health(+ {+ "status": "connected",+ "scriptHash": disk_hash,+ "sendReadReceipts": False,+ "session": str(tmp_path / "session"),+ }+ )+ mock_proc = MagicMock()++ 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=mock_proc) as mock_popen, \+ patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True):+ assert await adapter.connect() is True++ mock_popen.assert_not_called()+ mock_kill_pidfile.assert_not_called()+ mock_kill_port.assert_not_called()++ @pytest.mark.asyncio+ async def test_foreign_session_bridge_is_fatal_and_not_killed(self, tmp_path):+ from plugins.platforms.whatsapp.adapter import _file_content_hash++ bridge_dir = _setup_bridge_dir(tmp_path)+ _fresh_node_modules(bridge_dir)+ adapter = _make_adapter(+ bridge_script=str(bridge_dir / "bridge.js"),+ session_path=tmp_path / "session",+ )+ foreign_session = tmp_path / "other-profile-session"+ disk_hash = _file_content_hash(bridge_dir / "bridge.js")+ mock_client = _mock_health(+ {+ "status": "connected",+ "scriptHash": disk_hash,+ "sendReadReceipts": False,+ "session": str(foreign_session),+ }+ )+ mock_proc = MagicMock()++ 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=mock_proc) as mock_popen, \+ patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True):+ assert await adapter.connect() is False++ mock_popen.assert_not_called()+ mock_kill_pidfile.assert_not_called()+ mock_kill_port.assert_not_called()+ message = adapter._fatal_error_message or ""+ assert str(adapter._bridge_port) in message+ assert str(foreign_session) in message+ assert "bridge_port" in message++ @pytest.mark.asyncio+ async def test_foreign_session_checked_before_connected_status(self, tmp_path):+ """Cell (d), F1: the session check must precede the status check.++ bridge.js reports only 'connected' or 'disconnected', so a FOREIGN+ bridge sitting in startup/reconnect reports ``status: disconnected``+ first. If the status check ran first, ``_reuse_running_bridge`` would+ return False without marking the session foreign and ``connect()``+ would kill the other profile's bridge.+ """+ from plugins.platforms.whatsapp.adapter import _file_content_hash++ bridge_dir = _setup_bridge_dir(tmp_path)+ _fresh_node_modules(bridge_dir)+ adapter = _make_adapter(+ bridge_script=str(bridge_dir / "bridge.js"),+ session_path=tmp_path / "session",+ )+ foreign_session = tmp_path / "other-profile-session"+ disk_hash = _file_content_hash(bridge_dir / "bridge.js")+ mock_client = _mock_health(+ {+ "status": "disconnected",+ "scriptHash": disk_hash,+ "sendReadReceipts": False,+ "session": str(foreign_session),+ }+ )+ mock_proc = MagicMock()++ 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=mock_proc) as mock_popen, \+ patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True):+ assert await adapter.connect() is False++ mock_popen.assert_not_called()+ mock_kill_pidfile.assert_not_called()+ mock_kill_port.assert_not_called()+ message = adapter._fatal_error_message or ""+ assert str(adapter._bridge_port) in message+ assert str(foreign_session) in message+ assert "bridge_port" in message+ # F2: the fatal error is stored on the adapter as non-retryable.+ assert adapter._fatal_error_code == "whatsapp_bridge_foreign_session"+ assert adapter._fatal_error_retryable is False++ @pytest.mark.asyncio+ async def test_restarts_when_bridge_reports_no_session(self, tmp_path):+ from plugins.platforms.whatsapp.adapter import _file_content_hash++ bridge_dir = _setup_bridge_dir(tmp_path)+ _fresh_node_modules(bridge_dir)+ adapter = _make_adapter(+ bridge_script=str(bridge_dir / "bridge.js"),+ session_path=tmp_path / "session",+ )+ disk_hash = _file_content_hash(bridge_dir / "bridge.js")+ mock_client = _mock_health(+ {+ "status": "connected",+ "scriptHash": disk_hash,+ "sendReadReceipts": False,+ }+ )+ mock_proc = MagicMock()++ 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"), \+ patch("plugins.platforms.whatsapp.adapter._kill_port_process"), \+ patch("subprocess.Popen", return_value=mock_proc) as mock_popen, \+ patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True):+ assert await adapter.connect() is False # not adopted; restart begins++ mock_popen.assert_called_once()+class TestDepRefreshStamp:@pytest.mark.asynciodiff --git a/website/docs/user-guide/messaging/whatsapp.md b/website/docs/user-guide/messaging/whatsapp.mdindex 11d93c25a7a..7984735996f 100644--- a/website/docs/user-guide/messaging/whatsapp.md+++ b/website/docs/user-guide/messaging/whatsapp.md@@ -283,6 +283,44 @@ Replying to (quoting) an earlier message gives the agent the quoted text as cont---+## Running several profiles on one host++Each Hermes profile runs its own WhatsApp bridge. Two profiles sharing the+default `bridge_port` (3000) cannot both own it: the second profile finds the+first profile's bridge and refuses to start.++Give every profile a distinct port under `platforms.whatsapp.extra` in that+profile's `config.yaml`:++```yaml+platforms:+ whatsapp:+ extra:+ bridge_port: 3001 # one distinct port per profile+```++- `bridge_port` must differ per profile. The adapter identifies a bridge by+ the session directory reported in `/health`; a bridge serving a different+ profile's session is never adopted and never stopped.+- Each profile already gets its own session directory by default, so no+ session configuration is needed for multi-profile setups.+- If you override `session_path`, use an absolute path and keep it distinct+ per profile, otherwise the profiles share one WhatsApp login.++When a profile finds a foreign bridge on its port, the profile's WhatsApp+platform fails to start with:++```+Port 3000 is already served by a WhatsApp bridge for a different session+(/home/you/.hermes/profiles/other/platforms/whatsapp/session). Give this+profile its own port via platforms.whatsapp.extra.bridge_port (one distinct+bridge_port per profile); nothing on port 3000 was stopped.+```++Bridges started by an older Hermes version report no session directory;+the adapter treats them as stale and restarts them once, as with a+bridge.js update.+## Troubleshooting| Problem | Solution |