Files
hermes-agent/tui_gateway/methods_browser.py
kshitijk4poor de5f56c92a refactor(deadline): one poll_until for check-until-deadline loops
Twenty loops across 17 files hand-wrote the same thing:

    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if condition(): return ...
        time.sleep(interval)

with small drifts between copies: some re-checked once after the loop,
some did not, one slept before its first check, and update_cmd_windows
kept a private _poll_until. A copy without the final check can miss a
condition that becomes true during the last sleep.

agent/deadline.py (already the home of clamp_timeout / run_bounded_*)
gains poll_until(predicate, timeout, interval): checks at once, cuts the
last sleep to the time left, checks again at the deadline, and returns
the predicate's last value so callers that wait for a pid / row /
identity get it back directly. timeout <= 0 is one check.

Converted: outbound_webhooks.flush, cron delivery wait and jobs flock,
host_attach channel wait, browser profile unlock, data-cleanup drain,
gateway dbus/bus waits, launchd fresh-pid and supervision waits,
supervised restart, gateway_migrate live-gateway wait, Windows
drain/absent waits, kanban init lock, local-runtime boot wait,
update_cmd_windows (private helper deleted), bot desktop start/stop
waits, TUI browser connect.

Left as is: loops whose body does more than check (progress callbacks,
interrupt handling, two distinct exits) and one site whose blind except
the health gate would reject once moved.

Behaviour changes, all small:
- loops that stopped at the deadline without re-checking now make one
  more check there;
- loops that already re-checked after a full last sleep now cut that
  sleep to the time left, so the check lands at the deadline (up to one
  interval sooner);
- a timeout <= 0 now means one check (some loops made none);
- the local-runtime boot wait checks before its first sleep instead of
  after it;
- _wait_for_user_dbus_socket also exports the user systemd env when the
  socket appears on that final check (before, that path returned True
  without it).

update_cmd_windows is imported by update_cmd on every OS, so the
fresh-source-install acceptance fixture (which keeps agent/ out of the
update path) now copies the stdlib-only agent/deadline.py too.

Tests: 4 pins for poll_until (two red against the classic
no-final-check variant), plus the existing suites for every touched
module.
2026-10-27 16:30:14 +05:30

176 lines
8.6 KiB
Python

