Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

Gateway: one browser open per session, whatever the CLI sends in parallel (#278)

github-actions[bot]7d4ebadfe3da
diff --git a/gateway/app.py b/gateway/app.py
index 4e1bdd03..7c7214e0 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -14021,6 +14021,13 @@ async def plugs_mcp(request: Request):
# address. The browser itself lives in browser_plane.py: one per harness session, opened on the
# first call, stopped at the turn's end, after idle, or at the cap. Money is the vendor's list
# price passed through under one unit, browser.usd, on the session's own audit row.
+# One open per session at a time. A CLI that issues tool calls in parallel (pi does) sent navigate
+# and screenshot together as a task's first browser calls; both found no session and both opened
+# a browser at the vendor, one of which nothing ever stopped (hr-test, 2026-09-25: two open rows,
+# one session row). The lock lives as long as the session's browser does.
+_browser_open_locks: dict[str, asyncio.Lock] = {}
+
+
async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str, tool: str, spec: dict, args: dict,
config: dict, started: float):
plug = plugs_plane.BROWSER
@@ -14035,22 +14042,25 @@ async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str,
return await refused("not configured", "The browser service is not set up on this deployment. Tell the person.")
s = browser_plane.sessions().get(sid)
if s is None:
- # The first call opens the browser: the estimate is written on the row for the record (a
- # self-hosted instance keeps no task cost cap; the vendor's own credit is the ceiling).
- estimate = browser_plane.session_estimate_usd()
- try:
- s = await browser_plane.open_session(sid, hid, org, workspace, allow, deny)
- except browser_plane.BrowserRefused as e:
- return await refused(e.code, str(e))
- except Exception as e: # noqa: BLE001
- await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error",
- f"open: {type(e).__name__}: {e}")
- return _jsonrpc_result(rid, _tool_text(f"The browser could not be started ({type(e).__name__}). Try again.", True))
- s.reserved = estimate
- await _plug_call_record(hid, sid, org, workspace, plug, "open", "session", started, "ok",
- detail={"estimate_usd": estimate, "session_minutes": browser_plane.SESSION_CAP_MIN,
- "vendor": browser_plane.VENDOR, "vendor_session": s.vendor_id})
- elif (s.allow, s.deny) != (allow, deny):
+ async with _browser_open_locks.setdefault(sid, asyncio.Lock()):
+ s = browser_plane.sessions().get(sid) # the call that waited finds the browser the first one opened
+ if s is None:
+ # The first call opens the browser: the estimate is written on the row for the record
+ # (a self-hosted instance keeps no task cost cap; the vendor's own credit is the ceiling).
+ estimate = browser_plane.session_estimate_usd()
+ try:
+ s = await browser_plane.open_session(sid, hid, org, workspace, allow, deny)
+ except browser_plane.BrowserRefused as e:
+ return await refused(e.code, str(e))
+ except Exception as e: # noqa: BLE001
+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error",
+ f"open: {type(e).__name__}: {e}")
+ return _jsonrpc_result(rid, _tool_text(f"The browser could not be started ({type(e).__name__}). Try again.", True))
+ s.reserved = estimate
+ await _plug_call_record(hid, sid, org, workspace, plug, "open", "session", started, "ok",
+ detail={"estimate_usd": estimate, "session_minutes": browser_plane.SESSION_CAP_MIN,
+ "vendor": browser_plane.VENDOR, "vendor_session": s.vendor_id})
+ if (s.allow, s.deny) != (allow, deny):
s.allow, s.deny, s.host_cache = list(allow), list(deny), {} # the workspace changed its lists
async with s.lock:
if s.closed:
@@ -14090,6 +14100,7 @@ async def _browser_close(sid: str, reason: str) -> None:
s = browser_plane.sessions().get(sid)
if not s or s.closed:
return
+ _browser_open_locks.pop(sid, None)
try:
fig = await browser_plane.close_session_browser(s)
except Exception as e: # noqa: BLE001
diff --git a/gateway/tests/test_browser.py b/gateway/tests/test_browser.py
index 1c6f6d38..85a81949 100644
--- a/gateway/tests/test_browser.py
+++ b/gateway/tests/test_browser.py
@@ -16,6 +16,7 @@ import base64
import json
import os
import sys
+import time
import urllib.parse
import zlib
from pathlib import Path
@@ -696,3 +697,36 @@ def test_no_secret_ever_reached_a_caller():
assert _seen
for body in _seen:
assert VENDOR_KEY not in body and CDP not in body and "SENTINEL" not in body
+
+
+def test_two_first_calls_at_once_open_one_browser(client, world, monkeypatch):
+ """A CLI that issues tool calls in parallel (pi) sent navigate and screenshot together as a
+ task's first browser calls; both found no session and both opened a browser at the vendor,
+ and only the one registered last was ever stopped (hr-test, 2026-09-25: two open rows, one
+ session row, one vendor session left running). The open is one per session now."""
+ reg, ven, posted = world
+ reg.record = _record()
+ hid = _harness(client)
+ _include(client, hid)
+ sid = _session_of(hid)
+ real = browser_plane.connector
+
+ async def slow_connect(cdp): # the vendor answered; the CDP connect takes a moment
+ await asyncio.sleep(0.02)
+ return await real(cdp)
+ monkeypatch.setattr(browser_plane, "connector", slow_connect)
+ cfg = {"allow_domains": [], "deny_domains": []}
+
+ async def both():
+ return await asyncio.gather(
+ gw._browser_plug_call(1, hid, sid, ORG, WS, "navigate", plugs_plane.find("browser", "navigate"), {"url": "example.com"}, cfg, time.time()),
+ gw._browser_plug_call(2, hid, sid, ORG, WS, "screenshot", plugs_plane.find("browser", "screenshot"), {}, cfg, time.time()))
+ a, b = asyncio.run(both())
+ assert json.loads(a.body)["result"]["isError"] is False and json.loads(b.body)["result"]["isError"] is False
+ assert len(ven.created) == 1, ven.created # one browser at the vendor, not two
+ opens = [r for r in _rows(hid) if r["tool"] == "open"]
+ assert len(opens) == 1
+ asyncio.run(gw._browser_close(sid, "turn_end"))
+ stops = [r for r in _rows(hid) if r["tool"] == "session"]
+ assert len(stops) == 1 and json.loads(stops[0]["detail"])["vendor_session"] == "bu_1"
+ assert sid not in gw._browser_open_locks