fix(whatsapp): adopt only the recorded bridge's own port; one port resolution for launch and send

A secondary treated a bound port as its own whenever its pidfile named a
live bridge, without checking that bridge listened on that port. After a
crash left the old bridge alive and bridge_port was pointed at a port
another profile's bridge held, the secondary probed and adopted the
foreign bridge (script hash and read-receipt config do not distinguish
phones). bridge.pid now records the spawn port on line 3; ownership
requires pid, start time and port to match. Pidfiles without a port fail
closed for secondaries; the default path reads lines 1-2 as before.

A profile that recorded a port as a secondary and later launched its own
gateway started its bridge on 3000 while `whatsapp send` read the record.
The launch adapter now resolves its port like standalone send (explicit,
then record, then 3000), so profiles without a record are unchanged.

gateway/AGENTS.md no longer lists the WhatsApp bridge as default-only
shared ingress.

Co-authored-by: Victor Kyriazakos <victor@rocketfueldev.com>
This commit is contained in:
unsupportedpastels
2026-10-04 01:34:46 +00:00
committed by Mark S.
parent 01071fdbbb
commit d385b01469
5 changed files with 111 additions and 30 deletions

View File

@@ -234,9 +234,12 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki
profile's scope; gate/allowlist reads go through `platform_gate_env`. A `if not os.getenv(X):
os.environ[X] = …` bridge is first-profile-wins across the process — test two profiles with
conflicting flags before touching precedence.
- **Unserved is reported, never silent.** Shared-ingress platforms (WhatsApp bridge, Relay) run on
the default profile only; a secondary enabling one is logged once with the remedy and stamped
into runtime status (`run_adapters.py::_note_unserved_secondary_platform`). `needs_attention` is
- **Unserved is reported, never silent.** Shared-ingress platforms (Relay) run on the default
profile only; a secondary enabling one is logged once with the remedy and stamped into runtime
status (`run_adapters.py::_note_unserved_secondary_platform`). The WhatsApp bridge is per profile:
a paired secondary gets its own adapter and port (`plugins/platforms/whatsapp/bridge_ownership.py`),
an unpaired one is reported as `whatsapp_unpaired`, and a secondary never adopts or signals a
bridge its own pidfile (pid + start time + port) does not identify. `needs_attention` is
set and cleared at the single writer (`_update_platform_runtime_status`) on the connect path.
- **One launch-home identity.** "Does this task serve a routed profile?" compares the override
with `hermes_constants.get_routing_process_hermes_home()` (`agent/secret_scope.py::

View File