"""Browser connect/disconnect helpers for the browser.* RPCs (CDP probing, no network I/O on
status). Bodies are rebound onto server.py's globals at install time (method_ctx.bind_module)."""
from __future__ import annotations
from .method_ctx import HandlerRegistry, bind_module
_registry = HandlerRegistry()
_CDP_SCHEMES = {"http", "https", "ws", "wss"}
def _resolve_browser_cdp_url() -> str:
"""Configured browser CDP override without network I/O (``/browser status`` must be fast;
``tools.browser_session_cdp.get_cdp_override`` HTTP-probes discovery URLs): the browser session's own
read (this profile's live connect, env, then the effective ``browser.cdp_url``) minus WS resolution; the
next browser session normalizes it."""
from tools.browser_session_cdp import get_cdp_override_raw
return get_cdp_override_raw()
def _is_default_local_cdp(parsed) -> bool:
"""Match the discovery-style local default; never the concrete WS form — a
``ws://127.0.0.1:9222/devtools/browser/<id>`` is connectable as-is and collapsing it to bare
``http://...:9222`` would break the connect."""
with contextlib.suppress(ValueError):
return (parsed.scheme in {"http", "ws"} and parsed.hostname in {"127.0.0.1", "localhost"}
and (parsed.port or 80) == 9222 and parsed.path in {"", "/", "/json", "/json/version"})
return False
def _cdp_http_reachable(parsed, timeout: float = 2.0) -> bool:
"""True when ``/json/version`` or ``/json`` on the CDP host answers 2xx."""
import urllib.request
scheme = {"ws": "http", "wss": "https"}.get(parsed.scheme, parsed.scheme)
root = f"{scheme}://{parsed.netloc}".rstrip("/")
for url in (f"{root}/json/version", f"{root}/json"):
with contextlib.suppress(Exception), urllib.request.urlopen(url, timeout=timeout) as resp:
if 200 <= getattr(resp, "status", 200) < 300:
return True
return False
def _connect_local_default(port: int, system: str, announce) -> str | None:
"""Discover (or launch) the default local debug browser → CDP URL, or None after announcing."""
from agent.deadline import poll_until
from hermes_cli.browser_connect import (
discover_local_cdp_url, find_free_debug_port, launch_chrome_debug, local_port_in_use,
manual_chrome_debug_command)
# Dual-stack discovery: when another app squats the IPv4 loopback on the debug port, a
# browser bound there comes up on [::1] only; an IPv4-only probe misses it AND hangs
# against squatters that accept TCP but never answer HTTP.
discovered = discover_local_cdp_url(port, timeout=2.0)
if discovered is not None:
announce(f"Chromium-family browser is already listening at {discovered}")
return discovered
launch_port = port
if local_port_in_use(port):
launch_port = find_free_debug_port(port)
announce(f"Port {port} is occupied by another application that isn't a CDP browser "
"(an IDE debugger or dev server may be using it) — launching a debug browser "
f"on port {launch_port} instead...")
else:
announce("Chromium-family browser isn't running with remote debugging — attempting to launch...")
launch = launch_chrome_debug(launch_port, system)
if launch.launched:
# Bounded wait: the whole connect must finish inside the client RPC timeout.
discovered = poll_until(lambda: discover_local_cdp_url(launch_port, timeout=1.0), 10.0, 0.5)
if discovered:
announce(f"Chromium-family browser launched and listening on port {launch_port}")
return discovered
if launch.hint:
announce(launch.hint, level="error")
command = manual_chrome_debug_command(launch_port, system)
hints = (
["Start a Chromium-family browser with remote debugging, then retry /browser connect:", command]
if command else [
"No supported Chromium-family browser executable was found in this environment.",
f"Install one or start a Chromium-family browser with --remote-debugging-port={launch_port}, then retry /browser connect."])
hints.append("Browser not connected — start a Chromium-family browser with remote debugging and retry /browser connect")
for line in hints:
announce(line, level="error")
return None
def _reap_profile_browsers() -> None:
"""Close the current profile's browsers only: the live connection is per profile, so other
profiles' sessions on a multiplexed gateway keep theirs."""
from hermes_constants import hermes_home_key
from tools.browser_session_lifecycle import cleanup_profile_browsers
cleanup_profile_browsers(hermes_home_key())
def _browser_connect(rid, params: dict) -> dict:
import platform
from hermes_cli.browser_connect import DEFAULT_BROWSER_CDP_URL
from tools.browser_session_cdp import set_live_cdp_override
from urllib.parse import urlparse
raw_url = params.get("url")
if raw_url is not None and not isinstance(raw_url, str):
return _err(rid, 4015, f"browser url must be a string, got {type(raw_url).__name__}")
url = (raw_url or "").strip() or DEFAULT_BROWSER_CDP_URL
sid, system, messages = params.get("session_id") or "", platform.system(), []
def announce(message: str, *, level: str = "info") -> None:
messages.append(message)
# Without a session id the TUI prints `messages` from the response (an event would double-render).
if sid:
_emit("browser.progress", sid, {"message": message, "level": level})
parsed = urlparse(url if "://" in url else f"http://{url}")
if parsed.scheme not in _CDP_SCHEMES:
return _err(rid, 4015, f"unsupported browser url: {url}")
if not parsed.hostname:
return _err(rid, 4015, f"missing host in browser url: {url}")
try:
port = parsed.port or (443 if parsed.scheme in {"https", "wss"} else 80)
except ValueError:
return _err(rid, 4015, f"invalid port in browser url: {url}")
# Normalize default-local to 127.0.0.1:9222 so comparisons + messaging match what we persist.
if _is_default_local_cdp(parsed):
url = DEFAULT_BROWSER_CDP_URL
parsed = urlparse(url)
port = parsed.port or 9222
try:
# Hosted ws[s]://.../devtools/browser/<id> endpoints don't serve the HTTP discovery path:
# check TCP reachability only and let the browser session handshake.
if parsed.scheme in {"ws", "wss"} and parsed.path.startswith("/devtools/browser/"):
import socket
try:
with socket.create_connection((parsed.hostname, port), timeout=2.0):
pass
except OSError as e:
return _err(rid, 5031, f"could not reach browser CDP at {url}: {e}")
elif _is_default_local_cdp(parsed):
discovered = _connect_local_default(port, system, announce)
if discovered is None:
return _ok(rid, {"connected": False, "url": url, "messages": messages})
# Adopt whatever loopback/port answered ([::1] and/or an alternate port when 9222 was squatted).
url = discovered
parsed = urlparse(url)
elif not _cdp_http_reachable(parsed):
return _err(rid, 5031, f"could not reach browser CDP at {url}")
# Concrete ``/devtools/browser/<id>`` endpoints stay as-is; discovery-style inputs collapse
# to ``scheme://host:port`` so ``_resolve_cdp_override`` can append ``/json/version``.
normalized = (parsed.geturl() if parsed.path.startswith("/devtools/browser/")
else parsed._replace(path="", params="", query="", fragment="").geturl())
# Reap BEFORE publishing this profile's endpoint (an in-flight tool call sees the old
# supervisor closed) and AFTER (the default task's cached supervisor drains against the new URL).
_reap_profile_browsers()
set_live_cdp_override(normalized)
_reap_profile_browsers()
except Exception as e:
return _err(rid, 5031, str(e))
return _ok(rid, {"connected": True, "url": normalized,
**({"messages": messages} if messages else {})})
def _browser_disconnect(rid) -> dict:
# Reap, drop this profile's override, reap again — same swap window as ``_browser_connect``.
from tools.browser_session_cdp import set_live_cdp_override
def reap() -> None:
with contextlib.suppress(Exception):
_reap_profile_browsers()
reap()
set_live_cdp_override(None)
reap()
return _ok(rid, {"connected": False})
def register(server) -> None:
"""Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
bind_module(globals(), server, skip=("_",))