Skip to content

The agent that grows with you

fix(whatsapp): reuse bridge ports after restart

KoNit-K155588754a61
diff --git a/plugins/platforms/whatsapp/bridge_ownership.py b/plugins/platforms/whatsapp/bridge_ownership.py
index 68966a9b489..484ce962316 100644
--- a/plugins/platforms/whatsapp/bridge_ownership.py
+++ b/plugins/platforms/whatsapp/bridge_ownership.py
@@ -11,6 +11,9 @@ SECONDARY_PORT_LAST = 3999
def port_is_free(port: int) -> bool:
with socket.socket() as sock:
+ # A just-stopped bridge can leave its accepted TCP connections in TIME-WAIT. The Node
+ # bridge enables this option too, so match its bind semantics while still rejecting a listener.
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind(("127.0.0.1", port))
except OSError:
diff --git a/tests/gateway/test_whatsapp_multiplex.py b/tests/gateway/test_whatsapp_multiplex.py
index 2d98f5b40fc..701fa9a5037 100644
--- a/tests/gateway/test_whatsapp_multiplex.py
+++ b/tests/gateway/test_whatsapp_multiplex.py
@@ -91,6 +91,34 @@ def _hold_port():
return sock, sock.getsockname()[1]
+def test_port_probe_reuses_time_wait_addresses(monkeypatch):
+ """A secondary restart must not mistake the prior bridge's TCP TIME-WAIT for a listener (#139425)."""
+ import plugins.platforms.whatsapp.bridge_ownership as ownership
+
+ calls = []
+
+ class ProbeSocket:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def setsockopt(self, level, option, value):
+ calls.append(("setsockopt", level, option, value))
+
+ def bind(self, address):
+ calls.append(("bind", address))
+
+ monkeypatch.setattr(ownership.socket, "socket", ProbeSocket)
+
+ assert ownership.port_is_free(3001)
+ assert calls == [
+ ("setsockopt", socket.SOL_SOCKET, socket.SO_REUSEADDR, 1),
+ ("bind", ("127.0.0.1", 3001)),
+ ]
+
+
def test_allocation_skips_ports_recorded_by_siblings(tmp_path):
"""A sibling whose bridge is down leaves its recorded port unbound; a new profile must not take it,
or the sibling hits a non-retryable port conflict on its next start. A corrupt record names itself."""