Skip to content

The agent that grows with you

fix(browser): preserve controller work across reconnects

abundantbeing095a1d078c5c
diff --git a/gateway/browser_control_broker.py b/gateway/browser_control_broker.py
index cba0df58d54..4ed28d48fcc 100644
--- a/gateway/browser_control_broker.py
+++ b/gateway/browser_control_broker.py
@@ -28,10 +28,12 @@ Contract (each rule is exercised by tests/gateway/test_browser_control_broker.py
- **Exact identity and capability selection.** ``attach`` registers a send
callback under a :class:`ControllerScope`; ``select`` returns a controller
- only when the caller's scope matches on *every* identity field —
+ only when the caller's scope matches on *every stable identity field* —
principal, profile, session, controller id, browser profile id, and
transport family — and the requested capability is present in the
- controller's capability set. Partial matches return ``None``.
+ controller's current negotiated capability set. Partial matches return
+ ``None``. A same-identity reconnect may renegotiate capabilities without
+ creating an ambiguous second controller.
- **One pending command per command id; single-shot completion.** Each
``dispatch`` mints a fresh command id, emits one
@@ -48,6 +50,13 @@ Contract (each rule is exercised by tests/gateway/test_browser_control_broker.py
:class:`ControllerCancelled` rather than hanging or racing a detached
controller's late ``complete``.
+- **Unexpected disconnects are recoverable.** ``disconnect`` marks an exact
+ transport owner offline without accepting new dispatches or cancelling
+ already-running work. Re-attaching the same stable identity refreshes the
+ transport callback and can deliver a terminal result for the original
+ command. Explicit detach, cancel, identity replacement, and timeout remain
+ terminal boundaries.
+
Thread-safety: all public state transitions happen under a single reentrant
lock; the send callback is invoked *outside* the lock so a controller may
synchronously ``complete`` from inside its own send (the no-op round trip),
@@ -70,6 +79,8 @@ _OWNER_UNSET = object()
DEFAULT_TICKET_TTL = 30.0
#: Default wall time a dispatch waits for the controller to complete.
DEFAULT_COMMAND_TIMEOUT = 30.0
+#: Maximum cancel frames retained while a same-identity controller is offline.
+MAX_DEFERRED_CANCELS = 512
#: Current wire protocol version. Registration requires this exact integer;
#: booleans are rejected even though ``bool`` subclasses ``int`` in Python.
@@ -163,6 +174,22 @@ class ControllerScope:
capabilities: frozenset = frozenset()
+def _scope_identity(scope: ControllerScope) -> tuple:
+ """Return stable controller identity, excluding negotiated capabilities."""
+ return (
+ scope.principal_id,
+ scope.profile_id,
+ scope.session_id,
+ scope.controller_id,
+ scope.browser_profile_id,
+ scope.transport_family,
+ )
+
+
+def _same_scope_identity(first: ControllerScope, second: ControllerScope) -> bool:
+ return _scope_identity(first) == _scope_identity(second)
+
+
@dataclass(frozen=True)
class Ticket:
"""Opaque, single-use registration credential."""
@@ -183,6 +210,8 @@ class _Controller:
scope: ControllerScope
send: Callable[[dict], None]
owner: Any = None
+ connected: bool = True
+ deferred_cancels: list[dict] = field(default_factory=list)
# Serialize command/cancel writes with detach or replacement. Broker state
# is never held while waiting for this lock, so a transport callback may
# synchronously call complete() without deadlocking the broker.
@@ -281,72 +310,155 @@ class BrowserControlBroker:
*,
owner: Any = None,
) -> None:
- """Register the controller owning ``scope`` with frame callback ``send``.
+ """Attach or refresh the controller for one stable identity.
- Re-attaching an already-attached scope replaces the prior controller
- (logged); a controller that wants to go away must call ``detach``.
+ A reconnect with the same principal/profile/session/controller/browser
+ profile/transport identity refreshes the send callback and negotiated
+ capabilities without cancelling pending work. Capabilities are not an
+ identity field. A different controller or browser profile in the same
+ authenticated session lane hard-replaces the previous identity.
"""
- replacement = _Controller(scope=scope, send=send, owner=owner)
- with self._lock:
- existing = self._controllers.get(scope)
- if existing is None:
+ while True:
with self._lock:
- # A concurrent attach may have won after the optimistic read;
- # retry through the replacement path rather than overwriting it.
- existing = self._controllers.get(scope)
- if existing is None:
- self._controllers[scope] = replacement
+ existing_entry = next(
+ (
+ (candidate_scope, controller)
+ for candidate_scope, controller in self._controllers.items()
+ if _same_scope_identity(candidate_scope, scope)
+ ),
+ None,
+ )
+ lane_scopes = [
+ candidate_scope
+ for candidate_scope in self._controllers
+ if candidate_scope.principal_id == scope.principal_id
+ and candidate_scope.profile_id == scope.profile_id
+ and candidate_scope.session_id == scope.session_id
+ and candidate_scope.transport_family == scope.transport_family
+ and not _same_scope_identity(candidate_scope, scope)
+ ]
+ if existing_entry is None and not lane_scopes:
+ self._controllers[scope] = _Controller(
+ scope=scope,
+ send=send,
+ owner=owner,
+ )
return
- assert existing is not None
- logger.warning(
- "browser controller re-attached for scope %r; replacing prior controller",
- scope,
- )
- with existing.send_lock:
- with self._lock:
- if self._controllers.get(scope) is not existing:
- # Another replacement won while this caller waited. Re-run
- # against the new generation so its pending work is not
- # orphaned by an unconditional overwrite.
- retry = True
- pendings = []
- else:
- retry = False
- pendings = self._pending_for_scope_locked(scope)
- for pending in pendings:
- self._resolve_pending(pending, cancelled=True)
- self._controllers[scope] = replacement
- if not retry:
- self._emit_cancel_frames(existing, pendings)
+ # A different identity in the same authenticated session lane is a
+ # hard replacement, not a recoverable reconnect. Terminalize it
+ # before inserting the successor so session lookup stays unique.
+ if lane_scopes:
+ for lane_scope in lane_scopes:
+ self.detach(lane_scope, notify_controller=False)
+ continue
+
+ if existing_entry is not None:
+ existing_scope, existing = existing_entry
+
+ with existing.send_lock:
+ with self._lock:
+ if self._controllers.get(existing_scope) is not existing:
+ continue
+ self._controllers.pop(existing_scope, None)
+ existing.scope = scope
+ existing.send = send
+ existing.owner = owner
+ existing.connected = False
+ for pending in self._pending.values():
+ if _same_scope_identity(pending.scope, scope):
+ pending.scope = scope
+ deferred = list(existing.deferred_cancels)
+ existing.deferred_cancels.clear()
+ self._controllers[scope] = existing
+
+ unsent: list[dict] = []
+ for index, frame in enumerate(deferred):
+ try:
+ send(frame)
+ except Exception:
+ logger.exception(
+ "failed to flush deferred browser-controller cancel"
+ )
+ unsent = deferred[index:]
+ break
+ if unsent:
+ with self._lock:
+ if self._controllers.get(scope) is existing:
+ existing.deferred_cancels = unsent[
+ -MAX_DEFERRED_CANCELS:
+ ]
+ raise ConnectionError(
+ "browser controller reconnect could not flush deferred cancels"
+ )
+ with self._lock:
+ if self._controllers.get(scope) is existing:
+ existing.connected = True
return
- self.attach(scope, send, owner=owner)
def select(self, scope: ControllerScope, capability: str) -> Optional[_Controller]:
- """Return the controller exactly matching ``scope`` and ``capability``.
+ """Return the connected controller matching identity and capability.
- ``None`` when any identity field differs or the capability is not in
- the controller's capability set. The controller's own scope is the
- authority on capabilities.
+ The caller's capabilities are not authoritative on reconnect. Selection
+ matches the stable identity fields, then checks the attached
+ controller's current negotiated capability set. Offline controllers
+ preserve old pending work but never accept new dispatches.
"""
with self._lock:
- controller = self._controllers.get(scope)
- if controller is None:
- return None
- if capability not in controller.scope.capabilities:
- return None
- return controller
+ matches = [
+ controller
+ for controller in self._controllers.values()
+ if _same_scope_identity(controller.scope, scope)
+ and controller.connected
+ and capability in controller.scope.capabilities
+ ]
+ return matches[0] if len(matches) == 1 else None
def is_owner(self, scope: ControllerScope, owner: Any) -> bool:
- """Return whether ``owner`` is the exact transport attached to ``scope``.
+ """Return whether ``owner`` is the exact live transport for ``scope``.
Ownership is independent of capabilities. Transport handlers use this
for heartbeat and result admission so a least-privilege controller does
not need to request ``controller.noop`` merely to complete a real action.
"""
with self._lock:
- controller = self._controllers.get(scope)
- return controller is not None and controller.owner is owner
+ matches = [
+ controller
+ for controller in self._controllers.values()
+ if _same_scope_identity(controller.scope, scope)
+ and controller.connected
+ and controller.owner is owner
+ ]
+ return len(matches) == 1
+
+ def disconnect(
+ self,
+ scope: ControllerScope,
+ *,
+ owner: Any = _OWNER_UNSET,
+ ) -> bool:
+ """Mark one exact controller transport offline without cancelling work."""
+ with self._lock:
+ entry = next(
+ (
+ (candidate_scope, controller)
+ for candidate_scope, controller in self._controllers.items()
+ if _same_scope_identity(candidate_scope, scope)
+ ),
+ None,
+ )
+ if entry is None:
+ return False
+ candidate_scope, controller = entry
+ with controller.send_lock:
+ with self._lock:
+ if self._controllers.get(candidate_scope) is not controller:
+ return False
+ if owner is not _OWNER_UNSET and controller.owner is not owner:
+ return False
+ controller.connected = False
+ controller.owner = None
+ return True
def detach(
self,
@@ -428,19 +540,28 @@ class BrowserControlBroker:
},
}
pending = _PendingCommand(
- scope=scope,
+ scope=controller.scope,
command_id=command_id,
tool_call_id=tool_call_id,
)
with controller.send_lock:
with self._lock:
# select() intentionally runs outside the send lock. Revalidate
- # the exact controller generation after acquiring it so detach
- # or replacement cannot leave a stale command waiting forever.
- if self._controllers.get(scope) is not controller:
+ # the exact live controller after acquiring it so disconnect or
+ # identity replacement cannot leave a stale command waiting.
+ attached = next(
+ (
+ candidate
+ for candidate in self._controllers.values()
+ if _same_scope_identity(candidate.scope, scope)
+ ),
+ None,
+ )
+ if attached is not controller or not controller.connected:
raise ControllerUnavailable(
f"controller for scope {scope!r} detached before dispatch"
)
+ pending.scope = controller.scope
self._pending[command_id] = pending
try:
@@ -464,9 +585,21 @@ class BrowserControlBroker:
if timed_out:
with controller.send_lock:
with self._lock:
- still_attached = self._controllers.get(scope) is controller
- if still_attached:
- self._emit_cancel_frames(controller, [pending])
+ active = next(
+ (
+ candidate
+ for candidate in self._controllers.values()
+ if _same_scope_identity(candidate.scope, scope)
+ ),
+ None,
+ )
+ if active is None:
+ active = controller
+ if not active.connected:
+ self._defer_cancel_locked(active, pending)
+ active = None
+ if active is not None:
+ self._emit_cancel_frames(active, [pending])
raise ControllerTimeout(
f"controller did not complete command {command_id!r} "
f"within {self._command_timeout}s"
@@ -517,17 +650,32 @@ class BrowserControlBroker:
without inventing state).
"""
with self._lock:
- controller = self._controllers.get(scope)
- if controller is None:
+ controller = next(
+ (
+ candidate
+ for candidate in self._controllers.values()
+ if _same_scope_identity(candidate.scope, scope)
+ ),
+ None,
+ )
+ if controller is None or not controller.connected:
return False
with controller.send_lock:
with self._lock:
- if self._controllers.get(scope) is not controller:
+ attached = next(
+ (
+ candidate
+ for candidate in self._controllers.values()
+ if _same_scope_identity(candidate.scope, scope)
+ ),
+ None,
+ )
+ if attached is not controller or not controller.connected:
return False
target = None
for pending in self._pending.values():
if (
- pending.scope == scope
+ _same_scope_identity(pending.scope, scope)
and pending.tool_call_id == tool_call_id
and not pending.done
):
@@ -550,24 +698,37 @@ class BrowserControlBroker:
del self._pending[pending.command_id]
pending.event.set()
+ @staticmethod
+ def _cancel_frame(pending: _PendingCommand) -> dict:
+ return {
+ "method": FRAME_CANCEL,
+ "params": {
+ "command_id": pending.command_id,
+ "tool_call_id": pending.tool_call_id,
+ },
+ }
+
+ def _defer_cancel_locked(
+ self,
+ controller: _Controller,
+ pending: _PendingCommand,
+ ) -> None:
+ controller.deferred_cancels.append(self._cancel_frame(pending))
+ if len(controller.deferred_cancels) > MAX_DEFERRED_CANCELS:
+ del controller.deferred_cancels[:-MAX_DEFERRED_CANCELS]
+
def _pending_for_scope_locked(self, scope: ControllerScope) -> list[_PendingCommand]:
return [
pending
for pending in list(self._pending.values())
- if pending.scope == scope
+ if _same_scope_identity(pending.scope, scope)
]
def _emit_cancel_frames(
self, controller: _Controller, pendings: list[_PendingCommand]
) -> None:
for pending in pendings:
- frame = {
- "method": FRAME_CANCEL,
- "params": {
- "command_id": pending.command_id,
- "tool_call_id": pending.tool_call_id,
- },
- }
+ frame = self._cancel_frame(pending)
try:
controller.send(frame)
except Exception:
@@ -605,13 +766,26 @@ class BrowserControlBroker:
]
return matches[0] if len(matches) == 1 else None
+ def disconnect_owner(self, owner: Any) -> int:
+ """Mark every controller owned by one lost transport offline."""
+ with self._lock:
+ scopes = [
+ scope
+ for scope, controller in self._controllers.items()
+ if controller.owner is owner
+ ]
+ disconnected = 0
+ for scope in scopes:
+ disconnected += int(self.disconnect(scope, owner=owner))
+ return disconnected
+
def detach_owner(self, owner: Any, *, notify_controller: bool = True) -> int:
- """Detach every controller owned by one transport connection."""
+ """Hard-detach every controller owned by one transport connection."""
with self._lock:
scopes = [
scope
for scope, controller in self._controllers.items()
- if controller.owner == owner
+ if controller.owner is owner
]
for scope in scopes:
self.detach(
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index feed75afc51..b0e9ce87148 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -41,6 +41,7 @@ Requires:
"""
import asyncio
+import concurrent.futures
import errno
import hashlib
import hmac
@@ -144,6 +145,42 @@ def _get_scoped_secret(name, default=None):
logger = logging.getLogger(__name__)
+def _browser_controller_ws_sender(ws, loop, *, wait_timeout: float = 10.0):
+ """Return a loop-aware broker sender for one aiohttp controller socket.
+
+ A wait timeout means the coroutine is still in flight on a live loop, not
+ that the frame was rejected. Keep the broker command pending and let its
+ own deadline/cancel path decide; a real send exception still propagates.
+ """
+
+ def send(frame: dict) -> None:
+ if ws.closed:
+ raise ConnectionError("browser-control websocket is closed")
+ try:
+ on_loop = asyncio.get_running_loop() is loop
+ except RuntimeError:
+ on_loop = False
+ if on_loop:
+ loop.create_task(ws.send_json(frame))
+ return
+ future = asyncio.run_coroutine_threadsafe(ws.send_json(frame), loop)
+ try:
+ future.result(timeout=wait_timeout)
+ except concurrent.futures.TimeoutError:
+ if future.done():
+ raise
+
+ def observe_late_send(completed):
+ try:
+ completed.result()
+ except Exception:
+ logger.exception("browser-controller websocket send failed after wait timeout")
+
+ future.add_done_callback(observe_late_send)
+
+ return send
+
+
def _hermes_version() -> str:
"""Return the canonical Hermes Agent version string.
@@ -3495,26 +3532,7 @@ class APIServerAdapter(BasePlatformAdapter):
)
await ws.prepare(request)
loop = asyncio.get_running_loop()
-
- def _send(frame: dict) -> None:
- """Broker send callback: forward a frame onto the aiohttp loop.
-
- Called from broker dispatch threads; aiohttp socket writes must
- happen on the event loop. Waiting for the write here preserves
- command ordering and lets a closed socket fail the dispatch
- instead of silently dropping the frame.
- """
- if ws.closed:
- raise ConnectionError("browser-control websocket is closed")
- try:
- on_loop = asyncio.get_running_loop() is loop
- except RuntimeError:
- on_loop = False
- if on_loop:
- loop.create_task(ws.send_json(frame))
- return
- future = asyncio.run_coroutine_threadsafe(ws.send_json(frame), loop)
- future.result(timeout=10.0)
+ _send = _browser_controller_ws_sender(ws, loop)
self._browser_control_broker.attach(scope, _send, owner=ws)
try:
@@ -3525,25 +3543,36 @@ class APIServerAdapter(BasePlatformAdapter):
except Exception:
continue
if isinstance(frame, dict):
- reply = self._handle_browser_control_frame(scope, frame)
+ reply = self._handle_browser_control_frame(
+ scope,
+ frame,
+ owner=ws,
+ )
if isinstance(reply, dict):
await ws.send_json(reply)
elif msg.type in (web.WSMsgType.CLOSE, web.WSMsgType.ERROR):
break
finally:
- self._browser_control_broker.detach(
+ self._browser_control_broker.disconnect(
scope,
owner=ws,
- notify_controller=False,
)
return ws
- def _handle_browser_control_frame(self, scope: "ControllerScope", frame: dict) -> None:
+ def _handle_browser_control_frame(
+ self,
+ scope: "ControllerScope",
+ frame: dict,
+ *,
+ owner: Any = None,
+ ) -> None:
"""Apply one controller→broker frame with exact-scope checks."""
method = frame.get("method")
params = frame.get("params")
if not isinstance(params, dict):
return
+ if owner is None or not self._browser_control_broker.is_owner(scope, owner):
+ return
if method == "browser.controller.heartbeat":
nonce = str(params.get("nonce") or "").strip()
if not nonce or len(nonce) > 128:
@@ -3555,6 +3584,16 @@ class APIServerAdapter(BasePlatformAdapter):
"method": "browser.controller.heartbeat",
"params": {"nonce": nonce, "ok": True},
}
+ if method == "browser.controller.detach":
+ self._browser_control_broker.detach(
+ scope,
+ owner=owner,
+ notify_controller=False,
+ )
+ return {
+ "method": "browser.controller.detach",
+ "params": {"ok": True},
+ }
if method == "browser.controller.result":
command_id = params.get("command_id")
if isinstance(command_id, str) and command_id:
diff --git a/tests/gateway/test_browser_control_api.py b/tests/gateway/test_browser_control_api.py
index cf70cb92fe3..d19735242c7 100644
--- a/tests/gateway/test_browser_control_api.py
+++ b/tests/gateway/test_browser_control_api.py
@@ -1,13 +1,21 @@
import asyncio
+import concurrent.futures
import time
import pytest
from aiohttp import WSServerHandshakeError, web
from aiohttp.test_utils import TestClient, TestServer
-from gateway.browser_control_broker import ControllerRejected, ControllerScope
+from gateway.browser_control_broker import (
+ ControllerCancelled,
+ ControllerRejected,
+ ControllerScope,
+)
from gateway.config import PlatformConfig
-from gateway.platforms.api_server import APIServerAdapter
+from gateway.platforms.api_server import (
+ APIServerAdapter,
+ _browser_controller_ws_sender,
+)
from tools.browser_extension_router import route_browser_tool
@@ -148,6 +156,65 @@ def test_route_table_advertises_registration_and_controller_ws_without_replacing
assert ("POST", "/v1/chat/completions") in routes
+def test_ws_sender_treats_wait_timeout_as_in_flight_and_real_error_as_failure(monkeypatch):
+ class WS:
+ closed = False
+
+ async def send_json(self, _frame):
+ return None
+
+ class Future:
+ def __init__(self, error, *, done=False):
+ self.error = error
+ self._done = done
+ self.callbacks = []
+
+ def result(self, timeout=None):
+ if self.error is not None:
+ raise self.error
+ return None
+
+ def add_done_callback(self, callback):
+ self.callbacks.append(callback)
+
+ def done(self):
+ return self._done
+
+ timeout_future = Future(concurrent.futures.TimeoutError())
+ def return_timeout(coro, _loop):
+ coro.close()
+ return timeout_future
+
+ monkeypatch.setattr(asyncio, "run_coroutine_threadsafe", return_timeout)
+ sender = _browser_controller_ws_sender(WS(), object(), wait_timeout=0.01)
+ sender({"method": "browser.controller.command"})
+ assert len(timeout_future.callbacks) == 1
+
+ error_future = Future(ConnectionError("socket write failed"))
+ def return_error(coro, _loop):
+ coro.close()
+ return error_future
+
+ monkeypatch.setattr(asyncio, "run_coroutine_threadsafe", return_error)
+ sender = _browser_controller_ws_sender(WS(), object(), wait_timeout=0.01)
+ with pytest.raises(ConnectionError, match="socket write failed"):
+ sender({"method": "browser.controller.command"})
+
+ completed_timeout = Future(concurrent.futures.TimeoutError(), done=True)
+ def return_completed_timeout(coro, _loop):
+ coro.close()
+ return completed_timeout
+
+ monkeypatch.setattr(
+ asyncio,
+ "run_coroutine_threadsafe",
+ return_completed_timeout,
+ )
+ sender = _browser_controller_ws_sender(WS(), object(), wait_timeout=0.01)
+ with pytest.raises(concurrent.futures.TimeoutError):
+ sender({"method": "browser.controller.command"})
+
+
def test_api_agent_context_binds_server_principal_and_transport_family():
from gateway.session_context import clear_session_vars, get_session_env
@@ -472,6 +539,129 @@ async def test_real_browser_action_routes_through_controller_without_legacy_fall
await ws.close()
+async def test_local_api_same_identity_reconnect_completes_command_started_on_old_socket(monkeypatch):
+ adapter = _adapter()
+ monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
+ async with TestClient(TestServer(_app(adapter))) as client:
+ first_response = await client.post(
+ "/v1/browser-control/register",
+ json=_registration_body(capabilities=["browser_snapshot"]),
+ headers={"Authorization": f"Bearer {API_KEY}"},
+ )
+ first = await first_response.json()
+ first_ws = await client.ws_connect(
+ "/v1/browser-control/ws",
+ protocols=[CONTROL_PROTOCOL, _ticket_protocol(first["ticket"])],
+ )
+
+ pending = asyncio.create_task(
+ asyncio.to_thread(
+ route_browser_tool,
+ "browser_snapshot",
+ {},
+ fallback=lambda: "legacy-result",
+ broker=adapter._browser_control_broker,
+ enabled=True,
+ session_id="session-fixture",
+ principal_id=first["scope"]["principal_id"],
+ transport_family="local-api",
+ tool_call_id="tool-call-reconnect",
+ )
+ )
+ command = await first_ws.receive_json(timeout=2.0)
+ await first_ws.close()
+ await asyncio.sleep(0)
+ assert not pending.done()
+
+ second_response = await client.post(
+ "/v1/browser-control/register",
+ json=_registration_body(capabilities=["browser_snapshot"]),
+ headers={"Authorization": f"Bearer {API_KEY}"},
+ )
+ second = await second_response.json()
+ second_ws = await client.ws_connect(
+ "/v1/browser-control/ws",
+ protocols=[CONTROL_PROTOCOL, _ticket_protocol(second["ticket"])],
+ )
+ await second_ws.send_json(
+ {
+ "method": "browser.controller.result",
+ "params": {
+ "command_id": command["params"]["command_id"],
+ "ok": True,
+ "result": {"reconnected": True},
+ },
+ }
+ )
+ assert await asyncio.wait_for(pending, timeout=2.0) == '{"reconnected": true}'
+ await second_ws.close()
+
+
+async def test_local_api_explicit_detach_is_hard_and_stale_socket_cannot_detach_refresh(monkeypatch):
+ adapter = _adapter()
+ monkeypatch.setattr(adapter, "_browser_control_enabled", lambda: True)
+ async with TestClient(TestServer(_app(adapter))) as client:
+ first_response = await client.post(
+ "/v1/browser-control/register",
+ json=_registration_body(capabilities=["controller.noop"]),
+ headers={"Authorization": f"Bearer {API_KEY}"},
+ )
+ first = await first_response.json()
+ first_ws = await client.ws_connect(
+ "/v1/browser-control/ws",
+ protocols=[CONTROL_PROTOCOL, _ticket_protocol(first["ticket"])],
+ )
+ second_response = await client.post(
+ "/v1/browser-control/register",
+ json=_registration_body(capabilities=["controller.noop"]),
+ headers={"Authorization": f"Bearer {API_KEY}"},
+ )
+ second = await second_response.json()
+ second_ws = await client.ws_connect(
+ "/v1/browser-control/ws",
+ protocols=[CONTROL_PROTOCOL, _ticket_protocol(second["ticket"])],
+ )
+
+ await first_ws.send_json(
+ {"method": "browser.controller.detach", "params": {}}
+ )
+ with pytest.raises(asyncio.TimeoutError):
+ await first_ws.receive_json(timeout=0.05)
+
+ pending = asyncio.create_task(
+ asyncio.to_thread(
+ adapter._browser_control_broker.dispatch,
+ ControllerScope(
+ principal_id=second["scope"]["principal_id"],
+ profile_id=second["scope"]["profile_id"],
+ session_id=second["scope"]["session_id"],
+ controller_id=second["scope"]["controller_id"],
+ browser_profile_id=second["scope"]["browser_profile_id"],
+ transport_family=second["scope"]["transport_family"],
+ capabilities=frozenset(second["scope"]["capabilities"]),
+ ),
+ action="controller.noop",
+ tool_call_id="tool-call-explicit-detach",
+ )
+ )
+ command = await second_ws.receive_json(timeout=2.0)
+ await second_ws.send_json(
+ {"method": "browser.controller.detach", "params": {}}
+ )
+ detached = await second_ws.receive_json(timeout=2.0)
+ assert detached == {
+ "method": "browser.controller.detach",
+ "params": {"ok": True},
+ }
+ with pytest.raises(ControllerCancelled):
+ await asyncio.wait_for(pending, timeout=2.0)
+ assert command["method"] == "browser.controller.command"
+ await first_ws.close()
+ await second_ws.close()
+
+
@pytest.mark.asyncio
async def test_remote_api_uses_the_same_authenticated_noop_round_trip(monkeypatch):
adapter = _adapter()
diff --git a/tests/gateway/test_browser_control_broker_hardening.py b/tests/gateway/test_browser_control_broker_hardening.py
index b78aec407bb..912ebb1d3cf 100644
--- a/tests/gateway/test_browser_control_broker_hardening.py
+++ b/tests/gateway/test_browser_control_broker_hardening.py
@@ -131,21 +131,254 @@ def test_completion_requires_the_same_scope_as_the_pending_command():
assert broker.pending_count == 0
-def test_reattach_cancels_pending_work_from_the_previous_controller_generation():
+def test_same_identity_reattach_preserves_pending_work_and_completes_on_new_owner():
broker = BrowserControlBroker(command_timeout=1.0)
scope = _scope()
thread, outcome, frames = _start_pending(broker, scope)
- old_command_id = frames[0]["params"]["command_id"]
+ command_id = frames[0]["params"]["command_id"]
+ replacement_frames = []
- broker.attach(scope, lambda _frame: None, owner="replacement-owner")
+ broker.attach(scope, replacement_frames.append, owner="replacement-owner")
+ assert thread.is_alive()
+ assert broker.pending_count == 1
+ assert broker.complete(
+ command_id,
+ scope=scope,
+ ok=True,
+ result={"reconnected": True},
+ ) is True
thread.join(timeout=1.0)
assert not thread.is_alive()
+ assert outcome.get("result") == {"reconnected": True}
+ assert "error" not in outcome
+ assert replacement_frames == []
+
+
+def test_same_stable_identity_can_renegotiate_capabilities_without_ambiguity():
+ broker = BrowserControlBroker(command_timeout=1.0)
+ original = _scope()
+ thread, outcome, frames = _start_pending(broker, original)
+ command_id = frames[0]["params"]["command_id"]
+ refreshed = _scope(capabilities=frozenset({"controller.noop", "browser_snapshot"}))
+
+ broker.attach(refreshed, lambda _frame: None, owner="replacement-owner")
+
+ assert broker.scope_for_session(
+ session_id="session-fixture",
+ principal_id="principal-fixture",
+ transport_family="local-api",
+ ) == refreshed
+ assert broker.complete(
+ command_id,
+ scope=refreshed,
+ ok=True,
+ result={"capabilities": "refreshed"},
+ ) is True
+ thread.join(timeout=1.0)
+ assert outcome.get("result") == {"capabilities": "refreshed"}
+
+
+def test_transport_disconnect_parks_pending_and_reconnect_completes_it():
+ broker = BrowserControlBroker(command_timeout=1.0)
+ scope = _scope()
+ thread, outcome, frames = _start_pending(broker, scope)
+ command_id = frames[0]["params"]["command_id"]
+
+ assert broker.disconnect_owner("owner-fixture") == 1
+ assert thread.is_alive()
+ assert broker.pending_count == 1
+ assert broker.select(scope, "controller.noop") is None
+ with pytest.raises(ControllerUnavailable):
+ broker.dispatch(scope, action="controller.noop")
+
+ broker.attach(scope, lambda _frame: None, owner="replacement-owner")
+ assert broker.complete(
+ command_id,
+ scope=scope,
+ ok=True,
+ result={"after": "reconnect"},
+ ) is True
+ thread.join(timeout=1.0)
+ assert outcome.get("result") == {"after": "reconnect"}
+
+
+def test_timeout_while_disconnected_flushes_cancel_before_new_dispatch():
+ broker = BrowserControlBroker(command_timeout=0.02)
+ scope = _scope()
+ thread, outcome, frames = _start_pending(broker, scope)
+ command_id = frames[0]["params"]["command_id"]
+
+ assert broker.disconnect_owner("owner-fixture") == 1
+ thread.join(timeout=1.0)
+ assert isinstance(outcome.get("error"), ControllerTimeout)
+ assert broker.pending_count == 0
+
+ replacement_frames = []
+ broker.attach(scope, replacement_frames.append, owner="replacement-owner")
+ assert replacement_frames == [
+ {
+ "method": "browser.controller.cancel",
+ "params": {
+ "command_id": command_id,
+ "tool_call_id": "tool-call-fixture",
+ },
+ }
+ ]
+
+ second = {}
+
+ def run_second():
+ try:
+ second["result"] = broker.dispatch(
+ scope,
+ action="controller.noop",
+ tool_call_id="tool-call-second",
+ )
+ except Exception as exc:
+ second["error"] = exc
+
+ second_thread = threading.Thread(target=run_second)
+ second_thread.start()
+ while len(replacement_frames) < 2:
+ second_thread.join(timeout=0.01)
+ assert replacement_frames[1]["method"] == "browser.controller.command"
+ assert broker.complete(
+ replacement_frames[1]["params"]["command_id"],
+ scope=scope,
+ ok=True,
+ result={"second": True},
+ ) is True
+ second_thread.join(timeout=1.0)
+ assert second.get("result") == {"second": True}
+
+
+def test_old_transport_owner_cannot_complete_after_same_identity_reconnect():
+ broker = BrowserControlBroker(command_timeout=1.0)
+ scope = _scope()
+ thread, outcome, frames = _start_pending(broker, scope)
+ command_id = frames[0]["params"]["command_id"]
+ refreshed_scope = _scope(capabilities=frozenset({"controller.noop", "browser_snapshot"}))
+
+ broker.attach(refreshed_scope, lambda _frame: None, owner="replacement-owner")
+
+ assert broker.is_owner(refreshed_scope, "owner-fixture") is False
+ assert broker.is_owner(refreshed_scope, "replacement-owner") is True
+ assert broker.complete(
+ command_id,
+ scope=scope,
+ ok=True,
+ result={"stale": True},
+ ) is False
+ assert broker.complete(
+ command_id,
+ scope=refreshed_scope,
+ ok=True,
+ result={"fresh": True},
+ ) is True
+ thread.join(timeout=1.0)
+ assert outcome.get("result") == {"fresh": True}
+
+
+def test_cancel_with_pre_reconnect_scope_still_cancels_same_stable_identity():
+ broker = BrowserControlBroker(command_timeout=1.0)
+ original = _scope()
+ thread, outcome, frames = _start_pending(
+ broker,
+ original,
+ tool_call_id="tool-call-before-reconnect",
+ )
+ refreshed = _scope(capabilities=frozenset({"controller.noop", "browser_snapshot"}))
+ refreshed_frames = []
+ broker.attach(refreshed, refreshed_frames.append, owner="replacement-owner")
+
+ assert broker.cancel(
+ original,
+ tool_call_id="tool-call-before-reconnect",
+ ) is True
+ thread.join(timeout=1.0)
assert isinstance(outcome.get("error"), ControllerCancelled)
- assert broker.complete(old_command_id, scope=scope, ok=True, result={}) is False
+ assert refreshed_frames == [
+ {
+ "method": "browser.controller.cancel",
+ "params": {
+ "command_id": frames[0]["params"]["command_id"],
+ "tool_call_id": "tool-call-before-reconnect",
+ },
+ }
+ ]
+
+
+def test_different_stable_identity_hard_replaces_and_cancels_pending_work():
+ broker = BrowserControlBroker(command_timeout=1.0)
+ original = _scope()
+ thread, outcome, frames = _start_pending(broker, original)
+ command_id = frames[0]["params"]["command_id"]
+ replacement = _scope(controller_id="different-controller")
+ broker.attach(replacement, lambda _frame: None, owner="replacement-owner")
-def test_session_lookup_fails_closed_on_ambiguity_and_owner_detach_is_scoped():
+ assert broker.complete(
+ command_id,
+ scope=replacement,
+ ok=True,
+ result={"unsafe": True},
+ ) is False
+ assert broker.complete(
+ command_id,
+ scope=original,
+ ok=True,
+ result={"original": True},
+ ) is False
+ thread.join(timeout=1.0)
+ assert isinstance(outcome.get("error"), ControllerCancelled)
+
+
+def test_different_controller_identity_hard_replaces_parked_session_controller():
+ broker = BrowserControlBroker(command_timeout=1.0)
+ original = _scope()
+ thread, outcome, _frames = _start_pending(broker, original)
+ assert broker.disconnect_owner("owner-fixture") == 1
+
+ replacement = ControllerScope(
+ principal_id=original.principal_id,
+ profile_id=original.profile_id,
+ session_id=original.session_id,
+ controller_id="replacement-controller",
+ browser_profile_id=original.browser_profile_id,
+ transport_family=original.transport_family,
+ capabilities=original.capabilities,
+ )
+ broker.attach(replacement, lambda _frame: None, owner="replacement-owner")
+
+ thread.join(timeout=1.0)
+ assert isinstance(outcome.get("error"), ControllerCancelled)
+ assert broker.scope_for_session(
+ session_id=original.session_id,
+ principal_id=original.principal_id,
+ transport_family=original.transport_family,
+ ) == replacement
+ assert broker.select(original, "controller.noop") is None
+ assert broker.select(replacement, "controller.noop") is not None
+
+
+def test_failed_deferred_cancel_flush_keeps_controller_offline():
+ broker = BrowserControlBroker(command_timeout=0.01)
+ scope = _scope()
+ thread, outcome, _frames = _start_pending(broker, scope)
+ assert broker.disconnect_owner("owner-fixture") == 1
+ thread.join(timeout=1.0)
+ assert isinstance(outcome.get("error"), ControllerTimeout)
+
+ def fail_send(_frame):
+ raise ConnectionError("fixture flush failed")
+
+ with pytest.raises(ConnectionError, match="flush"):
+ broker.attach(scope, fail_send, owner="replacement-owner")
+ assert broker.select(scope, "controller.noop") is None
+
+
+def test_session_lane_replacement_and_owner_detach_are_scoped():
broker = BrowserControlBroker()
first = _scope(controller_id="controller-one")
second = _scope(controller_id="controller-two")
@@ -162,14 +395,19 @@ def test_session_lookup_fails_closed_on_ambiguity_and_owner_detach_is_scoped():
session_id="session-fixture",
principal_id="principal-fixture",
transport_family="local-api",
- ) is None
+ ) == second
assert broker.scope_for_session(
session_id="other-session",
principal_id="principal-fixture",
transport_family="cloud-ticket-ws",
) == other
- assert broker.detach_owner("owner-shared") == 2
+ assert broker.detach_owner("owner-shared") == 1
+ assert broker.scope_for_session(
+ session_id="session-fixture",
+ principal_id="principal-fixture",
+ transport_family="local-api",
+ ) is None
assert broker.scope_for_session(
session_id="other-session",
principal_id="principal-fixture",
diff --git a/tests/gateway/test_browser_control_cloud.py b/tests/gateway/test_browser_control_cloud.py
index 3b2561551db..c92235a4576 100644
--- a/tests/gateway/test_browser_control_cloud.py
+++ b/tests/gateway/test_browser_control_cloud.py
@@ -400,3 +400,189 @@ def test_cloud_gateway_real_action_round_trip_is_bound_to_identity_and_transport
finally:
broker.reset()
server._sessions.pop("session-fixture", None)
+
+
+def test_cloud_same_identity_reconnect_refreshes_transport_and_completes_pending(monkeypatch):
+ monkeypatch.setattr(
+ "gateway.browser_control_broker.browser_control_enabled", lambda: True
+ )
+ broker = get_browser_control_broker()
+ broker.reset()
+ ready = threading.Event()
+ first_frames = []
+ second_frames = []
+
+ class Transport:
+ auth_identity = {
+ "user_id": "reconnect-user",
+ "provider": "provider-fixture",
+ }
+
+ def __init__(self, frames):
+ self.frames = frames
+
+ def write(self, frame):
+ self.frames.append(frame)
+ if frame.get("method") == "event":
+ ready.set()
+ return True
+
+ first = Transport(first_frames)
+ second = Transport(second_frames)
+ session = {
+ "transport": first,
+ "session_key": "stored-reconnect-session",
+ "profile": "default",
+ }
+ server._sessions["reconnect-session"] = session
+ try:
+ first_registration = server.dispatch(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "browser.controller.register",
+ "params": {
+ "protocol_version": 1,
+ "session_id": "reconnect-session",
+ "controller_id": "controller-fixture",
+ "browser_profile_id": "browser-profile-fixture",
+ "capabilities": ["browser_navigate"],
+ },
+ },
+ first,
+ )
+ scope_payload = first_registration["result"]["scope"]
+ scope = broker.scope_for_session(
+ session_id="reconnect-session",
+ principal_id=scope_payload["principal_id"],
+ transport_family="cloud-ticket-ws",
+ )
+ outcome = {}
+
+ def dispatch():
+ outcome["result"] = broker.dispatch(
+ scope,
+ action="browser_navigate",
+ arguments={"url": "https://example.test"},
+ tool_call_id="tool-call-reconnect",
+ )
+
+ thread = threading.Thread(target=dispatch)
+ thread.start()
+ assert ready.wait(timeout=1.0)
+ command_id = first_frames[-1]["params"]["payload"]["command_id"]
+
+ assert broker.disconnect_owner(first) == 1
+ assert thread.is_alive()
+ session["transport"] = second
+ second_registration = server.dispatch(
+ {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "browser.controller.register",
+ "params": {
+ "protocol_version": 1,
+ "session_id": "reconnect-session",
+ "controller_id": "controller-fixture",
+ "browser_profile_id": "browser-profile-fixture",
+ "capabilities": ["browser_navigate", "browser_snapshot"],
+ },
+ },
+ second,
+ )
+ assert second_registration["result"]["scope"]["capabilities"] == [
+ "browser_navigate",
+ "browser_snapshot",
+ ]
+ result = server.dispatch(
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "browser.controller.result",
+ "params": {
+ "session_id": "reconnect-session",
+ "command_id": command_id,
+ "ok": True,
+ "result": {"reconnected": True},
+ },
+ },
+ second,
+ )
+ assert result["result"]["accepted"] is True
+ thread.join(timeout=1.0)
+ assert outcome.get("result") == {"reconnected": True}
+ finally:
+ broker.reset()
+ server._sessions.pop("reconnect-session", None)
+
+
+def test_cloud_explicit_detach_requires_current_authenticated_owner(monkeypatch):
+ monkeypatch.setattr(
+ "gateway.browser_control_broker.browser_control_enabled", lambda: True
+ )
+ broker = get_browser_control_broker()
+ broker.reset()
+
+ class Transport:
+ auth_identity = {
+ "user_id": "detach-user",
+ "provider": "provider-fixture",
+ }
+
+ def write(self, _frame):
+ return True
+
+ owner = Transport()
+ foreign = Transport()
+ server._sessions["detach-session"] = {
+ "transport": owner,
+ "session_key": "stored-detach-session",
+ "profile": "default",
+ }
+ try:
+ registration = server.dispatch(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "browser.controller.register",
+ "params": {
+ "protocol_version": 1,
+ "session_id": "detach-session",
+ "controller_id": "controller-fixture",
+ "browser_profile_id": "browser-profile-fixture",
+ "capabilities": ["controller.noop"],
+ },
+ },
+ owner,
+ )
+ assert "result" in registration
+
+ foreign_result = server.dispatch(
+ {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "browser.controller.detach",
+ "params": {"session_id": "detach-session"},
+ },
+ foreign,
+ )
+ assert foreign_result["error"]["code"] == 4403
+
+ detached = server.dispatch(
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "browser.controller.detach",
+ "params": {"session_id": "detach-session"},
+ },
+ owner,
+ )
+ assert detached["result"] == {"detached": True}
+ assert broker.scope_for_session(
+ session_id="detach-session",
+ principal_id=registration["result"]["scope"]["principal_id"],
+ transport_family="cloud-ticket-ws",
+ ) is None
+ finally:
+ broker.reset()
+ server._sessions.pop("detach-session", None)
diff --git a/tests/tools/test_snapshot_session_id_leak.py b/tests/tools/test_snapshot_session_id_leak.py
index 39b13a44fcc..f2e65c716e2 100644
--- a/tests/tools/test_snapshot_session_id_leak.py
+++ b/tests/tools/test_snapshot_session_id_leak.py
@@ -49,6 +49,7 @@ def test_export_snippet_shape():
assert "unset" in snippet
assert "${!HERMES_SESSION_*}" in snippet
assert "${!HERMES_CRON_AUTO_DELIVER_*}" in snippet
+ assert "${!HERMES_BROWSER_CONTROL_*}" in snippet
assert "HERMES_UI_SESSION_ID" in snippet
assert "grep -vE" not in snippet
assert '"$__hermes_snap_tmp"' in snippet
diff --git a/tools/environments/base.py b/tools/environments/base.py
index dbdb8742401..460c5eaee32 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -529,7 +529,8 @@ def _cwd_marker(session_id: str) -> str:
# as the Python-side contract for the exclusion set; the dump path unsets by
# name/prefix instead of grepping declare lines (see below / issue #71296).
_SNAPSHOT_EXCLUDED_ENV_REGEX = (
- "^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|HERMES_CRON_SESSION)"
+ "^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|"
+ "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_)"
)
_SHELL_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@@ -573,6 +574,7 @@ def _export_dump_excluding_session_vars(
return (
"{ ( "
"unset ${!HERMES_SESSION_*} ${!HERMES_CRON_AUTO_DELIVER_*} "
+ "${!HERMES_BROWSER_CONTROL_*} "
# AI_AGENT / HERMES_AGENT are per-command attribution markers
# (re-exported by every _wrap_command with outer-harness-preserving
# ${VAR:-default} semantics). Persisting them into the snapshot
diff --git a/tui_gateway/methods_browser_control.py b/tui_gateway/methods_browser_control.py
index 98819a3e2f2..65409ee69fe 100644
--- a/tui_gateway/methods_browser_control.py
+++ b/tui_gateway/methods_browser_control.py
@@ -345,6 +345,40 @@ def _(
return _ok(rid, {"ok": True})
+@method("browser.controller.detach")
+def _(
+ rid,
+ params: dict,
+ _family=_CLOUD_TRANSPORT_FAMILY,
+ _forbidden=_ERR_FORBIDDEN,
+ _identity_ok=_is_authenticated_identity,
+ _digest=_principal_digest,
+) -> dict:
+ """Hard-detach only the controller owned by this authenticated transport."""
+ from gateway import browser_control_broker
+
+ transport = current_transport()
+ identity = getattr(transport, "auth_identity", None)
+ if not _identity_ok(identity):
+ return _err(rid, _forbidden, "authenticated controller identity required")
+ session_id = str(params.get("session_id") or "")
+ with _sessions_lock:
+ session = _sessions.get(session_id)
+ if session is None or session.get("transport") is not transport:
+ return _err(rid, _forbidden, "session is not owned by this transport")
+
+ broker = browser_control_broker.get_browser_control_broker()
+ scope = broker.scope_for_session(
+ session_id=session_id,
+ principal_id=_digest(identity),
+ transport_family=_family,
+ )
+ if scope is None or not broker.is_owner(scope, transport):
+ return _err(rid, _forbidden, "controller is not owned by this transport")
+ broker.detach(scope, owner=transport, notify_controller=False)
+ return _ok(rid, {"detached": True})
+
+
def register(server) -> None:
"""Bind this module's handlers onto ``server``'s globals and registry."""
_registry.install(server)
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 47d0f9b1ef9..637b7f9e1fb 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -462,20 +462,18 @@ async def handle_ws(
if transport is not None:
server.unregister_live_transport(transport)
- # Owner-safely detach browser controllers this transport
- # registered. The socket itself is closing, so no
- # peer cancel write is attempted; every server-side pending command
- # is still failed closed immediately.
+ # Owner-safely park browser controllers this transport registered.
+ # A reconnect with the same stable identity may deliver a terminal
+ # result for work already in flight; no new dispatch is admitted
+ # while the controller is offline.
try:
from gateway.browser_control_broker import (
get_browser_control_broker,
)
- get_browser_control_broker().detach_owner(
- transport, notify_controller=False
- )
+ get_browser_control_broker().disconnect_owner(transport)
except Exception:
- _log.exception("ws browser-controller detach failed peer=%s", peer)
+ _log.exception("ws browser-controller disconnect failed peer=%s", peer)
transport.close()
diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md
index 66e7f9bc92e..18dd5f4e622 100644
--- a/website/docs/user-guide/features/api-server.md
+++ b/website/docs/user-guide/features/api-server.md
@@ -321,6 +321,18 @@ same `command_id`, an exact boolean `ok`, and either `result` or `error`.
Cancellation and timeout emit `browser.controller.cancel`; late results are
ignored.
+An unexpected socket loss marks the controller offline and preserves work
+already in flight until each command's original deadline. A reconnect with the
+same principal, profile, session, controller id, browser profile, and transport
+identity refreshes the transport without admitting new work before any deferred
+cancels are flushed. Negotiated capabilities may change on that reconnect; they
+are not an identity field. A different controller id or browser profile in the
+same authenticated session lane is a hard replacement: old pending work is
+cancelled before the successor becomes routable. Send
+`browser.controller.detach` on the authenticated controller transport for an
+intentional hard detach — that immediately cancels pending work. Merely closing
+the socket is treated as a recoverable disconnect.
+
The authenticated dashboard transport exposes the same registration, result,
heartbeat, capability, and ownership semantics over its Gateway RPC/event
channel. In both transports, selection requires one unambiguous exact match on