@@ -122,18 +122,20 @@ def _unlink_quietly(path: Path) -> None:
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, kernel_start_time, port)`` from ``bridge.pid``; all ``None`` when absent or unparseable.
Line 1 = pid, optional line 2 = kernel start time, optional line 3 = the ``--port`` it was spawned
with (legacy files: pid only, or pid + start time)."""
pid_file = session_path / "bridge.pid"
if not pid_file.exists():
return None, None
return None, 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
recorded_port = int(lines[2]) if len(lines) > 2 and lines[2] else None
except (ValueError, OSError, TypeError, IndexError):
return None, None
return pid, recorded_start
return None, None, None
return pid, recorded_start, recorded_port
def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:
@@ -142,7 +144,7 @@ def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:
pid_file = session_path / "bridge.pid"
if not pid_file.exists():
return
pid, recorded_start = _read_bridge_pidfile(session_path)
pid, recorded_start, _ = _read_bridge_pidfile(session_path)
if pid is None:
_unlink_quietly(pid_file)
return
@@ -158,12 +160,14 @@ def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:
_unlink_quietly(pid_file)
def _write_bridge_pidfile(session_path: Path, pid: int) -> None:
"""Write the bridge PID plus its kernel start time (line 2) for identity-checked cleanup."""
def _write_bridge_pidfile(session_path: Path, pid: int, port: Optional[int] = None) -> None:
"""Write the bridge PID plus its kernel start time (line 2) for identity-checked cleanup, and the
port it listens on (line 3) so a secondary adopts only the endpoint that process actually serves."""
with suppress(OSError):
from gateway.status import get_process_start_time
start = get_process_start_time(pid)
(session_path / "bridge.pid").write_text(str(pid) if start is None else f"{pid}\n{start}", encoding="utf-8")
text = str(pid) if start is None else f"{pid}\n{start}" + ("" if port is None else f"\n{port}")
(session_path / "bridge.pid").write_text(text, encoding="utf-8")
def _terminate_bridge_process(proc, *, force: bool = False) -> None:
@@ -298,7 +302,14 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
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)
from .bridge_ownership import standalone_bridge_port
try:
# Same resolution as out-of-process sends, so a profile that recorded a port while serving as a
# secondary keeps it when it launches; a secondary re-resolves (and may allocate) in connect().
self._bridge_port: int = standalone_bridge_port(self._profile_home, extra.get("bridge_port"))
except ValueError as exc:
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"))
self._session_path = Path(extra.get("session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")))
self._reply_prefix: Optional[str] = extra.get("reply_prefix")
@@ -564,7 +575,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
self._bridge_process = subprocess.Popen(
[node, str(bridge_path), "--port", str(self._bridge_port), "--session", str(self._session_path),
"--mode", _wenv("WHATSAPP_MODE", "self-chat")], stdout=bridge_log_fh, stderr=bridge_log_fh, env=self._bridge_env(), **windows_detach_popen_kwargs())
_write_bridge_pidfile(self._session_path, self._bridge_process.pid)
_write_bridge_pidfile(self._session_path, self._bridge_process.pid, self._bridge_port)
if not await self._wait_for_bridge():
return False
self._attach_to_bridge(self._bridge_process)

View File

@@ -56,11 +56,11 @@ def secondary_bridge_port(home: Path, explicit) -> int:
def standalone_bridge_port(home: Path, explicit) -> int:
"""Resolve a port for an out-of-process send without allocating one.
"""Port for the launch profile's startup and for out-of-process sends; never allocates.
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.
Explicit config wins, then the profile's persisted record (written when it served as a
secondary), then the historical default 3000. Startup and delivery share this one
resolution so they always target the same bridge.
"""
if explicit is not None:
port = int(explicit)
@@ -76,15 +76,16 @@ def standalone_bridge_port(home: Path, explicit) -> int:
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."""
``bridge.pid`` names a live process (pid plus kernel start time, the same fingerprint the default
path trusts) that was spawned on this same port, so a bridge orphaned by a gateway crash can be
adopted or reaped by identity. A live recorded bridge on a different port proves nothing about
who holds this one. 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):
pid, recorded_start, recorded_port = _read_bridge_pidfile(session)
if pid is not None and recorded_port == port 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")

View File

@@ -122,9 +122,16 @@ def test_ownership_verdicts(tmp_path):
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
_write_bridge_pidfile(session, os.getpid(), port) # pid + start time + port 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")
_write_bridge_pidfile(session, os.getpid(), port + 1)
with pytest.raises(ValueError, match="does not own"):
check_secondary_ownership(session, port) # live recorded bridge, but spawned on another port
_write_bridge_pidfile(session, os.getpid())
with pytest.raises(ValueError, match="does not own"):
check_secondary_ownership(session, port) # pre-port pidfile: endpoint unproven, fail closed
(session / "bridge.pid").write_text(
f"{os.getpid()}\n{status.get_process_start_time(os.getpid()) + 1}\n{port}\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
@@ -149,7 +156,7 @@ async def test_secondary_adopts_its_own_orphaned_bridge(tmp_path, monkeypatch):
(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())
_write_bridge_pidfile(adapter._session_path, os.getpid(), port)
reuse = AsyncMock(return_value=True)
monkeypatch.setattr(adapter, "_reuse_running_bridge", reuse)
def no_port_kill(*args):
@@ -160,3 +167,59 @@ async def test_secondary_adopts_its_own_orphaned_bridge(tmp_path, monkeypatch):
reuse.assert_awaited_once()
assert not adapter.has_fatal_error
await adapter.disconnect()
@pytest.mark.asyncio
async def test_live_old_bridge_does_not_authorize_a_different_port(tmp_path, monkeypatch):
"""Crash leaves this profile's bridge alive on its old port; the operator then points bridge_port at a
port another listener holds. The live pidfile must not make that foreign endpoint "ours"."""
import plugins.platforms.whatsapp.adapter as module
from plugins.platforms.whatsapp.adapter import _write_bridge_pidfile
monkeypatch.setattr(module, "find_node_executable", lambda name: f"/usr/bin/{name}")
old_sock, old_port = _hold_port()
foreign_sock, foreign_port = _hold_port()
home = tmp_path / "d"
home.mkdir()
with _profile_runtime_scope(home, hydrate_secrets=False):
adapter = WhatsAppAdapter(PlatformConfig(extra={"bridge_port": foreign_port}))
adapter._runtime_status_platform_key = "d:whatsapp"
monkeypatch.setattr(adapter, "_preflight", lambda: True)
monkeypatch.setattr(adapter, "_ensure_bridge_deps", lambda path: True)
adapter._session_path.mkdir(parents=True, exist_ok=True)
_write_bridge_pidfile(adapter._session_path, os.getpid(), old_port)
reuse = AsyncMock(side_effect=AssertionError("must not probe or adopt a foreign endpoint"))
monkeypatch.setattr(adapter, "_reuse_running_bridge", reuse)
def no_kill(*args):
raise AssertionError("must not signal anything")
monkeypatch.setattr(module, "_kill_port_process", no_kill)
monkeypatch.setattr(module, "_kill_stale_bridge_by_pidfile", no_kill)
with old_sock, foreign_sock:
assert not await adapter.connect()
assert adapter.has_fatal_error and not adapter.fatal_error_retryable
assert str(foreign_port) in adapter.fatal_error_message
reuse.assert_not_called()
await adapter.disconnect()
@pytest.mark.asyncio
async def test_launch_startup_and_standalone_send_agree_after_role_change(tmp_path, monkeypatch):
"""A profile that recorded a port as a secondary and later launches its own gateway starts its bridge
on the port `whatsapp send` resolves, instead of 3000 while sends go to the abandoned record."""
import plugins.platforms.whatsapp.adapter as module
from plugins.platforms.whatsapp.bridge_ownership import secondary_bridge_port, standalone_bridge_port
monkeypatch.setattr(module, "find_node_executable", lambda name: f"/usr/bin/{name}")
home = tmp_path / "profiles" / "e"
home.mkdir(parents=True)
recorded = secondary_bridge_port(home, None)
with _profile_runtime_scope(home, hydrate_secrets=False):
launch = WhatsAppAdapter(PlatformConfig())
monkeypatch.setattr(launch, "_preflight", lambda: False) # stop before any bridge work
await launch.connect()
assert launch._bridge_port == recorded == standalone_bridge_port(home, None)
fresh = tmp_path / "profiles" / "f"
fresh.mkdir()
with _profile_runtime_scope(fresh, hydrate_secrets=False):
default_like = WhatsAppAdapter(PlatformConfig())
monkeypatch.setattr(default_like, "_preflight", lambda: False)
await default_like.connect()
assert default_like._bridge_port == 3000 == standalone_bridge_port(fresh, None) # no record: unchanged

View File

@@ -42,10 +42,13 @@ An explicit `platforms.whatsapp.extra.bridge_port` takes precedence. Otherwise,
a secondary selects the first free port in 3001 to 3999 that no other profile's
record claims, and saves it in its own `platforms/whatsapp/bridge_port` file for
subsequent starts. Operators can pre-create that file with a port number; delete
it to have a new port allocated. The launch profile keeps port 3000.
it to have a new port allocated. The launch profile uses port 3000 unless it
already has that file (from serving as a secondary), in which case its gateway
and `hermes whatsapp send` both keep using the recorded port.
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
session pidfile identifies that process (pid, kernel start time, and the port it
was started on), 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