Skip to content

The agent that grows with you

fix(browser): offload broker lock acquisition off the event loop

kshitijk4poor45078eb9413e
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index f393ba8b8c4..9620ba6ff24 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3605,7 +3605,14 @@ class APIServerAdapter(BasePlatformAdapter):
loop = asyncio.get_running_loop()
_send = _browser_controller_ws_sender(ws, loop)
- self._browser_control_broker.attach(scope, _send, owner=ws)
+ # attach/disconnect/detach acquire the controller's send_lock, which a
+ # worker-thread dispatch may hold while blocking on THIS loop to
+ # transmit its frame (run_coroutine_threadsafe + result(timeout=10)).
+ # Offload them so a teardown/attach racing an in-flight send parks a
+ # worker thread, never the event loop.
+ await asyncio.to_thread(
+ self._browser_control_broker.attach, scope, _send, owner=ws
+ )
try:
async for msg in ws:
if msg.type == web.WSMsgType.TEXT:
@@ -3614,7 +3621,8 @@ class APIServerAdapter(BasePlatformAdapter):
except Exception:
continue
if isinstance(frame, dict):
- reply = self._handle_browser_control_frame(
+ reply = await asyncio.to_thread(
+ self._handle_browser_control_frame,
scope,
frame,
owner=ws,
@@ -3624,7 +3632,8 @@ class APIServerAdapter(BasePlatformAdapter):
elif msg.type in (web.WSMsgType.CLOSE, web.WSMsgType.ERROR):
break
finally:
- self._browser_control_broker.disconnect(
+ await asyncio.to_thread(
+ self._browser_control_broker.disconnect,
scope,
owner=ws,
)
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 637b7f9e1fb..1afaba0991a 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -466,12 +466,20 @@ async def handle_ws(
# 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.
+ #
+ # Offloaded via to_thread: disconnect acquires the controller's
+ # send_lock, which a worker-thread dispatch may hold while blocking
+ # on THIS loop to transmit its frame (run_coroutine_threadsafe +
+ # result(timeout=10)). Acquiring it synchronously here would park
+ # the whole event loop behind that 10s send bridge.
try:
from gateway.browser_control_broker import (
get_browser_control_broker,
)
- get_browser_control_broker().disconnect_owner(transport)
+ await asyncio.to_thread(
+ get_browser_control_broker().disconnect_owner, transport
+ )
except Exception:
_log.exception("ws browser-controller disconnect failed peer=%s", peer)