Skip to content

The agent that grows with you

fix(whatsapp): fold the session check into main's multiplex connect path

unsupportedpastels029574fa01ef
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index fa5003fdf77..8b2e06f3046 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -312,9 +312,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
logger.warning("[whatsapp] %s; using port 3000", exc)
self._bridge_port = 3000
self._bridge_script: str = extra.get("bridge_script", str(self._DEFAULT_BRIDGE_DIR / "bridge.js"))
- # 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.
+ # 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._reply_prefix: Optional[str] = extra.get("reply_prefix")
self._dm_policy = str(_extra_or_secret(extra, "dm_policy", "WHATSAPP_DM_POLICY", "pairing")).strip().lower()
@@ -402,31 +401,19 @@ 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 = None
try:
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.
+ # Another profile's bridge (same default port) is neither adopted, which would answer as that
+ # profile's phone, nor killed: connect() reports it. Checked before status because a bridge in
+ # startup, reconnect or QR wait reports "disconnected". A bridge without ``session`` predates the
+ # field, so its scriptHash no longer matches bridge.js and it restarts as stale below.
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 False
bridge_status = data.get("status", "unknown")
if bridge_status != "connected":
print(f"[{self.name}] Bridge found but not connected (status: {bridge_status}), restarting")
diff --git a/scripts/whatsapp-bridge/bridge.js b/scripts/whatsapp-bridge/bridge.js
index a18b4183658..94a2ea513c7 100644
--- a/scripts/whatsapp-bridge/bridge.js
+++ b/scripts/whatsapp-bridge/bridge.js
@@ -51,7 +51,6 @@ import {
normalizeWhatsAppId,
pollCreationMessageFromPayload,
pollUpdateForAggregation,
- sessionIdentity,
writeJsonLine,
} from './bridge_helpers.js';
@@ -1133,7 +1132,8 @@ app.get('/health', (req, res) => {
uptime: process.uptime(),
scriptHash: SCRIPT_HASH,
sendReadReceipts: SEND_READ_RECEIPTS,
- session: sessionIdentity(SESSION_DIR),
+ // path.resolve, not realpath: the adapter compares against os.path.abspath, which keeps symlinks.
+ session: path.resolve(SESSION_DIR),
capabilities: { outboundMentions: true },
});
});
diff --git a/scripts/whatsapp-bridge/bridge_helpers.js b/scripts/whatsapp-bridge/bridge_helpers.js
index 77ed482a201..d8f78cb8b3d 100644
--- a/scripts/whatsapp-bridge/bridge_helpers.js
+++ b/scripts/whatsapp-bridge/bridge_helpers.js
@@ -3,18 +3,6 @@ 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.mjs
deleted file mode 100644
index 30d0190f2d1..00000000000
--- a/scripts/whatsapp-bridge/session_identity.test.mjs
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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.py
index 8111bc0f876..d2b5161ab22 100644
--- a/tests/gateway/test_whatsapp_stale_bridge.py
+++ b/tests/gateway/test_whatsapp_stale_bridge.py
@@ -137,6 +137,7 @@ class TestStaleBridgeHandshake:
"status": "connected",
"scriptHash": disk_hash,
"sendReadReceipts": False,
+ "session": str(tmp_path / "session"),
}
)
mock_proc = MagicMock()
@@ -155,7 +156,14 @@ class TestStaleBridgeHandshake:
mock_popen.assert_called_once()
@pytest.mark.asyncio
- async def test_adopts_bridge_serving_same_session(self, tmp_path):
+ @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)."""
from plugins.platforms.whatsapp.adapter import _file_content_hash
bridge_dir = _setup_bridge_dir(tmp_path)
@@ -164,149 +172,33 @@ class TestStaleBridgeHandshake:
bridge_script=str(bridge_dir / "bridge.js"),
session_path=tmp_path / "session",
)
- disk_hash = _file_content_hash(bridge_dir / "bridge.js")
+ reported = tmp_path / ("session" if session == "own" else "other-profile-session")
mock_client = _mock_health(
{
- "status": "connected",
- "scriptHash": disk_hash,
+ "status": status,
+ "scriptHash": _file_content_hash(bridge_dir / "bridge.js"),
"sendReadReceipts": False,
- "session": str(tmp_path / "session"),
+ "session": str(reported),
}
)
- 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("subprocess.Popen", return_value=MagicMock()) as mock_popen, \
patch.object(adapter, "_acquire_platform_lock", return_value=True, create=True):
- assert await adapter.connect() is True
+ assert await adapter.connect() is adopted
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()
+ 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
+ assert "bridge_port" in adapter._fatal_error_message
class TestDepRefreshStamp:
diff --git a/website/docs/user-guide/messaging/whatsapp.md b/website/docs/user-guide/messaging/whatsapp.md
index 7984735996f..6b5f6e8f7cd 100644
--- a/website/docs/user-guide/messaging/whatsapp.md
+++ b/website/docs/user-guide/messaging/whatsapp.md
@@ -56,6 +56,25 @@ distinct free port, or stop the process holding it. Other
profiles continue running. `hermes gateway status --profile work` reports the
profile's own WhatsApp adapter rather than shared ingress.
+Profiles that each run their own gateway, rather than one multiplexed gateway,
+all use port 3000 unless configured otherwise. Give each one a distinct port in
+that profile's `config.yaml`:
+
+```yaml
+platforms:
+ whatsapp:
+ extra:
+ bridge_port: 3001 # one distinct port per profile
+```
+
+A gateway identifies a running bridge by the session directory the bridge
+reports in `/health`. A bridge serving another profile's session is never
+adopted 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
+override `session_path`, keep it distinct per profile, or the profiles share one
+WhatsApp login. Bridges started by an older Hermes report no session directory
+and are restarted once, as after a bridge update.
+
## Two Modes
| Mode | How it works | Best for |
@@ -283,44 +302,6 @@ 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 |