Skip to content

The agent that grows with you

fix(bot-screen): browser tools obey the lease, epoch-only fence, dropped viewer link keeps exclusion

teknium115c51a030773
diff --git a/hermes_cli/web_routers/display.py b/hermes_cli/web_routers/display.py
index 4d81e24abba..541be828eb7 100644
--- a/hermes_cli/web_routers/display.py
+++ b/hermes_cli/web_routers/display.py
@@ -26,6 +26,7 @@ router = APIRouter()
_READ_CHUNK = 64 * 1024
_CLOSE_CONTROL_TAKEN = 4000
+_CLEAN_CLOSE = frozenset({1000, 1001})
_CLOSE_DESKTOP_GONE = 4001
_CLOSE_BAD_TICKET = 4401
_CLOSE_NOT_ALLOWED = 4403
@@ -55,7 +56,11 @@ async def display_ws(ws: WebSocket) -> None:
if info is None:
await ws.close(code=_CLOSE_BAD_TICKET, reason="display ticket missing, expired or used")
return
+ await _bridge(ws, info)
+
+async def _bridge(ws: WebSocket, info: dict) -> None:
+ """Pump RFB bytes between the viewer socket and THIS profile's Xvnc, gated by the lease."""
from hermes_constants import hermes_home_key
from tools.bot_desktop import lease as _lease
from tools.bot_desktop.rfb_filter import RfbClientFilter
@@ -94,6 +99,8 @@ async def display_ws(ws: WebSocket) -> None:
rfb_filter = RfbClientFilter(lambda: _lease.viewer_may_send_input(viewer_id, profile_key=profile_home))
+ viewer_closed = asyncio.Event()
+
async def rfb_to_ws() -> None:
while True:
chunk = await reader.read(_READ_CHUNK)
@@ -105,6 +112,9 @@ async def display_ws(ws: WebSocket) -> None:
while True:
message = await ws.receive()
if message.get("type") == "websocket.disconnect":
+ # 1000/1001 = the viewer closed the window; anything else is a dropped link.
+ if message.get("code") in _CLEAN_CLOSE:
+ viewer_closed.set()
return
data = message.get("bytes")
if data is None:
@@ -136,8 +146,10 @@ async def display_ws(ws: WebSocket) -> None:
finally:
unsubscribe()
writer.close()
- # Closing the viewer window hands control back; a stale holder never pins the agent out.
- if _lease.viewer_may_send_input(viewer_id, profile_key=profile_home):
+ # Closing the viewer window hands control back. A DROPPED link (laptop lid, Wi-Fi, 1006)
+ # keeps the human's exclusion: they may be mid-login on that screen and the agent must not
+ # resume into it. The Desktop reconnects into the same lease, or the human hands back.
+ if viewer_closed.is_set() and _lease.viewer_may_send_input(viewer_id, profile_key=profile_home):
_lease.release(viewer_id, profile_key=profile_home)
try:
await ws.close()
diff --git a/tests/hermes_cli/test_display_ws_drop_keeps_lease.py b/tests/hermes_cli/test_display_ws_drop_keeps_lease.py
new file mode 100644
index 00000000000..e1ea23d7329
--- /dev/null
+++ b/tests/hermes_cli/test_display_ws_drop_keeps_lease.py
@@ -0,0 +1,62 @@
+"""A dropped viewer link (1006: lid closed, Wi-Fi) must NOT hand the screen back to the agent — the
+human may be mid-login on it. Only a clean close (1000/1001) releases."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import tempfile
+
+import pytest
+
+from hermes_cli.web_routers import display
+from tools.bot_desktop import lease
+
+
+class _Ws:
+ """Just enough of a Starlette WebSocket: one disconnect message with the given close code."""
+
+ def __init__(self, close_code: int):
+ self._code = close_code
+ self.closed = False
+
+ async def accept(self):
+ pass
+
+ async def receive(self):
+ await asyncio.sleep(0.05)
+ return {"type": "websocket.disconnect", "code": self._code}
+
+ async def send_bytes(self, data):
+ pass
+
+ async def close(self, code=1000, reason=""):
+ self.closed = True
+
+
+async def _bridge_once(close_code: int, home: str) -> lease.Lease:
+ sock_dir = os.path.join(home, "bot-desktop")
+ os.makedirs(sock_dir, exist_ok=True)
+ sock = os.path.join(sock_dir, "rfb.sock")
+
+ async def _xvnc(reader, writer): # a silent framebuffer
+ await asyncio.sleep(1)
+ writer.close()
+
+ server = await asyncio.start_unix_server(_xvnc, path=sock)
+ try:
+ info = {"hermes_home": home, "viewer_id": "desk-1"}
+ await display._bridge(_Ws(close_code), info)
+ finally:
+ server.close()
+ return lease.get(profile_key=home)
+
+
[email protected](("close_code", "human_keeps_control"), [(1006, True), (1000, False)])
+def test_only_a_clean_viewer_close_hands_the_screen_back(monkeypatch, close_code, human_keeps_control):
+ lease._reset_for_tests()
+ with tempfile.TemporaryDirectory() as home:
+ lease.acquire("desk-1", profile_key=home)
+ after = asyncio.run(_bridge_once(close_code, home))
+ lease._reset_for_tests()
+ assert (after.holder == lease.HUMAN) is human_keeps_control, after
diff --git a/tests/tools/test_bot_desktop_browser_fence.py b/tests/tools/test_bot_desktop_browser_fence.py
new file mode 100644
index 00000000000..f791ac2419f
--- /dev/null
+++ b/tests/tools/test_bot_desktop_browser_fence.py
@@ -0,0 +1,61 @@
+"""The bot's browser tools obey the screen lease: while a human holds the shared browser, nothing is
+dispatched, and a command whose run crossed a takeover loses its result."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from tools.bot_desktop import lease, runtime
+
+
[email protected](autouse=True)
+def _fresh(monkeypatch):
+ lease._reset_for_tests()
+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":37"})
+ yield
+ lease._reset_for_tests()
+
+
+def _wire(monkeypatch, commands):
+ from tools import browser_tool as browser
+ from tools import browser_tool_session as session
+
+ monkeypatch.delenv("AGENT_BROWSER_PROFILE", raising=False)
+ monkeypatch.setattr(browser, "_is_camofox_mode", lambda: False)
+ monkeypatch.setattr(browser, "_blocked_private_page_action", lambda *a: None)
+ monkeypatch.setattr(session, "_browser_command_preflight", lambda: {"browser_cmd": "agent-browser"})
+ monkeypatch.setattr(session, "_get_session_info", lambda *a: {"session_name": "review"})
+ monkeypatch.setattr(session._cloud, "_get_browser_engine", lambda: "chrome")
+ monkeypatch.setattr(session._cloud, "_is_headed_mode", lambda: True)
+
+ def spawn(*args):
+ commands.append(args[2])
+ return {"success": True, "data": {"secret": "WHAT-THE-HUMAN-TYPED"}}
+
+ monkeypatch.setattr(session, "_spawn_and_collect", spawn)
+ return browser, session
+
+
+def test_browser_click_is_fenced_while_human_controls_shared_browser(monkeypatch):
+ commands: list = []
+ browser, _ = _wire(monkeypatch, commands)
+ lease.acquire("human-viewer")
+ result = json.loads(browser.browser_click("e1", task_id="review"))
+ assert commands == [], f"human holds the lease, yet a browser command was dispatched: {commands}"
+ assert result.get("code") == "human_has_control"
+
+
+def test_browser_result_crossing_a_takeover_is_discarded(monkeypatch):
+ commands: list = []
+ browser, session = _wire(monkeypatch, commands)
+
+ def spawn_then_takeover(*args):
+ lease.acquire("human-viewer")
+ lease.release("human-viewer") # a full cycle, control is back — the frame is still theirs
+ return {"success": True, "data": {"secret": "WHAT-THE-HUMAN-TYPED"}}
+
+ monkeypatch.setattr(session, "_spawn_and_collect", spawn_then_takeover)
+ result = browser.browser_click("e1", task_id="review")
+ assert "WHAT-THE-HUMAN-TYPED" not in result
diff --git a/tests/tools/test_bot_desktop_lease.py b/tests/tools/test_bot_desktop_lease.py
index 7a3665eb6f7..aa8e7b83dce 100644
--- a/tests/tools/test_bot_desktop_lease.py
+++ b/tests/tools/test_bot_desktop_lease.py
@@ -94,7 +94,8 @@ def test_takeover_during_an_admitted_action_discards_its_result(monkeypatch):
monkeypatch.setattr(tool, "_get_backend", lambda session_id="": object())
def _dispatch_then_takeover(backend, action, args):
- lease.acquire("human") # flips while the driver call is in flight
+ lease.acquire("human") # a whole take-over / hand-back cycle inside the driver call:
+ lease.release("human") # control is back, but the frame is still the human's turn
return json.dumps({"ok": True, "action": action, "png_b64": "SECRET"})
monkeypatch.setattr(tool, "_dispatch", _dispatch_then_takeover)
diff --git a/tools/browser_tool.py b/tools/browser_tool.py
index 5a8c67b3abc..99af9a0a070 100644
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@ -819,7 +819,9 @@ def _json_with_fallback(response: Dict[str, Any], result: Dict[str, Any]) -> str
def _failed_response(result: Dict[str, Any], default_error: str) -> str:
- return _json_with_fallback(_err(result.get("error", default_error)), result)
+ # ``code`` = machine-readable refusal (human_has_control), same shape as computer_use's.
+ extra = {"code": result["code"]} if result.get("code") else {}
+ return _json_with_fallback(_err(result.get("error", default_error), **extra), result)
def _tool_response(result: Dict[str, Any], ok: Dict[str, Any], default_error: str) -> str:
diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.py
index 4b9b353b3e0..14fa7edceda 100644
--- a/tools/browser_tool_session.py
+++ b/tools/browser_tool_session.py
@@ -574,6 +574,36 @@ def _run_browser_command(
except Exception as e:
_bt.logger.warning("Failed to create browser session for task=%s: %s", task_id, e)
return {"success": False, "error": f"Failed to create browser session: {str(e)}"}
+ # The bot's LOCAL browser lives on its Bot Desktop screen, in the same profile a human who took
+ # over is typing into. While the human holds the lease every action AND read against it is
+ # refused (the page may show their credential); the fence brackets the whole run so a takeover
+ # mid-command also voids the result. Cloud / user-supplied CDP sessions are a different browser.
+ if _shares_bot_desktop_browser(session_info):
+ from tools.bot_desktop import lease as _bd_lease
+ try:
+ admitted = _bd_lease.assert_agent_may_act()
+ except _bd_lease.HumanHasControl as e:
+ return {"success": False, "error": str(e), "code": "human_has_control"}
+ result = _run_browser_command_unfenced(task_id, command, args, timeout, _engine_override, browser_cmd, session_info)
+ if _bd_lease.get().epoch != admitted.epoch:
+ return {"success": False, "code": "human_has_control",
+ "error": "A human took over the bot's screen while this browser command ran; its result was "
+ "discarded. Call computer_use action='wait_for_human' to block until they hand back."}
+ return result
+ return _run_browser_command_unfenced(task_id, command, args, timeout, _engine_override, browser_cmd, session_info)
+
+
+def _shares_bot_desktop_browser(session_info: Dict[str, Any]) -> bool:
+ """Local agent-browser session (no CDP url: the dispatcher runs it with ``--session``, i.e. on this
+ host's display) while this profile's Bot Desktop screen is running."""
+ if session_info.get("cdp_url"):
+ return False
+ from tools.bot_desktop import runtime as _bd_runtime
+ return bool(_bd_runtime.published_env().get("DISPLAY"))
+
+
+def _run_browser_command_unfenced(task_id: str, command: str, args: List[str], timeout: int,
+ _engine_override: Optional[str], browser_cmd, session_info: Dict[str, Any]) -> Dict[str, Any]:
# Cleanup stops the supervisor before closing the backend; keep it stopped.
if command != "close" and session_info.get("cdp_url"):
_cdp._ensure_cdp_supervisor(task_id)
diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.py
index c7d3c3e5050..4476de4b49c 100644
--- a/tools/computer_use/tool.py
+++ b/tools/computer_use/tool.py
@@ -286,10 +286,12 @@ def handle_computer_use(args: Dict[str, Any], **kwargs) -> Any:
except _bd_lease.HumanHasControl as e:
return _refused(e)
result = _dispatch(backend, action, args)
- if _bd_lease.get().epoch != admitted.epoch and _bd_lease.human_holds():
+ # Any lease transition during the run voids the result — including a full take-over /
+ # hand-back cycle that already finished: the frame still belongs to the human's turn.
+ if _bd_lease.get().epoch != admitted.epoch:
return _refused(_bd_lease.HumanHasControl(
- "A human took over this desktop while the action ran; its result was discarded. Call "
- "computer_use action='wait_for_human' to block until they hand control back."))
+ "A human took over this desktop while the action ran; its result was discarded. "
+ "Re-capture (or call computer_use action='wait_for_human' if they still hold control)."))
return result
except Exception as e:
logger.exception("computer_use %s failed", action)