Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions tests/tools/test_browser_orphan_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,3 +405,82 @@ def _spy_reaper():
assert reaper_called, (
"Reaper must run on exit even with no active sessions"
)


class TestReapOrphanedChromeProcesses:
"""Tests for _reap_orphaned_chrome_processes() — Windows orphan Chrome killer."""

@pytest.mark.skipif(os.name != "nt", reason="Windows-only test")
def test_no_chrome_processes_is_noop(self, monkeypatch):
"""When wmic finds no chrome.exe, return 0."""
import tools.browser_tool as bt

monkeypatch.setattr(bt, "_active_sessions", {})

fake_result = type("R", (), {"stdout": b"Node,CommandLine,ParentProcessId,ProcessId\n"})()
monkeypatch.setattr("subprocess.run", lambda *a, **kw: fake_result)
assert bt._reap_orphaned_chrome_processes() == 0

@pytest.mark.skipif(os.name != "nt", reason="Windows-only test")
def test_skips_when_active_sessions_exist(self, monkeypatch):
"""Must not kill anything when this process has active browser sessions."""
import tools.browser_tool as bt

monkeypatch.setattr(bt, "_active_sessions", {"some_task": {"session_name": "h_abc"}})
assert bt._reap_orphaned_chrome_processes() == 0

@pytest.mark.skipif(os.name != "nt", reason="Windows-only test")
def test_kills_orphaned_headless_chrome(self, monkeypatch):
"""Kill main headless Chrome processes using agent-browser-chrome user-data-dir."""
import tools.browser_tool as bt

monkeypatch.setattr(bt, "_active_sessions", {})

csv_lines = (
"Node,CommandLine,ParentProcessId,ProcessId\n"
'SKYNET,"C:\\\\chrome.exe --headless=new --user-data-dir=C:\\\\Temp\\\\agent-browser-chrome-abc123",100,200\n'
'SKYNET,"C:\\\\chrome.exe --type=renderer --user-data-dir=C:\\\\Temp\\\\agent-browser-chrome-abc123",200,201\n'
'SKYNET,"C:\\\\chrome.exe --headless=new --user-data-dir=C:\\\\Users\\\\chuckie\\\\Chrome\\\\User Data",300,301\n'
)
fake_result = type("R", (), {"stdout": csv_lines.encode()})()
monkeypatch.setattr("subprocess.run", lambda *a, **kw: fake_result)

killed_pids = []
monkeypatch.setattr(
"tools.process_registry.ProcessRegistry._terminate_host_pid",
lambda pid: killed_pids.append(pid),
)

assert bt._reap_orphaned_chrome_processes() == 1
assert killed_pids == [200]

@pytest.mark.skipif(os.name != "nt", reason="Windows-only test")
def test_ignores_non_agent_browser_chrome(self, monkeypatch):
"""Chrome with normal user-data-dir must not be touched."""
import tools.browser_tool as bt

monkeypatch.setattr(bt, "_active_sessions", {})

csv_lines = (
"Node,CommandLine,ParentProcessId,ProcessId\n"
'SKYNET,"C:\\\\chrome.exe --headless=new --user-data-dir=C:\\\\Users\\\\chuckie\\\\Chrome\\\\User Data",300,301\n'
)
fake_result = type("R", (), {"stdout": csv_lines.encode()})()
monkeypatch.setattr("subprocess.run", lambda *a, **kw: fake_result)

killed_pids = []
monkeypatch.setattr(
"tools.process_registry.ProcessRegistry._terminate_host_pid",
lambda pid: killed_pids.append(pid),
)

assert bt._reap_orphaned_chrome_processes() == 0
assert killed_pids == []

@pytest.mark.skipif(os.name == "nt", reason="POSIX-only test")
def test_noop_on_posix(self, monkeypatch):
"""On non-Windows, the function should be a no-op."""
import tools.browser_tool as bt

monkeypatch.setattr(bt, "_active_sessions", {})
assert bt._reap_orphaned_chrome_processes() == 0
95 changes: 95 additions & 0 deletions tools/browser_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,94 @@ def _write_owner_pid(socket_dir: str, session_name: str) -> None:
session_name, exc)


