Skip to content

The agent that grows with you

fix(whatsapp): serve a paired WhatsApp session on every profile under the host multiplexer

Victor Kyriazakos5827154a324a
diff --git a/gateway/run.py b/gateway/run.py
index f745ad816df..1f439863fc3 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1938,6 +1938,11 @@ def _platform_has_bot_credential(platform: "Platform", platform_config: "Platfor
"""Return True when a token-authenticated platform has a usable bot credential; platforms not using
``PlatformConfig.token`` (Signal session paths, port-binding HTTP adapters) always return True."""
from gateway.config import PLATFORM_TOKEN_ENV_NAMES, Platform
+ if platform is Platform.WHATSAPP:
+ from hermes_constants import get_hermes_dir
+ session = Path(platform_config.extra.get(
+ "session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")))
+ return (session / "creds.json").exists()
if platform not in PLATFORM_TOKEN_ENV_NAMES:
return True
for attr in ("token", "api_key"): # some adapters accept api_key as the primary credential
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 0252ca9aa85..7c2f8109ec2 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -1181,8 +1181,7 @@ class GatewayAdapterLifecycleMixin:
return True
def _note_unserved_secondary_platform(self, profile_name: str, platform: Platform) -> None:
- """A secondary enabled a shared-ingress platform (Relay, WhatsApp) the multiplexer only runs on
- the default profile. Log the reason + remedy once per (profile, platform) and stamp a
+ """Report unpaired WhatsApp or secondary-only Relay. Log the reason and remedy and stamp a
``<profile>:<platform>`` status entry so ``hermes gateway status --profile X`` and the
dashboard show *why* the channel is dead instead of nothing at all."""
noted = getattr(self, "_unserved_secondary_platforms", None)
@@ -1192,6 +1191,14 @@ class GatewayAdapterLifecycleMixin:
return
noted.add((profile_name, platform))
pv = platform.value
+ if platform is Platform.WHATSAPP:
+ message = f"WhatsApp is not paired; pair it: hermes -p {profile_name} whatsapp"
+ logger.info("[MULTIPLEX] Profile '%s': %s", profile_name, message)
+ self._update_platform_runtime_status(
+ f"{profile_name}:{pv}", platform_state="disabled",
+ error_code="whatsapp_unpaired", error_message=message,
+ )
+ return
logger.info(
"[MULTIPLEX] Profile '%s': %s is enabled but not served — %s is process-level shared ingress "
"owned by the default profile under multiplex. Enable and configure %s on the default profile "
@@ -1209,6 +1216,8 @@ class GatewayAdapterLifecycleMixin:
noted = getattr(self, "_unserved_secondary_platforms", None) or ()
lines = []
for platform in sorted({p for _n, p in noted}, key=lambda p: p.value):
+ if platform is Platform.WHATSAPP:
+ continue # unpaired sessions have their own per-profile remedy
if platform in self.adapters or platform in (getattr(self, "_failed_platforms", None) or {}):
continue # the default owns it: secondaries ARE served through the shared adapter
profiles = sorted(n for n, p in noted if p is platform)
@@ -1243,15 +1252,18 @@ class GatewayAdapterLifecycleMixin:
(getattr(self, "_profile_failed_platforms", None) or {}).get(profile_name) or {}):
continue
# No credential in THIS profile's scope: an adapter would fan inbound across every such profile.
- if multiplex and not _platform_has_bot_credential(platform, platform_config):
+ with _profile_runtime_scope(profile_home, hydrate_secrets=False):
+ has_credential = _platform_has_bot_credential(platform, platform_config)
+ if multiplex and not has_credential:
+ if platform is Platform.WHATSAPP:
+ self._note_unserved_secondary_platform(profile_name, platform)
logger.info(
"[MULTIPLEX] Profile '%s': skipping %s - no bot credential "
"in this profile's secrets", profile_name, platform.value,
)
continue
- # Relay/WhatsApp are shared process-level ingress under multiplex; a secondary would retry-loop.
- # Say so: four profiles with WHATSAPP_ENABLED=true and nothing in the log is a silent dead channel.
- if multiplex and platform in (Platform.RELAY, Platform.WHATSAPP):
+ # Relay still uses process-level shared ingress; WhatsApp owns a session per profile.
+ if multiplex and platform is Platform.RELAY:
self._note_unserved_secondary_platform(profile_name, platform)
continue
# api_server / webhook: the default's listener already mirrors them at /p/<profile>/; a second
diff --git a/hermes_cli/gateway_multiplex_served.py b/hermes_cli/gateway_multiplex_served.py
index ace60640877..ba63b328261 100644
--- a/hermes_cli/gateway_multiplex_served.py
+++ b/hermes_cli/gateway_multiplex_served.py
@@ -50,8 +50,8 @@ def multiplexer_served_secondaries() -> list[str]:
def served_profile_unserved_platforms(profile: str) -> dict[str, str]:
"""``{platform: reason}`` for a served profile's platforms the multiplexer deliberately does not run
- (WhatsApp/Relay are shared ingress owned by the default; ``gateway.run_adapters`` stamps
- ``<profile>:<platform>`` as ``disabled`` with ``error_code=multiplex_shared_ingress``)."""
+ (unpaired WhatsApp or Relay shared ingress; ``gateway.run_adapters`` stamps
+ ``<profile>:<platform>`` as ``disabled`` with a reason and remedy)."""
from hermes_constants import get_default_hermes_root
from gateway.status import read_runtime_status
if not profile or live_default_gateway_pid() is None:
@@ -65,7 +65,7 @@ def served_profile_unserved_platforms(profile: str) -> dict[str, str]:
key[len(prefix):]: str(entry.get("error_message") or "not served under multiplex")
for key, entry in platforms.items()
if isinstance(key, str) and key.startswith(prefix) and isinstance(entry, dict)
- and entry.get("error_code") == "multiplex_shared_ingress"
+ and entry.get("error_code") in {"multiplex_shared_ingress", "whatsapp_unpaired"}
}
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index 6d50a5326ef..6a7b23ecd95 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -121,22 +121,29 @@ def _unlink_quietly(path: Path) -> None:
path.unlink()
+def _read_bridge_pidfile(session_path: Path) -> tuple:
+ """``(pid, kernel_start_time)`` from ``bridge.pid``; ``(None, None)`` when absent or unparseable.
+ Line 1 = pid, optional line 2 = kernel start time (legacy files: pid only)."""
+ pid_file = session_path / "bridge.pid"
+ if not pid_file.exists():
+ return None, None
+ try:
+ lines = [ln.strip() for ln in pid_file.read_text(encoding="utf-8-sig").split("\n")]
+ pid = int(lines[0])
+ recorded_start = int(lines[1]) if len(lines) > 1 and lines[1] else None
+ except (ValueError, OSError, TypeError, IndexError):
+ return None, None
+ return pid, recorded_start
+
+
def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:
"""Kill an orphaned bridge recorded in ``bridge.pid``, after :func:`_bridge_pid_is_ours`."""
from gateway.status import _pid_exists
pid_file = session_path / "bridge.pid"
if not pid_file.exists():
return
- pid = None
- recorded_start = None
- try:
- # Format: line 1 = pid, optional line 2 = kernel start time. Legacy
- # files written before the guard existed have only the pid.
- lines = pid_file.read_text(encoding="utf-8-sig").split("\n")
- pid = int(lines[0].strip())
- if len(lines) > 1 and lines[1].strip():
- recorded_start = int(lines[1].strip())
- except (ValueError, OSError, TypeError, IndexError):
+ pid, recorded_start = _read_bridge_pidfile(session_path)
+ if pid is None:
_unlink_quietly(pid_file)
return
if _bridge_pid_is_ours(pid, recorded_start):
@@ -288,6 +295,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
from gateway.platforms.whatsapp_common import resolve_whatsapp_bridge_dir
WhatsAppAdapter._DEFAULT_BRIDGE_DIR = resolve_whatsapp_bridge_dir()
extra = config.extra
+ from hermes_constants import get_hermes_home
+ self._profile_home = get_hermes_home()
self._bridge_process: Optional[subprocess.Popen] = None
self._bridge_port: int = extra.get("bridge_port", 3000)
self._bridge_script: str = extra.get("bridge_script", str(self._DEFAULT_BRIDGE_DIR / "bridge.js"))
@@ -509,6 +518,19 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
except pm.InstallError as exc:
self._set_fatal_error("whatsapp_node_missing", str(exc), retryable=False)
return False
+ secondary = bool(getattr(self, "_runtime_status_platform_key", ""))
+ prior_bridge_is_ours = False
+ if secondary:
+ from .bridge_ownership import secondary_bridge_port, check_secondary_ownership
+ try:
+ self._bridge_port = secondary_bridge_port(self._profile_home, self.config.extra.get("bridge_port"))
+ prior_bridge_is_ours = check_secondary_ownership(self._session_path, self._bridge_port) == "ours"
+ except (OSError, ValueError) as exc:
+ self._set_fatal_error(
+ "whatsapp_bridge_conflict",
+ f"{exc}. Set platforms.whatsapp.extra.bridge_port to a distinct free port; "
+ "or stop the process holding it.", retryable=False)
+ return False
if not self._preflight():
return False
bridge_path = Path(self._bridge_script)
@@ -523,11 +545,16 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
if not self._ensure_bridge_deps(bridge_path.parent):
return False
self._session_path.mkdir(parents=True, exist_ok=True)
- if await self._reuse_running_bridge(bridge_path):
+ # A secondary adopts or reaps only a bridge its own pidfile identifies (crash restart);
+ # 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
- _kill_stale_bridge_by_pidfile(self._session_path)
- _kill_port_process(self._bridge_port)
- await asyncio.sleep(1)
+ if not secondary or prior_bridge_is_ours:
+ _kill_stale_bridge_by_pidfile(self._session_path)
+ if not secondary:
+ _kill_port_process(self._bridge_port)
+ if not secondary or prior_bridge_is_ours:
+ await asyncio.sleep(1)
# Bridge output goes to a log file so QR codes, errors, and reconnection messages survive for troubleshooting.
self._bridge_log = self._session_path.parent / "bridge.log"
self._bridge_log_fh = bridge_log_fh = open(self._bridge_log, "a", encoding="utf-8")
@@ -602,7 +629,8 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
self._terminate_bridge(force=True)
except Exception as e:
print(f"[{self.name}] Error stopping bridge: {e}")
- _unlink_quietly(self._session_path / "bridge.pid")
+ if self._bridge_process or not getattr(self, "_runtime_status_platform_key", ""):
+ _unlink_quietly(self._session_path / "bridge.pid")
await cancel_task(self._poll_task)
if self._http_session and not self._http_session.closed:
await self._http_session.close()
@@ -946,7 +974,11 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
except ImportError:
return send_error("aiohttp not installed. Run: pip install aiohttp")
try:
- bridge_port = (getattr(pconfig, "extra", {}) or {}).get("bridge_port", 3000)
+ from hermes_constants import get_hermes_home
+ from .bridge_ownership import standalone_bridge_port
+ bridge_port = standalone_bridge_port(
+ get_hermes_home(), (getattr(pconfig, "extra", {}) or {}).get("bridge_port")
+ )
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.
diff --git a/plugins/platforms/whatsapp/bridge_ownership.py b/plugins/platforms/whatsapp/bridge_ownership.py
new file mode 100644
index 00000000000..3f4884a1821
--- /dev/null
+++ b/plugins/platforms/whatsapp/bridge_ownership.py
@@ -0,0 +1,69 @@
+"""Non-destructive bridge allocation for multiplexed secondary profiles."""
+import socket
+from pathlib import Path
+
+# 3000 stays the default profile's historical port; secondaries allocate above it. 999 ports
+# covers any realistic number of paired phones on one host.
+SECONDARY_PORT_FIRST = 3001
+SECONDARY_PORT_LAST = 3999
+
+
+def port_is_free(port: int) -> bool:
+ with socket.socket() as sock:
+ try:
+ sock.bind(("127.0.0.1", port))
+ except OSError:
+ return False
+ return True
+
+
+def secondary_bridge_port(home: Path, explicit) -> int:
+ record = home / "platforms/whatsapp/bridge_port"
+ if explicit is not None:
+ port = int(explicit)
+ elif record.exists():
+ port = int(record.read_text().strip())
+ else:
+ port = next((p for p in range(SECONDARY_PORT_FIRST, SECONDARY_PORT_LAST + 1) if port_is_free(p)), None)
+ if port is None:
+ raise ValueError(f"No free bridge port in {SECONDARY_PORT_FIRST}..{SECONDARY_PORT_LAST}")
+ record.parent.mkdir(parents=True, exist_ok=True)
+ record.write_text(str(port), encoding="utf-8")
+ if not 1 <= port <= 65535:
+ raise ValueError(f"Invalid bridge port {port}")
+ return port
+
+
+def standalone_bridge_port(home: Path, explicit) -> int:
+ """Resolve a port for an out-of-process send without allocating one.
+
+ Startup is responsible for creating the secondary record. A standalone
+ sender may only consume an explicit value or an already persisted record;
+ an unknown profile keeps the historical default port.
+ """
+ if explicit is not None:
+ port = int(explicit)
+ else:
+ record = home / "platforms/whatsapp/bridge_port"
+ if not record.exists():
+ return 3000
+ port = int(record.read_text(encoding="utf-8").strip())
+ if not 1 <= port <= 65535:
+ raise ValueError(f"Invalid bridge port {port}")
+ return port
+
+
+def check_secondary_ownership(session: Path, port: int) -> str:
+ """``"free"`` when the port is unbound, ``"ours"`` when it is bound and this profile's own
+ ``bridge.pid`` (pid plus kernel start time, the same fingerprint the default path trusts) names
+ a live process, so a bridge orphaned by a gateway crash can be adopted or reaped by identity.
+ Anything else bound on the port belongs to someone else and is a fatal for this profile: no HTTP
+ probe is safe before ownership is known, a healthy listener can still be another phone, and a
+ secondary never signals a process it cannot prove is its own."""
+ if port_is_free(port):
+ return "free"
+ from .adapter import _bridge_pid_is_ours, _read_bridge_pidfile
+ pid, recorded_start = _read_bridge_pidfile(session)
+ if pid is not None and _bridge_pid_is_ours(pid, recorded_start):
+ return "ours"
+ raise ValueError(f"Bridge port {port} is bound by a process this profile does not own")
diff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.py
index f21b12a946a..a59d9317b5c 100644
--- a/tests/gateway/test_multiplex_adapter_registry.py
+++ b/tests/gateway/test_multiplex_adapter_registry.py
@@ -1054,14 +1054,21 @@ class TestSecondaryProfileConfigHandling:
assert runner._profile_adapters["later"][photon] is later
@pytest.mark.asyncio
- async def test_secondary_profile_adapter_start_skips_whatsapp(self, monkeypatch):
- """WhatsApp is shared process-level ingress like Relay: the bridge is
- one authenticated session tied to a single phone number, so a
- credential-less secondary profile must be skipped (not stall startup
- in a connect/retry loop) while its other platforms start normally."""
+ @pytest.mark.parametrize("paired", [False, True])
+ async def test_secondary_profile_adapter_start_skips_whatsapp(self, monkeypatch, tmp_path, paired):
+ """Only paired secondaries start a profile-local WhatsApp adapter."""
runner = _secondary_recovery_runner()
direct = _SecondaryRecoveryAdapter()
+ _real_profile_scope = gateway_run._profile_runtime_scope
_install_secondary_reconnect_context(monkeypatch, runner, direct)
+ monkeypatch.setattr(gateway_run, "_profile_runtime_scope", _real_profile_scope)
+ home = tmp_path / "secondary"
+ session = home / "platforms/whatsapp/session"
+ session.mkdir(parents=True)
+ if paired:
+ (session / "creds.json").write_text("{}")
+ statuses = []
+ monkeypatch.setattr(runner, "_update_platform_runtime_status", lambda *a, **kw: statuses.append((a, kw)))
monkeypatch.setattr(
"gateway.config.load_gateway_config",
lambda: GatewayConfig(
@@ -1076,6 +1083,11 @@ class TestSecondaryProfileConfigHandling:
def _create_adapter(platform, config):
factory_calls.append(platform)
+ if platform is Platform.WHATSAPP:
+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
+ wa = WhatsAppAdapter(config)
+ assert wa._session_path == session
+ return wa
return direct
async def _connect(adapter, platform):
@@ -1084,11 +1096,14 @@ class TestSecondaryProfileConfigHandling:
monkeypatch.setattr(runner, "_create_adapter", _create_adapter)
monkeypatch.setattr(runner, "_connect_initial_adapter_with_timeout", _connect)
- connected = await runner._start_one_profile_adapters("clientbot", "/tmp/x", {})
+ monkeypatch.setattr(runner, "_configure_profile_adapter", lambda *a: None)
+ connected = await runner._start_one_profile_adapters("clientbot", home, {})
- assert connected == 1
- assert factory_calls == [Platform.DISCORD]
- assert runner._profile_adapters["clientbot"] == {Platform.DISCORD: direct}
+ assert connected == (2 if paired else 1)
+ assert factory_calls == ([Platform.WHATSAPP, Platform.DISCORD] if paired else [Platform.DISCORD])
+ if not paired:
+ assert statuses[-1][1]["error_code"] == "whatsapp_unpaired"
+ assert "hermes -p clientbot whatsapp" in statuses[-1][1]["error_message"]
class TestSecondaryProfileHookRegistration:
diff --git a/tests/gateway/test_multiplex_unserved_shared_ingress.py b/tests/gateway/test_multiplex_unserved_shared_ingress.py
index f4a3efd2d4e..c50e0e79868 100644
--- a/tests/gateway/test_multiplex_unserved_shared_ingress.py
+++ b/tests/gateway/test_multiplex_unserved_shared_ingress.py
@@ -1,4 +1,4 @@
-"""Multiplex secondaries that enable shared-ingress platforms (WhatsApp/Relay) must not be
+"""Multiplex secondaries that enable shared-ingress Relay must not be
silently unserved: one INFO per skipped platform, a stamped ``<profile>:<platform>`` status
entry, and the loud "not being served" WARNING when no profile (default included) runs it."""
@@ -43,7 +43,7 @@ def _install_secondary(monkeypatch, runner, stamps):
"gateway.config.load_gateway_config",
lambda: GatewayConfig(
multiplex_profiles=True,
- platforms={Platform.WHATSAPP: PlatformConfig(enabled=True)},
+ platforms={Platform.RELAY: PlatformConfig(enabled=True)},
),
)
monkeypatch.setattr(
@@ -54,7 +54,7 @@ def _install_secondary(monkeypatch, runner, stamps):
@pytest.mark.asyncio
-async def test_secondary_whatsapp_without_primary_is_reported_unserved(monkeypatch, caplog):
+async def test_secondary_relay_without_primary_is_reported_unserved(monkeypatch, caplog):
runner = _runner()
stamps = []
_install_secondary(monkeypatch, runner, stamps)
@@ -68,29 +68,29 @@ async def test_secondary_whatsapp_without_primary_is_reported_unserved(monkeypat
infos = [r for r in caplog.records if r.levelno == logging.INFO and "not served" in r.getMessage()]
assert infos and "'work'" in infos[0].getMessage() and "default profile" in infos[0].getMessage()
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
- assert any("whatsapp" in w and "not being served" in w and "work" in w for w in warnings), warnings
+ assert any("relay" in w and "not being served" in w and "work" in w for w in warnings), warnings
# Stamped so `hermes gateway status --profile work` / the dashboard can show the reason.
- assert ("work:whatsapp", {
+ assert ("work:relay", {
"platform_state": "disabled", "error_code": "multiplex_shared_ingress",
"error_message": "not served under multiplex (shared ingress owned by default)",
}) in stamps
# ...and the CLI reader turns that stamp into the status line.
from gateway.status import write_runtime_status
from hermes_cli import gateway_multiplex_served as served
- key, kw = next(s for s in stamps if s[0] == "work:whatsapp")
+ key, kw = next(s for s in stamps if s[0] == "work:relay")
write_runtime_status(platform=key, **kw)
monkeypatch.setattr(served, "live_default_gateway_pid", lambda: 4242)
assert served.served_profile_unserved_platforms("work") == {
- "whatsapp": "not served under multiplex (shared ingress owned by default)"}
+ "relay": "not served under multiplex (shared ingress owned by default)"}
assert served.served_profile_unserved_platforms("other") == {}
@pytest.mark.asyncio
-async def test_secondary_whatsapp_served_by_default_is_not_warned(monkeypatch, caplog):
- """The default owns WhatsApp: the secondary IS served through the shared adapter — no WARNING,
+async def test_secondary_relay_served_by_default_is_not_warned(monkeypatch, caplog):
+ """The default owns Relay: the secondary IS served through the shared adapter — no WARNING,
the INFO line still explains where the channel lives."""
runner = _runner()
- runner.adapters[Platform.WHATSAPP] = object()
+ runner.adapters[Platform.RELAY] = object()
_install_secondary(monkeypatch, runner, [])
with caplog.at_level(logging.INFO, logger="gateway.run"):
diff --git a/tests/gateway/test_whatsapp_multiplex.py b/tests/gateway/test_whatsapp_multiplex.py
new file mode 100644
index 00000000000..8d8efee5d31
--- /dev/null
+++ b/tests/gateway/test_whatsapp_multiplex.py
@@ -0,0 +1,143 @@
+"""Profile-local WhatsApp credentials and non-destructive secondary startup."""
+import socket
+import os
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import Platform, PlatformConfig
+from gateway.run import _platform_has_bot_credential, _profile_runtime_scope
+from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
+
+
+def test_credentials_follow_profile_home(tmp_path):
+ a, b = tmp_path / "a", tmp_path / "b"
+ for home in (a, b):
+ (home / "platforms/whatsapp/session").mkdir(parents=True)
+ (a / "platforms/whatsapp/session/creds.json").write_text("{}")
+ for home, expected in ((a, True), (b, False), (a, True)):
+ with _profile_runtime_scope(home, hydrate_secrets=False):
+ assert _platform_has_bot_credential(Platform.WHATSAPP, PlatformConfig()) is expected
+ overridden = PlatformConfig(extra={"session_path": str(a / "platforms/whatsapp/session")})
+ assert _platform_has_bot_credential(Platform.WHATSAPP, overridden)
+ from gateway.status import write_runtime_status
+ from hermes_cli import gateway_multiplex_served as served
+ from unittest.mock import patch
+ write_runtime_status(platform="work:whatsapp", platform_state="disabled",
+ error_code="whatsapp_unpaired", error_message="pair it: hermes -p work whatsapp")
+ with patch.object(served, "live_default_gateway_pid", return_value=os.getpid()):
+ assert served.served_profile_unserved_platforms("work") == {
+ "whatsapp": "pair it: hermes -p work whatsapp"}
+
+
+async def test_secondary_ports_and_foreign_listener(tmp_path, monkeypatch):
+ import plugins.platforms.whatsapp.adapter as module
+ adapters = []
+ listener = socket.socket()
+ monkeypatch.setattr(module, "_write_bridge_pidfile", lambda *a: None)
+ for name in ("a", "b"):
+ home = tmp_path / name
+ home.mkdir()
+ with _profile_runtime_scope(home, hydrate_secrets=False):
+ adapter = WhatsAppAdapter(PlatformConfig())
+ adapter._hermes_profile_name = name
+ adapter._runtime_status_platform_key = f"{name}:whatsapp"
+ monkeypatch.setattr(adapter, "_preflight", lambda: True)
+ monkeypatch.setattr(adapter, "_ensure_bridge_deps", lambda path: False)
+ await adapter.connect()
+ adapters.append(adapter)
+ if name == "a":
+ listener.bind(("127.0.0.1", adapter._bridge_port))
+ listener.listen()
+ assert 3001 <= adapters[0]._bridge_port <= 3999
+ # Reserve the first profile's actual listener before the next startup.
+ with listener:
+ with _profile_runtime_scope(tmp_path / "b", hydrate_secrets=False):
+ explicit = WhatsAppAdapter(PlatformConfig(extra={"bridge_port": adapters[0]._bridge_port}))
+ explicit._hermes_profile_name = "b"
+ explicit._runtime_status_platform_key = "b:whatsapp"
+ monkeypatch.setattr(explicit, "_preflight", lambda: True)
+ monkeypatch.setattr(explicit, "_ensure_bridge_deps", lambda path: True)
+ probe = AsyncMock(side_effect=AssertionError("must not probe foreign bridge"))
+ monkeypatch.setattr(explicit, "_probe_bridge_health", probe)
+ def no_kill(*args):
+ raise AssertionError("must not kill foreign bridge")
+ monkeypatch.setattr(module, "_kill_port_process", no_kill)
+ monkeypatch.setattr(module, "_kill_stale_bridge_by_pidfile", no_kill)
+ assert not await explicit.connect()
+ assert explicit.has_fatal_error
+ assert not explicit.fatal_error_retryable
+ assert str(explicit._bridge_port) in explicit.fatal_error_message
+ assert "platforms.whatsapp.extra.bridge_port" in explicit.fatal_error_message
+ probe.assert_not_called()
+ await explicit.disconnect()
+ assert adapters[0]._bridge_port != adapters[1]._bridge_port
+ for name, adapter in zip(("a", "b"), adapters):
+ assert int((tmp_path / name / "platforms/whatsapp/bridge_port").read_text()) == adapter._bridge_port
+ with _profile_runtime_scope(tmp_path / name, hydrate_secrets=False):
+ restart = WhatsAppAdapter(PlatformConfig())
+ restart._runtime_status_platform_key = f"{name}:whatsapp"
+ monkeypatch.setattr(restart, "_preflight", lambda: False)
+ await restart.connect()
+ assert restart._bridge_port == adapter._bridge_port
+
+
+def _hold_port():
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ sock.listen()
+ return sock, sock.getsockname()[1]
+
+
+def test_ownership_verdicts(tmp_path):
+ """free: unbound port (a stale pidfile changes nothing, and nothing is signalled). ours: bound port
+ and this profile's pidfile names a live process by pid + kernel start time. Anything else bound
+ is a fatal, so a secondary never probes or signals another profile's bridge."""
+ from gateway import status
+ from plugins.platforms.whatsapp.adapter import _write_bridge_pidfile
+ from plugins.platforms.whatsapp.bridge_ownership import check_secondary_ownership
+ session = tmp_path / "session"
+ session.mkdir()
+ (session / "bridge.pid").write_text(str(os.getpid())) # legacy, no start time
+ sock, port = _hold_port()
+ with sock:
+ with pytest.raises(ValueError, match="does not own"):
+ check_secondary_ownership(session, port) # bound, pidfile unverifiable: fail closed
+ _write_bridge_pidfile(session, os.getpid()) # pid + start time of a live process
+ assert check_secondary_ownership(session, port) == "ours"
+ (session / "bridge.pid").write_text(f"{os.getpid()}\n{status.get_process_start_time(os.getpid()) + 1}\n")
+ with pytest.raises(ValueError, match="does not own"):
+ check_secondary_ownership(session, port) # recycled pid: fingerprint mismatch
+ assert check_secondary_ownership(session, port) == "free" # unbound now, pidfile irrelevant
+ assert (session / "bridge.pid").exists() # nothing was signalled or unlinked
+
+
+async def test_secondary_adopts_its_own_orphaned_bridge(tmp_path, monkeypatch):
+ """Gateway crash, bridge child survives on the recorded port: the restart adopts it when healthy
+ instead of dying with a port conflict. Only the identity-checked pidfile path may reap it."""
+ import plugins.platforms.whatsapp.adapter as module
+ from plugins.platforms.whatsapp.adapter import _write_bridge_pidfile
+ home = tmp_path / "c"
+ home.mkdir()
+ with _profile_runtime_scope(home, hydrate_secrets=False):
+ adapter = WhatsAppAdapter(PlatformConfig())
+ adapter._runtime_status_platform_key = "c:whatsapp"
+ monkeypatch.setattr(adapter, "_preflight", lambda: True)
+ monkeypatch.setattr(adapter, "_ensure_bridge_deps", lambda path: True)
+ sock, port = _hold_port()
+ (home / "platforms/whatsapp").mkdir(parents=True)
+ (home / "platforms/whatsapp/bridge_port").write_text(str(port))
+ adapter._session_path.mkdir(parents=True, exist_ok=True)
+ _write_bridge_pidfile(adapter._session_path, os.getpid())
+ reuse = AsyncMock(return_value=True)
+ monkeypatch.setattr(adapter, "_reuse_running_bridge", reuse)
+ def no_port_kill(*args):
+ raise AssertionError("a secondary never clears a port by scan")
+ monkeypatch.setattr(module, "_kill_port_process", no_port_kill)
+ with sock:
+ assert await adapter.connect()
+ reuse.assert_awaited_once()
+ assert not adapter.has_fatal_error
+ await adapter.disconnect()
diff --git a/tests/tools/test_whatsapp_send_message_media.py b/tests/tools/test_whatsapp_send_message_media.py
index 67950ad99a4..024a6af8048 100644
--- a/tests/tools/test_whatsapp_send_message_media.py
+++ b/tests/tools/test_whatsapp_send_message_media.py
@@ -17,6 +17,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from plugins.platforms.whatsapp.adapter import _bridge_media_type, _standalone_send
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
# ---------------------------------------------------------------------------
@@ -67,7 +68,7 @@ def _resp(status, json_data=None, text_data=None):
def _session_with(responses):
"""Build a mocked aiohttp.ClientSession that returns *responses* in order
- and records every POST (url, json_payload)."""
+ and records every GET/POST (url, json_payload)."""
calls = []
idx = [0]
@@ -82,6 +83,7 @@ def _session_with(responses):
session = MagicMock()
session.post = MagicMock(side_effect=_post)
+ session.get = MagicMock(side_effect=_post)
session_ctx = MagicMock()
session_ctx.__aenter__ = AsyncMock(return_value=session)
session_ctx.__aexit__ = AsyncMock(return_value=False)
@@ -155,3 +157,70 @@ def test_missing_captioned_file_falls_back_to_text():
assert len(calls) == 1
assert calls[0][0].endswith("/send")
assert calls[0][1]["message"] == "floor plan"
+
+
+def test_standalone_send_uses_persisted_secondary_bridge_port(tmp_path, monkeypatch):
+ """A secondary's automatic port must route standalone sends to its bridge."""
+ home = tmp_path / ".hermes"
+ record = home / "platforms" / "whatsapp" / "bridge_port"
+ record.parent.mkdir(parents=True)
+ record.write_text("3042", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ session_ctx, calls = _session_with([_resp(200, {"messageId": "t1"})])
+ with 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"
+
+
+ "persisted_port,extra,expected_port",
+ [(3057, {}, 3057), (3057, {"bridge_port": 3061}, 3061), (None, {}, 3000)],
+ ids=["persisted", "explicit-wins", "unallocated-default"],
+)
+def test_secondary_standalone_sends_use_active_profile_port_for_text_media_and_mentions(
+ tmp_path, monkeypatch, persisted_port, extra, expected_port,
+):
+ """The active multiplex profile, not launch HOME, owns all standalone routes."""
+ launch_home = tmp_path / "launch"
+ secondary_home = tmp_path / "secondary"
+ record = secondary_home / "platforms" / "whatsapp" / "bridge_port"
+ secondary_home.mkdir()
+ if persisted_port is not None:
+ record.parent.mkdir(parents=True)
+ record.write_text(str(persisted_port), encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(launch_home))
+ media = tmp_path / "image.png"
+ media.write_bytes(b"image")
+ for home, config_extra, port in (
+ (launch_home, {}, 3000),
+ (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"}),
+ ])
+ override = set_hermes_home_override(home)
+ try:
+ with patch("aiohttp.ClientSession", return_value=session_ctx):
+ result = asyncio.run(_standalone_send(
+ SimpleNamespace(token="", extra=config_extra), "12345", "hello",
+ media_files=[(str(media), False)], mentions=["12345"],
+ ))
+ finally:
+ reset_hermes_home_override(override)
+ assert result.get("success") is True, result
+ assert [url for url, _ in calls] == [
+ f"http://localhost:{port}/health",
+ f"http://localhost:{port}/send",
+ f"http://localhost:{port}/send-media",
+ ]
+ assert calls[1][1]["mentions"] == ["[email protected]"]
+ assert calls[2][1]["filePath"] == str(media)
+ assert not (launch_home / "platforms/whatsapp/bridge_port").exists()
+ if persisted_port is None:
+ assert not record.exists()
+ else:
+ assert record.read_text(encoding="utf-8") == str(persisted_port)
diff --git a/website/docs/user-guide/messaging/whatsapp.md b/website/docs/user-guide/messaging/whatsapp.md
index b2a85ef6279..28903949351 100644
--- a/website/docs/user-guide/messaging/whatsapp.md
+++ b/website/docs/user-guide/messaging/whatsapp.md
@@ -31,6 +31,27 @@ with third-party bridges. When this happens, Hermes will update the bridge depen
bot stops working after a WhatsApp update, pull the latest Hermes version and re-pair.
:::
+## Multiple profiles
+
+The host multiplexer can serve a separate paired WhatsApp session for each profile.
+Run `hermes -p work whatsapp` to pair a secondary profile, then enable WhatsApp
+for that profile. An enabled profile without `creds.json` is skipped with the
+`whatsapp_unpaired` status and its pairing command.
+
+An explicit `platforms.whatsapp.extra.bridge_port` takes precedence. Otherwise,
+a secondary selects the first free port in 3001 to 3999 and saves it in its own
+`platforms/whatsapp/bridge_port` file for subsequent starts. Operators can
+pre-create that file with a port number. The launch profile keeps port 3000.
+
+A secondary adopts a bridge already running on its port only when its own
+session pidfile identifies that process (pid and kernel start time), which is
+what a gateway crash leaves behind. An unhealthy one is reaped by that same
+identity and restarted. Any other process bound on the port is a fatal error
+for that profile only. Set `platforms.whatsapp.extra.bridge_port` to a
+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.
+
## Two Modes
| Mode | How it works | Best for |
diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md
index 00ca1eae682..8e135593b18 100644
--- a/website/docs/user-guide/multi-profile-gateways.md
+++ b/website/docs/user-guide/multi-profile-gateways.md
@@ -424,17 +424,15 @@ no API server is enabled); it serves three kinds of profile-prefixed paths:
adapter instance built without a port; the default listener forwards
`/p/<profile>/<the adapter's usual path>` to it. See
[Inbound-port platforms under the multiplexer](#inbound-port-platforms-under-the-multiplexer).
-- **WhatsApp (bridge) and Relay are shared ingress owned by the default profile.**
- The multiplexer never starts them for a secondary: `WHATSAPP_ENABLED=true` in
- `profiles/work/.env` does nothing on its own. Enable and configure them on the
- default profile (their inbound is routed to profiles via `profile_routes`), or
- disable them in the secondary. The gateway logs one INFO line per skipped
- secondary platform, and if **no** profile runs it a WARNING says the platform
- is not being served; `hermes gateway status --profile work` shows
- `whatsapp: not served under multiplex (shared ingress owned by default)`.
- The one exception is a profile that opted out with `gateway.standalone:
- true` — it runs its own WhatsApp bridge and relay in its own gateway, as any
- standalone gateway does.
+- **WhatsApp (bridge) runs per paired profile.** Pair each secondary with
+ `hermes -p work whatsapp`. Each profile uses its own session and bridge port;
+ an unpaired profile is skipped with `whatsapp_unpaired` and a pairing remedy.
+ See [WhatsApp multi-profile setup](messaging/whatsapp.md#multiple-profiles).
+- **Relay remains shared ingress owned by the default profile.** Enable and
+ configure Relay on the default profile, then route inbound to profiles via
+ `profile_routes`. A secondary-only Relay configuration is reported as not served.
+ A profile that opted out with `gateway.standalone: true` runs its own relay
+ in its own gateway, as any standalone gateway does.
Authentication follows the profile named in the URL. Unprefixed endpoints keep
using the default listener's existing credentials.