The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(computer-use): keep Bot Screen backend alive through dispatch
Xipongc40e045ec74d
diff --git a/tests/tools/test_bot_desktop_lease.py b/tests/tools/test_bot_desktop_lease.pyindex f85a719718e..5023c5bf594 100644--- a/tests/tools/test_bot_desktop_lease.py+++ b/tests/tools/test_bot_desktop_lease.py@@ -22,8 +22,12 @@ _SETENC = b"\x02\x00\x00\x02" + b"\x00\x00\x00\x07" + b"\xff\xff\xff\x21" # Set@pytest.fixture(autouse=True)def _fresh_lease():+ from tools.computer_use import tool++ tool.reset_backend_for_tests()lease._reset_for_tests()yield+ tool.reset_backend_for_tests()lease._reset_for_tests()@@ -84,7 +88,7 @@ def test_takeover_during_an_admitted_action_discards_its_result(monkeypatch):their keystrokes captured by an action admitted before they did."""from tools.computer_use import tool- monkeypatch.setattr(tool, "_get_backend", lambda session_id="": object())+ monkeypatch.setattr(tool, "_new_backend", lambda mode: tool._NoopBackend())def _dispatch_then_takeover(backend, action, args, **_):lease.acquire("human") # a whole take-over / hand-back cycle inside the driver call:@@ -102,7 +106,7 @@ def test_takeover_handback_during_approval_does_not_start_the_device_op(monkeypanot only after. Do not patch _dispatch — a recording backend must never be called."""from tools.computer_use import tool- class Rec:+ class Rec(tool._NoopBackend):def __init__(self):self.calls = []@@ -111,7 +115,7 @@ def test_takeover_handback_during_approval_does_not_start_the_device_op(monkeypareturn json.dumps({"ok": True, "action": "click"})rec = Rec()- monkeypatch.setattr(tool, "_get_backend", lambda session_id="": rec)+ monkeypatch.setattr(tool, "_new_backend", lambda mode: rec)def _approval_cycles_the_lease(scope, args, session_id=""):lease.acquire("human")diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.pyindex 737a503f518..9b217f4b237 100644--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@ -269,7 +269,7 @@ class TestCaptureResponse:def focus_app(self, app, raise_window=False): ...cu_tool.reset_backend_for_tests()- with patch.object(cu_tool, "_get_backend", return_value=FakeBackend()), \+ with patch.object(cu_tool, "_new_backend", return_value=FakeBackend()), \patch.object(cu_tool, "_should_route_through_aux_vision",return_value=False):out = cu_tool.handle_computer_use({"action": "capture", "mode": "vision"})@@ -309,7 +309,7 @@ class TestCaptureResponse:def focus_app(self, app, raise_window=False): ...cu_tool.reset_backend_for_tests()- with patch.object(cu_tool, "_get_backend", return_value=FakeBackend()), \+ with patch.object(cu_tool, "_new_backend", return_value=FakeBackend()), \patch.object(cu_tool, "_should_route_through_aux_vision",return_value=False):out = cu_tool.handle_computer_use({"action": "capture", "mode": "som"})@@ -358,7 +358,7 @@ class TestCaptureResponse:fake_backend = self._ax_backend_with(600)cu_tool.reset_backend_for_tests()- with patch.object(cu_tool, "_get_backend", return_value=fake_backend):+ with patch.object(cu_tool, "_new_backend", return_value=fake_backend):out = cu_tool.handle_computer_use({"action": "capture", "mode": "ax"})parsed = json.loads(out)@@ -379,7 +379,7 @@ class TestCaptureResponse:fake_backend = self._ax_backend_with(5000)cu_tool.reset_backend_for_tests()- with patch.object(cu_tool, "_get_backend", return_value=fake_backend):+ with patch.object(cu_tool, "_new_backend", return_value=fake_backend):out = cu_tool.handle_computer_use({"action": "capture", "mode": "ax", "max_elements": 10_000})diff --git a/tests/tools/test_computer_use_backend_lifecycle.py b/tests/tools/test_computer_use_backend_lifecycle.pynew file mode 100644index 00000000000..b2536ea7dd6--- /dev/null+++ b/tests/tools/test_computer_use_backend_lifecycle.py@@ -0,0 +1,226 @@+"""Backend admission during Bot Screen rebind/release; extracted from #114565 for #108914."""++from __future__ import annotations++import contextvars+import json+import threading+from concurrent.futures import Future+from contextlib import contextmanager++import pytest++from hermes_constants import reset_hermes_home_override, set_hermes_home_override+from tools.bot_desktop import browser, lease, runtime as desktop+from tools.computer_use import tool as cu+from tools.computer_use_tool import registry+++@contextmanager+def _profile(home):+ token = set_hermes_home_override(str(home))+ try:+ yield+ finally:+ reset_hermes_home_override(token)+++def _spawn(fn, name):+ future = Future()+ context = contextvars.copy_context()++ def run():+ try:+ future.set_result(context.run(fn))+ except BaseException as exc:+ future.set_exception(exc)++ thread = threading.Thread(target=run, name=name, daemon=True)+ thread.start()+ return thread, future+++def _call():+ return json.loads(registry.dispatch("computer_use", {"action": "list_apps"}, session_id="shared"))+++def runtime(tmp_path, monkeypatch):+ homes = [tmp_path / "a", tmp_path / "b"]+ for home, display in zip(homes, (":37", ":38")):+ (home / "bot-desktop").mkdir(parents=True)+ (home / "bot-desktop" / "env").write_text(f"DISPLAY={display}\n", encoding="utf-8")+ (home / "config.yaml").write_text("computer_use:\n permission_mode: standard\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(homes[0]))+ # Fake the device boundary only. Profile env publication, spawn identity,+ # config, backend caches, dispatch and persisted human leases stay real.+ monkeypatch.setattr(desktop, "_launcher_pid", lambda: 1)+ monkeypatch.setattr(browser, "executable", lambda: None)+ created = []++ class Backend(cu._NoopBackend):+ def __init__(self, mode):+ super().__init__()+ self.stopped = False+ self.count = 0+ self.before_action = lambda: None+ created.append(self)++ def stop(self):+ self.stopped = True++ def list_apps(self):+ assert not self.stopped, "dispatch used a retired backend"+ self.count += 1+ self.before_action()+ assert not self.stopped, "teardown ran during dispatch"+ return [{"name": str(created.index(self))}]++ cu.reset_backend_for_tests()+ monkeypatch.setattr(cu, "_new_backend", Backend)+ yield homes, created+ cu.reset_backend_for_tests()+ lease._reset_for_tests()++[email protected]("pause_at", ["after_lookup", "before_acquire"])[email protected]("change", ["display", "mode", "release", "queued_display"])+def test_dispatch_rechecks_admission(runtime, monkeypatch, pause_at, change):+ homes, created = runtime+ paused, resume = threading.Event(), threading.Event()+ real_get = cu._get_backend+ old = real_get("shared")+ old_lock = cu._backend_call_locks["shared"]++ def pause():+ if threading.current_thread().name == "waiting-call" and not paused.is_set():+ paused.set()+ assert resume.wait(10), "test did not release the waiting call"++ def get(session_id=""):+ backend = real_get(session_id)+ if pause_at == "after_lookup":+ pause()+ return backend++ class PausingLock:+ def __enter__(self):+ pause()+ old_lock.acquire()+ return self++ def __exit__(self, *_):+ old_lock.release()++ monkeypatch.setattr(cu, "_get_backend", get)+ if pause_at == "before_acquire":+ cu._backend_call_locks["shared"] = PausingLock()+ worker, result = _spawn(_call, "waiting-call")+ try:+ assert paused.wait(10)+ if change == "release":+ assert cu.release_computer_use_session("shared")+ else:+ if change == "mode":+ (homes[0] / "config.yaml").write_text("computer_use:\n permission_mode: bounded\n", encoding="utf-8")+ else:+ (homes[0] / "bot-desktop" / "env").write_text("DISPLAY=:39\n", encoding="utf-8")+ if change != "queued_display":+ assert real_get("shared") is not old+ if change != "queued_display":+ assert old.stopped+ resume.set()+ value = result.result(timeout=10)+ assert "error" not in value, value+ assert old.count == 0+ assert sum(backend.count for backend in created) == 1+ assert value["apps"] == [{"name": str(created.index(real_get("shared")))}]+ finally:+ resume.set()+ worker.join(timeout=10)+ assert not worker.is_alive()++[email protected]("fail_action", [False, True])+def test_release_waits_without_blocking_another_profile_or_replaying(runtime, monkeypatch, fail_action):+ homes, created = runtime+ action_entered, finish_action, stop_attempted = (threading.Event() for _ in range(3))+ threads = []+ with _profile(homes[0]):+ old = cu._get_backend("shared")++ def action():+ action_entered.set()+ assert finish_action.wait(10)+ if fail_action:+ raise RuntimeError("action outcome is unknown; do not replay")++ old.before_action = action+ real_stop = cu._stop_backend++ def stop(backend, lock, on_error):+ if backend is old:+ stop_attempted.set()+ return real_stop(backend, lock, on_error)++ monkeypatch.setattr(cu, "_stop_backend", stop)+ try:+ thread, result = _spawn(_call, "admitted-call")+ threads.append(thread)+ assert action_entered.wait(10)+ thread, released = _spawn(lambda: cu.release_computer_use_session("shared"), "release")+ threads.append(thread)+ assert stop_attempted.wait(10)+ assert not old.stopped and not released.done()+ with _profile(homes[1]):+ thread, other = _spawn(_call, "other-profile")+ threads.append(thread)+ assert "error" not in other.result(timeout=10)+ assert not old.stopped+ finish_action.set()+ value = result.result(timeout=10)+ assert ("error" in value) is fail_action+ assert released.result(timeout=10) is True+ assert old.stopped and old.count == 1+ # A -> B -> A: the released profile gets its own fresh backend.+ assert "error" not in _call()+ assert cu._get_backend("shared") is not old+ with _profile(homes[1]):+ assert not cu._get_backend("shared").stopped+ finally:+ finish_action.set()+ for thread in threads:+ thread.join(timeout=10)+ assert not thread.is_alive()++[email protected]("hand_back", [False, True])+def test_backend_retry_preserves_the_original_human_lease_epoch(runtime, monkeypatch, hand_back):+ _, created = runtime+ paused, resume = threading.Event(), threading.Event()+ real_get = cu._get_backend+ old = real_get("shared")++ def get(session_id=""):+ backend = real_get(session_id)+ if threading.current_thread().name == "waiting-call" and not paused.is_set():+ paused.set()+ assert resume.wait(10)+ return backend++ monkeypatch.setattr(cu, "_get_backend", get)+ worker, result = _spawn(_call, "waiting-call")+ try:+ assert paused.wait(10)+ assert cu.release_computer_use_session("shared")+ assert old.stopped+ lease.acquire("human")+ if hand_back:+ lease.release("human")+ resume.set()+ assert result.result(timeout=10)["code"] == "human_has_control"+ assert all(backend.count == 0 for backend in created)+ finally:+ resume.set()+ worker.join(timeout=10)+ assert not worker.is_alive()diff --git a/tests/tools/test_computer_use_capture_fence.py b/tests/tools/test_computer_use_capture_fence.pyindex 65736e5ca12..2b1952f8cb4 100644--- a/tests/tools/test_computer_use_capture_fence.py+++ b/tests/tools/test_computer_use_capture_fence.py@@ -9,17 +9,20 @@ import jsonimport pytestfrom tools.bot_desktop import lease+from tools.computer_use import toolfrom tools.computer_use.backend import ActionResult, CaptureResult@pytest.fixture(autouse=True)def _fresh_lease():+ tool.reset_backend_for_tests()lease._reset_for_tests()yield+ tool.reset_backend_for_tests()lease._reset_for_tests()-class _TakeoverBackend:+class _TakeoverBackend(tool._NoopBackend):"""Driver whose capture returns while a take-over / hand-back cycle happened underneath it."""_last_target = None_last_app = None@@ -45,9 +48,7 @@ def _spy_sinks(monkeypatch, tool):@pytest.mark.parametrize("args", [{"action": "capture"}, {"action": "click", "coordinate": [1, 1], "capture_after": True}])def test_frame_captured_across_a_takeover_is_dropped_before_any_sink(monkeypatch, args):- from tools.computer_use import tool-- monkeypatch.setattr(tool, "_get_backend", lambda session_id="": _TakeoverBackend())+ monkeypatch.setattr(tool, "_new_backend", lambda mode: _TakeoverBackend())monkeypatch.setattr(tool, "_request_approval", lambda *a, **k: None)leaked = _spy_sinks(monkeypatch, tool)res = json.loads(tool.handle_computer_use(args))diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex b2ee1514e55..020bd5b9aa3 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -19,7 +19,7 @@ import uuidfrom collections import namedtuplefrom functools import partialfrom types import SimpleNamespace-from typing import Any, Callable, Dict, List, Optional, Tuple+from typing import Any, Callable, Dict, Iterator, List, Optional, Tuplefrom tools.computer_use.backend import ActionResult, CaptureResult, ComputerUseBackend, UIElement, image_dimensions_from_bytes@@ -227,6 +227,37 @@ def _get_backend(session_id: str = "") -> ComputerUseBackend:_, stale_lock = _detach_locked(sid) # stopped outside the cache lock; the loop re-reads the mode first_stop_backend(cached, stale_lock, lambda e: None)+def _backend_for_call(session_id: str = "") -> Iterator[ComputerUseBackend]:+ """Hold a live backend through dispatch, retrying admission but never an action.++ A display/mode change or release can retire a backend before lock lookup or+ while a caller waits. Revalidate AFTER acquiring its profile-scoped call+ lock; teardown needs that same lock. Never wait under the global cache lock.+ """+ from tools.computer_use.cua_backend import backend_display_stale, desktop_identity++ sid = _scoped_sid(session_id)+ while True:+ backend = _get_backend(session_id=session_id)+ with _backend_lock:+ if _backends.get(sid) is not backend:+ continue+ call_lock = _backend_call_locks[sid]+ with call_lock:+ with _backend_lock:+ if (_backends.get(sid) is not backend+ or _backend_call_locks.get(sid) is not call_lock):+ continue+ # A queued call can outlive a display/config change even when+ # no other caller has replaced the cached backend yet.+ if (_backend_permission_modes.get(sid) != _cua_permission_mode(str(session_id or ""))+ or backend_display_stale(_backend_displays.get(sid, ""), desktop_identity())):+ continue+ yield backend+ return++def release_computer_use_session(session_id: str) -> bool:"""Release one session-owned backend (lifecycle seam for hosts/plugins); idempotent, True iff one was released.Cache entries are removed BEFORE stopping so new lookups cannot retain the stale target/ref namespace. Approval@@ -316,16 +347,17 @@ def handle_computer_use(args: Dict[str, Any], **kwargs) -> Any:for scope in scopes:if (err := _request_approval(scope, args)) is not None:return err+ # Acquire separately so startup errors retain the install hint; the stack+ # releases the admitted call lock on every dispatch return or exception.+ call = contextlib.ExitStack()try:- backend = _get_backend(session_id=session_id)+ backend = call.enter_context(_backend_for_call(session_id))except Exception as e:return json.dumps({"error": f"computer_use backend unavailable: {e}","hint": "If the cua-driver binary is missing, run `hermes computer-use install`. ""If a Python dependency is missing, the error above shows the exact install command."})try:- with _backend_lock:- call_lock = _backend_call_locks.setdefault(session_id, threading.RLock())- with call_lock:+ with call:# Re-check under the dispatch lock: approval, backend start-up and lock waits above can take# seconds, and a human may have taken over meanwhile. A result produced after such a flip is# discarded too — it may picture what they typed.