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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
Gateway: the browser's record is one per session; each process attaches to it (#279)
github-actions[bot]b6c3064faa70
diff --git a/gateway/app.py b/gateway/app.pyindex 7c7214e0..e5c94295 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -13888,6 +13888,30 @@ _PLUG_REFUSALS = {}+# A plug call served when this process holds no trace handle for the session (another replica is+# running the turn on the hosted service; here, a reaper's stop after the turn's handle is gone)+# belongs in the session's trace all the same: its chunk goes under the session's own prefix (the+# vertex names it) with this process's nonce keeping the key unique. Bounded: one handle per session.+_plug_trace_handles: "collections.OrderedDict[str, dict]" = collections.OrderedDict()+++async def _plug_trace_handle(sid: str) -> dict | None:+ tr = _plug_trace_handles.get(sid)+ if tr is None:+ try:+ v = await _vertex_get(sid) or {}+ except Exception: # noqa: BLE001+ return None+ prefix = str(v.get("trace_blob") or "")+ if not prefix:+ return None+ tr = {"prefix": prefix, "org": str(v.get("tenant") or ""), "since": 0, "chunk": 0, "count": 0}+ _plug_trace_handles[sid] = tr+ while len(_plug_trace_handles) > 500:+ _plug_trace_handles.popitem(last=False)+ return tr++async def _plug_call_record(hid: str, sid: str, org: str, workspace: str, plug: str, tool: str, risk: str,started: float, outcome: str, error: str = "", *, unit: str = "call",usd: float = 0.0, detail: dict | None = None) -> None:@@ -13907,6 +13931,8 @@ async def _plug_call_record(hid: str, sid: str, org: str, workspace: str, plug:with contextlib.suppress(Exception):await _vg_upsert(_PLUG_CALL_LABEL, _rid("pcall"), props)tr = _session_trace.get(sid)+ if not (tr and tr.get("prefix")):+ tr = await _plug_trace_handle(sid)if tr and tr.get("prefix"):with contextlib.suppress(Exception):await _trace_flush(tr, {"events": [{"type": "plug", "plug": plug, "tool": tool, "risk": risk,@@ -14021,10 +14047,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.+# One open per session at a time in this process. 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.+# The record of the browser itself is the plane's registry (browser_plane.registry): one process on+# a self-hosted instance keeps it in memory; the hosted service keeps it in its control store so+# every replica the sandbox's calls reach attaches to the one browser instead of opening its own._browser_open_locks: dict[str, asyncio.Lock] = {}@@ -14040,28 +14069,41 @@ async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str,if not browser_plane.configured():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:+ try:+ rec = await browser_plane.registry.get(sid)+ except Exception as e: # noqa: BLE001+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error", f"registry: {type(e).__name__}: {e}")+ return _jsonrpc_result(rid, _tool_text("The browser service could not be reached. Try again.", True))+ s = None+ if rec is None: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:+ rec = await browser_plane.registry.get(sid) # the call that waited finds the browser the first one opened+ if rec 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)+ s = await browser_plane.open_session(sid, hid, org, workspace, allow, deny, estimate)except browser_plane.BrowserRefused as e:return await refused(e.code, str(e))except Exception as e: # noqa: BLE001await _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.opened:+ 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 is None:+ try:+ s = await browser_plane.attach(rec) # this process's attachment to the recorded browser+ except Exception as e: # noqa: BLE001+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error",+ f"attach: {type(e).__name__}: {e}")+ return _jsonrpc_result(rid, _tool_text(f"The browser could not be reached ({type(e).__name__}). Try again.", True))if (s.allow, s.deny) != (allow, deny):s.allow, s.deny, s.host_cache = list(allow), list(deny), {} # the workspace changed its lists+ await browser_plane.registry.bump(sid, allow=list(allow), deny=list(deny))async with s.lock:if s.closed:return await refused("session closed", "The browser for this task was stopped. Call again to open a new one.")@@ -14098,21 +14140,33 @@ async def _browser_close(sid: str, reason: str) -> None:ran and the vendor's dollars for them, metered under browser.usd. Closing the CDP socket alonekeeps the vendor's meter running, so the stop is explicit and it is in the audit trail."""s = browser_plane.sessions().get(sid)- if not s or s.closed:+ try:+ rec = await browser_plane.registry.get(sid)+ except Exception as e: # noqa: BLE001+ print(f"[browser] {sid}: record not read at {reason}: {type(e).__name__}: {e}", flush=True)+ return+ if rec is None or not await browser_plane.registry.delete(sid):+ # Stopped by another process (or never opened): that one writes the row; ours is only an+ # attachment to drop.+ if s is not None:+ await browser_plane.detach(s)return_browser_open_locks.pop(sid, None)try:- fig = await browser_plane.close_session_browser(s)+ fig = await browser_plane.close_session_browser(rec, s)except Exception as e: # noqa: BLE001- fig = {"minutes": s.minutes, "usd": round(s.minutes * browser_plane.PRICES["browser.minute"], 6),- "usd_source": "table", "calls": s.calls, "screenshots": s.screenshots, "blocked": [],- "stop_error": f"{type(e).__name__}: {str(e)[:120]}"}+ mins = browser_plane.minutes(rec)+ fig = {"minutes": mins, "usd": round(mins * browser_plane.PRICES["browser.minute"], 6),+ "usd_source": "table", "calls": int(rec.get("calls") or 0), "screenshots": int(rec.get("screenshots") or 0),+ "blocked": [], "stop_error": f"{type(e).__name__}: {str(e)[:120]}"}print(f"[browser] {sid}: stopped ({reason}) after {fig['minutes']} min, ${fig['usd']:.6f} ({fig['usd_source']})", flush=True)- released = round(max(0.0, s.reserved - float(fig["usd"])), 6)- await _plug_call_record(s.hid, sid, s.org, s.workspace, plugs_plane.BROWSER, "session", "session", s.created, "ok", "",+ reserved = float(rec.get("reserved") or 0.0)+ released = round(max(0.0, reserved - float(fig["usd"])), 6)+ await _plug_call_record(str(rec["hid"]), sid, str(rec["org"]), str(rec["workspace"]), plugs_plane.BROWSER, "session", "session",+ float(rec.get("created") or time.time()), "ok", "",unit=browser_plane.UNIT, usd=float(fig["usd"]),- detail={"reason": reason, "vendor": browser_plane.VENDOR, "vendor_session": s.vendor_id,- "reserved_usd": s.reserved, "released_usd": released, **fig})+ detail={"reason": reason, "vendor": browser_plane.VENDOR, "vendor_session": str(rec.get("vendor_id") or ""),+ "reserved_usd": reserved, "released_usd": released, **fig})@app.on_event("startup")@@ -14121,9 +14175,11 @@ async def _browser_reaper_start() -> None:async def loop() -> None:while True:await asyncio.sleep(15)- for s, why in browser_plane.expired_sessions():- with contextlib.suppress(Exception):- await _browser_close(s.sid, why)+ with contextlib.suppress(Exception):+ for rec, why in await browser_plane.expired_sessions():+ with contextlib.suppress(Exception):+ await _browser_close(str(rec["sid"]), why)+ await browser_plane.sweep_attachments()asyncio.get_running_loop().create_task(loop())diff --git a/gateway/browser_plane.py b/gateway/browser_plane.pyindex c6051978..1e323b86 100644--- a/gateway/browser_plane.py+++ b/gateway/browser_plane.py@@ -209,39 +209,98 @@ async def resolves_private(host: str) -> bool:# ── the session ──────────────────────────────────────────────────────────────────────────────+# One browser per harness session, wherever the call lands. The RECORD of it (the vendor's id,+# the CDP address, when it opened and was last used, its counts, its lists) is kept once for every+# gateway process by the registry below; the ATTACHMENT (the CDP connection, the context, the+# page) is this process's own, made by the first call that reaches it and dropped when the record+# goes. A CLI's tool calls are load-balanced over every replica, and a per-process record let one+# turn open a browser on each replica it reached (four for one turn on 2026-09-25, three of them+# stopped only by the idle reaper, none of them the page the agent had opened).class Session:- def __init__(self, sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str]):- self.sid, self.hid, self.org, self.workspace = sid, hid, org, workspace- self.allow, self.deny = list(allow), list(deny)- self.vendor_id = ""- self.live_url = ""+ """This process's attachment to a session's browser, built from its record."""++ def __init__(self, rec: dict):+ self.sid, self.hid, self.org, self.workspace = str(rec["sid"]), str(rec["hid"]), str(rec["org"]), str(rec["workspace"])+ self.allow, self.deny = list(rec.get("allow") or []), list(rec.get("deny") or [])+ self.vendor_id = str(rec.get("vendor_id") or "")+ self.cdp_url = str(rec.get("cdp_url") or "")+ self.live_url = str(rec.get("live_url") or "")+ self.created = float(rec.get("created") or time.time())+ self.reserved = float(rec.get("reserved") or 0.0) # what was counted against the task before the browser openedself.browser = Noneself.context = Noneself.page = None- self.created = time.time()- self.last_used = self.created- self.calls = 0- self.screenshots = 0- self.reserved = 0.0 # what was counted against the task before the browser opened- self.blocked: list[str] = [] # hosts refused during this session, for the record+ self.blocked: list[str] = [] # hosts this attachment refused, so each is recorded onceself.host_cache: dict[str, bool] = {}self.lock = asyncio.Lock()self.closed = False+ self.opened = False # this call made the browser at the vendor: the caller writes the open row once- @property- def minutes(self) -> int:- return max(1, math.ceil((time.time() - self.created) / 60))- def expired(self, now: float | None = None) -> str | None:- now = now or time.time()- if now - self.created > SESSION_CAP_MIN * 60:- return "session_cap"- if now - self.last_used > IDLE_S:- return "idle"- return None+def minutes(rec: dict) -> int:+ return max(1, math.ceil((time.time() - float(rec.get("created") or time.time())) / 60))+++def expired(rec: dict, now: float | None = None) -> str | None:+ now = now or time.time()+ if now - float(rec.get("created") or now) > SESSION_CAP_MIN * 60:+ return "session_cap"+ if now - float(rec.get("last_used") or now) > IDLE_S:+ return "idle"+ return None++# ── the registry ─────────────────────────────────────────────────────────────────────────────+# Where the records live. In this process by default, which is right for one gateway process (a+# self-hosted instance); a deployment that runs several installs one over its shared store, so+# the same session reads the same browser from every replica. `bump` increments the counters+# named in COUNTERS, appends to the lists named in LISTS and sets anything else.+COUNTERS = ("calls", "screenshots")+LISTS = ("blocked",)+++class LocalRegistry:+ def __init__(self):+ self._recs: dict[str, dict] = {}++ async def get(self, sid: str) -> dict | None:+ return self._recs.get(sid)++ async def create(self, sid: str, rec: dict) -> bool:+ """True iff this call made the record; False when one is there already."""+ if sid in self._recs:+ return False+ self._recs[sid] = rec+ return True-_SESSIONS: dict[str, Session] = {}+ async def bump(self, sid: str, **fields) -> None:+ rec = self._recs.get(sid)+ if rec is None:+ return+ for k, v in fields.items():+ if k in COUNTERS:+ rec[k] = int(rec.get(k) or 0) + int(v)+ elif k in LISTS:+ rec.setdefault(k, []).append(v)+ else:+ rec[k] = v++ async def delete(self, sid: str) -> bool:+ """True iff this call removed the record: the remover stops the browser and writes its row."""+ return self._recs.pop(sid, None) is not None++ async def all(self) -> list[dict]:+ return list(self._recs.values())++ async def lock(self, sid: str, ttl_s: int) -> bool:+ return True # one process: the caller's own lock serialises its opens++ async def unlock(self, sid: str) -> None:+ pass+++registry = LocalRegistry()+_SESSIONS: dict[str, Session] = {} # this process's attachments, by session_pw = None@@ -249,6 +308,15 @@ def sessions() -> dict[str, Session]:return _SESSIONS+def _record(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str], d: dict,+ reserved: float) -> dict:+ now = time.time()+ return {"sid": sid, "hid": hid, "org": org, "workspace": workspace, "allow": list(allow), "deny": list(deny),+ "vendor_id": str(d["id"]), "cdp_url": str(d["cdpUrl"]), "live_url": str(d.get("liveUrl") or ""),+ "created": now, "last_used": now, "calls": 0, "screenshots": 0, "blocked": [],+ "reserved": float(reserved)}++async def _connect(cdp_url: str):global _pwif connector is not None:@@ -276,22 +344,79 @@ async def _allowed(s: Session, url: str) -> str | None:return "a private or local address" if s.host_cache[host] else None-async def open_session(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str]) -> Session:- """A browser for this harness session: the vendor's, then Playwright over CDP, then a fresh- context that accepts no downloads, with every request of every page gated by _allowed."""+async def open_session(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str],+ reserved: float = 0.0) -> Session:+ """The session's browser, attached here: the recorded one when there is one, else a new one at+ the vendor, recorded for every process first. One opener at a time across processes: the+ others wait for its record. `opened` on the result says this call made the browser."""if not configured():raise BrowserRefused("not_configured", "The browser service is not set up on this deployment. Tell the person.")- live = [x for x in _SESSIONS.values() if not x.closed]- if sum(1 for x in live if x.org == org) >= ORG_SESSIONS:- raise BrowserRefused("org_busy", f"This account already has {ORG_SESSIONS} browsers open. Try again when one of them finishes.")- if len(live) >= MAX_SESSIONS:- raise BrowserRefused("busy", "Every browser is in use right now. Try again in a minute.")- s = Session(sid, hid, org, workspace, allow, deny)- d = await vendor_create(SESSION_CAP_MIN, {"harness": hid, "session": sid})- s.vendor_id, s.live_url = str(d["id"]), str(d.get("liveUrl") or "")+ rec = await registry.get(sid)+ locked = False+ if rec is None:+ for _ in range(60):+ if await registry.lock(sid, 30):+ locked = True+ break+ await asyncio.sleep(0.5)+ rec = await registry.get(sid)+ if rec is not None:+ break+ else:+ raise BrowserRefused("busy", "The browser is still being started. Try again in a moment.")+ opened = Falsetry:- s.browser = await _connect(str(d["cdpUrl"]))- s.context = await s.browser.new_context(accept_downloads=False, viewport={"width": 1280, "height": 800})+ if rec is None:+ live = await registry.all()+ if sum(1 for x in live if x.get("org") == org) >= ORG_SESSIONS:+ raise BrowserRefused("org_busy", f"This account already has {ORG_SESSIONS} browsers open. Try again when one of them finishes.")+ if len(live) >= MAX_SESSIONS:+ raise BrowserRefused("busy", "Every browser is in use right now. Try again in a minute.")+ d = await vendor_create(SESSION_CAP_MIN, {"harness": hid, "session": sid})+ rec = _record(sid, hid, org, workspace, allow, deny, d, reserved)+ if await registry.create(sid, rec):+ opened = True+ else:+ # Made elsewhere between the lock and here (a lock the store could not keep): theirs stands.+ try:+ await vendor_stop(rec["vendor_id"])+ except Exception: # noqa: BLE001+ pass+ rec = await registry.get(sid)+ if rec is None:+ raise BrowserRefused("busy", "The browser could not be started. Try again.")+ finally:+ if locked:+ await registry.unlock(sid)+ try:+ s = await attach(rec)+ except Exception:+ if opened: # a browser nobody can reach: not left for the reaper+ await registry.delete(sid)+ try:+ await vendor_stop(rec["vendor_id"])+ except Exception: # noqa: BLE001+ pass+ raise+ s.opened = opened+ return s+++async def attach(rec: dict) -> Session:+ """This process's attachment to the recorded browser, made on first use and kept. Every process+ uses the browser's own default context and its first tab, so the page is the same page from+ every replica; the request gate is installed per attachment and reads the record's lists."""+ sid = str(rec["sid"])+ s = _SESSIONS.get(sid)+ if s is not None and not s.closed and s.vendor_id == str(rec.get("vendor_id") or ""):+ return s+ if s is not None:+ await detach(s) # the record names another browser: this one is gone+ s = Session(rec)+ s.browser = await _connect(s.cdp_url)+ try:+ contexts = list(getattr(s.browser, "contexts", None) or [])+ s.context = contexts[0] if contexts else await s.browser.new_context(accept_downloads=False, viewport={"width": 1280, "height": 800})async def gate(route, request):why = await _allowed(s, request.url)@@ -299,49 +424,76 @@ async def open_session(sid: str, hid: str, org: str, workspace: str, allow: listhost = urllib.parse.urlsplit(request.url).hostname or request.url[:60]if host not in s.blocked:s.blocked.append(host)+ await registry.bump(sid, blocked=host)await route.abort("blockedbyclient")else:await route.continue_()await s.context.route("**/*", gate)- s.page = await s.context.new_page()+ pages = list(getattr(s.context, "pages", None) or [])+ s.page = pages[0] if pages else await s.context.new_page()s.page.set_default_timeout(30000)except Exception:- await close_session_browser(s)+ await detach(s)raise_SESSIONS[sid] = sreturn s-async def close_session_browser(s: Session) -> dict:- """Stop everything and read the vendor's figures. Every step is best effort: a browser that- would not close must not keep its minutes from being metered."""+async def detach(s: Session) -> None:+ """Drop this process's attachment; the browser itself stays as it is (a connected browser's+ close disconnects it and closes only the contexts this attachment made)."""s.closed = True- _SESSIONS.pop(s.sid, None)- for closer in (getattr(s.context, "close", None), getattr(s.browser, "close", None)):- if closer:- try:- await asyncio.wait_for(closer(), 10)- except Exception: # noqa: BLE001- pass+ if _SESSIONS.get(s.sid) is s:+ _SESSIONS.pop(s.sid, None)+ closer = getattr(s.browser, "close", None)+ if closer:+ try:+ await asyncio.wait_for(closer(), 10)+ except Exception: # noqa: BLE001+ pass+++async def close_session_browser(rec: dict, s: Session | None) -> dict:+ """Stop the recorded browser and read the vendor's figures, dropping this process's attachment+ when it has one. Every step is best effort: a browser that would not close must not keep its+ minutes from being metered."""+ if s is not None:+ s.closed = True+ if _SESSIONS.get(s.sid) is s:+ _SESSIONS.pop(s.sid, None)+ for closer in (getattr(s.context, "close", None), getattr(s.browser, "close", None)):+ if closer:+ try:+ await asyncio.wait_for(closer(), 10)+ except Exception: # noqa: BLE001+ passfigures: dict = {}- if s.vendor_id:+ if rec.get("vendor_id"):try:- figures = await vendor_stop(s.vendor_id)+ figures = await vendor_stop(str(rec["vendor_id"]))except Exception: # noqa: BLE001figures = {}usd = vendor_cost(figures)source = "vendor"if usd is None:- usd, source = round(s.minutes * PRICES["browser.minute"], 6), "table"- return {"minutes": s.minutes, "usd": usd, "usd_source": source, "calls": s.calls,- "screenshots": s.screenshots, "blocked": s.blocked[:20],+ usd, source = round(minutes(rec) * PRICES["browser.minute"], 6), "table"+ return {"minutes": minutes(rec), "usd": usd, "usd_source": source, "calls": int(rec.get("calls") or 0),+ "screenshots": int(rec.get("screenshots") or 0), "blocked": list(rec.get("blocked") or [])[:20],"proxy_mb": figures.get("proxyUsedMb") or 0}-def expired_sessions(now: float | None = None) -> list[tuple[Session, str]]:+async def expired_sessions(now: float | None = None) -> list[tuple[dict, str]]:+ """Every recorded browser past its cap or idle, from any process."""now = now or time.time()- return [(s, why) for s in list(_SESSIONS.values()) if (why := s.expired(now))]+ return [(rec, why) for rec in await registry.all() if (why := expired(rec, now))]+++async def sweep_attachments() -> None:+ """Drop the attachments whose browser was stopped from another process."""+ for s in list(_SESSIONS.values()):+ if await registry.get(s.sid) is None:+ await detach(s)# ── the tools ────────────────────────────────────────────────────────────────────────────────@@ -481,8 +633,7 @@ async def _settled(s: Session) -> None:async def call(s: Session, name: str, args: dict):"""Run one tool on this session. Returns text, or ("image", png bytes, caption) for ascreenshot the caller stores. Raises BrowserToolError with a sentence the agent can act on."""- s.calls += 1- s.last_used = time.time()+ await registry.bump(s.sid, last_used=time.time(), calls=1)page = s.pageif name == "navigate":url = str(args.get("url") or "").strip()@@ -564,7 +715,7 @@ async def call(s: Session, name: str, args: dict):png = await page.screenshot(type="png", full_page=bool(args.get("full_page")))except Exception as e: # noqa: BLE001raise BrowserToolError(f"The screenshot failed: {str(e).splitlines()[0][:160]}") from None- s.screenshots += 1+ await registry.bump(s.sid, screenshots=1)return ("image", png, f"Screenshot of {await _where(s)}")if name == "back":try:diff --git a/gateway/tests/test_browser.py b/gateway/tests/test_browser.pyindex 85a81949..3318f578 100644--- a/gateway/tests/test_browser.py+++ b/gateway/tests/test_browser.py@@ -97,7 +97,7 @@ class Vendor:body = json.loads(r.content)self.created.append(body)bid = f"bu_{len(self.created)}"- return httpx.Response(201, json={"id": bid, "cdpUrl": CDP, "liveUrl": "https://live.example/x",+ return httpx.Response(201, json={"id": bid, "cdpUrl": f"{CDP}/{bid}", "liveUrl": "https://live.example/x","status": "active", "timeoutAt": "2026-09-24T22:00:00Z"})if r.url.path.startswith("/api/v4/browsers/") and r.method == "PATCH":bid = r.url.path.rsplit("/", 1)[1]@@ -276,6 +276,12 @@ browsers: list[Browser] = []async def _connect(cdp):+ """The vendor's one browser at that address: a second connection (another replica) reaches the+ same contexts and pages, and a disconnect leaves them as they are."""+ for b in browsers:+ if b.cdp == cdp:+ b.closed = False+ return bb = Browser(cdp)browsers.append(b)return b@@ -304,6 +310,9 @@ def world(monkeypatch):for s in list(browser_plane.sessions().values()):s.closed = Truebrowser_plane.sessions().clear()+ browser_plane.registry = browser_plane.LocalRegistry()+ gw._browser_open_locks.clear()+ gw._plug_trace_handles.clear()yield reg, ven, postedasyncio.run(rc.aclose())@@ -417,7 +426,7 @@ def test_a_turn_browses_and_the_session_is_priced_metered_and_stopped(client, woassert text.startswith("Opened https://example.com/ (Example Domain)") and 'e1 link "More information..." href=https://www.iana.org/domains/example' in textassert ven.created == [{"timeout": 20, "proxyCountryCode": None, "solveCaptchas": False, "enableRecording": False,"metadata": {"harness": hid, "session": sid}}]- assert browsers[-1].cdp == CDP and browsers[-1].contexts[0].kw == {"accept_downloads": False, "viewport": {"width": 1280, "height": 800}}+ assert browsers[-1].cdp == f"{CDP}/bu_1" and browsers[-1].contexts[0].kw == {"accept_downloads": False, "viewport": {"width": 1280, "height": 800}}assert _call(client, tok, "get_url")["content"][0]["text"] == "https://example.com/ (Example Domain)"snap = _call(client, tok, "snapshot")["content"][0]["text"]@@ -558,15 +567,15 @@ def test_caps_and_the_vendor_saying_no(client, world, monkeypatch):assert _rows(hid)[-1]["error"] == "timeout"monkeypatch.setattr(browser_plane, "CALL_CAP_S", 60.0)# idle and the session cap are found by the reaper, and each stop is in the trail- s = browser_plane.sessions()[sid]- s.last_used -= browser_plane.IDLE_S + 1- assert [(x.sid, why) for x, why in browser_plane.expired_sessions()] == [(sid, "idle")]+ rec = asyncio.run(browser_plane.registry.get(sid))+ rec["last_used"] -= browser_plane.IDLE_S + 1+ assert [(x["sid"], why) for x, why in asyncio.run(browser_plane.expired_sessions())] == [(sid, "idle")]asyncio.run(gw._browser_close(sid, "idle"))assert ven.stopped == ["bu_1"] and json.loads(_rows(hid)[-1]["detail"])["reason"] == "idle"assert _call(client, tok, "navigate", url="https://example.com/")["isError"] is False- s = browser_plane.sessions()[sid]- s.created -= browser_plane.SESSION_CAP_MIN * 60 + 1- assert [why for _, why in browser_plane.expired_sessions()] == ["session_cap"]+ rec = asyncio.run(browser_plane.registry.get(sid))+ rec["created"] -= browser_plane.SESSION_CAP_MIN * 60 + 1+ assert [why for _, why in asyncio.run(browser_plane.expired_sessions())] == ["session_cap"]asyncio.run(gw._browser_close(sid, "session_cap"))assert ven.stopped == ["bu_1", "bu_2"] and json.loads(_rows(hid)[-1]["detail"])["minutes"] == 21@@ -730,3 +739,93 @@ def test_two_first_calls_at_once_open_one_browser(client, world, monkeypatch):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+++def test_a_call_that_lands_on_another_replica_reaches_the_same_browser(client, world):+ """The sandbox's tool calls are load-balanced over every gateway replica on the hosted service.+ The record of a session's browser is one for all of them; a replica that has never seen the+ session attaches to the recorded browser and finds the page the agent opened, instead of+ opening its own (four browsers for one turn on 2026-09-25, the agent's screenshot of+ about:blank among them). A self-hosted instance is one process, and the same code runs it."""+ reg, ven, posted = world+ reg.record = _record()+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ assert _call(client, tok, "navigate", url="example.com")["isError"] is False+ first = browser_plane.sessions()[sid]+ # another replica: no attachment, no open lock, the same records+ browser_plane.sessions().clear()+ gw._browser_open_locks.clear()+ out = _call(client, tok, "get_url")+ assert out["content"][0]["text"] == "https://example.com/ (Example Domain)", out # the page the first replica opened+ assert len(ven.created) == 1 and len(browsers) == 1 # one browser at the vendor+ second = browser_plane.sessions()[sid]+ assert second is not first and second.vendor_id == first.vendor_id == "bu_1"+ assert second.context is first.context and second.page is first.page # the browser's own context and tab+ rec = asyncio.run(browser_plane.registry.get(sid))+ assert rec["calls"] == 2 and rec["vendor_id"] == "bu_1" # the counters are the record's+ opens = [r for r in _rows(hid) if r["tool"] == "open"]+ assert len(opens) == 1+ # the lists changed on the workspace: the attachment and the record both follow+ reg.record = _record(deny=["example.com"])+ out = _call(client, tok, "navigate", url="https://example.com/")+ assert out["isError"] and "not allowed to visit" in out["content"][0]["text"], out+ assert asyncio.run(browser_plane.registry.get(sid))["deny"] == ["example.com"]+++def test_the_replica_that_removes_the_record_stops_the_browser_and_writes_its_row(client, world):+ """A stop can come from any replica (the turn's owner at its end, any reaper at idle or the+ cap). Whoever removes the record stops the browser at the vendor and writes the session row,+ once; a replica that finds the record gone only drops its attachment and writes nothing."""+ reg, ven, posted = world+ reg.record = _record()+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ assert _call(client, tok, "navigate", url="example.com")["isError"] is False+ mine = browser_plane.sessions()[sid]+ # another replica's reaper found it idle and stopped it (its record went with it)+ rec = asyncio.run(browser_plane.registry.get(sid))+ assert asyncio.run(browser_plane.registry.delete(sid)) is True+ asyncio.run(browser_plane.close_session_browser(rec, None))+ assert ven.stopped == ["bu_1"]+ # this replica's turn end: nothing to stop, nothing to write, the attachment goes+ before = len(_rows(hid))+ asyncio.run(gw._browser_close(sid, "turn_end"))+ assert len(_rows(hid)) == before and mine.closed and sid not in browser_plane.sessions()+ assert ven.stopped == ["bu_1"]+ # the reaper's sweep does the same for an attachment whose record is gone+ assert _call(client, tok, "navigate", url="example.com")["isError"] is False # a new browser, recorded+ assert len(ven.created) == 2+ assert asyncio.run(browser_plane.registry.delete(sid)) is True+ asyncio.run(browser_plane.sweep_attachments())+ assert sid not in browser_plane.sessions()+ # no record, no row: the session rows on the harness are the one the closer wrote+ assert [r for r in _rows(hid) if r["tool"] == "session"] == []+++def test_a_row_served_off_the_owning_replica_still_lands_in_the_trace(client, world):+ """The trace is written by the process running the turn. A plug call served without that+ handle (another replica on the hosted service; here, a reaper's stop after the turn) goes into+ the same trace under the session's own prefix, which the session vertex names; the hosted trace+ held 4 of a turn's 16 rows before this (2026-09-25)."""+ reg, ven, posted = world+ reg.record = _record()+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ prefix = f"{ORG}/000_{sid}"+ asyncio.run(gw._vg_upsert("HarnessSession", sid, {"trace_blob": prefix}))+ assert sid not in gw._session_trace # not the owner of any turn here+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ assert _call(client, tok, "navigate", url="example.com")["isError"] is False+ chunks = asyncio.run(gw._blob_list_all(f"{prefix}/events/", kb=gw.TRACE_KB))+ events = []+ for c in sorted(it["file_id"] for it in chunks):+ body = asyncio.run(gw._blob_get(c, kb=gw.TRACE_KB)) or b""+ events += [json.loads(line) for line in body.decode().splitlines() if line.strip()]+ assert [(e["type"], e["tool"], e["outcome"]) for e in events] == [("plug", "open", "ok"), ("plug", "navigate", "ok")]+ assert all(gw._TRACE_NONCE in it["file_id"] for it in chunks) # this process's chunks, unique beside the owner'sdiff --git a/gateway/tests/test_plugs_local.py b/gateway/tests/test_plugs_local.pyindex 2f6e995d..4b19136f 100644--- a/gateway/tests/test_plugs_local.py+++ b/gateway/tests/test_plugs_local.py@@ -49,6 +49,9 @@ def world(monkeypatch):for s in list(browser_plane.sessions().values()):s.closed = Truebrowser_plane.sessions().clear()+ browser_plane.registry = browser_plane.LocalRegistry()+ gw._browser_open_locks.clear()+ gw._plug_trace_handles.clear()gw._plug_fields_cache.clear()yield ven, posted