def _reap_orphaned_chrome_processes() -> int:
"""Kill orphaned headless Chrome processes from dead agent-browser daemons.

On Windows, when an agent-browser daemon exits (gateway restart, crash),
its Chromium child processes get reparented to Explorer.exe. The main
reaper ``_reap_orphaned_browser_sessions`` handles daemons that are
*still alive*, but cannot reach Chrome children whose daemon already
exited. This function catches those orphans by scanning for Chrome
processes whose ``--user-data-dir`` points at a stale
``agent-browser-chrome-*`` temp directory.

Safe to call from the cleanup thread or on startup.
"""
if os.name != "nt":
# On POSIX, process-tree SIGTERM cascades reliably; this is a
# Windows-specific reparenting problem.
return 0

try:
import subprocess, tempfile, re
from gateway.status import _pid_exists

# Only reap when there are NO active browser sessions in this
# process. If sessions exist, Chrome processes likely belong to
# them and should not be touched.
with _cleanup_lock:
if _active_sessions:
return 0

tmpdir = tempfile.gettempdir()
result = subprocess.run(
[
"wmic", "process",
"where", "name='chrome.exe'",
"get", "processid,parentprocessid,commandline",
"/format:csv",
],
capture_output=True, timeout=15,
creationflags=0x08000000, # CREATE_NO_WINDOW
)
stdout = result.stdout.decode("utf-8", errors="replace")

# Collect PIDs of main (non-child-type) Chrome processes that use
# an agent-browser-chrome user-data-dir.
udd_re = re.compile(
r'--user-data-dir="?([^"]*agent-browser-chrome-[^" ]+)')
main_pids: list[int] = []
for line in stdout.splitlines():
line = line.strip()
if not line or line.startswith("Node"):
continue
parts = line.split(",", 3)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is WMIC CSV output, but CommandLine is a quoted free-form field and may contain commas. Parse with csv.reader; otherwise a comma shifts parts[3] and silently prevents correct PID selection.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c78a324. WMIC output is now parsed with csv.reader in a pure selection helper, with a cross-platform test covering a quoted CommandLine field containing a comma.

if len(parts) < 4:
continue
try:
pid = int(parts[3])
cmdline = parts[1]
except (ValueError, IndexError):
continue
m = udd_re.search(cmdline)
if not m:
continue
# Only match main browser processes (have --headless, no --type)
if "--headless" in cmdline and "--type=" not in cmdline:
main_pids.append(pid)

if not main_pids:
return 0

reaped = 0
from tools.process_registry import ProcessRegistry
for pid in main_pids:
try:
ProcessRegistry._terminate_host_pid(pid)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ParentProcessId is requested but never used. With only this process's _active_sessions guard, a second Hermes process can own a live matching Chrome tree while this process has no sessions, and this tree-kill will terminate it. Positively verify the reparented/orphan relationship before killing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c78a324. Selection now uses the returned ParentProcessId and fails closed: a matching Chrome process is only reaped when its recorded parent is confirmed dead. Added a cross-platform test proving a live parent from a concurrent Hermes session is skipped.

reaped += 1
except (ProcessLookupError, PermissionError, OSError):
pass

if reaped:
logger.info(
"Reaped %d orphaned Chrome process tree(s) whose daemon "
"already exited (Windows reparenting workaround)", reaped)
return reaped
except Exception as exc:
logger.debug("Orphan Chrome reap skipped: %s", exc)
return 0


def _reap_orphaned_browser_sessions():
"""Scan for orphaned agent-browser daemon processes from previous runs.

Expand Down Expand Up @@ -1418,6 +1506,13 @@ def _browser_cleanup_thread_worker():
except Exception as e:
logger.warning("Orphan reap error: %s", e)

# Second pass: kill orphaned Chrome processes whose daemon already
# exited (Windows reparenting workaround — see _reap_orphaned_chrome_processes).
try:
_reap_orphaned_chrome_processes()
except Exception as e:
logger.warning("Orphan Chrome reap error: %s", e)

while _cleanup_running:
try:
_cleanup_inactive_browser_sessions()
Expand Down