The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(computer-use): diagnose empty window discovery; fail fast on dead-daemon CLI fallback
Teknium95aa709606fe
diff --git a/tests/tools/test_computer_use_empty_discovery_diagnosis.py b/tests/tools/test_computer_use_empty_discovery_diagnosis.pynew file mode 100644index 00000000000..0c00b44ae77--- /dev/null+++ b/tests/tools/test_computer_use_empty_discovery_diagnosis.py@@ -0,0 +1,121 @@+"""Diagnosability of empty window discovery + CLI-fallback fail-fast.++Live-QA findings (Aug 2026, locked KDE desktop):+1. capture() returned a bare ``capture mode=ax 0x0`` with zero hint while+ the desktop was locked — undiagnosable for the model AND the user.+2. `_call_tool_via_cli` retried 4x with ~3.5s of sleeps on "daemon is not+ running", a permanent condition for that invocation.+"""+from typing import Any, Dict++import pytest++from tools.computer_use import cua_backend as cb+++# ── _empty_discovery_reason ─────────────────────────────────────────────+++def test_locked_session_reason_names_the_lock(monkeypatch):+ monkeypatch.setattr(cb, "_linux_session_locked", lambda: True)+ reason = cb._empty_discovery_reason()+ assert "LOCKED" in reason+ assert "unlock" in reason.lower()+++def test_no_display_reason(monkeypatch):+ monkeypatch.setattr(cb, "_linux_session_locked", lambda: False)+ monkeypatch.setattr(cb.sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ reason = cb._empty_discovery_reason()+ assert "DISPLAY" in reason+++def test_unknown_reason_points_at_doctor(monkeypatch):+ monkeypatch.setattr(cb, "_linux_session_locked", lambda: None)+ monkeypatch.setenv("DISPLAY", ":0")+ reason = cb._empty_discovery_reason()+ assert "doctor" in reason+++def test_locked_probe_fails_safe(monkeypatch):+ def _boom(*a, **kw):+ raise OSError("no loginctl")+ monkeypatch.setattr(cb.subprocess, "run", _boom)+ assert cb._linux_session_locked() in (None, False) if cb.sys.platform != "linux" else cb._linux_session_locked() is None+++def test_empty_capture_carries_reason(monkeypatch):+ """capture() with zero discovered windows must explain itself."""+ backend = object.__new__(cb.CuaDriverBackend)+ backend._active_pid = None+ backend._active_window_id = None+ backend._last_app = None+ backend._last_target = None+ backend._snapshot_tokens = {}+ monkeypatch.setattr(backend, "_load_windows", lambda: [], raising=False)+ monkeypatch.setattr(cb, "_empty_discovery_reason",+ lambda: "the desktop session is LOCKED (test)")+ cap = backend.capture(mode="ax")+ assert cap.width == 0 and cap.height == 0+ assert "LOCKED" in cap.window_title+++# ── CLI fallback fail-fast on dead daemon ───────────────────────────────+++class _Proc:+ def __init__(self, stdout="", stderr=""):+ self.stdout = stdout+ self.stderr = stderr+ self.returncode = 0+++def _make_session():+ session = object.__new__(cb._CuaDriverSession)+ session._embedded_daemon = None+ return session+++def test_cli_fallback_fails_fast_on_daemon_not_running(monkeypatch):+ session = _make_session()+ calls = {"n": 0}+ sleeps = []++ def _fake_run(cmd, **kw):+ calls["n"] += 1+ return _Proc(stdout="Cua Driver daemon is not running on /x.sock.\nStart it first with: cua-driver serve")++ monkeypatch.setattr(cb, "resolve_cua_driver_cmd", lambda override=None: "cua-driver")+ import subprocess as _sp+ import time as _time+ monkeypatch.setattr(_sp, "run", _fake_run)+ monkeypatch.setattr(_time, "sleep", lambda s: sleeps.append(s))++ with pytest.raises(RuntimeError, match="daemon is not running"):+ session._call_tool_via_cli("list_windows", {}, 10.0)++ assert calls["n"] == 1, f"expected fail-fast, got {calls['n']} attempts"+ assert sleeps == [], f"expected no backoff sleeps, got {sleeps}"+++def test_cli_fallback_still_retries_transient_empty(monkeypatch):+ """Genuinely empty output (EAGAIN congestion) keeps the retry loop."""+ session = _make_session()+ calls = {"n": 0}++ def _fake_run(cmd, **kw):+ calls["n"] += 1+ if calls["n"] < 3:+ return _Proc(stdout="")+ return _Proc(stdout='{"windows": []}')++ monkeypatch.setattr(cb, "resolve_cua_driver_cmd", lambda override=None: "cua-driver")+ import subprocess as _sp+ import time as _time+ monkeypatch.setattr(_sp, "run", _fake_run)+ monkeypatch.setattr(_time, "sleep", lambda s: None)++ out = session._call_tool_via_cli("list_windows", {}, 10.0)+ assert calls["n"] == 3+ assert out.get("structuredContent") == {"windows": []}diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.pyindex 9801c4a900c..0f189d5c73d 100644--- a/tools/computer_use/cua_backend.py+++ b/tools/computer_use/cua_backend.py@@ -311,6 +311,58 @@ def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str,return env+def _linux_session_locked() -> Optional[bool]:+ """Best-effort: is the graphical session locked? (Linux only.)++ A locked KDE/GNOME session freezes app renderers and half-disables the+ AX tree, so window discovery legitimately returns nothing — but a bare+ empty result reads as a driver bug (live QA, Aug 2026: every capture+ came back 0x0 with no hint). True/False when loginctl answers, None+ when unavailable (non-Linux, no systemd-logind, probe failure).+ """+ if sys.platform != "linux":+ return None+ try:+ proc = subprocess.run(+ ["loginctl", "list-sessions", "--no-legend"],+ capture_output=True, text=True, timeout=2.0,+ )+ if proc.returncode != 0:+ return None+ any_seat = False+ for line in proc.stdout.splitlines():+ parts = line.split()+ if len(parts) < 2 or "seat" not in line:+ continue+ any_seat = True+ probe = subprocess.run(+ ["loginctl", "show-session", parts[0], "-p", "LockedHint"],+ capture_output=True, text=True, timeout=2.0,+ )+ if "LockedHint=no" in probe.stdout:+ return False+ return True if any_seat else None+ except Exception:+ return None+++def _empty_discovery_reason() -> str:+ """One-line diagnosis for 'window discovery found nothing'."""+ locked = _linux_session_locked()+ if locked is True:+ return (+ "the desktop session is LOCKED (loginctl LockedHint=yes) — "+ "unlock the screen; a locked compositor hides windows and "+ "freezes app renderers"+ )+ if sys.platform == "linux" and not os.environ.get("DISPLAY"):+ return "no DISPLAY is set — X11/XWayland is not reachable from this process"+ return (+ "window discovery returned no windows; run `hermes computer-use "+ "doctor` (display reachability, AX capability)"+ )++def _z_index_uninformative(windows: List[Dict[str, Any]]) -> bool:"""True when every window shares the same z_index (common on Linux/X11)."""if not windows:@@ -1684,6 +1736,19 @@ class _CuaDriverSession:out = (proc.stdout or "").strip()last_err = out[:200] or (proc.stderr or "")[:200]+ # "daemon is not running" is a PERMANENT condition for this+ # invocation (`cua-driver call` requires the machine-wide+ # daemon socket, which Linux installs typically never start —+ # Hermes talks to the direct `cua-driver mcp` runtime+ # instead). Retrying with backoff burns ~3.5s of sleeps per+ # fallback for an outcome that cannot change; fail fast so+ # callers surface a diagnosable error immediately.+ if "daemon is not running" in out or "daemon is not running" in (proc.stderr or ""):+ raise RuntimeError(+ f"cua-driver CLI fallback for {name} unavailable: the "+ "machine-wide cua-driver daemon is not running (the "+ "CLI transport requires it; the MCP runtime does not)."+ )start = min((i for i in (out.find("{"), out.find("[")) if i != -1),default=-1,@@ -2377,7 +2442,9 @@ class CuaDriverBackend(ComputerUseBackend):self._clear_active_target()raiseif not windows:- return self._failed_capture(mode)+ # Diagnose instead of returning a bare 0x0: the dominant+ # real-world cause on Linux is a locked desktop session.+ return self._failed_capture(mode, _empty_discovery_reason())# Filter by app name (case-insensitive substring) if requested.# When the filter matches nothing, surface that explicitly instead of