The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(computer_use): bound the driver's accessibility-tree walk per capture
vgarlua85b6f9cdd4c
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 3776bf8f21d..10d081553f6 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2473,6 +2473,17 @@ DEFAULT_CONFIG = {# capture_after mode: som = screenshot + overlays; ax = elements only, no PNG (faster);# vision = pixels only."capture_after_mode": "som",+ # Bound cua-driver's accessibility-tree WALK on every capture (get_window_state max_elements).+ # _DEFAULT_MAX_ELEMENTS in tools/computer_use/tool.py caps the SURFACED element list at 100 and+ # spills the rest to a cache file, so an unbounded walk pays for nodes the model never sees:+ # measured on macOS (cua-driver 0.28.2, M-series) a 1,444-node Chrome window went 540 ms -> 83 ms+ # and a 456-node Finder window 6.9 s -> 0.6 s at 200, with the returned elements a prefix of the+ # unbounded walk. 0 = driver default (2,000 elements / depth 25) — the pre-fix behaviour.+ # ~400 keeps the full first 100 visible elements on a pathological tree, at ~1.4 s on Finder;+ # the walk's cost grows with the bound, so keep it in the low hundreds. This caps the nodes+ # COLLECTED, not the walk's wall clock: a target whose AX surface exceeds the driver's own 20 s+ # walk timeout still fails at every bound (measured; a depth bound does not help there either).+ "ax_max_elements": 200,# Disable cua-driver's cursor overlay, which can peg a core when idle (macOS redraw loop;# Linux/WSL2 idle spin). None = auto (off on macOS + headless/ WSL2 Linux, on elsewhere);# True = always disable; False = always enable.diff --git a/tests/tools/test_computer_use_ax_walk_bound.py b/tests/tools/test_computer_use_ax_walk_bound.pynew file mode 100644index 00000000000..dd87edd0e8d--- /dev/null+++ b/tests/tools/test_computer_use_ax_walk_bound.py@@ -0,0 +1,77 @@+"""Bound on the driver's accessibility-tree walk per capture (``computer_use.ax_max_elements``).++``_DEFAULT_MAX_ELEMENTS`` in ``tool.py`` caps the SURFACED element list; the walk that produces it was+unbounded, so a capture paid for every node in the target's tree before trimming. A bound is pure+latency: the bounded tree is a prefix of the unbounded one, so the elements the model sees are+unchanged. Disabled by 0 (driver default), tuned by config, and read through the real loader.+"""++from __future__ import annotations++from typing import Any, Dict, List, Optional++import pytest++from tools.computer_use import cua_backend+from tools.computer_use.cua_backend_capture import _CaptureMixin+++class _StubCapture(_CaptureMixin):+ """Capture-lane shell: enough state for ``_gws_args``, no driver, no session."""++ def __init__(self) -> None:+ self._active_pid: Optional[int] = 607+ self._active_window_id: Optional[int] = 382+ self._session_id: Optional[str] = None+ self._last_app = ""++ def _resolve_capture_windows(self, mode: str, app: Optional[str], pid: Optional[int],+ window_id: Optional[int]) -> List[Dict[str, Any]]:+ return [{"app_name": "Finder", "pid": 607, "window_id": 382, "title": "", "z_index": 1,+ "off_screen": False}]+++def _write_config(tmp_path, body: str) -> None:+ """A user config.yaml the backend readers reach through ``load_config`` (not a patched reader)."""+ (tmp_path / "config.yaml").write_text(body, encoding="utf-8")+++class TestAxWalkBound:++ def test_default_is_a_finite_bound(self):+ """No config line: the walk is bounded, not unbounded. The whole point of the fix."""+ assert cua_backend._DEFAULT_AX_MAX_ELEMENTS > 0+ assert cua_backend._cua_configured_ax_max_elements() == cua_backend._DEFAULT_AX_MAX_ELEMENTS++ def test_configured_value_reaches_the_driver_args(self, tmp_path, monkeypatch):+ """End to end through the loader the backend uses: config.yaml -> get_window_state args."""+ _write_config(tmp_path, "computer_use:\n ax_max_elements: 350\n")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ assert cua_backend._cua_configured_ax_max_elements() == 350+ assert _StubCapture()._gws_args()["max_elements"] == 350++ def test_zero_disables_the_bound(self, tmp_path, monkeypatch):+ """0 restores the driver default and must not leak a ``max_elements`` key into the payload."""+ _write_config(tmp_path, "computer_use:\n ax_max_elements: 0\n")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ assert cua_backend._cua_configured_ax_max_elements() == 0+ assert "max_elements" not in _StubCapture()._gws_args()++ def test_unusable_value_fails_to_the_default_not_to_unbounded(self, tmp_path, monkeypatch):+ """A junk config line is a latency regression, never a silent revert to walking everything."""+ _write_config(tmp_path, "computer_use:\n ax_max_elements: plenty\n")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ assert cua_backend._cua_configured_ax_max_elements() == cua_backend._DEFAULT_AX_MAX_ELEMENTS++ def test_negative_values_are_clamped(self, tmp_path, monkeypatch):+ _write_config(tmp_path, "computer_use:\n ax_max_elements: -5\n")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ assert cua_backend._cua_configured_ax_max_elements() == 0++ def test_bound_rides_alongside_the_target(self, tmp_path, monkeypatch):+ """The bound is an addition: pid/window_id addressing is untouched."""+ _write_config(tmp_path, "computer_use:\n ax_max_elements: 250\n")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ args = _StubCapture()._gws_args()+ assert args["pid"] == 607 and args["window_id"] == 382+ assert args["max_elements"] == 250diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.pyindex ff64fd8ea67..651922711ef 100644--- a/tools/computer_use/cua_backend.py+++ b/tools/computer_use/cua_backend.py@@ -77,6 +77,28 @@ def _cua_configured_permission_mode() -> str:raw = str(_computer_use_cfg().get("permission_mode", "standard") or "").strip().lower()return "bounded" if raw == "bounded" else "standard"+# ``computer_use.ax_max_elements``: bound on the DRIVER's accessibility-tree walk per capture. The+# visible-element cap in tool.py (_DEFAULT_MAX_ELEMENTS) trims the RESPONSE only, so without this an+# unbounded walk pays for nodes the model never sees; 0 disables the bound (driver default: 2,000+# elements / depth 25).+_DEFAULT_AX_MAX_ELEMENTS = 200++def _cua_configured_ax_max_elements() -> int:+ """Bound on ``get_window_state``'s AX walk; 0 = no bound (driver default). Unreadable config fails to+ the default, never to unbounded. Measured on macOS (cua-driver 0.28.2, M-series): a 1,444-node Chrome+ window 540 ms -> 83 ms and a 456-node Finder window 6.9 s -> 0.6 s at 200, on the CLI transport. The+ bounded result is a prefix of the unbounded walk, so the elements the model sees are unchanged. Raise+ it toward 400 to keep the full first 100 visible elements on a pathological tree (~1.4 s on Finder);+ cost grows with the bound, and a bound in the thousands buys nothing the response cap keeps. This+ bounds the nodes COLLECTED, not the walk's wall clock: a target whose accessibility surface exceeds the+ driver's own 20 s walk timeout still fails at every bound (and every depth bound), so a timeout error is+ never an argument for a smaller or larger value here."""+ raw = _computer_use_cfg().get("ax_max_elements", _DEFAULT_AX_MAX_ELEMENTS)+ try:+ return max(0, int(raw))+ except (TypeError, ValueError):+ return _DEFAULT_AX_MAX_ELEMENTS+def _manifest_is_mode_independent(path: str) -> bool:"""True when this manifest may accompany any permission mode: v1/v2 declare ``mode: bounded`` and abortstartup under an unrestricted runtime; v3 has no mode and is the ceiling the driver accepts alongside anydiff --git a/tools/computer_use/cua_backend_capture.py b/tools/computer_use/cua_backend_capture.pyindex b8877a86911..b027966d996 100644--- a/tools/computer_use/cua_backend_capture.py+++ b/tools/computer_use/cua_backend_capture.py@@ -5,6 +5,7 @@ log-based tests and operators see one backend logger."""from __future__ import annotationsimport base64+import contextlibimport loggingimport osimport re@@ -228,7 +229,23 @@ class _CaptureMixin:return self._match_windows_for_app(windows, app) or self._failed_capture(mode, _NO_APP_MATCH_MSG.format(app=app))def _gws_args(self) -> Dict[str, Any]:- return {"pid": self._active_pid, "window_id": self._active_window_id, "session": self._session_id}+ """``get_window_state`` args.++ ``max_elements`` bounds the DRIVER's accessibility walk, not just its response: tool.py caps the+ surfaced element window at ``_DEFAULT_MAX_ELEMENTS`` (100) and spills the rest to a cache file, so+ walking a 1,444-node Electron tree — or Finder's, whose AX surface is pathologically slow — buys+ latency and nothing else. The bounded tree is a prefix of the unbounded one, so the elements the+ model sees are unchanged. ``computer_use.ax_max_elements`` tunes it; 0 disables.+ """+ args: Dict[str, Any] = {"pid": self._active_pid, "window_id": self._active_window_id,+ "session": self._session_id}+ capped = 0+ with contextlib.suppress(Exception): # lazy import: cua_backend imports this module at import time+ from tools.computer_use import cua_backend as _cb+ capped = _cb._cua_configured_ax_max_elements()+ if capped:+ args["max_elements"] = capped+ return argsdef _capture_vision(self) -> Tuple[Optional[str], Optional[str], List[UIElement], str]:"""Pixels only, ``elements`` always empty: ``(png_b64, mime, [], window_title)``. Drivers advertising the