Skip to content

The agent that grows with you

test: consolidate tool consumers at process and SDK boundaries

ethernet925e93b56f8f
diff --git a/tests/tools/test_a2a_reason_roundtrip.py b/tests/tools/test_a2a_reason_roundtrip.py
index 8cb49b26e60..ad368448d29 100644
--- a/tests/tools/test_a2a_reason_roundtrip.py
+++ b/tests/tools/test_a2a_reason_roundtrip.py
@@ -11,8 +11,7 @@ from __future__ import annotations
import json
import subprocess
-import sys
-from pathlib import Path
+import os
import pytest
@@ -32,18 +31,6 @@ def _reply_file(home, envelope_id):
return bot_relay.relay_root(home) / bot_relay.REPLIES_DIR / f"{envelope_id}.json"
-def test_write_reply_persists_forwarded_reason(home):
- """A reason forwarded by the Desktop drain loop lands in the reply file."""
- envelope_id = "a" * 32
- bot_relay.write_reply(
- home,
- envelope_id,
- error="delivery turn failed: Error code: 429",
- reason=bfr.PROVIDER_RATE_LIMIT,
- )
- data = json.loads(_reply_file(home, envelope_id).read_text(encoding="utf-8"))
- assert data["reason"] == bfr.PROVIDER_RATE_LIMIT
-
def test_write_reply_classifies_when_reason_omitted(home):
"""Old senders that never forward a reason still get a classified code."""
@@ -59,28 +46,18 @@ def test_write_reply_classifies_when_reason_omitted(home):
def _run_waiter(home, envelope):
cmd = bot_relay.waiter_command(home, envelope)
- # Resolve a launchable bash (PATH may resolve the MSIX payload copy,
- # which WinError-5s outside its package context) and pass a complete
- # child env — same pattern as tests/pm/test_activate_scripts.py.
- import os
- import shutil
-
- bash = shutil.which("bash") or "bash"
- if sys.platform == "win32" and "windowsapps" in str(bash).lower():
- pf = os.environ.get("ProgramFiles", r"C:\Program Files")
- for rel in (("Git", "bin", "bash.exe"), ("Git", "usr", "bin", "bash.exe")):
- cand = Path(pf).joinpath(*rel) if isinstance(pf, str) else Path(pf, *rel)
- if cand.exists():
- bash = str(cand)
- break
+ from pm.shell import bash as resolve_bash
+
+ bash = resolve_bash()
+ assert bash, "PM must resolve a runnable shell for the waiter"
env = os.environ.copy()
- if sys.platform == "win32":
+ if os.name == "nt":
env.setdefault("SystemRoot", r"C:\Windows")
env.setdefault("ComSpec", r"C:\Windows\system32\cmd.exe")
env.setdefault("PATHEXT", ".COM;.EXE;.BAT;.CMD")
return subprocess.run(
[bash, "-c", cmd],
- capture_output=True, text=True, timeout=30, env=env,
+ capture_output=True, text=True, timeout=30, env=env, cwd=home,
)
@@ -89,7 +66,7 @@ def _envelope(home):
"profile": "scout",
"handle": "scout",
"connection_id": "cloud-1",
- "connection_label": "",
+ "connection_label": "hostile ' $(touch injected-by-label) ; label",
"title": "",
"description": "",
}
@@ -102,6 +79,7 @@ def _envelope(home):
)
[email protected]("posix", "windows")
def test_waiter_surfaces_reason_tag_to_sending_agent(home, monkeypatch):
"""The waiter's stdout — the sending agent's completion notification —
carries the typed reason so the agent can branch without parsing prose."""
@@ -116,6 +94,7 @@ def test_waiter_surfaces_reason_tag_to_sending_agent(home, monkeypatch):
proc = _run_waiter(home, env)
assert proc.returncode == 1
assert f"[reason: {bfr.PROVIDER_RATE_LIMIT}]" in proc.stdout
+ assert not (home / "injected-by-label").exists()
def test_waiter_healthy_reply_has_no_reason_tag(home, monkeypatch):
diff --git a/tests/tools/test_browser_chromium_autoinstall.py b/tests/tools/test_browser_chromium_autoinstall.py
deleted file mode 100644
index 063d4706172..00000000000
--- a/tests/tools/test_browser_chromium_autoinstall.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""Local cold starts provision Chromium through the pinned package manager."""
-import pytest
-
-from pm.package import InstallError
-from tools import browser_tool as bt
-from tools import browser_tool_install as bt_install
-
-
[email protected](autouse=True)
-def reset_state():
- bt._chromium_autoinstall_attempted = False
- yield
- bt._chromium_autoinstall_attempted = False
-
-
-def test_install_uses_pm_once_and_preserves_failure(monkeypatch):
- monkeypatch.setattr(bt_install, "_running_in_docker", lambda: False)
- monkeypatch.setattr("pm.lazy_installs_allowed", lambda: True)
- installed = False
- calls = []
-
- def ensure(name):
- nonlocal installed
- calls.append(name)
- installed = True
-
- monkeypatch.setattr("pm.ensure", ensure)
- monkeypatch.setattr(bt_install, "_chromium_installed", lambda: installed)
- assert bt_install._maybe_autoinstall_chromium()
- assert bt_install._maybe_autoinstall_chromium()
- assert calls == ["chromium"]
-
- bt._chromium_autoinstall_attempted = False
- installed = False
-
- def fail(name):
- raise InstallError(name, "download failed")
-
- monkeypatch.setattr("pm.ensure", fail)
- assert not bt_install._maybe_autoinstall_chromium()
-
-
[email protected](("docker", "allowed"), [(True, True), (False, False)])
-def test_install_policy_never_provisions(monkeypatch, docker, allowed):
- monkeypatch.setattr(bt_install, "_running_in_docker", lambda: docker)
- monkeypatch.setattr("pm.lazy_installs_allowed", lambda: allowed)
-
- def forbidden(*args, **kwargs):
- pytest.fail("blocked auto-install reached provisioning")
-
- monkeypatch.setattr("pm.ensure", forbidden)
- monkeypatch.setattr(bt_install, "_find_agent_browser", forbidden)
- assert not bt_install._maybe_autoinstall_chromium()
diff --git a/tests/tools/test_browser_chromium_check.py b/tests/tools/test_browser_chromium_check.py
deleted file mode 100644
index b235bb965dc..00000000000
--- a/tests/tools/test_browser_chromium_check.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""Tests for Chromium-presence detection in browser_tool.
-
-Regression guard for the "browser tool advertised but Chromium missing"
-class of bug — where ``agent-browser`` CLI is discoverable but no
-Chromium build is on disk, causing every browser_* tool call to hang
-for the full command timeout before surfacing a useless error.
-"""
-
-import os
-import shutil
-
-import pytest
-
-from tools import browser_tool as bt
-from tools import browser_tool_install as bt_install
-from tools import browser_tool_cloud as bt_cloud
-
-
[email protected](autouse=True)
-def _isolated_browser_store(monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "tools"))
-
-
-
-class TestChromiumInstalled:
- def test_shell_only_cache_does_not_satisfy_full_browser(self, monkeypatch, tmp_path):
- monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)
- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))
- (tmp_path / "chromium_headless_shell-1234").mkdir()
- assert bt_install._chromium_installed() is False
-
- def test_system_chromium_on_path_alone_is_not_enough(self, monkeypatch, tmp_path):
- """Pinned-store-only (gap plan D3): a system Chromium in PATH does
- NOT satisfy the check — only AGENT_BROWSER_EXECUTABLE_PATH or the
- pinned browser store do."""
- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))
- monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)
- monkeypatch.setattr(
- shutil,
- "which",
- lambda name, path=None: "/usr/bin/chromium" if name == "chromium" else None,
- )
-
- assert bt_install._chromium_installed() is False
-
-
- def test_true_when_agent_browser_executable_path_set(self, monkeypatch, tmp_path):
- exe = tmp_path / ("chrome.exe" if os.name == "nt" else "chrome")
- exe.write_bytes(b"")
- monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(exe))
- assert bt_install._chromium_installed() is True
-
-
- def test_removed_override_is_no_longer_ready(self, monkeypatch, tmp_path):
- browser = tmp_path / "browser"
- browser.touch()
- monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(browser))
- assert bt_install._chromium_installed() is True
- browser.unlink()
- assert bt_install._chromium_installed() is False
-
-
-class TestCheckBrowserRequirementsChromium:
-
- def test_local_mode_with_chromium_returns_true(self, monkeypatch, tmp_path):
- monkeypatch.setattr(bt, "_is_camofox_mode", lambda: False)
- monkeypatch.setattr(bt_install, "_find_agent_browser", lambda **_kw: "/usr/local/bin/agent-browser")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
- browser = tmp_path / "browser"
- browser.touch()
- monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(browser))
-
- assert bt_install.check_browser_requirements() is True
-
-
- def test_camofox_mode_does_not_require_chromium(self, monkeypatch, tmp_path):
- monkeypatch.setattr(bt, "_is_camofox_mode", lambda: True)
- # Even with no chromium on disk, camofox drives its own backend.
- monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(tmp_path))
- monkeypatch.setattr("os.path.expanduser", lambda p: str(tmp_path / "fakehome"))
-
- assert bt_install.check_browser_requirements() is True
-
-
-class TestRunBrowserCommandChromiumGuard:
- """Verify _run_browser_command fails fast (no timeout hang) when
- Chromium is missing in local mode.
- """
-
-
diff --git a/tests/tools/test_browser_pm.py b/tests/tools/test_browser_pm.py
index e2f81119c84..f18eac0c059 100644
--- a/tests/tools/test_browser_pm.py
+++ b/tests/tools/test_browser_pm.py
@@ -28,6 +28,8 @@ def browser_store(tmp_path, monkeypatch):
monkeypatch.setattr(install, "_discover_homebrew_node_dirs", lambda: ())
monkeypatch.delenv("AGENT_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("PLAYWRIGHT_BROWSERS_PATH", raising=False)
+ monkeypatch.delenv("TERMUX_VERSION", raising=False)
+ monkeypatch.setattr(bt, "_chromium_autoinstall_attempted", False)
lock = pm.Lockfile(paths.lockfile_path())
target = pm.current_target()
@@ -156,7 +158,7 @@ def test_cdp_override_does_not_require_pm_browser(browser_store, monkeypatch):
assert install.check_browser_requirements() is True
[email protected]("linux", "darwin")
def test_external_browser_on_path_remains_supported_without_pm(browser_store, monkeypatch, tmp_path):
_, store, _ = browser_store
bin_dir = tmp_path / "external browser"
@@ -170,14 +172,13 @@ def test_external_browser_on_path_remains_supported_without_pm(browser_store, mo
assert not store.exists()
[email protected]("entrypoint", [bt.warm_agent_browser_npx_cache, install.warm_agent_browser_npx_cache])
-def test_historical_warmer_is_inert(entrypoint, monkeypatch):
+def test_historical_warmer_is_inert(monkeypatch):
def forbidden(*args, **kwargs):
pytest.fail("historical browser warmer must do no work")
monkeypatch.setattr("subprocess.Popen", forbidden)
monkeypatch.setattr(pm, "ensure", forbidden)
- assert entrypoint(timeout=0.1) is False
+ assert install.warm_agent_browser_npx_cache(timeout=0.1) is False
def test_external_chromium_override_survives_pm_composition(browser_store, monkeypatch, tmp_path):
@@ -224,7 +225,7 @@ def test_pm_browser_wins_over_legacy_and_ambient_installs(browser_store, monkeyp
assert (store / "facts.json").read_bytes() == before
[email protected]("linux", "darwin")
def test_exact_pm_child_receives_composed_scrubbed_environment(browser_store, monkeypatch, tmp_path):
_, store, publish = browser_store
binary = publish("agent-browser", f"#!{sys.executable}\n" + '''import json, os, sys
@@ -259,7 +260,7 @@ print(json.dumps({"argv": sys.argv, "env": dict(os.environ)}))
assert dict(os.environ) == before
[email protected]("linux", "darwin")
def test_runtime_and_chrome_fallback_launch_the_same_pm_binary(browser_store, monkeypatch, tmp_path):
from tools import browser_tool_cloud as cloud
from tools import browser_tool_lightpanda_fallback as fallback
@@ -287,4 +288,66 @@ print(json.dumps({"success": True, "data": {
assert result["data"]["argv"][0] == str(binary)
assert result["data"]["browser"] == str(chromium)
assert direct["data"]["argv"][1:3] == ["--session", "fixture"]
- assert chrome["data"]["argv"][1:3] == ["--engine", "chrome"]
\ No newline at end of file
+ assert chrome["data"]["argv"][1:3] == ["--engine", "chrome"]
+
+
[email protected]("fails", [False, True])
+def test_chromium_autoinstall_is_one_shot(browser_store, monkeypatch, fails):
+ import pm.client
+
+ _, _, publish = browser_store
+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "0")
+ monkeypatch.setattr(install, "_running_in_docker", lambda: False)
+ calls = []
+
+ def request(operation, payload, **kwargs):
+ calls.append((operation, payload))
+ if fails:
+ raise pm.InstallError("chromium", "download failed")
+ publish("chromium")
+
+ monkeypatch.setattr(pm.client, "_request", request)
+ assert install._maybe_autoinstall_chromium() is (not fails)
+ assert install._maybe_autoinstall_chromium() is (not fails)
+ assert calls == [("ensure", {"name": "chromium", "explicit": False})]
+
+
[email protected]("policy", ["docker", "disabled", "termux", "override"])
+def test_chromium_acquisition_policy(browser_store, monkeypatch, policy, tmp_path):
+ import pm.client
+
+ monkeypatch.setattr(install, "_running_in_docker", lambda: policy == "docker")
+ monkeypatch.setenv("HERMES_DISABLE_LAZY_INSTALLS", "1" if policy == "disabled" else "0")
+ if policy == "termux":
+ monkeypatch.setenv("TERMUX_VERSION", "test")
+ if policy == "override":
+ override = tmp_path / "external-chrome"
+ override.touch()
+ monkeypatch.setenv("AGENT_BROWSER_EXECUTABLE_PATH", str(override))
+ assert install._chromium_installed()
+ override.unlink()
+ assert not install._chromium_installed()
+ monkeypatch.setattr(pm.client, "_request", lambda *a, **kw: pytest.fail("forbidden acquisition"))
+ assert not install._maybe_autoinstall_chromium()
+
+
[email protected]("backend", ["local", "camofox", "cdp"])
+def test_browser_readiness_ignores_ambient_chromium(browser_store, monkeypatch, backend):
+ from tools import browser_tool_cloud, browser_tool_lightpanda_fallback
+
+ home, _, publish = browser_store
+ publish("agent-browser")
+ (home / "chromium_headless_shell-1234").mkdir()
+ monkeypatch.setenv("PLAYWRIGHT_BROWSERS_PATH", str(home))
+ ambient = home / ("chromium.exe" if os.name == "nt" else "chromium")
+ ambient.touch()
+ ambient.chmod(0o755)
+ monkeypatch.setenv("PATH", str(home))
+ monkeypatch.setattr(bt, "_is_browser_use_cli_mode", lambda: False)
+ monkeypatch.setattr(bt, "_is_camofox_mode", lambda: backend == "camofox")
+ monkeypatch.setattr(browser_tool_cloud, "_get_cloud_provider", lambda: None)
+ monkeypatch.setattr(browser_tool_lightpanda_fallback, "_using_lightpanda_engine", lambda: False)
+ monkeypatch.setenv("BROWSER_CDP_URL", "ws://example.test/cdp" if backend == "cdp" else "")
+ assert install.check_browser_requirements() is (backend != "local")
+ publish("chromium")
+ assert install.check_browser_requirements()
\ No newline at end of file
diff --git a/tests/tools/test_browser_process_tree.py b/tests/tools/test_browser_process_tree.py
index 785df6058a9..a56d2837b95 100644
--- a/tests/tools/test_browser_process_tree.py
+++ b/tests/tools/test_browser_process_tree.py
@@ -9,7 +9,7 @@ import pytest
from tools.browser_tool_lifecycle import _legacy_kill_process_tree
[email protected]("linux", "darwin")
def test_posix_kills_process_group_term_then_kill(monkeypatch):
proc = MagicMock(pid=999)
monkeypatch.setattr(os, "getpgid", lambda pid: 999)
@@ -19,7 +19,7 @@ def test_posix_kills_process_group_term_then_kill(monkeypatch):
assert calls == [(999, signal.SIGTERM), (999, signal.SIGKILL)]
[email protected]("linux", "darwin")
def test_posix_missing_process_returns_silently(monkeypatch):
def missing(pid):
raise ProcessLookupError()
@@ -28,7 +28,7 @@ def test_posix_missing_process_returns_silently(monkeypatch):
_legacy_kill_process_tree(MagicMock(pid=999))
[email protected]("linux", "darwin")
@pytest.mark.parametrize("kill_error", [None, OSError("already reaped")])
def test_missing_killpg_falls_back_to_proc_kill(monkeypatch, kill_error):
proc = MagicMock(pid=999)
@@ -38,7 +38,7 @@ def test_missing_killpg_falls_back_to_proc_kill(monkeypatch, kill_error):
proc.kill.assert_called_once()
[email protected]("linux", "darwin")
def test_permission_denied_does_not_attempt_sigkill(monkeypatch):
monkeypatch.setattr(os, "getpgid", lambda pid: 999)
calls = []
@@ -52,7 +52,7 @@ def test_permission_denied_does_not_attempt_sigkill(monkeypatch):
assert calls == [(999, signal.SIGTERM)]
@pytest.mark.parametrize("error", [None, OSError("taskkill missing")])
def test_windows_taskkill_targets_tree_and_is_best_effort(error):
with patch("subprocess.run", side_effect=error) as run:
diff --git a/tests/tools/test_browser_supervisor.py b/tests/tools/test_browser_supervisor.py
index 7934aef7ffe..438203eb919 100644
--- a/tests/tools/test_browser_supervisor.py
+++ b/tests/tools/test_browser_supervisor.py
@@ -36,6 +36,7 @@ import shutil
import subprocess
import tempfile
import time
+from pathlib import Path
import pytest
@@ -62,7 +63,7 @@ def _find_chrome() -> str:
@pytest.fixture
-def chrome_cdp(request):
+def chrome_cdp(tmp_path):
"""Start a headless Chrome with --remote-debugging-port, yield its WS URL.
Binds an ephemeral port (bind port 0, read back the real one) so
@@ -71,17 +72,12 @@ def chrome_cdp(request):
Always launches with ``--site-per-process`` so cross-origin iframes
become real OOPIFs (needed by the iframe interaction tests).
"""
- import socket
-
- sock = socket.socket()
- sock.bind(("127.0.0.1", 0))
- port = sock.getsockname()[1]
- sock.close()
profile = tempfile.mkdtemp(prefix="hermes-supervisor-test-")
+ stderr = (tmp_path / "chrome.stderr").open("w+b")
proc = subprocess.Popen(
[
_find_chrome(),
- f"--remote-debugging-port={port}",
+ "--remote-debugging-port=0",
f"--user-data-dir={profile}",
"--no-first-run",
"--no-default-browser-check",
@@ -90,13 +86,17 @@ def chrome_cdp(request):
"--site-per-process", # force OOPIFs for cross-origin iframes
],
stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
+ stderr=stderr,
)
ws_url = None
+ port = None
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
+ if proc.poll() is not None:
+ break
try:
+ port = int((Path(profile) / "DevToolsActivePort").read_text(encoding="utf-8").splitlines()[0])
import urllib.request
with urllib.request.urlopen(
f"http://127.0.0.1:{port}/json/version", timeout=1
@@ -120,7 +120,10 @@ def chrome_cdp(request):
except (AssertionError, Exception):
pass
shutil.rmtree(profile, ignore_errors=True)
- pytest.skip("Chrome didn't expose CDP in time")
+ stderr.seek(0)
+ diagnostic = stderr.read().decode("utf-8", errors="replace")
+ stderr.close()
+ pytest.fail(f"Chrome didn't expose CDP in time: {diagnostic}")
yield ws_url, port
@@ -147,6 +150,7 @@ def chrome_cdp(request):
except (AssertionError, Exception):
pass
shutil.rmtree(profile, ignore_errors=True)
+ stderr.close()
def _test_page_url() -> str:
@@ -307,36 +311,6 @@ def test_browser_dialog_tool_end_to_end(chrome_cdp, supervisor_registry):
assert "PYTEST-TOOL-END2END" in r["dialog"]["message"]
-def test_browser_cdp_frame_id_real_oopif_smoke_documented():
- """Document that real-OOPIF E2E was manually verified — see PR #14540.
-
- A pytest version of this hits an asyncio version-quirk in the venv
- (3.11) that doesn't show up in standalone scripts (3.13 + system
- websockets). The mechanism IS verified end-to-end by two separate
- smoke scripts in /tmp/dialog-iframe-test/:
-
- * smoke_local_oopif.py — local Chrome + 2 http servers on
- different hostnames + --site-per-process. Outer page on
- localhost:18905, iframe src=http://127.0.0.1:18906. Calls
- browser_cdp(method='Runtime.evaluate', frame_id=<OOPIF>) and
- verifies inner page's title comes back from the OOPIF session.
- PASSED on 2026-04-23: iframe document.title = 'INNER-FRAME-XYZ'
-
- * smoke_bb_iframe_agent_path.py — Browserbase + real cross-origin
- iframe (src=https://example.com/). Same browser_cdp(frame_id=)
- path. PASSED on 2026-04-23: iframe document.title =
- 'Example Domain'
-
- The test_browser_cdp_frame_id_routes_via_supervisor pytest covers
- the supervisor-routing plumbing with a fake injected OOPIF.
- """
- pytest.skip(
- "Real-OOPIF E2E verified manually with smoke_local_oopif.py and "
- "smoke_bb_iframe_agent_path.py — pytest version hits an asyncio "
- "version quirk between venv (3.11) and standalone (3.13). "
- "Smoke logs preserved in /tmp/dialog-iframe-test/."
- )
-
def test_evaluate_runtime_unserializable_value(chrome_cdp, supervisor_registry):
"""``Infinity``/``NaN``/``BigInt`` come back via ``unserializableValue``."""
diff --git a/tests/tools/test_browser_use_cli.py b/tests/tools/test_browser_use_cli.py
index 17d5f8dfeca..d52e8084060 100644
--- a/tests/tools/test_browser_use_cli.py
+++ b/tests/tools/test_browser_use_cli.py
@@ -77,93 +77,40 @@ def _fake_cli(tmp_path, body):
return str(script)
-class TestModeDetection:
- def test_default_on_when_cli_available(self, monkeypatch):
- """Backend unset: Browser Use mode is the default when the CLI runs."""
- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {})
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["/usr/bin/browser-use"])
- assert bu_cli.is_browser_use_cli_mode() is True
-
- def test_default_off_when_cli_unavailable(self, monkeypatch):
- """Backend unset + no runnable CLI: keep the built-in browser tools."""
- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {})
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_explicit_off_wins_over_default(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"backend": bu_cli.BACKEND_DISABLED}},
- )
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["/usr/bin/browser-use"])
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_yaml_bool_off_means_disabled(self, monkeypatch):
- """YAML 1.1 parses unquoted `off` as False — must mean disabled."""
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"backend": False}},
- )
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["/usr/bin/browser-use"])
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_config_opt_in(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"backend": "browser-use"}},
- )
- assert bu_cli.is_browser_use_cli_mode() is True
-
- def test_other_backend_value_is_not_cli_mode(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"backend": "something-else"}},
- )
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_config_read_failure_uses_default(self, monkeypatch):
- def boom():
- raise RuntimeError("config unreadable")
-
- monkeypatch.setattr("hermes_cli.config.read_raw_config", boom)
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
[email protected]("config,installed,key,camofox,expected", [
+ ({}, True, False, False, True), ({}, False, False, False, False),
+ ({"backend": "off"}, True, True, False, False),
+ ({"backend": False}, True, True, False, False),
+ ({"backend": "browser-use"}, False, False, False, True),
+ ({"backend": "other"}, True, True, False, False),
+ ({"cloud_provider": "browser-use"}, False, True, False, True),
+ ({"cloud_provider": "browser-use", "use_gateway": True}, False, True, False, False),
+ ({"cloud_provider": "browser-use"}, False, False, False, False),
+ ({}, True, True, True, False),
+ ({"backend": "browser-use"}, True, True, True, False),
+ ({"cloud_provider": "browser-use", "backend": "other"}, True, True, False, False),
+ ({"cloud_provider": "browserbase"}, False, True, False, False),
+ ({"cloud_provider": "local"}, False, True, False, False),
+ ({}, False, True, False, True),
+ (None, False, False, False, False),
+])
+def test_mode_precedence(config, installed, key, camofox, expected, monkeypatch):
+ def read():
+ if config is None:
+ raise OSError("config unreadable")
+ return {"browser": config}
+
+ monkeypatch.setattr("hermes_cli.config.read_raw_config", read)
+ monkeypatch.setattr("tools.browser_camofox.is_camofox_mode", lambda: camofox)
+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["browser-use"] if installed else None)
+ monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key" if key else "")
+ monkeypatch.setenv("BROWSERBASE_API_KEY", "bb-key")
+ monkeypatch.setenv("BROWSERBASE_PROJECT_ID", "bb-project")
+ assert bu_cli.is_browser_use_cli_mode() is expected
class TestSubprocessEnvironment:
- def test_browser_use_telemetry_defaults_off(self, monkeypatch):
- import sys
- from types import ModuleType
-
- browser_tool = ModuleType("tools.browser_tool")
- browser_tool._build_browser_env = lambda: {}
- monkeypatch.setitem(sys.modules, "tools.browser_tool", browser_tool)
- env = bu_cli._base_subprocess_env()
- assert env["ANONYMIZED_TELEMETRY"] == "false"
-
- def test_subprocess_env_strips_parent_python_import_paths(self, monkeypatch):
- """#83427/#84841/#86006/#86104: the browser-use CLI runs under its
- own Python — inherited PYTHONPATH/PYTHONHOME pointing at Hermes's
- venv make it import wrong-ABI C-extensions (pydantic_core) and
- crash. Both must be stripped; unrelated vars survive."""
- import sys
- from types import ModuleType
-
- browser_tool = ModuleType("tools.browser_tool")
- browser_tool._build_browser_env = lambda: {
- "PYTHONPATH": "/hermes:/hermes/venv/lib/site-packages",
- "PYTHONHOME": "/hermes/venv",
- "KEEP_ME": "yes",
- }
- monkeypatch.setitem(sys.modules, "tools.browser_tool", browser_tool)
-
- env = bu_cli._base_subprocess_env()
-
- assert "PYTHONPATH" not in env
- assert "PYTHONHOME" not in env
- assert env["KEEP_ME"] == "yes"
-
- @pytest.mark.skipif(os.name == "nt", reason="POSIX PATH-floor semantics")
+ @pytest.mark.platforms("posix")
def test_subprocess_env_floors_version_manager_only_path(self, monkeypatch):
"""Profile workers (kanban bots, cron) can inherit a PATH of only
version-manager dirs (observed in the wild: one nvm dir repeated
@@ -187,7 +134,7 @@ class TestSubprocessEnvironment:
assert "/usr/bin" in parts
assert "/bin" in parts
- @pytest.mark.skipif(os.name == "nt", reason="POSIX PATH-floor semantics")
+ @pytest.mark.platforms("posix")
def test_floor_preserves_existing_entries_and_order(self):
"""The floor only adds dirs — never drops or reorders what the
caller's environment already had."""
@@ -198,7 +145,7 @@ class TestSubprocessEnvironment:
positions = [merged.index(p) for p in original.split(os.pathsep)]
assert positions == sorted(positions)
- @pytest.mark.skipif(os.name == "nt", reason="POSIX PATH-floor semantics")
+ @pytest.mark.platforms("posix")
def test_floor_survives_missing_sibling_helper(self, monkeypatch):
"""If browser_tool stops exporting _merge_browser_path, the floor
degrades to appending FHS bin dirs instead of vanishing."""
@@ -287,21 +234,6 @@ class TestVaultSupervisorAttach:
assert _fake_supervisor_registry == [("t-vault", "ws://127.0.0.1:47000/devtools/browser/t-vault")]
-class TestFindCli:
- def test_uses_only_pm_selected_tool(self, monkeypatch, tmp_path):
- import pm
- selected = tmp_path / "pm-generation" / "browser-use"
- monkeypatch.setattr(pm, "python_tool", lambda name, executable: selected)
- monkeypatch.setattr(shutil, "which", lambda *a, **kw: "/unmanaged/browser-use")
- assert bu_cli._find_cli_unpatched() == [str(selected)]
-
- def test_missing_managed_tool_does_not_use_path(self, monkeypatch):
- import pm
- monkeypatch.setattr(pm, "python_tool", lambda *a, **kw: None)
- monkeypatch.setattr(shutil, "which", lambda *a, **kw: "/unmanaged/browser-use")
- assert bu_cli._find_cli_unpatched() is None
-
-
class TestLegacyCloudMigration:
"""Pre-CLI direct-API Browser Use cloud configs (cloud_provider:
"browser-use" + BROWSER_USE_API_KEY) auto-route to the CLI backend;
@@ -309,91 +241,6 @@ class TestLegacyCloudMigration:
_LEGACY = {"browser": {"cloud_provider": "browser-use"}}
- def test_direct_api_config_migrates(self, monkeypatch):
- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: self._LEGACY)
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- assert bu_cli.is_browser_use_cli_mode() is True
-
- def test_gateway_config_stays_on_legacy_path(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"cloud_provider": "browser-use", "use_gateway": True}},
- )
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_no_api_key_stays_on_legacy_path(self, monkeypatch):
- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: self._LEGACY)
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_camofox_user_does_not_migrate(self, monkeypatch):
- """A Camofox user (env-var selected, cloud_provider unset) with a
- stray BROWSER_USE_API_KEY keeps Camofox — no silent mode flip."""
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config", lambda: {"browser": {}}
- )
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- import tools.browser_camofox as camofox
-
- monkeypatch.setattr(camofox, "is_camofox_mode", lambda: True)
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_camofox_overrides_explicit_backend(self, monkeypatch):
- """Even with browser.backend: browser-use, an active Camofox setup
- falls back to the built-in tools (no CDP surface to drive)."""
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"backend": "browser-use"}},
- )
- import tools.browser_camofox as camofox
-
- monkeypatch.setattr(camofox, "is_camofox_mode", lambda: True)
- assert bu_cli.is_browser_use_cli_mode() is False
-
-
- def test_explicit_other_backend_wins(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"cloud_provider": "browser-use", "backend": "something-else"}},
- )
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_other_cloud_provider_does_not_migrate(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"cloud_provider": "browserbase"}},
- )
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_explicit_local_does_not_migrate(self, monkeypatch):
- monkeypatch.setattr(
- "hermes_cli.config.read_raw_config",
- lambda: {"browser": {"cloud_provider": "local"}},
- )
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
-
- def test_auto_detect_with_key_migrates(self, monkeypatch):
- """No cloud_provider configured + BROWSER_USE_API_KEY set: credential
- auto-detection prefers Browser Use (even when Browserbase creds are
- also present), which now means Browser Use mode."""
- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {})
- monkeypatch.setenv("BROWSER_USE_API_KEY", "bu-key")
- monkeypatch.setenv("BROWSERBASE_API_KEY", "bb-key")
- monkeypatch.setenv("BROWSERBASE_PROJECT_ID", "bb-project")
- assert bu_cli.is_browser_use_cli_mode() is True
-
- def test_auto_detect_without_key_does_not_migrate(self, monkeypatch):
- """No key, no CLI: nothing to migrate and no default flip."""
- monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {})
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: None)
- assert bu_cli.is_browser_use_cli_mode() is False
@pytest.mark.platforms("linux")
def test_migrated_config_gets_bu_autospawn(self, tmp_path, monkeypatch):
@@ -427,222 +274,77 @@ class TestLegacyCloudMigration:
assert _is_provider_active(cli_row, dict(self._LEGACY)) is False
-class TestBackendCdpResolution:
- """browser_exec routes through the configured browser backend by reusing
- the legacy stack's provider session machinery (_get_session_info)."""
-
- def _env(self):
- return {}
-
- def test_existing_bu_env_wins(self, monkeypatch):
- env = {"BU_CDP_WS": "ws://operator-override:9222"}
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_WS"] == "ws://operator-override:9222"
-
- def test_cdp_override_exported(self, monkeypatch):
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "http://127.0.0.1:9222")
- env = self._env()
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_URL"] == "http://127.0.0.1:9222"
-
- def test_ws_override_uses_bu_cdp_ws(self, monkeypatch):
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "wss://connect.example/x")
- env = self._env()
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_WS"] == "wss://connect.example/x"
-
- def test_cloud_provider_session_exported(self, monkeypatch):
- import tools.browser_tool as bt
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(
- bt_session, "_get_session_info",
- lambda task_id: {"cdp_url": "wss://browser.example/cdp/abc"},
- )
- env = self._env()
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_WS"] == "wss://browser.example/cdp/abc"
-
- def test_no_provider_drives_packaged_chromium_not_user_chrome(self, monkeypatch, _fake_managed_chromium):
- """Local mode must hand the harness the agent-browser-launched Chromium (same browser the built-in
- tools use) — never leave BU_CDP_* unset, which makes the harness hunt for the user's installed
- Chrome (Allow popup, >=136 default-profile block, chrome-not-running on headless hosts)."""
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
- env = self._env()
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_WS"] == "ws://127.0.0.1:47000/devtools/browser/t1"
- assert env[bu_cli._PRIVATE_BROWSER_SENTINEL] == "1"
- assert _fake_managed_chromium == [("t1", "get", ("cdp-url",))]
- env = self._env()
- assert bu_cli._resolve_backend_cdp(env, "t1", session_name="r7k2") is None
- assert _fake_managed_chromium[-1][0] == "bu-named-r7k2" # named session → its own Chromium
-
- def test_packaged_chromium_launch_failure_is_an_error(self, monkeypatch):
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
- monkeypatch.setattr(bt_session, "_run_browser_command",
- lambda *a, **k: {"success": False, "error": "Chromium browser not installed"})
- env = self._env()
- err = bu_cli._resolve_backend_cdp(env, "t1")
- assert err and "Chromium browser not installed" in err
- assert "BU_CDP_WS" not in env and "BU_CDP_URL" not in env
-
- def test_provider_failure_returns_error(self, monkeypatch):
-
- def boom(task_id):
[email protected]("operator,override,provider,gateway,engine,session,endpoint,expected_key,expected_env,private", [
+ ("ws://operator/x", "http://override", "cloud", False, True, "", "http://engine", None, {"BU_CDP_WS": "ws://operator/x"}, False),
+ ("", "http://override", "cloud", False, True, "", "http://engine", None, {"BU_CDP_URL": "http://override"}, False),
+ ("", "wss://override/x", None, False, True, "named", "http://engine", None, {"BU_CDP_WS": "wss://override/x"}, False),
+ ("", "", "cloud", False, True, "", "wss://cloud/x", "task", {"BU_CDP_WS": "wss://cloud/x"}, False),
+ ("", "", "cloud", False, True, "research", "wss://cloud/x", "bu-named-research", {"BU_CDP_WS": "wss://cloud/x"}, True),
+ ("", "", "browser-use", False, False, "research", "unused", None, {}, True),
+ ("", "", "browser-use", True, False, "research", "wss://gateway/x", "bu-named-research", {"BU_CDP_WS": "wss://gateway/x"}, True),
+ ("", "", None, False, True, "", "http://engine", "task", {"BU_CDP_URL": "http://engine"}, True),
+ ("", "", None, False, True, "research", "http://engine", "bu-named-research", {"BU_CDP_URL": "http://engine"}, True),
+ ("", "", None, False, False, "", "unused", None, {"BU_CDP_WS": "ws://127.0.0.1:47000/devtools/browser/task"}, True),
+ ("", "", None, False, False, "research", "unused", None, {"BU_CDP_WS": "ws://127.0.0.1:47000/devtools/browser/bu-named-research"}, True),
+])
+def test_exec_cdp_precedence(monkeypatch, operator, override, provider, gateway, engine,
+ session, endpoint, expected_key, expected_env, private):
+ from types import SimpleNamespace
+
+ monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {"browser": {"use_gateway": gateway}})
+ monkeypatch.setenv("BU_CDP_WS", operator)
+ monkeypatch.delenv("BU_CDP_URL", raising=False)
+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: override)
+ monkeypatch.setattr("tools.browser_tool_cdp._resolve_cdp_override", lambda url: url)
+ monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: SimpleNamespace(name=provider) if provider else None)
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: engine)
+ seen = []
+ monkeypatch.setattr(bt_session, "_get_session_info", lambda key: seen.append(key) or {"cdp_url": endpoint})
+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["fixture"])
+ monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda cmd, code, env, timeout:
+ subprocess.CompletedProcess(cmd, 0, json.dumps({"code": code, "env": env}), ""))
+ tasks = ["task", "followup"] if session else ["task"]
+ for task in tasks:
+ result = json.loads(bu_cli.browser_exec("print('payload')", session=session, task_id=task))
+ assert result["success"], result
+ child = json.loads(result["output"])
+ assert {k: v for k, v in child["env"].items() if k in {"BU_CDP_URL", "BU_CDP_WS"} and v} == expected_env
+ assert "_HERMES_BU_PRIVATE_BROWSER" not in child["env"]
+ assert ("_hermes_ensure_own_tab" in child["code"]) is bool(session and not private)
+ assert child["code"].endswith("print('payload')")
+ compile(child["code"], "browser-payload", "exec")
+ assert seen == ([expected_key] * len(tasks) if expected_key else [])
+
+
+def test_exec_without_task_uses_default_backend_identity(monkeypatch, _fake_managed_chromium):
+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
+ monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["fixture"])
+ monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda cmd, *a:
+ subprocess.CompletedProcess(cmd, 0, "ok", ""))
+ assert json.loads(bu_cli.browser_exec("print(1)"))["success"]
+ assert _fake_managed_chromium == [("browser-exec-default", "get", ("cdp-url",))]
+
+
[email protected]("provider,engine,fault,expected", [
+ (True, False, "raises", "api down"), (True, False, "missing", "no CDP endpoint"),
+ (False, True, "raises", "browser.engine"), (False, True, "missing", "no CDP endpoint"),
+ (False, False, "missing", "Chromium browser not installed"),
+])
+def test_exec_backend_failure_never_launches_cli(monkeypatch, provider, engine, fault, expected):
+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
+ monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object() if provider else None)
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: engine)
+ def info(key):
+ if fault == "raises":
raise RuntimeError("api down")
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(bt_session, "_get_session_info", boom)
- err = bu_cli._resolve_backend_cdp(self._env(), "t1")
- assert err and "api down" in err
-
- def test_provider_without_cdp_returns_error(self, monkeypatch):
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(bt_session, "_get_session_info", lambda task_id: {"cdp_url": None})
- err = bu_cli._resolve_backend_cdp(self._env(), "t1")
- assert err and "no" in err.lower() and "CDP" in err
-
- @pytest.mark.platforms("linux")
- def test_named_session_composes_with_provider_backend(self, tmp_path, monkeypatch):
- """session=<name> composes with a configured provider backend: the
- name keys its OWN provider browser (bu-named-<name>), so concurrent
- named sessions never share one browser (#86894)."""
-
- seen = []
-
- def fake_session_info(key):
- seen.append(key)
- return {"cdp_url": "wss://browser.example/cdp/" + key}
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(bt_session, "_get_session_info", fake_session_info)
- cli = _fake_cli(tmp_path, 'cat > /dev/null\necho "bu:$BU_NAME ws:$BU_CDP_WS"\n')
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
- result = json.loads(bu_cli.browser_exec("print(1)", session="r7k2"))
- assert result["success"] is True
- assert seen == ["bu-named-r7k2"]
- assert "bu:r7k2" in result["output"]
- assert "ws:wss://browser.example/cdp/bu-named-r7k2" in result["output"]
-
- def test_named_session_key_stable_across_tasks(self, monkeypatch):
- """The same session name maps to the same provider cache key no
- matter which task calls it — that is what lets a follow-up call
- reattach to the same cloud browser."""
- import tools.browser_tool as bt
-
- seen = []
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(
- bt_session, "_get_session_info",
- lambda key: seen.append(key) or {"cdp_url": "wss://x/cdp/a"},
- )
- env1, env2 = {}, {}
- assert bu_cli._resolve_backend_cdp(env1, "task-A", session_name="research") is None
- assert bu_cli._resolve_backend_cdp(env2, "task-B", session_name="research") is None
- assert seen == ["bu-named-research", "bu-named-research"]
-
- def test_named_session_direct_api_bu_cloud_still_skips_provider(
- self, tmp_path, monkeypatch
- ):
- """Direct-API Browser Use cloud configs keep the native named-daemon
- path: resolving through the provider would double-session and
- double-bill."""
- import tools.browser_tool as bt
-
- class _BUProvider:
- name = "browser-use"
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: _BUProvider())
- monkeypatch.setattr(
- bt_session, "_get_session_info",
- lambda key: (_ for _ in ()).throw(AssertionError("must skip provider")),
- )
- monkeypatch.setattr(bu_cli, "_read_browser_cfg", lambda: {"cloud_provider": "browser-use"})
- env = {}
- assert bu_cli._resolve_backend_cdp(env, "t1", session_name="r7k2") is None
- assert "BU_CDP_WS" not in env and "BU_CDP_URL" not in env
-
-
-class TestOwnTabPreamble:
- """Named sessions on SHARED browsers (a /browser connect CDP override) get the own-tab preamble
- prepended; private per-name browsers (packaged Chromium, provider) and unnamed sessions do not."""
-
- def _run(self, tmp_path, monkeypatch, *, session="", private=False, provider=False, shared_cdp=""):
- import tools.browser_tool as bt
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: shared_cdp)
- if provider:
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(
- bt_session, "_get_session_info",
- lambda key: {"cdp_url": "wss://browser.example/cdp/" + key},
- )
- else:
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
- # fake CLI echoes stdin back so we can inspect what code was sent
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["test-browser-use"])
- monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda cmd, code, env, timeout:
- subprocess.CompletedProcess(cmd, 0, code, ""))
- return json.loads(bu_cli.browser_exec("print('payload')", session=session))
-
- @pytest.mark.platforms("linux")
- def test_named_shared_browser_gets_preamble(self, tmp_path, monkeypatch):
- result = self._run(tmp_path, monkeypatch, session="r7k2", shared_cdp="http://127.0.0.1:9222")
- assert result["success"] is True
- assert "_hermes_ensure_own_tab" in result["output"]
- # model code still present, after the preamble
- assert result["output"].index("_hermes_ensure_own_tab") < result["output"].index("print('payload')")
-
- def test_named_packaged_chromium_skips_preamble(self, tmp_path, monkeypatch):
- """Each named session launches its own packaged Chromium — nothing to share a tab with."""
- result = self._run(tmp_path, monkeypatch, session="r7k2")
- assert result["success"] is True
- assert "_hermes_ensure_own_tab" not in result["output"]
-
- def test_unnamed_session_gets_no_preamble(self, tmp_path, monkeypatch):
- result = self._run(tmp_path, monkeypatch, session="")
- assert result["success"] is True
- assert "_hermes_ensure_own_tab" not in result["output"]
-
- @pytest.mark.platforms("linux")
- def test_named_provider_browser_skips_preamble(self, tmp_path, monkeypatch):
- """Per-name provider browsers are private — preamble would leak a tab."""
- result = self._run(tmp_path, monkeypatch, session="r7k2", provider=True)
- assert result["success"] is True
- assert "_hermes_ensure_own_tab" not in result["output"]
-
- @pytest.mark.platforms("linux")
- def test_sentinel_never_reaches_subprocess_env(self, tmp_path, monkeypatch):
- import tools.browser_tool as bt
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- monkeypatch.setattr(
- bt_session, "_get_session_info",
- lambda key: {"cdp_url": "wss://browser.example/cdp/" + key},
- )
- cli = _fake_cli(tmp_path, 'cat > /dev/null\necho "sentinel:${_HERMES_BU_PRIVATE_BROWSER:-unset}"\n')
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
- result = json.loads(bu_cli.browser_exec("print(1)", session="r7k2"))
- assert "sentinel:unset" in result["output"]
-
- def test_preamble_is_valid_python(self):
- import ast
-
- ast.parse(bu_cli._OWN_TAB_PREAMBLE)
- # and composes with model code
- ast.parse(bu_cli._OWN_TAB_PREAMBLE + "print('x')")
+ return {"cdp_url": None}
+ monkeypatch.setattr(bt_session, "_get_session_info", info)
+ monkeypatch.setattr(bt_session, "_run_browser_command", lambda *a, **kw:
+ {"success": False, "error": "Chromium browser not installed"})
+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["fixture"])
+ monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda *a: pytest.fail("launched on routing failure"))
+ assert expected in json.loads(bu_cli.browser_exec("print(1)"))["error"]
class TestProviderPickerIntegration:
@@ -862,56 +564,16 @@ class TestStepLabels:
assert "Searching Amazon for paper towels" in line
assert "new_tab" not in line
- def test_header_instructs_leading_comment(self):
- assert "one-line comment" in bu_cli._HEADER_BASE
- assert "step label" in bu_cli._HEADER_BASE
-
-
-class TestHeaderVariants:
- def test_vision_header_forbids_vision_tool_detour(self, monkeypatch):
- monkeypatch.setattr(
- "tools.vision_tools._should_use_native_vision_fast_path", lambda: True
- )
- header = bu_cli._description_header()
- assert header.startswith(bu_cli._HEADER_BASE)
- assert "attached to your context automatically" in header
-
- def test_text_only_header_teaches_text_workflow(self, monkeypatch):
- monkeypatch.setattr(
- "tools.vision_tools._should_use_native_vision_fast_path", lambda: False
- )
- header = bu_cli._description_header()
- assert "cannot view images" in header
- assert "page_info()" in header
-
-
-class TestSkillTextDescription:
- """The schema description is fully pinned: header + _HELPERS_DIGEST.
-
- The live ``browser-use skill`` fetch was removed after A/B benchmarking
- showed the pinned digest matches the full skill dump on success rate
- (36/36 vs 36/36, opus-4.8 + kimi-k3) — see tools/browser_use_cli.py.
- """
-
- def test_description_is_pinned_header_plus_digest(self, monkeypatch):
- # Even with a CLI present, the description must NOT shell out.
- monkeypatch.setattr(
- bu_cli, "_find_cli",
- lambda: (_ for _ in ()).throw(AssertionError("schema must not invoke the CLI")),
- )
- overrides = bu_cli._dynamic_schema_overrides()
- assert overrides["description"].startswith(bu_cli._HEADER_BASE)
- assert overrides["description"].endswith(bu_cli._HELPERS_DIGEST)
-
- def test_digest_names_core_helpers(self):
- for helper in ("new_tab(", "page_info()", "js(", "fill_input(",
- "click_at_xy(", "capture_screenshot()", "cdp("):
- assert helper in bu_cli._HELPERS_DIGEST
-
- def test_static_fallback_carries_digest_and_install_hint(self):
- desc = bu_cli.BROWSER_EXEC_SCHEMA["description"]
- assert bu_cli._HELPERS_DIGEST in desc
- assert "hermes tools" in desc
[email protected]("vision,lightpanda,expected", [
+ (True, False, "attached to your context automatically"),
+ (False, False, "cannot view images"), (True, True, "Lightpanda"),
+])
+def test_schema_is_dynamic_without_cli_io(monkeypatch, vision, lightpanda, expected):
+ monkeypatch.setattr("tools.vision_tools._should_use_native_vision_fast_path", lambda: vision)
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback.lightpanda_engine_status", lambda: (lightpanda, ""))
+ monkeypatch.setattr(bu_cli, "_find_cli", lambda: pytest.fail("schema invoked CLI"))
+ monkeypatch.setattr(subprocess, "Popen", lambda *a, **kw: pytest.fail("schema spawned child"))
+ assert expected in bu_cli._dynamic_schema_overrides()["description"]
class TestBrowserExec:
@@ -962,43 +624,11 @@ class TestBrowserExec:
def test_timeout_returns_actionable_error(self, tmp_path, monkeypatch):
cli = _fake_cli(tmp_path, "cat > /dev/null\nsleep 30\n")
monkeypatch.setattr(bu_cli, "_find_cli", lambda: [cli])
- monkeypatch.setattr(bu_cli, "_MIN_TIMEOUT_S", 1)
- result = json.loads(bu_cli.browser_exec("print(1)", timeout_s=1))
+ monkeypatch.setattr(bu_cli, "_MIN_TIMEOUT_S", 2)
+ result = json.loads(bu_cli.browser_exec("print(1)", timeout_s=2))
assert "timed out" in result["error"]
-class TestInstallCli:
- def test_installs_through_pm_even_with_an_unmanaged_binary(self, tmp_path, monkeypatch):
- import pm
- selected = tmp_path / "pm-generation" / "browser-use"
- seen = {}
-
- def install(name, requirements, executable, **kwargs):
- seen.update(name=name, requirements=requirements, executable=executable, **kwargs)
- return selected
-
- monkeypatch.setattr(pm, "ensure_python_tool", install)
- monkeypatch.setattr(shutil, "which", lambda *a, **kw: "/unmanaged/browser-use")
- ok, message = bu_cli.install_cli(timeout_s=321)
- assert ok, message
- assert str(selected) in message
- assert seen == dict(name="browser-use", requirements=bu_cli._CLI_REQUIREMENTS,
- executable="browser-use", explicit=True, timeout=321)
-
- def test_pm_install_failure_is_actionable(self, monkeypatch):
- import pm
-
- def fail(*args, **kwargs):
- raise RuntimeError("network unavailable; retry hermes tools")
-
- monkeypatch.setattr(pm, "ensure_python_tool", fail)
- monkeypatch.setattr(shutil, "which", lambda *a, **kw: None)
- ok, message = bu_cli.install_cli()
- assert not ok
- assert "network unavailable" in message
- assert "hermes tools" in message
-
-
class TestDefaultDowngradeNotice:
def _isolate(self, tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
@@ -1032,112 +662,6 @@ class TestDefaultDowngradeNotice:
assert bu_cli.default_downgrade_notice() is None
-class TestLightpandaBackendResolution:
- """browser.engine: lightpanda in Browser Use mode — Hermes spawns
- ``lightpanda serve`` through the same _get_session_info machinery and
- exports its endpoint, but only when nothing with higher precedence
- (BU_CDP_* env, a CDP override, a cloud provider) claimed the session."""
-
- def _setup(self, monkeypatch, *, engine=True, info=None, boom=None):
-
- seen = []
-
- def fake_session_info(key):
- seen.append(key)
- if boom:
- raise boom
- return info if info is not None else {"cdp_url": "http://127.0.0.1:43111"}
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: engine)
- monkeypatch.setattr(bt_session, "_get_session_info", fake_session_info)
- return seen
-
- def test_exports_bu_cdp_url_and_private_sentinel(self, monkeypatch):
- seen = self._setup(monkeypatch)
- env = {}
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_URL"] == "http://127.0.0.1:43111"
- assert env[bu_cli._PRIVATE_BROWSER_SENTINEL] == "1"
- assert seen == ["t1"]
-
- def test_named_session_keys_its_own_process(self, monkeypatch):
- seen = self._setup(monkeypatch)
- assert bu_cli._resolve_backend_cdp({}, "t1", session_name="r7k2") is None
- assert seen == ["bu-named-r7k2"]
-
- def test_default_key_without_task(self, monkeypatch):
- seen = self._setup(monkeypatch)
- assert bu_cli._resolve_backend_cdp({}, None) is None
- assert seen == ["browser-exec-default"]
-
- def test_launch_failure_returns_actionable_error(self, monkeypatch):
- self._setup(monkeypatch, boom=RuntimeError("no lightpanda binary was found"))
- err = bu_cli._resolve_backend_cdp({}, "t1")
- assert err and "no lightpanda binary was found" in err
- assert "browser.engine" in err
-
- def test_missing_cdp_returns_error(self, monkeypatch):
- self._setup(monkeypatch, info={"cdp_url": None})
- err = bu_cli._resolve_backend_cdp({}, "t1")
- assert err and "no CDP endpoint" in err
-
- def test_engine_auto_falls_through_to_packaged_chromium(self, monkeypatch, _fake_managed_chromium):
- seen = self._setup(monkeypatch, engine=False)
- env = {}
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert seen == [] # no lightpanda process
- assert env["BU_CDP_WS"].startswith("ws://") and _fake_managed_chromium[0][1:] == ("get", ("cdp-url",))
-
- def test_bu_env_wins(self, monkeypatch):
- seen = self._setup(monkeypatch)
- env = {"BU_CDP_WS": "ws://operator:9222"}
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_WS"] == "ws://operator:9222"
- assert seen == []
-
- def test_cdp_override_wins(self, monkeypatch):
-
- seen = self._setup(monkeypatch)
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "http://127.0.0.1:9222")
- env = {}
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_URL"] == "http://127.0.0.1:9222"
- assert seen == []
-
- def test_cloud_provider_wins(self, monkeypatch):
-
- seen = self._setup(monkeypatch, info={"cdp_url": "wss://cloud.example/x"})
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: object())
- env = {}
- assert bu_cli._resolve_backend_cdp(env, "t1") is None
- assert env["BU_CDP_WS"] == "wss://cloud.example/x"
- assert seen == ["t1"] # provider path, same cache key
-
-
-class TestLightpandaPreamble:
- def test_lightpanda_session_skips_own_tab_preamble(self, tmp_path, monkeypatch):
- """A Lightpanda process is private to its session: no sibling daemon
- to collide with, and Target.createTarget would fail anyway
- (lightpanda-io/browser#1962)."""
- import tools.browser_tool as bt
-
- monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
- monkeypatch.setattr(bt_cloud, "_get_cloud_provider", lambda: None)
- monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: True)
- monkeypatch.setattr(
- bt_session, "_get_session_info", lambda key: {"cdp_url": "http://127.0.0.1:43111"}
- )
- monkeypatch.setattr(bu_cli, "_find_cli", lambda: ["test-browser-use"])
- monkeypatch.setattr(bu_cli, "_run_cli_killing_process_group", lambda cmd, code, env, timeout:
- subprocess.CompletedProcess(cmd, 0, code, ""))
- result = json.loads(bu_cli.browser_exec("print('payload')", session="r7k2"))
- assert result["success"] is True
- assert "_hermes_ensure_own_tab" not in result["output"]
- assert "print('payload')" in result["output"]
-
-
class TestLightpandaHeader:
def test_lightpanda_header_is_text_first_even_for_vision_models(self, monkeypatch):
monkeypatch.setattr(
@@ -1251,7 +775,7 @@ class TestTimeoutProcessGroupKill:
blocked forever, and the wedged call's activity heartbeat pins the session at
"now" in the sidebar indefinitely."""
- @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups")
+ @pytest.mark.platforms("posix")
def test_timeout_kills_grandchild_and_returns_promptly(self, tmp_path, monkeypatch):
"""A grandchild that outlives the direct child and holds the inherited stdout
pipe must not keep browser_exec blocked past the timeout (it wedged permanently
diff --git a/tests/tools/test_browser_use_pm.py b/tests/tools/test_browser_use_pm.py
new file mode 100644
index 00000000000..9aa4540d562
--- /dev/null
+++ b/tests/tools/test_browser_use_pm.py
@@ -0,0 +1,83 @@
+"""Browser Use caller -> real PM worker -> locally built CLI -> actual child."""
+import json
+import os
+from pathlib import Path
+import zipfile
+
+import pytest
+
+import pm
+from tests.pm._fixtures import _wheel, build_worker, client, isolated_python # noqa: F401
+from tools import browser_use_cli as bu
+
+
[email protected]("posix", "windows")
+def test_installed_cli_selection_and_child_environment(build_worker, tmp_path, monkeypatch):
+ from tools import browser_tool_session, browser_supervisor
+
+ wheel = _wheel(tmp_path, "browser_use_probe")
+ with zipfile.ZipFile(wheel, "a") as archive:
+ archive.writestr("browser_use_probe/cli.py", """import json, os, sys
+def main():
+ print(json.dumps({'argv': sys.argv, 'stdin': sys.stdin.read(), 'env': dict(os.environ)}))
+""")
+ archive.writestr("browser_use_probe-1.0.dist-info/entry_points.txt",
+ "[console_scripts]\nbrowser-use = browser_use_probe.cli:main\n")
+ monkeypatch.setattr(bu, "_CLI_REQUIREMENTS", (f"browser-use-probe @ {wheel.as_uri()}",))
+ monkeypatch.setattr(bu, "_find_cli", bu._find_cli_unpatched)
+ monkeypatch.setattr("hermes_cli.config.read_raw_config", lambda: {"browser": {"backend": "browser-use"}})
+ monkeypatch.setattr("tools.browser_tool_cdp._get_cdp_override", lambda: "")
+ monkeypatch.setattr("tools.browser_tool_cdp._resolve_cdp_override", lambda url: url)
+ monkeypatch.setattr("tools.browser_tool_cloud._get_cloud_provider", lambda: None)
+ monkeypatch.setattr("tools.browser_tool_lightpanda_fallback._using_lightpanda_engine", lambda: False)
+ def local_browser(task_id, command, args, **kwargs):
+ assert (task_id, command, args) == ("bu-named-research", "get", ["cdp-url"])
+ return {"success": True, "data": {"cdpUrl": "ws://127.0.0.1:47000/private"}}
+ monkeypatch.setattr(browser_tool_session, "_run_browser_command", local_browser)
+ attached = []
+ monkeypatch.setattr(browser_supervisor.SUPERVISOR_REGISTRY, "get_or_start",
+ lambda task_id, cdp_url, **kw: attached.append((task_id, cdp_url)))
+ # A PATH binary must never substitute for missing or corrupted PM selection.
+ ambient = tmp_path / "ambient"
+ ambient.mkdir()
+ (ambient / "browser-use").write_text("#!/bin/sh\nexit 99\n", encoding="utf-8")
+ (ambient / "browser-use").chmod(0o755)
+ monkeypatch.setenv("PATH", str(ambient) + os.pathsep + os.environ["PATH"])
+ assert bu._find_cli() is None
+ assert "hermes tools" in json.loads(bu.browser_exec("print(1)"))["error"]
+ ok, message = bu.install_cli(timeout_s=120)
+ assert ok, message
+ binary = pm.python_tool("browser-use", "browser-use")
+ assert binary is not None and bu._find_cli() == [str(binary)]
+ assert str(binary) in message
+ assert bu.install_cli(timeout_s=120)[0]
+ assert pm.python_tool("browser-use", "browser-use") == binary
+ monkeypatch.setenv("PYTHONPATH", "/wrong-abi")
+ monkeypatch.setenv("PYTHONHOME", "/wrong-python")
+ monkeypatch.setenv("OPENAI_API_KEY", "must-not-leak")
+ monkeypatch.setenv("BROWSERBASE_API_KEY", "browser-key")
+ monkeypatch.setenv("KEEP_BROWSER_PROBE", "kept")
+ monkeypatch.delenv("ANONYMIZED_TELEMETRY", raising=False)
+ result = json.loads(bu.browser_exec("print('payload')", session="research", task_id="owner"))
+ assert result["success"], result
+ child = json.loads(result["output"])
+ assert Path(child["argv"][0]) == binary
+ assert child["stdin"] == "print('payload')"
+ for key in ("PYTHONPATH", "PYTHONHOME", "OPENAI_API_KEY", "_HERMES_BU_PRIVATE_BROWSER"):
+ assert key not in child["env"]
+ assert child["env"]["BU_NAME"] == "research"
+ assert child["env"]["BU_CDP_WS"] == "ws://127.0.0.1:47000/private"
+ assert child["env"]["ANONYMIZED_TELEMETRY"] == "false"
+ assert child["env"]["BROWSERBASE_API_KEY"] == "browser-key"
+ assert child["env"]["KEEP_BROWSER_PROBE"] == "kept"
+ assert attached == [("owner", "ws://127.0.0.1:47000/private")]
+ # Invalid wheel reaches real worker/uv failure, and leaves the old CLI selected.
+ monkeypatch.delenv("PYTHONPATH")
+ monkeypatch.delenv("PYTHONHOME")
+ monkeypatch.setattr(bu, "_CLI_REQUIREMENTS", (f"browser-use-probe @ {(tmp_path / 'missing.whl').as_uri()}",))
+ ok, message = bu.install_cli(timeout_s=120)
+ assert not ok and "Could not install browser-use CLI" in message
+ assert "missing.whl" in message
+ assert bu._find_cli() == [str(binary)]
+ binary.unlink()
+ assert bu._find_cli() is None
diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.py
index 9eb5951ab11..ba7721008be 100644
--- a/tests/tools/test_code_execution.py
+++ b/tests/tools/test_code_execution.py
@@ -123,42 +123,6 @@ class TestInterruptedOutput(unittest.TestCase):
)
-class TestHermesToolsGeneration(unittest.TestCase):
- def test_generates_all_allowed_tools(self):
- src = generate_hermes_tools_module(list(SANDBOX_ALLOWED_TOOLS))
- for tool in SANDBOX_ALLOWED_TOOLS:
- self.assertIn(f"def {tool}(", src)
-
-
- def test_empty_list_generates_nothing(self):
- src = generate_hermes_tools_module([])
- self.assertNotIn("def terminal(", src)
- self.assertIn("def _call(", src) # infrastructure still present
-
-
- def test_file_transport_uses_tempfile_fallback_for_rpc_dir(self):
- src = generate_hermes_tools_module(["terminal"], transport="file")
- self.assertIn("import json, os, shlex, tempfile, threading, time", src)
- self.assertIn("os.path.join(tempfile.gettempdir(), \"hermes_rpc\")", src)
- self.assertNotIn('os.environ.get("HERMES_RPC_DIR", "/tmp/hermes_rpc")', src)
-
- def test_uds_transport_serializes_concurrent_calls(self):
- """Regression: UDS _call() must hold a lock across send+recv so that
- concurrent tool calls from multiple threads don't interleave on the
- shared socket and receive each other's responses."""
- src = generate_hermes_tools_module(["terminal"], transport="uds")
- self.assertIn("_call_lock = threading.Lock()", src)
- self.assertIn("with _call_lock:", src)
-
- def test_file_transport_serializes_seq_allocation(self):
- """Regression: file transport _call() must allocate `_seq` under a
- lock, otherwise concurrent threads can pick the same seq and clobber
- each other's request files."""
- src = generate_hermes_tools_module(["terminal"], transport="file")
- self.assertIn("_seq_lock = threading.Lock()", src)
- self.assertIn("with _seq_lock:", src)
-
-
class TestExecuteCodeRemoteTempDir(unittest.TestCase):
def test_execute_remote_uses_backend_temp_dir_for_sandbox(self):
class FakeEnv:
@@ -250,10 +214,6 @@ class TestExecuteCode(unittest.TestCase):
def _run(self, code, enabled_tools=None):
"""Helper: run code with mocked handle_function_call."""
- with patch("tools.code_execution_rpc._rpc_server_loop") as mock_rpc:
- # Use real execution but mock the tool dispatcher
- pass
- # Actually run with full integration, mocking at the model_tools level
with patch("model_tools.handle_function_call", side_effect=_mock_handle_function_call):
result = execute_code(
code=code,
@@ -418,75 +378,6 @@ except ValueError as e:
self.assertIn("caught: nope", result["output"])
-class TestStubSchemaDrift(unittest.TestCase):
- """Verify that _TOOL_STUBS in code_execution_tool.py stay in sync with
- the real tool schemas registered in tools/registry.py.
-
- If a tool gains a new parameter but the sandbox stub isn't updated,
- the LLM will try to use the parameter (it sees it in the system prompt)
- and get a TypeError. This test catches that drift.
- """
-
- # Parameters that are internal (injected by the handler, not user-facing)
- _INTERNAL_PARAMS = {"task_id", "user_task"}
- # Parameters intentionally blocked in the sandbox
- _BLOCKED_TERMINAL_PARAMS = {"background", "pty", "notify", "notify_on_complete", "watch_patterns"}
-
- def test_stubs_cover_all_schema_params(self):
- """Every user-facing parameter in the real schema must appear in the
- corresponding _TOOL_STUBS entry."""
- import re
- from tools.code_execution_tool import _TOOL_STUBS
-
- # Import the registry and trigger tool registration
- from tools.registry import registry
- import tools.file_tools # noqa: F401 - registers read_file, write_file, patch, search_files
- import tools.web_tools # noqa: F401 - registers web_search, web_extract
-
- for tool_name, (sig, doc, args_expr) in _TOOL_STUBS.items():
- entry = registry._tools.get(tool_name)
- if not entry:
- # Tool might not be registered yet (e.g., terminal uses a
- # different registration path). Skip gracefully.
- continue
-
- schema_props = entry.schema.get("parameters", {}).get("properties", {})
- schema_params = set(schema_props.keys()) - self._INTERNAL_PARAMS
- if tool_name == "terminal":
- schema_params -= self._BLOCKED_TERMINAL_PARAMS
-
- # Extract parameter names from the stub signature string
- # Match word before colon: "pattern: str, target: str = ..."
- stub_params = set(re.findall(r'(\w+)\s*:', sig))
-
- missing = schema_params - stub_params
- self.assertEqual(
- missing, set(),
- f"Stub for '{tool_name}' is missing parameters that exist in "
- f"the real schema: {missing}. Update _TOOL_STUBS in "
- f"code_execution_tool.py to include them."
- )
-
-
- def test_generated_module_accepts_all_params(self):
- """The generated hermes_tools.py module should accept all current params
- without TypeError when called with keyword arguments."""
- src = generate_hermes_tools_module(list(SANDBOX_ALLOWED_TOOLS))
-
- # Compile the generated module to check for syntax errors
- compile(src, "hermes_tools.py", "exec")
-
- # Verify specific parameter signatures are in the source
- # search_files must accept its pagination, output, and ordering controls
- self.assertIn("context", src)
- self.assertIn("offset", src)
- self.assertIn("output_mode", src)
- self.assertIn("order", src)
-
- # patch must accept mode and patch params
- self.assertIn("mode", src)
-
-
# ---------------------------------------------------------------------------
# build_execute_code_schema
# ---------------------------------------------------------------------------
@@ -905,12 +796,5 @@ class TestRpcTokenAuthorization(unittest.TestCase):
self.assertIn("Unauthorized", resp[0].get("error", ""))
- def test_generated_module_sends_token(self):
- """The generated hermes_tools module reads HERMES_RPC_TOKEN and sends it."""
- src = generate_hermes_tools_module(["terminal"], transport="uds")
- self.assertIn("HERMES_RPC_TOKEN", src)
- self.assertIn('"token"', src)
-
-
if __name__ == "__main__":
unittest.main()
diff --git a/tests/tools/test_code_execution_file_rpc.py b/tests/tools/test_code_execution_file_rpc.py
new file mode 100644
index 00000000000..45a3624d6ff
--- /dev/null
+++ b/tests/tools/test_code_execution_file_rpc.py
@@ -0,0 +1,99 @@
+"""Generated stubs and the production file poller over real shell/filesystem I/O."""
+import concurrent.futures
+import json
+import os
+from pathlib import Path
+import subprocess
+import threading
+import time
+
+import pytest
+
+from tools.code_execution_tool import generate_hermes_tools_module
+from tools.code_execution_rpc import _rpc_poll_loop
+
+
+CALLS = {
+ "web_search": {"query": "fixture", "limit": 3},
+ "web_extract": {"urls": ["https://example.test"], "char_limit": 3000},
+ "read_file": {"path": "reference", "offset": 2, "limit": 4},
+ "write_file": {"path": "output", "content": "café", "cross_profile": False},
+ "search_files": {"pattern": "x", "target": "files", "path": ".", "file_glob": "*.py",
+ "limit": 4, "offset": 2, "output_mode": "count", "context": 3, "order": "modified"},
+ "patch": {"path": "output", "old_string": "old", "new_string": "new", "replace_all": True,
+ "mode": "replace", "patch": None, "cross_profile": False},
+ "terminal": {"command": "echo fixture", "timeout": 3, "workdir": "/tmp"},
+}
+
+
+def test_generated_file_rpc_kwargs_correlation_and_authority(tmp_path, monkeypatch):
+ from pm.shell import bash
+ from tools.registry import registry
+ import tools.file_tools # noqa: F401 - populate schemas
+ import tools.web_tools # noqa: F401
+ import tools.terminal_tool # noqa: F401
+
+ shell = bash()
+ assert shell
+ rpc = tmp_path / "rpc with spaces"
+ rpc.mkdir()
+ monkeypatch.delenv("HERMES_RPC_DIR", raising=False)
+ monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
+ namespace = {}
+ exec(generate_hermes_tools_module([], transport="file"), namespace)
+ assert namespace["_RPC_DIR"] == str(tmp_path / "hermes_rpc")
+ assert "terminal" not in namespace
+ monkeypatch.setenv("HERMES_RPC_DIR", str(rpc))
+ monkeypatch.setenv("HERMES_RPC_TOKEN", "right-token")
+ exec(generate_hermes_tools_module(list(CALLS), transport="file"), namespace)
+ seen, log, counter = [], [], [0]
+
+ def dispatch(name, args, **kwargs):
+ seen.append((name, args.copy()))
+ return json.dumps({"name": name, "args": args})
+
+ monkeypatch.setattr("model_tools.handle_function_call", dispatch)
+
+ class Shell:
+ def execute(self, command, cwd=None, timeout=None):
+ result = subprocess.run([shell, "-c", command], cwd=cwd, timeout=timeout,
+ env=dict(os.environ), stdin=subprocess.DEVNULL, capture_output=True, text=True)
+ assert result.returncode == 0, result.stderr
+ return {"output": result.stdout}
+
+ stop = threading.Event()
+ budget = len(CALLS) + 8
+ poller = threading.Thread(target=_rpc_poll_loop, args=(Shell(), str(rpc), "owner", log, counter,
+ budget, frozenset(CALLS), stop, "right-token"), daemon=True)
+ poller.start()
+ try:
+ # Raw clients bypass stub visibility; neither missing nor wrong token may dispatch.
+ for seq, token in [(9001, None), (9002, "wrong-token")]:
+ request = {"seq": seq, "tool": "terminal", "args": {"command": "forbidden"}}
+ if token is not None:
+ request["token"] = token
+ path = rpc / f"req_{seq}"
+ path.write_text(json.dumps(request), encoding="utf-8")
+ deadline = time.monotonic() + 5
+ while path.exists() and time.monotonic() < deadline:
+ stop.wait(.01)
+ assert not path.exists()
+ assert not (rpc / f"res_{seq:06d}").exists()
+ assert seen == [] and counter == [0]
+ for name, args in CALLS.items():
+ blocked = {"background", "pty", "notify", "notify_on_complete", "watch_patterns"} if name == "terminal" else set()
+ schema_keys = set(registry.get_entry(name).schema["parameters"]["properties"]) - blocked
+ assert schema_keys <= set(args), (name, schema_keys - set(args))
+ assert namespace[name](**args) == {"name": name, "args": args}
+ assert seen == list(CALLS.items())
+ with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
+ results = list(pool.map(lambda i: namespace["terminal"](f"tag-{i}", 3, "/tmp"), range(8)))
+ assert [r["args"]["command"] for r in results] == [f"tag-{i}" for i in range(8)]
+ assert "not available" in namespace["_call"]("unauthorized-tool", {})["error"]
+ assert "limit reached" in namespace["terminal"]("over-budget")["error"]
+ assert counter == [budget] and len(seen) == len(log) == budget
+ finally:
+ stop.set()
+ poller.join(timeout=10)
+ assert not poller.is_alive()
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 470c6cb0e63..7d2689368d1 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -751,22 +751,6 @@ class TestLazyMcpInstall:
driver_ensure.assert_called_once_with("cua-driver")
mock_sess_start.assert_called_once()
- def test_start_reports_incompatible_existing_driver_before_mcp_setup(self):
- from tools.computer_use import cua_backend
-
- state = {
- "ready": False,
- "reason": "Hermes computer use requires cua-driver 0.20.0 or newer",
- }
- with patch.object(
- cua_backend,
- "cua_driver_runtime_contract_status",
- return_value=state,
- ), patch("pm.ensure"), patch("pm.ensure_import") as mock_ensure:
- with pytest.raises(RuntimeError, match="hermes computer-use install"):
- cua_backend.CuaDriverBackend().start()
-
- mock_ensure.assert_not_called()
def test_start_propagates_feature_unavailable(self):
"""When mcp can't be installed (lazy installs off / network), start()
@@ -803,12 +787,13 @@ class TestDriverPreparation:
return_value={"ready": False, "reason": "invalid manifest"}), \
patch("pm.ensure") as ensure, \
patch("pm.ensure_import") as sdk:
- with pytest.raises(RuntimeError, match="invalid manifest"):
+ with pytest.raises(RuntimeError, match="invalid manifest") as caught:
cua_backend.CuaDriverBackend().start()
if override:
ensure.assert_not_called()
else:
ensure.assert_called_once_with("cua-driver")
+ assert "hermes computer-use install" in str(caught.value)
sdk.assert_not_called()
diff --git a/tests/tools/test_daemon_pool.py b/tests/tools/test_daemon_pool.py
index 5b14b231d60..b8e1e129c85 100644
--- a/tests/tools/test_daemon_pool.py
+++ b/tests/tools/test_daemon_pool.py
@@ -17,20 +17,6 @@ from concurrent.futures.thread import _threads_queues
from tools.daemon_pool import DaemonThreadPoolExecutor
-def test_workers_are_daemon_threads():
- pool = DaemonThreadPoolExecutor(max_workers=2)
- try:
- info = pool.submit(
- lambda: (threading.current_thread().daemon, threading.current_thread())
- ).result(timeout=10)
- is_daemon, worker = info
- assert is_daemon is True
- # Not registered with concurrent.futures' atexit join hook.
- assert worker not in _threads_queues
- finally:
- pool.shutdown(wait=True)
-
-
def test_initializer_runs_on_each_worker_before_tasks():
local = threading.local()
ready = threading.Barrier(2, timeout=10)
diff --git a/tests/tools/test_fal_common.py b/tests/tools/test_fal_common.py
deleted file mode 100644
index 5f23343733a..00000000000
--- a/tests/tools/test_fal_common.py
+++ /dev/null
@@ -1,644 +0,0 @@
-"""Tests for tools/fal_common.py — shared FAL.ai SDK plumbing.
-
-Covers: import_fal_client, _normalize_fal_queue_url_format,
-_extract_http_status, _ManagedFalSyncClient (init + submit).
-"""
-
-import sys
-import types
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from tools.fal_common import (
- _ManagedFalSyncClient,
- _extract_http_status,
- _normalize_fal_queue_url_format,
- import_fal_client,
-)
-
-
-# ---------------------------------------------------------------------------
-# import_fal_client
-# ---------------------------------------------------------------------------
-
-
-def fake_fal_client(monkeypatch):
- module = types.ModuleType("fal_client")
- monkeypatch.setitem(sys.modules, "fal_client", module)
- return module
-
-
-class TestImportFalClient:
- def test_returns_fal_client_module(self, monkeypatch, fake_fal_client):
- """import_fal_client returns the fal_client module reference."""
- ensure = MagicMock()
- monkeypatch.setattr("pm.ensure_import", ensure)
-
- result = import_fal_client()
- assert result is fake_fal_client
- ensure.assert_called_once_with("fal")
-
- def test_lazy_ensure_import_error_is_swallowed(self, monkeypatch, fake_fal_client):
- """If pm.ensure_import raises ImportError, it's swallowed (fal_client still imported)."""
- monkeypatch.setattr(
- "pm.ensure_import",
- MagicMock(side_effect=ImportError("no pm")),
- )
-
- assert import_fal_client() is fake_fal_client
-
- def test_lazy_ensure_other_exception_raises_import_error(self):
- """If pm.ensure_import raises a non-ImportError, it's re-raised as ImportError."""
- with patch("pm.ensure_import", side_effect=RuntimeError("install hint")):
- with pytest.raises(ImportError, match="install hint"):
- import_fal_client()
-
- def test_lazy_ensure_module_missing_is_swallowed(self, fake_fal_client):
- """If pm itself can't be imported, ImportError is swallowed."""
- import builtins
-
- original_import = builtins.__import__
-
- def failing_import(name, *args, **kwargs):
- if name == "pm":
- raise ImportError("no module")
- return original_import(name, *args, **kwargs)
-
- with patch("builtins.__import__", side_effect=failing_import):
- result = import_fal_client()
- assert result is fake_fal_client
-
-
-# ---------------------------------------------------------------------------
-# _normalize_fal_queue_url_format
-# ---------------------------------------------------------------------------
-
-
-class TestNormalizeFalQueueUrlFormat:
- def test_adds_trailing_slash(self):
- assert (
- _normalize_fal_queue_url_format("https://queue.example.com")
- == "https://queue.example.com/"
- )
-
- def test_strips_trailing_slashes_then_adds_one(self):
- assert (
- _normalize_fal_queue_url_format("https://queue.example.com///")
- == "https://queue.example.com/"
- )
-
- def test_strips_whitespace(self):
- assert (
- _normalize_fal_queue_url_format(" https://queue.example.com ")
- == "https://queue.example.com/"
- )
-
- def test_empty_string_raises(self):
- with pytest.raises(ValueError, match="Managed FAL queue origin is required"):
- _normalize_fal_queue_url_format("")
-
- def test_none_raises(self):
- with pytest.raises(ValueError, match="Managed FAL queue origin is required"):
- _normalize_fal_queue_url_format(None) # type: ignore[arg-type]
-
- def test_whitespace_only_raises(self):
- with pytest.raises(ValueError, match="Managed FAL queue origin is required"):
- _normalize_fal_queue_url_format(" ")
-
-
-# ---------------------------------------------------------------------------
-# _extract_http_status
-# ---------------------------------------------------------------------------
-
-
-class TestExtractHttpStatus:
- def test_returns_status_from_response_attribute(self):
- """httpx.HTTPStatusError exposes .response.status_code."""
- exc = MagicMock()
- exc.response = MagicMock()
- exc.response.status_code = 404
- assert _extract_http_status(exc) == 404
-
- def test_returns_status_from_exc_status_code(self):
- """fal_client wrappers expose .status_code directly."""
- exc = MagicMock()
- exc.response = None
- exc.status_code = 500
- assert _extract_http_status(exc) == 500
-
- def test_returns_none_when_no_response_and_no_status_code(self):
- exc = Exception("plain error")
- assert _extract_http_status(exc) is None
-
- def test_returns_none_when_response_is_none(self):
- exc = MagicMock()
- exc.response = None
- del exc.status_code
- assert _extract_http_status(exc) is None
-
- def test_returns_none_when_response_status_code_not_int(self):
- exc = MagicMock()
- exc.response = MagicMock()
- exc.response.status_code = "not-int"
- del exc.status_code
- assert _extract_http_status(exc) is None
-
- def test_returns_none_when_status_code_not_int(self):
- exc = MagicMock()
- exc.response = None
- exc.status_code = "not-int"
- assert _extract_http_status(exc) is None
-
- def test_response_status_takes_precedence_over_exc_status(self):
- exc = MagicMock()
- exc.response = MagicMock()
- exc.response.status_code = 200
- exc.status_code = 500
- assert _extract_http_status(exc) == 200
-
- def test_falls_back_to_exc_status_when_response_status_not_int(self):
- exc = MagicMock()
- exc.response = MagicMock()
- exc.response.status_code = "bad"
- exc.status_code = 503
- assert _extract_http_status(exc) == 503
-
-
-# ---------------------------------------------------------------------------
-# _ManagedFalSyncClient — __init__
-# ---------------------------------------------------------------------------
-
-
-def _make_fal_client_mock(
- *,
- sync_client_class=None,
- client_module=None,
- http_client=None,
- default_timeout=120.0,
-):
- """Build a mock fal_client module with all required attributes."""
- if sync_client_class is None:
- sync_client_class = MagicMock()
- if client_module is None:
- client_module = MagicMock()
-
- sync_client_instance = MagicMock()
- sync_client_instance._client = (
- http_client if http_client is not None else MagicMock()
- )
- sync_client_instance.default_timeout = default_timeout
- sync_client_class.return_value = sync_client_instance
-
- fal_client = MagicMock()
- fal_client.SyncClient = sync_client_class
- fal_client.client = client_module
- return fal_client, sync_client_instance
-
-
-class TestManagedFalSyncClientInit:
- def test_init_succeeds_with_all_attributes(self):
- fal_client, _ = _make_fal_client_mock()
- client = _ManagedFalSyncClient(
- fal_client, key="test-key", queue_run_origin="https://queue.example.com"
- )
- assert client._queue_url_format == "https://queue.example.com/"
- assert client._http_client is not None
- assert client._maybe_retry_request is not None
- assert client._raise_for_status is not None
- assert client._request_handle_class is not None
-
- def test_init_raises_when_sync_client_missing(self):
- fal_client = MagicMock()
- fal_client.SyncClient = None
- fal_client.client = MagicMock()
- with pytest.raises(RuntimeError, match="fal_client.SyncClient is required"):
- _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
-
- def test_init_raises_when_client_module_missing(self):
- fal_client = MagicMock()
- fal_client.SyncClient = MagicMock()
- fal_client.client = None
- with pytest.raises(RuntimeError, match="fal_client.client is required"):
- _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
-
- def test_init_raises_when_http_client_missing(self):
- """SyncClient._client is None → RuntimeError."""
- fal_client = MagicMock()
- sync_instance = MagicMock()
- sync_instance._client = None
- fal_client.SyncClient.return_value = sync_instance
- fal_client.client = MagicMock()
- with pytest.raises(RuntimeError, match="SyncClient._client is required"):
- _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
-
- def test_init_raises_when_retry_request_missing(self):
- fal_client, _ = _make_fal_client_mock()
- fal_client.client._maybe_retry_request = None
- with pytest.raises(RuntimeError, match="request helpers are required"):
- _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
-
- def test_init_raises_when_raise_for_status_missing(self):
- fal_client, _ = _make_fal_client_mock()
- fal_client.client._raise_for_status = None
- with pytest.raises(RuntimeError, match="request helpers are required"):
- _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
-
- def test_init_raises_when_request_handle_class_missing(self):
- fal_client, _ = _make_fal_client_mock()
- fal_client.client.SyncRequestHandle = None
- with pytest.raises(RuntimeError, match="SyncRequestHandle is required"):
- _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
-
- def test_init_passes_key_to_sync_client(self):
- fal_client, sync_instance = _make_fal_client_mock()
- _ManagedFalSyncClient(
- fal_client, key="my-secret-key", queue_run_origin="https://q.example.com"
- )
- fal_client.SyncClient.assert_called_once_with(key="my-secret-key")
-
- def test_init_normalizes_queue_url(self):
- fal_client, _ = _make_fal_client_mock()
- client = _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com///"
- )
- assert client._queue_url_format == "https://q.example.com/"
-
-
-# ---------------------------------------------------------------------------
-# _ManagedFalSyncClient — submit
-# ---------------------------------------------------------------------------
-
-
-class TestManagedFalSyncClientSubmit:
- def _make_client(self, **kwargs):
- fal_client, sync_instance = _make_fal_client_mock(**kwargs)
- client = _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://queue.example.com"
- )
- return client, sync_instance, fal_client
-
- def test_submit_basic(self):
- client, sync_instance, fal_client = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "req-1",
- "response_url": "https://q.example.com/resp",
- "status_url": "https://q.example.com/status",
- "cancel_url": "https://q.example.com/cancel",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- result = client.submit("my-app", {"prompt": "hello"})
-
- client._maybe_retry_request.assert_called_once()
- call_args = client._maybe_retry_request.call_args
- assert call_args[0][0] is client._http_client
- assert call_args[0][1] == "POST"
- assert call_args[0][2] == "https://queue.example.com/my-app"
- assert call_args[1]["json"] == {"prompt": "hello"}
- assert call_args[1]["timeout"] == 120.0
- client._raise_for_status.assert_called_once_with(response)
- client._request_handle_class.assert_called_once()
- assert result is client._request_handle_class.return_value
-
- def test_submit_with_idempotency_key_is_not_retried(self):
- """The Nous gateway cannot replay an accepted submit reliably.
-
- A retry can replace the original billing/entitlement response with a
- misleading ``idempotency key ... without a reusable request handle``
- conflict, so keyed submits must make exactly one POST attempt.
- """
- http_client = MagicMock()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "req-1",
- "response_url": "https://q.example.com/resp",
- "status_url": "https://q.example.com/status",
- "cancel_url": "https://q.example.com/cancel",
- }
- http_client.request.return_value = response
- client, _, _ = self._make_client(http_client=http_client)
- client._maybe_retry_request = MagicMock()
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit(
- "my-app", {"prompt": "hello"},
- headers={"X-Idempotency-Key": "submission-1"},
- )
-
- http_client.request.assert_called_once_with(
- "POST", "https://queue.example.com/my-app",
- json={"prompt": "hello"}, timeout=120.0,
- headers={"X-Idempotency-Key": "submission-1"},
- )
- client._maybe_retry_request.assert_not_called()
-
- # Negative arm: an unkeyed submit keeps the SDK's retry ladder (transport errors, 429, ingress 5xx).
- client._maybe_retry_request = MagicMock(return_value=response)
- client.submit("my-app", {"prompt": "hello"})
- client._maybe_retry_request.assert_called_once()
- assert http_client.request.call_count == 1
-
- def test_submit_with_path(self):
- client, _, _ = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, path="sub/path")
-
- url = client._maybe_retry_request.call_args[0][2]
- assert url == "https://queue.example.com/my-app/sub/path"
-
- def test_submit_with_path_strips_leading_slash(self):
- client, _, _ = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, path="/leading/slash")
-
- url = client._maybe_retry_request.call_args[0][2]
- assert url == "https://queue.example.com/my-app/leading/slash"
-
- def test_submit_with_webhook_url(self):
- client, _, _ = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, webhook_url="https://hook.example.com/cb")
-
- url = client._maybe_retry_request.call_args[0][2]
- assert "fal_webhook=https%3A%2F%2Fhook.example.com%2Fcb" in url
-
- def test_submit_with_hint(self):
- client, _, _ = self._make_client()
- client._add_hint_header = MagicMock()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, hint="my-hint")
-
- client._add_hint_header.assert_called_once()
- args = client._add_hint_header.call_args[0]
- assert args[0] == "my-hint"
-
- def test_submit_with_priority(self):
- client, _, _ = self._make_client()
- client._add_priority_header = MagicMock()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, priority=5)
-
- client._add_priority_header.assert_called_once()
- args = client._add_priority_header.call_args[0]
- assert args[0] == 5
-
- def test_submit_with_priority_raises_when_header_fn_missing(self):
- client, _, _ = self._make_client()
- client._add_priority_header = None
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- with pytest.raises(RuntimeError, match="add_priority_header is required"):
- client.submit("my-app", {}, priority=5)
-
- def test_submit_with_start_timeout(self):
- client, _, _ = self._make_client()
- client._add_timeout_header = MagicMock()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, start_timeout=30)
-
- client._add_timeout_header.assert_called_once()
- args = client._add_timeout_header.call_args[0]
- assert args[0] == 30
-
- def test_submit_with_start_timeout_raises_when_header_fn_missing(self):
- client, _, _ = self._make_client()
- client._add_timeout_header = None
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- with pytest.raises(RuntimeError, match="add_timeout_header is required"):
- client.submit("my-app", {}, start_timeout=30)
-
- def test_submit_with_custom_headers(self):
- client, _, _ = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, headers={"X-Custom": "value"})
-
- headers = client._maybe_retry_request.call_args[1]["headers"]
- assert headers["X-Custom"] == "value"
-
- def test_submit_with_none_headers_defaults_to_empty_dict(self):
- client, _, _ = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("my-app", {}, headers=None)
-
- headers = client._maybe_retry_request.call_args[1]["headers"]
- assert headers == {}
-
- def test_submit_uses_custom_default_timeout(self):
- """SyncClient.default_timeout is used if present."""
- fal_client, sync_instance = _make_fal_client_mock(default_timeout=300.0)
- client = _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("app", {})
-
- assert client._maybe_retry_request.call_args[1]["timeout"] == 300.0
-
- def test_submit_falls_back_to_120_when_no_default_timeout(self):
- """SyncClient without default_timeout attr → 120.0 fallback."""
- fal_client, sync_instance = _make_fal_client_mock()
- # Remove default_timeout
- del sync_instance.default_timeout
- client = _ManagedFalSyncClient(
- fal_client, key="k", queue_run_origin="https://q.example.com"
- )
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("app", {})
-
- assert client._maybe_retry_request.call_args[1]["timeout"] == 120.0
-
- def test_submit_passes_request_handle_kwargs(self):
- client, _, _ = self._make_client()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "req-123",
- "response_url": "https://q.example.com/resp",
- "status_url": "https://q.example.com/status",
- "cancel_url": "https://q.example.com/cancel",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit("app", {})
-
- kwargs = client._request_handle_class.call_args[1]
- assert kwargs["request_id"] == "req-123"
- assert kwargs["response_url"] == "https://q.example.com/resp"
- assert kwargs["status_url"] == "https://q.example.com/status"
- assert kwargs["cancel_url"] == "https://q.example.com/cancel"
- assert kwargs["client"] is client._http_client
-
- def test_submit_with_all_optional_params(self):
- """All optional params set at once."""
- client, _, _ = self._make_client()
- client._add_hint_header = MagicMock()
- client._add_priority_header = MagicMock()
- client._add_timeout_header = MagicMock()
- response = MagicMock()
- response.json.return_value = {
- "request_id": "r",
- "response_url": "",
- "status_url": "",
- "cancel_url": "",
- }
- client._maybe_retry_request = MagicMock(return_value=response)
- client._raise_for_status = MagicMock()
- client._request_handle_class = MagicMock()
-
- client.submit(
- "app",
- {"prompt": "test"},
- path="sub",
- hint="hint-val",
- webhook_url="https://hook.example.com",
- priority=10,
- headers={"X-Custom": "val"},
- start_timeout=60,
- )
-
- url = client._maybe_retry_request.call_args[0][2]
- assert "app/sub?" in url
- assert "fal_webhook=" in url
- client._add_hint_header.assert_called_once()
- client._add_priority_header.assert_called_once()
- client._add_timeout_header.assert_called_once()
- headers = client._maybe_retry_request.call_args[1]["headers"]
- assert headers["X-Custom"] == "val"
diff --git a/tests/tools/test_fal_sdk.py b/tests/tools/test_fal_sdk.py
new file mode 100644
index 00000000000..66c3a214763
--- /dev/null
+++ b/tests/tools/test_fal_sdk.py
@@ -0,0 +1,186 @@
+"""Managed FAL adapter against the installed SDK; only HTTP leaves are replaced."""
+import json
+from types import SimpleNamespace
+
+import fal_client
+import httpx
+import pytest
+
+from tools.fal_common import (
+ _ManagedFalSyncClient, _extract_http_status, _managed_fal_billing_error,
+ _normalize_fal_queue_url_format, import_fal_client,
+)
+
+
+def transport(monkeypatch):
+ requests, responses, clients = [], [], []
+ original = httpx.Client.__init__
+
+ def handle(request):
+ assert request.url.host == "queue.test", "no external FAL requests allowed"
+ requests.append(request)
+ reply = responses.pop(0)
+ if isinstance(reply, Exception):
+ raise reply
+ status, body = reply
+ return httpx.Response(status, json=body)
+
+ def initialize(client, *args, **kwargs):
+ kwargs.update(transport=httpx.MockTransport(handle), trust_env=False)
+ original(client, *args, **kwargs)
+ clients.append(client)
+
+ monkeypatch.setattr(httpx.Client, "__init__", initialize)
+ # Keep the SDK retry algorithm, but do not spend wall time backing off.
+ monkeypatch.setattr(fal_client.client.time, "sleep", lambda delay: None)
+ yield requests, responses
+ for client in clients:
+ client.close()
+
+
+def accepted():
+ return 200, {
+ "request_id": "r1", "response_url": "https://queue.test/result",
+ "status_url": "https://queue.test/status", "cancel_url": "https://queue.test/cancel",
+ }
+
+
[email protected]("path", ["sub/path", "/sub/path"])
+def test_sdk_submit_preserves_wire_contract(transport, path):
+ requests, replies = transport
+ replies.append(accepted())
+ client = _ManagedFalSyncClient(fal_client, key="test-token", queue_run_origin=" https://queue.test/// ")
+ assert isinstance(client._sync_client, fal_client.SyncClient)
+ object.__setattr__(client._sync_client, "default_timeout", 37)
+ headers = {"X-Custom": "kept", "X-Idempotency-Key": "one-operation"}
+ handle = client.submit("app", {"prompt": "local fixture"}, path=path, hint="runner",
+ webhook_url="https://hook.test/cb?a=1", priority="low",
+ start_timeout=60, headers=headers)
+ assert len(requests) == 1
+ request = requests[0]
+ assert request.method == "POST"
+ assert str(request.url) == "https://queue.test/app/sub/path?fal_webhook=https%3A%2F%2Fhook.test%2Fcb%3Fa%3D1"
+ assert json.loads(request.content) == {"prompt": "local fixture"}
+ for key, value in {
+ "authorization": "Key test-token", "x-custom": "kept", "x-idempotency-key": "one-operation",
+ "x-fal-runner-hint": "runner", "x-fal-queue-priority": "low", "x-fal-request-timeout": "60.0",
+ }.items():
+ assert request.headers[key] == value
+ assert request.extensions["timeout"]["read"] == 37
+ assert headers == {"X-Custom": "kept", "X-Idempotency-Key": "one-operation"}
+ assert isinstance(handle, fal_client.client.SyncRequestHandle)
+ assert (handle.request_id, handle.response_url, handle.status_url, handle.cancel_url) == (
+ "r1", "https://queue.test/result", "https://queue.test/status", "https://queue.test/cancel")
+ assert handle.client is client._http_client
+
+
[email protected]("status", [402, 409, 429, 503, "transport"])
[email protected]("keyed", [True, False])
+def test_keyed_errors_survive_without_duplicate_submission(transport, status, keyed):
+ requests, replies = transport
+ body = {"error": {"code": "BILLING_ERROR", "message": "meter disabled",
+ "details": {"upstreamPayload": {"code": "meter_missing", "error": "not configured"}}}}
+ replies.extend([httpx.ConnectError("connection lost") if status == "transport" else (status, body), accepted()])
+ client = _ManagedFalSyncClient(fal_client, key="token", queue_run_origin="https://queue.test")
+ headers = {"x-IDEMPOTENCY-key": "operation"} if keyed else None
+ # A JSON 503 is an application error, not the SDK's retryable ingress 503.
+ if keyed or status in (402, 503):
+ error = httpx.ConnectError if status == "transport" else fal_client.client.FalClientHTTPError
+ with pytest.raises(error) as caught:
+ client.submit("app", {}, headers=headers)
+ assert len(requests) == 1
+ if status != "transport":
+ assert _extract_http_status(caught.value) == status
+ assert caught.value.response.json() == body
+ assert "meter_missing" in _managed_fal_billing_error(caught.value, "model")
+ else:
+ assert client.submit("app", {}, headers=headers).request_id == "r1"
+ assert len(requests) == 2
+ assert str(requests[0].url) == "https://queue.test/app"
+ assert "x-custom" not in requests[0].headers
+
+
[email protected]("origin", ["", None, " "])
+def test_empty_origin_refused(origin):
+ with pytest.raises(ValueError, match="origin is required"):
+ _normalize_fal_queue_url_format(origin)
+
+
[email protected]("response_status,status,expected", [
+ (404, None, 404), (None, 500, 500), (None, None, None),
+ ("bad", None, None), (None, "bad", None), (200, 500, 200), ("bad", 503, 503),
+])
+def test_exception_status_shapes(response_status, status, expected):
+ exc = SimpleNamespace(response=SimpleNamespace(status_code=response_status), status_code=status)
+ assert _extract_http_status(exc) == expected
+ assert _extract_http_status(Exception("plain")) is None
+
+
[email protected]("missing,message", [
+ ("SyncClient", "fal_client.SyncClient"), ("client", "fal_client.client"),
+ ("_client", "SyncClient._client"), ("_maybe_retry_request", "request helpers"),
+ ("_raise_for_status", "request helpers"), ("SyncRequestHandle", "SyncRequestHandle"),
+])
+def test_missing_sdk_surface_is_actionable(transport, monkeypatch, missing, message):
+ owner = fal_client if missing in {"SyncClient", "client"} else fal_client.client
+ if missing == "_client":
+ owner = fal_client.SyncClient
+ monkeypatch.setattr(owner, missing, None)
+ with pytest.raises(RuntimeError, match=message):
+ _ManagedFalSyncClient(fal_client, key="token", queue_run_origin="https://queue.test")
+
+
[email protected]("helper,options,message", [
+ ("add_priority_header", {"priority": "low"}, "add_priority_header"),
+ ("add_timeout_header", {"start_timeout": 60}, "add_timeout_header"),
+])
+def test_optional_sdk_surface_refused_before_http(transport, monkeypatch, helper, options, message):
+ monkeypatch.setattr(fal_client.client, helper, None)
+ client = _ManagedFalSyncClient(fal_client, key="token", queue_run_origin="https://queue.test")
+ with pytest.raises(RuntimeError, match=message):
+ client.submit("app", {}, **options)
+ assert transport[0] == []
+
+
[email protected]("failure", [None, ImportError("external SDK"), RuntimeError("PM acquisition failed")])
+def test_import_adapter_keeps_pm_failure_policy(monkeypatch, failure):
+ import pm
+ calls = []
+
+ def ensure(feature):
+ calls.append(feature)
+ if failure:
+ raise failure
+
+ monkeypatch.setattr(pm, "ensure_import", ensure)
+ if isinstance(failure, RuntimeError):
+ with pytest.raises(ImportError, match="PM acquisition failed"):
+ import_fal_client()
+ else:
+ assert import_fal_client() is fal_client
+ assert calls == ["fal"]
+
+
+def test_import_adapter_runs_real_pm_availability_without_install(monkeypatch):
+ import pm.client
+ monkeypatch.setattr(pm.client, "sync_venv", lambda *a, **kw: pytest.fail("available SDK must not install"))
+ assert import_fal_client() is fal_client
+
+
+def test_external_sdk_remains_importable_without_pm(monkeypatch):
+ import sys
+ monkeypatch.setitem(sys.modules, "pm", None)
+ assert import_fal_client() is fal_client
+
+
[email protected]("timeout,expected", [(None, 120.0), (300.0, 300.0)])
+def test_older_sdk_timeout_default_and_optional_hint(transport, monkeypatch, timeout, expected):
+ monkeypatch.setattr(fal_client.client, "add_hint_header", None)
+ client = _ManagedFalSyncClient(fal_client, key="token", queue_run_origin="https://queue.test")
+ # Keep its real HTTP client and request helpers, vary only older SDK metadata.
+ client._sync_client = SimpleNamespace(**({} if timeout is None else {"default_timeout": timeout}))
+ transport[1].append(accepted())
+ assert client.submit("app", {}, hint="ignored-on-old-sdk").request_id == "r1"
+ assert transport[0][0].extensions["timeout"]["read"] == expected
+ assert "x-fal-runner-hint" not in transport[0][0].headers
diff --git a/tests/tools/test_find_shell.py b/tests/tools/test_find_shell.py
index 6fb4ff03567..69b723fdd28 100644
--- a/tests/tools/test_find_shell.py
+++ b/tests/tools/test_find_shell.py
@@ -81,29 +81,6 @@ class TestFindShellWindowsBehavior:
assert result == _find_bash()
-class TestFindShellReturnsString:
- """_find_shell must return a string, never None."""
-
- def test_returns_string(self):
- """_find_shell always returns a non-empty string on any platform."""
- result = _find_shell()
- assert isinstance(result, str)
- assert len(result) > 0
-
-
-class TestFindBashUnchanged:
- """_find_bash should be unaffected by the _find_shell change."""
-
- def test_find_bash_still_prefers_bash(self):
- """_find_bash still returns bash (not $SHELL) on POSIX."""
- result = _find_bash()
- # On any system, _find_bash should return something containing "bash"
- # or fall back to $SHELL or /bin/sh — but it should NOT prefer $SHELL
- # over bash the way _find_shell does.
- assert isinstance(result, str)
- assert len(result) > 0
-
-
class TestFindBashCollapsedToPmShell:
"""_find_bash is now a thin wrapper over pm.shell(); the Windows
candidate ladder (HERMES_GIT_BASH_PATH → %LOCALAPPDATA%\\hermes\\git →
diff --git a/tests/tools/test_mcp_npx_cached_bin.py b/tests/tools/test_mcp_npx_cached_bin.py
index d3f27cec00a..3f00a4be0e2 100644
--- a/tests/tools/test_mcp_npx_cached_bin.py
+++ b/tests/tools/test_mcp_npx_cached_bin.py
@@ -125,56 +125,27 @@ def test_unusable_args_are_ignored(args):
assert _npx_cached_bin(args) is None
-def test_osv_preflight_runs_before_the_swap():
- """The malware gate must still see `npx` + the package name.
[email protected]("rejected", [False, True])
+def test_preflight_checks_original_package_before_cache_access(tmp_path, monkeypatch, rejected):
+ import asyncio
+ from tools import mcp_tool
- `_infer_ecosystem` keys off the command basename, so a command already
- rewritten to `.../node_modules/.bin/mcp-linear` yields no ecosystem and
- `check_package_for_malware` returns None — the gate silently becomes a
- no-op. This pins the ordering: OSV inspects the original invocation.
- """
- from tools.osv_check import _infer_ecosystem, _parse_package_from_args
-
- # What the preflight sees today, before any swap.
- assert _infer_ecosystem("npx") == "npm"
- assert _parse_package_from_args(["-y", "@tacticlaunch/mcp-linear"], "npm")[0] == (
- "@tacticlaunch/mcp-linear"
- )
-
- # What it would see if the swap happened first — nothing.
- assert _infer_ecosystem("/home/u/.npm/_npx/abc/node_modules/.bin/mcp-linear") is None
-
-
-def test_swap_happens_after_the_osv_call_in_source():
- """Structural guard for the ordering above.
-
- The swap and the preflight live in one async function; a future edit that
- moves the swap earlier would disable the malware gate silently, and no
- unit test of either piece alone would notice.
- """
- from pathlib import Path as _P
-
- src = _P(__file__).resolve().parents[2] / "tools" / "mcp_tool.py"
- text = src.read_text(encoding="utf-8")
- osv_needle = "check_package_for_malware, command, args"
- swap_needle = "cached = _npx_cached_bin(args)"
- # Report a rename explicitly: a bare .index() ValueError here reads like a
- # broken test rather than "someone renamed the thing this guards".
- assert osv_needle in text, (
- f"cannot find the OSV preflight call ({osv_needle!r}) — it was renamed; "
- "update this guard and re-verify the swap still happens after it"
- )
- assert swap_needle in text, (
- f"cannot find the npx swap ({swap_needle!r}) — it was renamed; update "
- "this guard and re-verify it still happens after the OSV preflight"
- )
-
- assert text.index(osv_needle) < text.index(swap_needle), (
- "the npx swap now precedes the OSV malware preflight, which silently "
- "disables it: _infer_ecosystem keys off the command basename being "
- "npx/uvx/pipx, so a rewritten command yields no ecosystem and "
- "check_package_for_malware returns None"
- )
+ target = _cache(tmp_path, package="mcp-linear", bin_field={"mcp-linear": "i.js"})
+ args = ["-y", "mcp-linear", "--port", "7"]
+ seen = []
+
+ def check(command, arguments):
+ seen.append((command, list(arguments)))
+ return "malicious package" if rejected else None
+
+ monkeypatch.setattr("tools.osv_check.check_package_for_malware", check)
+ if rejected:
+ monkeypatch.setattr(mcp_tool, "_npx_cached_bin", lambda *a: pytest.fail("cache read before refusal"))
+ with pytest.raises(ValueError, match="malicious package"):
+ asyncio.run(mcp_tool._preflight_stdio_command("server", "npx", args))
+ else:
+ assert asyncio.run(mcp_tool._preflight_stdio_command("server", "npx", args)) == (str(target), ["--port", "7"])
+ assert seen == [("npx", ["-y", "mcp-linear", "--port", "7"])]
def test_windows_selects_launchers_never_the_sh_script():
diff --git a/tests/tools/test_read_file_schema_gating.py b/tests/tools/test_read_file_schema_gating.py
index 24b2e36bbaa..0bd1b6afc38 100644
--- a/tests/tools/test_read_file_schema_gating.py
+++ b/tests/tools/test_read_file_schema_gating.py
@@ -100,27 +100,6 @@ class TestReadFileSchemaStatic(unittest.TestCase):
self.assertIsNone(key)
self.assertIsNone(url)
- def test_coverage_warning_teaching_left_to_the_warning(self):
- """The response-time warning owns the recovery curriculum."""
- from tools.file_tools import READ_FILE_SCHEMA
-
- desc = READ_FILE_SCHEMA["description"]
- self.assertNotIn("EXTRACTION COVERAGE WARNING", desc)
- self.assertNotIn("NEEDS OCR", desc)
- self.assertNotIn("pdftoppm", desc)
- import inspect
- from tools import read_extract
-
- src = inspect.getsource(read_extract)
- self.assertIn("NEEDS OCR", src)
- self.assertIn("pdftoppm", src)
- self.assertIn("vision_analyze", src)
-
- def test_binary_note_stays_last(self):
- from tools.file_tools import READ_FILE_SCHEMA
-
- desc = READ_FILE_SCHEMA["description"]
- self.assertLess(desc.find("EPUB"), desc.find("Cannot read images/binary"))
def test_missing_anydoc_error_teaches_install(self):
from tools.read_extract import _anydoc_missing_error
@@ -203,22 +182,15 @@ class TestNeedsOcrPath(unittest.TestCase):
self.assertNotIn("ocr-and-documents", out)
def test_pin_lockstep(self):
- """Core and doc-extract pins of firecrawl-anydoc must agree.
-
- tools/lazy_deps.py is gone; pyproject.toml is the single pin
- authority. The self-heal path is now pm.ensure_import("doc-extract"),
- which syncs the extra — so the remaining lockstep contract is that
- the core dependency pin and the doc-extract extra pin name the SAME
- version (a drift here means a lean install re-syncs a different
- anydoc than a full one).
- """
- import re
+ """Lean and full installs must resolve the same anydoc requirement."""
+ import tomllib
from pathlib import Path
+ from packaging.requirements import Requirement
- py = Path("pyproject.toml").read_text(encoding="utf-8-sig")
- pins = re.findall(r'"firecrawl-anydoc==([\d.]+)"', py)
- self.assertTrue(pins, "firecrawl-anydoc pin missing from pyproject")
- self.assertEqual(len(set(pins)), 1, f"pins disagree: {pins}")
+ project = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8-sig"))["project"]
+ core, extra = ({r.name: str(r.specifier) for r in map(Requirement, deps)} for deps in
+ (project["dependencies"], project["optional-dependencies"]["doc-extract"]))
+ self.assertEqual(core["firecrawl-anydoc"], extra["firecrawl-anydoc"])
if __name__ == "__main__":
diff --git a/tests/tools/test_skill_view_path_check.py b/tests/tools/test_skill_view_path_check.py
deleted file mode 100644
index 376ee9d90d1..00000000000
--- a/tests/tools/test_skill_view_path_check.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Tests for the skill_view path boundary check.
-
-Regression test: the original check used a hardcoded "/" separator which
-fails on Windows where Path.resolve() returns backslash-separated paths.
-Now uses Path.is_relative_to() which handles all platforms correctly.
-"""
-
-import pytest
-from pathlib import Path
-
-
-def _path_escapes_skill_dir(resolved: Path, skill_dir_resolved: Path) -> bool:
- """Reproduce the boundary check from tools/skills_tool.py.
-
- Returns True when the resolved path is OUTSIDE the skill directory.
- """
- return not resolved.is_relative_to(skill_dir_resolved)
-
-
-class TestSkillViewPathBoundaryCheck:
- """Verify the path boundary check works on all platforms."""
-
- def test_valid_subpath_allowed(self, tmp_path):
- """A file inside the skill directory must NOT be flagged."""
- skill_dir = tmp_path / "skills" / "axolotl"
- ref_file = skill_dir / "references" / "api.md"
- skill_dir.mkdir(parents=True)
- ref_file.parent.mkdir()
- ref_file.write_text("content")
-
- resolved = ref_file.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is False
-
-
- def test_outside_path_blocked(self, tmp_path):
- """A file outside the skill directory must be flagged."""
- skill_dir = tmp_path / "skills" / "axolotl"
- skill_dir.mkdir(parents=True)
- outside_file = tmp_path / "secret.env"
- outside_file.write_text("SECRET=123")
-
- resolved = outside_file.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is True
-
- def test_sibling_skill_dir_blocked(self, tmp_path):
- """A file in a sibling skill directory must be flagged.
-
- This catches prefix confusion: 'axolotl-v2' starts with 'axolotl'
- as a string but is a different directory.
- """
- skill_dir = tmp_path / "skills" / "axolotl"
- sibling_dir = tmp_path / "skills" / "axolotl-v2"
- skill_dir.mkdir(parents=True)
- sibling_dir.mkdir(parents=True)
- sibling_file = sibling_dir / "SKILL.md"
- sibling_file.write_text("other skill")
-
- resolved = sibling_file.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is True
-
- def test_skill_dir_itself_allowed(self, tmp_path):
- """Requesting the skill directory itself must be allowed."""
- skill_dir = tmp_path / "skills" / "axolotl"
- skill_dir.mkdir(parents=True)
-
- resolved = skill_dir.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is False
-
-
-class TestOldCheckWouldFail:
- """Demonstrate the bug: the old hardcoded '/' check fails on Windows."""
-
- def _old_path_escapes(self, resolved: Path, skill_dir_resolved: Path) -> bool:
- """The BROKEN check that used hardcoded '/'."""
- return (
- not str(resolved).startswith(str(skill_dir_resolved) + "/")
- and resolved != skill_dir_resolved
- )
-
- # ``platforms("windows")`` rather than ``skipif(os.sep == "/")``: the Windows CI
- # job greps for the marker to decide which files to import, so a bare
- # skipif leaves this running on no host at all.
- @pytest.mark.platforms("windows")
- def test_old_check_false_positive_on_windows(self, tmp_path):
- """On Windows, the old check incorrectly blocks valid subpaths."""
- skill_dir = tmp_path / "skills" / "axolotl"
- ref_file = skill_dir / "references" / "api.md"
- skill_dir.mkdir(parents=True)
- ref_file.parent.mkdir()
- ref_file.write_text("content")
-
- resolved = ref_file.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- # Old check says it escapes (WRONG on Windows)
- assert self._old_path_escapes(resolved, skill_dir_resolved) is True
- # New check correctly allows it
- assert _path_escapes_skill_dir(resolved, skill_dir_resolved) is False
diff --git a/tests/tools/test_skill_view_traversal.py b/tests/tools/test_skill_view_traversal.py
index cfa23e077eb..deab2b9376a 100644
--- a/tests/tools/test_skill_view_traversal.py
+++ b/tests/tools/test_skill_view_traversal.py
@@ -84,6 +84,7 @@ class TestPathTraversalBlocked:
assert result["success"] is False
assert "traversal" in result["error"].lower()
+ @pytest.mark.platforms("posix", "windows")
def test_legitimate_file_still_works(self, fake_skills):
"""Valid paths within the skill directory should work normally."""
result = json.loads(skill_view("test-skill", file_path="references/api.md"))
@@ -95,10 +96,13 @@ class TestPathTraversalBlocked:
result = json.loads(skill_view("test-skill"))
assert result["success"] is True
- def test_symlink_escape_blocked(self, fake_skills):
+ @pytest.mark.parametrize("sibling", [False, True])
+ def test_symlink_escape_blocked(self, fake_skills, sibling):
"""Symlinks pointing outside the skill directory should be blocked."""
skill_dir = fake_skills["skill_dir"]
- secret = fake_skills["tmp_path"] / "secret.txt"
+ outside = fake_skills["skills_dir"] / "test-skill-v2" if sibling else fake_skills["tmp_path"]
+ outside.mkdir(exist_ok=True)
+ secret = outside / "secret.txt"
secret.write_text("TOP SECRET DATA")
symlink = skill_dir / "evil-link"
@@ -111,6 +115,7 @@ class TestPathTraversalBlocked:
# The resolve() check should catch the symlink escaping
assert result["success"] is False
assert "escapes" in result["error"].lower() or "boundary" in result["error"].lower()
+ assert "TOP SECRET DATA" not in json.dumps(result)
def test_sensitive_file_not_leaked(self, fake_skills):
"""Even if traversal somehow passes, sensitive content must not leak."""
diff --git a/tests/tools/test_symlink_prefix_confusion.py b/tests/tools/test_symlink_prefix_confusion.py
deleted file mode 100644
index 80789129723..00000000000
--- a/tests/tools/test_symlink_prefix_confusion.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""Tests for the symlink boundary check prefix confusion fix in skills_guard.py.
-
-Regression test: the original check used startswith() without a trailing
-separator, so a symlink resolving to 'axolotl-backdoor/' passed the check
-for 'axolotl/' because the string prefix matched. Now uses
-Path.is_relative_to() which handles directory boundaries correctly.
-"""
-
-import pytest
-from pathlib import Path
-
-
-def _old_check_escapes(resolved: Path, skill_dir_resolved: Path) -> bool:
- """The BROKEN check that used startswith without separator.
-
- Returns True when the path is OUTSIDE the skill directory.
- """
- return (
- not str(resolved).startswith(str(skill_dir_resolved))
- and resolved != skill_dir_resolved
- )
-
-
-def _new_check_escapes(resolved: Path, skill_dir_resolved: Path) -> bool:
- """The FIXED check using is_relative_to().
-
- Returns True when the path is OUTSIDE the skill directory.
- """
- return not resolved.is_relative_to(skill_dir_resolved)
-
-
-class TestPrefixConfusionRegression:
- """The core bug: startswith() can't distinguish directory boundaries."""
-
- def test_old_check_misses_sibling_with_shared_prefix(self, tmp_path):
- """Old startswith check fails on sibling dirs that share a prefix."""
- skill_dir = tmp_path / "skills" / "axolotl"
- sibling_file = tmp_path / "skills" / "axolotl-backdoor" / "evil.py"
- skill_dir.mkdir(parents=True)
- sibling_file.parent.mkdir(parents=True)
- sibling_file.write_text("evil")
-
- resolved = sibling_file.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- # Bug: old check says the file is INSIDE the skill dir
- assert _old_check_escapes(resolved, skill_dir_resolved) is False
-
-
- def test_both_agree_on_completely_outside_path(self, tmp_path):
- """Both checks block a path that's completely outside."""
- skill_dir = tmp_path / "skills" / "axolotl"
- outside_file = tmp_path / "etc" / "passwd"
- skill_dir.mkdir(parents=True)
- outside_file.parent.mkdir(parents=True)
- outside_file.write_text("root:x:0:0")
-
- resolved = outside_file.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _old_check_escapes(resolved, skill_dir_resolved) is True
- assert _new_check_escapes(resolved, skill_dir_resolved) is True
-
- def test_skill_dir_itself_allowed(self, tmp_path):
- """Requesting the skill directory itself is fine."""
- skill_dir = tmp_path / "skills" / "axolotl"
- skill_dir.mkdir(parents=True)
-
- resolved = skill_dir.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- # Both should allow the dir itself
- assert _old_check_escapes(resolved, skill_dir_resolved) is False
- assert _new_check_escapes(resolved, skill_dir_resolved) is False
-
-
-def _can_symlink():
- """Check if we can create symlinks (needs admin/dev-mode on Windows)."""
- import tempfile
- try:
- with tempfile.TemporaryDirectory() as d:
- src = Path(d) / "src"
- src.write_text("x")
- lnk = Path(d) / "lnk"
- lnk.symlink_to(src)
- return True
- except OSError:
- return False
-
-
[email protected](not _can_symlink(), reason="Symlinks need elevated privileges")
-class TestSymlinkEscapeWithActualSymlinks:
- """Test the full symlink scenario with real filesystem symlinks."""
-
- def test_symlink_to_sibling_prefix_dir_detected(self, tmp_path):
- """A symlink from axolotl/ to axolotl-backdoor/ must be caught."""
- skills = tmp_path / "skills"
- skill_dir = skills / "axolotl"
- sibling_dir = skills / "axolotl-backdoor"
- skill_dir.mkdir(parents=True)
- sibling_dir.mkdir(parents=True)
-
- malicious = sibling_dir / "malicious.py"
- malicious.write_text("evil code")
-
- link = skill_dir / "helper.py"
- link.symlink_to(malicious)
-
- resolved = link.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- # Old check would miss this (prefix confusion)
- assert _old_check_escapes(resolved, skill_dir_resolved) is False
- # New check catches it
- assert _new_check_escapes(resolved, skill_dir_resolved) is True
-
- def test_symlink_within_skill_dir_allowed(self, tmp_path):
- """A symlink that stays within the skill directory is fine."""
- skill_dir = tmp_path / "my-skill"
- skill_dir.mkdir()
- real_file = skill_dir / "real.py"
- real_file.write_text("print('ok')")
- link = skill_dir / "alias.py"
- link.symlink_to(real_file)
-
- resolved = link.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _new_check_escapes(resolved, skill_dir_resolved) is False
-
- def test_symlink_to_parent_dir_blocked(self, tmp_path):
- """A symlink pointing outside (to parent) is blocked."""
- skill_dir = tmp_path / "skill"
- skill_dir.mkdir()
- outside = tmp_path / "secret.env"
- outside.write_text("SECRET=123")
-
- link = skill_dir / "config.env"
- link.symlink_to(outside)
-
- resolved = link.resolve()
- skill_dir_resolved = skill_dir.resolve()
-
- assert _new_check_escapes(resolved, skill_dir_resolved) is True
diff --git a/tests/tools/test_tirith_security.py b/tests/tools/test_tirith_security.py
deleted file mode 100644
index ee32ea09b6e..00000000000
--- a/tests/tools/test_tirith_security.py
+++ /dev/null
@@ -1,316 +0,0 @@
-"""Tests for the tirith security scanning subprocess wrapper."""
-
-import json
-import subprocess
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-import tools.tirith_security as _tirith_mod
-from tools.tirith_security import check_command_security
-
-
[email protected](autouse=True)
-def _scan_boundary(monkeypatch):
- """Acquisition is exercised by test_security_consumers; isolate verdict rules."""
- monkeypatch.setattr(_tirith_mod, "_resolve_tirith_path", lambda configured: "tirith")
- monkeypatch.setattr(_tirith_mod, "_crash_count", 0)
- monkeypatch.setattr(_tirith_mod, "_circuit_open", False)
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-def _mock_run(returncode=0, stdout="", stderr=""):
- """Build a mock subprocess.CompletedProcess."""
- cp = MagicMock(spec=subprocess.CompletedProcess)
- cp.returncode = returncode
- cp.stdout = stdout
- cp.stderr = stderr
- return cp
-
-
-def _json_stdout(findings=None, summary=""):
- return json.dumps({"findings": findings or [], "summary": summary})
-
-
-# ---------------------------------------------------------------------------
-# Exit code → action mapping
-# ---------------------------------------------------------------------------
-
-class TestExitCodeMapping:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_exit_0_allow(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- mock_run.return_value = _mock_run(0, _json_stdout())
- result = check_command_security("echo hello")
- assert result["action"] == "allow"
- assert result["findings"] == []
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_exit_1_block_with_findings(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- findings = [{"rule_id": "homograph_url", "severity": "high"}]
- mock_run.return_value = _mock_run(1, _json_stdout(findings, "homograph detected"))
- result = check_command_security("curl http://gооgle.com")
- assert result["action"] == "block"
- assert len(result["findings"]) == 1
- assert result["summary"] == "homograph detected"
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_exit_2_warn_with_findings(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- findings = [{"rule_id": "shortened_url", "severity": "medium"}]
- mock_run.return_value = _mock_run(2, _json_stdout(findings, "shortened URL"))
- result = check_command_security("curl https://bit.ly/abc")
- assert result["action"] == "warn"
- assert len(result["findings"]) == 1
- assert result["summary"] == "shortened URL"
-
-
-# ---------------------------------------------------------------------------
-# JSON parse failure (exit code still wins)
-# ---------------------------------------------------------------------------
-
-class TestJsonParseFailure:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_exit_1_invalid_json_still_blocks(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- mock_run.return_value = _mock_run(1, "NOT JSON")
- result = check_command_security("bad command")
- assert result["action"] == "block"
- assert "details unavailable" in result["summary"]
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_exit_0_invalid_json_allows(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- mock_run.return_value = _mock_run(0, "NOT JSON")
- result = check_command_security("safe command")
- assert result["action"] == "allow"
-
-
-# ---------------------------------------------------------------------------
-# Operational failures + fail_open
-# ---------------------------------------------------------------------------
-
-class TestOSErrorFailOpen:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_file_not_found_fail_open(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- mock_run.side_effect = FileNotFoundError("No such file: tirith")
- result = check_command_security("echo hi")
- assert result["action"] == "allow"
- assert "unavailable" in result["summary"]
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_os_error_fail_closed(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": False}
- mock_run.side_effect = FileNotFoundError("No such file: tirith")
- result = check_command_security("echo hi")
- assert result["action"] == "block"
- assert "fail-closed" in result["summary"]
-
-
-class TestTimeoutFailOpen:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_timeout_fail_closed(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": False}
- mock_run.side_effect = subprocess.TimeoutExpired(cmd="tirith", timeout=5)
- result = check_command_security("slow command")
- assert result["action"] == "block"
- assert "fail-closed" in result["summary"]
-
-
-class TestUnknownExitCode:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_unknown_exit_code_fail_closed(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": False}
- mock_run.return_value = _mock_run(99, "")
- result = check_command_security("cmd")
- assert result["action"] == "block"
- assert "exit code 99" in result["summary"]
-
-
-# ---------------------------------------------------------------------------
-# Disabled
-# ---------------------------------------------------------------------------
-
-class TestDisabled:
- @patch("tools.tirith_security._load_security_config")
- def test_disabled_returns_allow(self, mock_cfg):
- mock_cfg.return_value = {"tirith_enabled": False, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- result = check_command_security("rm -rf /")
- assert result["action"] == "allow"
-
-
-# ---------------------------------------------------------------------------
-# Findings cap + summary cap
-# ---------------------------------------------------------------------------
-
-class TestCaps:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_findings_and_summary_capped(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- findings = [{"rule_id": f"rule_{i}"} for i in range(100)]
- mock_run.return_value = _mock_run(2, _json_stdout(findings, "x" * 1000))
- result = check_command_security("cmd")
- assert len(result["findings"]) == 50
- assert len(result["summary"]) == 500
-
-
-# ---------------------------------------------------------------------------
-# Programming errors propagate
-# ---------------------------------------------------------------------------
-
-class TestProgrammingErrors:
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_attribute_error_propagates(self, mock_cfg, mock_run):
- mock_cfg.return_value = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
- mock_run.side_effect = AttributeError("unexpected bug")
- with pytest.raises(AttributeError):
- check_command_security("cmd")
-
-
-# ---------------------------------------------------------------------------
-# Warn-once dedupe (issue: tirith spawn failed spamming on Windows)
-# ---------------------------------------------------------------------------
-
-class TestSpawnWarningDedup:
- """When tirith isn't installed yet (background install in flight, or
- install marked failed), every terminal command spammed an identical
- ``tirith spawn failed: [WinError 2]`` warning to ``errors.log``. The
- dedupe set in ``_warn_once`` collapses repeats by ``(exc class, errno)``
- while still surfacing the first occurrence so users see the failure.
- """
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_repeated_spawn_failure_logs_once(self, mock_cfg, mock_run, caplog):
- mock_cfg.return_value = {
- "tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True,
- }
- mock_run.side_effect = FileNotFoundError("[WinError 2]")
- # Fresh dedupe state — clear any keys left by other tests.
- _tirith_mod._warned_messages.clear()
-
- with caplog.at_level("WARNING", logger="tools.tirith_security"):
- for i in range(15):
- result = check_command_security("echo hi")
- # Behavior must remain the same on every call —
- # fail-open allow, with the exception captured in summary.
- assert result["action"] == "allow"
- if i < _tirith_mod._CRASH_LIMIT:
- # Before circuit breaker opens, summary has the exception
- assert "unavailable" in result["summary"]
- else:
- # After circuit breaker opens, summary is generic
- assert "circuit breaker" in result["summary"]
-
- spawn_warnings = [
- rec for rec in caplog.records
- if "tirith spawn failed" in rec.message
- ]
- assert len(spawn_warnings) == 1, (
- f"expected exactly 1 spawn-failed warning across 15 commands, "
- f"got {len(spawn_warnings)}: {[r.message for r in spawn_warnings]}"
- )
-
-
-# ---------------------------------------------------------------------------
-# .app TLD suppression (issue #24461)
-# ---------------------------------------------------------------------------
-
-_CFG = {"tirith_enabled": True, "tirith_path": "tirith",
- "tirith_timeout": 5, "tirith_fail_open": True}
-
-
-class TestAppTldSuppression:
- """warn verdicts whose only finding is lookalike_tld/.app are downgraded to allow."""
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_app_only_warn_downgraded_to_allow(self, mock_cfg, mock_run):
- mock_cfg.return_value = _CFG
- findings = [{"rule_id": "lookalike_tld", "value": ".app",
- "message": "Domain uses '.app' TLD which can be confused with file extensions"}]
- mock_run.return_value = _mock_run(2, _json_stdout(findings, ".app TLD warning"))
- result = check_command_security("curl https://example.app")
- assert result["action"] == "allow"
- assert result["findings"] == []
- assert result["summary"] == ""
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_mixed_findings_preserve_warn(self, mock_cfg, mock_run):
- """If .app finding is accompanied by another finding, warn is preserved."""
- mock_cfg.return_value = _CFG
- findings = [
- {"rule_id": "lookalike_tld", "value": ".app"},
- {"rule_id": "shortened_url", "severity": "medium"},
- ]
- mock_run.return_value = _mock_run(2, _json_stdout(findings, "mixed"))
- result = check_command_security("curl https://bit.ly/test.app")
- assert result["action"] == "warn"
- assert len(result["findings"]) == 2
-
- @patch("tools.tirith_security.subprocess.run")
- @patch("tools.tirith_security._load_security_config")
- def test_block_verdict_never_suppressed(self, mock_cfg, mock_run):
- """block exit code is never downgraded, even if finding looks like .app."""
- mock_cfg.return_value = _CFG
- findings = [{"rule_id": "lookalike_tld", "value": ".app"}]
- mock_run.return_value = _mock_run(1, _json_stdout(findings, "block"))
- result = check_command_security("curl https://example.app")
- assert result["action"] == "block"
-
-
-class TestIsAppTldFinding:
- """Unit tests for the _is_app_tld_finding helper."""
-
- @pytest.mark.parametrize("finding, expected", [
- ({"rule_id": "lookalike_tld", "value": ".APP"}, True), # case-insensitive
- ({"rule_id": "lookalike_tld", "message": "Domain uses '.app' TLD"}, True),
- ({"rule_id": "shortened_url", "value": ".app"}, False), # wrong rule_id
- ({"rule_id": "lookalike_tld", "value": ".zip"}, False), # other TLD
- ])
- def test_app_tld_detection(self, finding, expected):
- from tools.tirith_security import _is_app_tld_finding
- assert _is_app_tld_finding(finding) is expected
-
-
-# ---------------------------------------------------------------------------
-# mkdtemp OSError → no_space (disk-full leak prevention)
diff --git a/tests/tools/test_tirith_verdicts.py b/tests/tools/test_tirith_verdicts.py
new file mode 100644
index 00000000000..112f58a5766
--- /dev/null
+++ b/tests/tools/test_tirith_verdicts.py
@@ -0,0 +1,119 @@
+"""Independent verdict rows; PM security-consumers owns acquisition/provenance."""
+import json
+import subprocess
+
+import pytest
+
+from tools import tirith_security as tirith
+
+
+def scan(monkeypatch):
+ config = {"tirith_enabled": True, "tirith_path": "/fixture/tirith",
+ "tirith_timeout": 5, "tirith_fail_open": True}
+ monkeypatch.setattr(tirith, "_load_security_config", lambda: config)
+ monkeypatch.setattr(tirith, "_resolve_tirith_path", lambda path: path)
+ monkeypatch.setattr(tirith, "_crash_count", 0)
+ monkeypatch.setattr(tirith, "_circuit_open", False)
+ monkeypatch.setattr(tirith, "_warned_messages", set())
+ return config
+
+
[email protected]("code,valid,fail_open,action", [
+ (0, True, True, "allow"), (1, True, True, "block"), (2, True, True, "warn"),
+ (0, False, True, "allow"), (1, False, True, "block"), (2, False, True, "warn"),
+ (99, False, True, "allow"), (99, False, False, "block"),
+])
+def test_exit_code_is_authority(scan, monkeypatch, code, valid, fail_open, action):
+ scan["tirith_fail_open"] = fail_open
+ body = json.dumps({"findings": [{"rule_id": "homograph"}], "summary": "diagnostic"}) if valid else "NOT JSON"
+ monkeypatch.setattr(subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, code, body, ""))
+ result = tirith.check_command_security("curl https://example.test")
+ assert result["action"] == action
+ if valid:
+ assert result["findings"] == [{"rule_id": "homograph"}]
+ assert result["summary"] == "diagnostic"
+ else:
+ assert result["findings"] == []
+ if code == 99:
+ assert "exit code 99" in result["summary"]
+ elif code:
+ assert "details unavailable" in result["summary"]
+
+
[email protected]("error", [FileNotFoundError("missing"), subprocess.TimeoutExpired("tirith", 5)])
[email protected]("fail_open,action", [(True, "allow"), (False, "block")])
+def test_operational_error_policy(scan, monkeypatch, error, fail_open, action):
+ scan["tirith_fail_open"] = fail_open
+ def fail(*a, **kw):
+ raise error
+ monkeypatch.setattr(subprocess, "run", fail)
+ result = tirith.check_command_security("echo safe")
+ assert result["action"] == action
+ assert ("fail-closed" in result["summary"]) is (not fail_open)
+
+
+def test_circuit_dedup_and_success_reset(scan, monkeypatch, caplog):
+ calls = []
+ def fail(*a, **kw):
+ calls.append(a)
+ raise FileNotFoundError("missing")
+ monkeypatch.setattr(subprocess, "run", fail)
+ with caplog.at_level("WARNING", logger=tirith.__name__):
+ tirith.check_command_security("one")
+ monkeypatch.setattr(subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 0, "{}", ""))
+ tirith.check_command_security("healthy")
+ assert tirith._crash_count == 0
+ monkeypatch.setattr(subprocess, "run", fail)
+ for _ in range(tirith._CRASH_LIMIT):
+ assert "unavailable" in tirith.check_command_security("fail")["summary"]
+ scan["tirith_fail_open"] = False
+ assert tirith.check_command_security("after") == {
+ "action": "allow", "findings": [], "summary": "tirith disabled (circuit breaker)"}
+ assert len(calls) == 1 + tirith._CRASH_LIMIT
+ assert sum("tirith spawn failed" in r.message for r in caplog.records) == 1
+
+
[email protected]("code,findings,expected", [
+ (2, [{"rule_id": "lookalike_tld", "value": ".app"}], "allow"),
+ (2, [{"rule_id": "lookalike_tld", "value": ".APP"}], "allow"),
+ (2, [{"rule_id": "lookalike_tld", "message": "Domain uses '.app' TLD"}], "allow"),
+ (2, [{"rule_id": "shortened_url", "value": ".app"}], "warn"),
+ (2, [{"rule_id": "lookalike_tld", "value": ".zip"}], "warn"),
+ (2, [{"rule_id": "lookalike_tld", "value": ".app"}, {"rule_id": "shortened_url"}], "warn"),
+ (1, [{"rule_id": "lookalike_tld", "value": ".app"}], "block"),
+])
+def test_app_warning_exception_never_downgrades_block(scan, monkeypatch, code, findings, expected):
+ body = json.dumps({"findings": findings, "summary": "finding"})
+ monkeypatch.setattr(subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, code, body, ""))
+ result = tirith.check_command_security("curl https://example.app")
+ assert result == {"action": expected, "findings": [] if expected == "allow" else findings,
+ "summary": "" if expected == "allow" else "finding"}
+
+
+def test_caps_disabled_and_programming_errors(scan, monkeypatch):
+ body = json.dumps({"findings": [{"rule_id": "other"}] * 100, "summary": "x" * 1000})
+ monkeypatch.setattr(subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 2, body, ""))
+ result = tirith.check_command_security("echo safe")
+ assert len(result["findings"]) == 50 and len(result["summary"]) == 500
+ def bug(*a, **kw):
+ raise AttributeError("programming error")
+ monkeypatch.setattr(subprocess, "run", bug)
+ with pytest.raises(AttributeError, match="programming error"):
+ tirith.check_command_security("echo safe")
+ scan["tirith_enabled"] = False
+ assert tirith.check_command_security("anything")["action"] == "allow"
+
+
+def test_windows_default_never_scans_but_override_does(scan, monkeypatch):
+ scan["tirith_path"] = "tirith"
+ def forbidden(*a, **kw):
+ pytest.fail("unsupported default must not scan or install")
+ monkeypatch.setattr(subprocess, "run", forbidden)
+ monkeypatch.setattr(tirith.threading.Thread, "start", forbidden)
+ assert tirith.check_command_security("echo safe")["action"] == "allow"
+ assert tirith.ensure_installed() is None
+ scan["tirith_path"] = r"C:\fixture\tirith.exe"
+ monkeypatch.setattr(subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 1, "{}", ""))
+ assert tirith.check_command_security("command")["action"] == "block"
diff --git a/tests/tools/test_transcription_tools.py b/tests/tools/test_transcription_tools.py
index 1cd4725e925..58f2d64eeea 100644
--- a/tests/tools/test_transcription_tools.py
+++ b/tests/tools/test_transcription_tools.py
@@ -1187,66 +1187,35 @@ class TestTranscribeCredentialReadGuard:
assert result["error"] == expected
-class TestRunCommandSttIdleTimeout:
- """_run_command_stt uses a progress-based idle timeout (mirrors TTS runner)."""
-
- @staticmethod
- def _shell_command(*args):
- import shlex
- if os.name == "nt":
- return subprocess.list2cmdline(list(args))
- return " ".join(shlex.quote(str(arg)) for arg in args)
-
- def test_stderr_progress_extends_beyond_timeout(self, tmp_path):
- """A slow-but-alive command that keeps emitting output survives an
- idle timeout shorter than its total runtime."""
- from tools.transcription_command import _run_command_stt
-
- script = tmp_path / "progress_then_exit.py"
- # Ticks span >2s so the idle deadline MUST be reset by progress: a
- # one-shot timeout of 2.0s would kill the child before it exits.
- script.write_text(
- "\n".join([
- "import sys, time",
- "for idx in range(6):",
- " print(f'tick {idx}', file=sys.stderr, flush=True)",
- " time.sleep(0.6)",
- "print('done', flush=True)",
- ]),
- encoding="utf-8",
- )
-
- result = _run_command_stt(
- self._shell_command(sys.executable, "-u", str(script)),
- timeout=2.0,
- )
-
- assert result.returncode == 0
- assert "tick 3" in result.stderr
- assert "done" in result.stdout
-
- def test_silent_stall_still_times_out(self, tmp_path):
- """A silently stalled command is killed once the idle window elapses,
- and pre-stall output is preserved on the TimeoutExpired."""
- from tools.transcription_command import _run_command_stt
-
- script = tmp_path / "progress_then_hang.py"
- script.write_text(
- "\n".join([
- "import sys, time",
- "print('starting pass 1', file=sys.stderr, flush=True)",
- "time.sleep(30)",
- ]),
- encoding="utf-8",
- )
-
- with pytest.raises(subprocess.TimeoutExpired) as excinfo:
- _run_command_stt(
- self._shell_command(sys.executable, "-u", str(script)),
- timeout=2.0,
- )
-
- assert "starting pass 1" in (excinfo.value.stderr or "")
[email protected]("posix", "windows")
[email protected]("progress", [True, False])
+def test_command_stt_idle_timeout_preserves_transcription_contract(tmp_path, progress):
+ import shlex
+ from tools.transcription_command import _transcribe_command_stt
+
+ audio = tmp_path / "audio.wav"
+ audio.write_bytes(b"fixture audio")
+ script = tmp_path / "transcribe.py"
+ script.write_text(
+ "import sys, time\n"
+ "from pathlib import Path\n"
+ "assert Path(sys.argv[1]).read_bytes() == b'fixture audio'\n"
+ + ("for i in range(6):\n print('progress', file=sys.stderr, flush=True)\n time.sleep(.6)\n"
+ if progress else "time.sleep(30)\n")
+ + "Path(sys.argv[2]).write_text('actual transcript', encoding='utf-8')\n",
+ encoding="utf-8",
+ )
+ args = [sys.executable, "-u", str(script)]
+ command = subprocess.list2cmdline(args) if os.name == "nt" else shlex.join(args)
+ result = _transcribe_command_stt(str(audio), "probe", {
+ "command": command + " {input_path} {output_path}", "timeout": 2,
+ }, {})
+ assert result["success"] is progress
+ assert result["provider"] == "probe"
+ if progress:
+ assert result["transcript"] == "actual transcript"
+ else:
+ assert "STT command provider 'probe' timed out after 2s" in result["error"]
# ============================================================================
diff --git a/tests/tools/test_tts_importers.py b/tests/tools/test_tts_importers.py
new file mode 100644
index 00000000000..4b6b17a796a
--- /dev/null
+++ b/tests/tools/test_tts_importers.py
@@ -0,0 +1,69 @@
+"""SDK import fallback uses the real import system and exact PM feature mapping."""
+import importlib
+import sys
+from contextlib import nullcontext
+from unittest.mock import MagicMock
+
+import pytest
+
+import pm
+from tools import tts_tool
+
+
[email protected]("importer,module,attribute,feature", [
+ (tts_tool._import_edge_tts, "edge_tts", None, "edge-tts"),
+ (tts_tool._import_elevenlabs, "elevenlabs.client", "ElevenLabs", "tts-premium"),
+ (tts_tool._import_mistral_client, "mistralai.client", "Mistral", "mistral"),
+])
[email protected]("missing,install_fails", [(False, False), (False, True), (True, True)])
+def test_sdk_import_fallback(tmp_path, monkeypatch, importer, module, attribute, feature, missing, install_fails):
+ parts = module.split(".")
+ for name in list(sys.modules):
+ if name == parts[0] or name.startswith(parts[0] + "."):
+ monkeypatch.delitem(sys.modules, name)
+ if missing:
+ monkeypatch.setitem(sys.modules, parts[0], None)
+ else:
+ package = tmp_path / parts[0]
+ package.mkdir()
+ (package / "__init__.py").write_text("marker = 'installed outside venv'\n", encoding="utf-8")
+ if attribute:
+ (package / "client.py").write_text(f"class {attribute}: pass\n", encoding="utf-8")
+ monkeypatch.syspath_prepend(str(tmp_path))
+ ensure = MagicMock(side_effect=pm.InstallError(feature, "fixture refusal") if install_fails else None)
+ monkeypatch.setattr(pm, "ensure_import", ensure)
+ with pytest.raises(ImportError) if missing else nullcontext():
+ result = importer()
+ loaded = importlib.import_module(module)
+ assert result is (getattr(loaded, attribute) if attribute else loaded)
+ assert str(tmp_path) in loaded.__file__
+ ensure.assert_called_once_with(feature)
+
+
+def test_mistral_stt_fallback_reads_audio_and_requires_key(tmp_path, monkeypatch):
+ from tools import transcription_tools
+
+ audio = tmp_path / "speech.wav"
+ audio.write_bytes(b"fixture-audio")
+ calls = []
+
+ def complete(**kwargs):
+ calls.append((kwargs["model"], kwargs["file"]["content"].read()))
+ return {"text": "hello"}
+
+ client = MagicMock()
+ client.return_value.__enter__.return_value.audio.transcriptions.complete.side_effect = complete
+ module = type(sys)("mistralai.client")
+ module.Mistral = client
+ monkeypatch.setitem(sys.modules, "mistralai.client", module)
+ ensure = MagicMock(side_effect=pm.InstallError("mistral", "fixture refusal"))
+ monkeypatch.setattr(pm, "ensure_import", ensure)
+ monkeypatch.setattr(transcription_tools, "_resolve_provider_key", lambda *a: "test-key")
+ result = transcription_tools._transcribe_mistral(str(audio), "fixture-model")
+ assert result["success"] and result["transcript"] == "hello"
+ assert calls == [("fixture-model", b"fixture-audio")]
+ client.assert_called_once_with(api_key="test-key")
+ ensure.assert_called_once_with("mistral")
+ monkeypatch.setattr(transcription_tools, "_resolve_provider_key", lambda *a: "")
+ assert "MISTRAL_API_KEY not set" in transcription_tools._transcribe_mistral(str(audio), "fixture-model")["error"]
+ assert len(calls) == 1
diff --git a/tests/tools/test_tts_lifecycle_leases.py b/tests/tools/test_tts_lifecycle_leases.py
index 79155e23166..2600e6f7255 100644
--- a/tests/tools/test_tts_lifecycle_leases.py
+++ b/tests/tools/test_tts_lifecycle_leases.py
@@ -117,28 +117,37 @@ def test_warm_is_noop_for_cloud_provider_without_lazy_sdk(monkeypatch):
assert result == {"provider": "openai", "warmed": False, "action": "noop"}
-def test_warm_lazy_sdk_provider_reports_cached_when_installed(monkeypatch):
- import pm
-
- monkeypatch.setattr(pm, "available", lambda extra: extra == "edge-tts")
- monkeypatch.setattr(
- pm, "ensure_import",
- lambda *a, **k: pytest.fail("ensure_import must not run when the SDK is present"),
- )
- result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})
- assert result["warmed"] is True
- assert result["action"] == "cached"
-
-
-def test_warm_lazy_sdk_provider_installs_when_missing(monkeypatch):
[email protected]("installed", [True, False])
+def test_warm_sdk_uses_pm_availability_and_refuses_inactive_generation(tmp_path, monkeypatch, installed):
import pm
+ import pm.client
+ import pm.paths
+ import pm.extras
+ from hermes_cli.runtime_paths import runtime_facts_path
calls = []
- monkeypatch.setattr(pm, "available", lambda extra: False)
- monkeypatch.setattr(pm, "ensure_import", lambda extra: calls.append(extra))
+ root = tmp_path / "repo"
+ root.mkdir()
+ monkeypatch.setattr(pm.paths, "repo_root", lambda: root)
+ # The real anchor probe sees a real temporary module, or an absent anchor.
+ (tmp_path / "warm_sdk_probe.py").write_text("ready = True\n", encoding="utf-8")
+ monkeypatch.syspath_prepend(str(tmp_path))
+ monkeypatch.setattr(pm.extras, "_anchors", lambda extra: ("warm_sdk_probe" if installed else "absent_warm_sdk_probe",))
+ candidate = runtime_facts_path(root).parent / "environments/new/venv"
+ candidate.mkdir(parents=True)
+ (candidate / "pyvenv.cfg").write_text("home = fixture\n", encoding="utf-8")
+
+ def prepare(extras):
+ calls.append(extras)
+ pm.Facts(runtime_facts_path(root)).record_state("venv", "new", extras, environment=candidate)
+
+ monkeypatch.setattr(pm.client, "sync_venv", prepare)
result = tts_tool_lifecycle.warm_tts_provider({"provider": "edge"})
- assert result["action"] == "installed"
- assert calls == ["edge-tts"]
+ assert result["warmed"] is installed
+ assert result["action"] == ("cached" if installed else "error")
+ assert calls == ([] if installed else [["edge-tts"]])
+ if not installed:
+ assert "restart" in result["error"]
# --------------------------------------------------------------------------
diff --git a/tests/tools/test_tts_pythonpath_fallback.py b/tests/tools/test_tts_pythonpath_fallback.py
deleted file mode 100644
index 09ebdc2fb3f..00000000000
--- a/tests/tools/test_tts_pythonpath_fallback.py
+++ /dev/null
@@ -1,147 +0,0 @@
-"""Regression tests for #53259.
-
-When TTS/STT packages (edge-tts, elevenlabs, mistralai) installed outside
-the venv but importable on sys.path (e.g. via PYTHONPATH, Docker layered
-filesystems), the lazy-import helpers must fall through to the raw import
-instead of re-raising pm.ensure_import() failures as ImportError.
-
-Uses sys.modules fixtures so builtins.__import__ stays intact — patching
-__import__ replaces the helper's own ``from pm import ...``
-and defeats the purpose of the test.
-"""
-
-import sys
-from unittest.mock import MagicMock, patch
-
-import pytest
-
-from pm import InstallError as FeatureUnavailable
-
-
[email protected](autouse=True)
-def _clean_tts_modules():
- """Remove TTS packages from sys.modules so each test starts fresh."""
- removed = {}
- for name in ("edge_tts", "elevenlabs", "elevenlabs.client",
- "mistralai", "mistralai.client"):
- if name in sys.modules:
- removed[name] = sys.modules.pop(name)
- yield
- for name in ("edge_tts", "elevenlabs", "elevenlabs.client",
- "mistralai", "mistralai.client"):
- sys.modules.pop(name, None)
- sys.modules.update(removed)
-
-
-class TestEdgeTtsPythonpathFallback:
- def test_falls_through_on_install_failure(self):
- """FeatureUnavailable from ensure() must not prevent raw import."""
- mock_edge_tts = MagicMock()
- with patch.dict(sys.modules, {"edge_tts": mock_edge_tts}), \
- patch("pm.ensure_import",
- side_effect=FeatureUnavailable("edge-tts", "test")):
- from tools.tts_tool import _import_edge_tts
- result = _import_edge_tts()
- assert result is mock_edge_tts
-
- def test_raises_when_package_truly_missing(self):
- """When the package is truly absent, ImportError must propagate."""
- with patch("pm.ensure_import"), \
- patch.dict(sys.modules, {"edge_tts": None}):
- from tools.tts_tool import _import_edge_tts
- with pytest.raises(ImportError):
- _import_edge_tts()
-
-
-class TestElevenLabsPythonpathFallback:
- def test_falls_through_on_install_failure(self):
- """FeatureUnavailable from ensure() must not prevent raw import."""
- mock_cls = MagicMock()
- mock_client_pkg = MagicMock()
- mock_client_pkg.ElevenLabs = mock_cls
- with patch.dict(sys.modules, {
- "elevenlabs": mock_client_pkg,
- "elevenlabs.client": mock_client_pkg,
- }), patch("pm.ensure_import",
- side_effect=FeatureUnavailable("tts-premium", "test")):
- from tools.tts_tool import _import_elevenlabs
- result = _import_elevenlabs()
- assert result is mock_cls
-
- def test_raises_when_package_truly_missing(self):
- """When the package is truly absent, ImportError must propagate."""
- with patch("pm.ensure_import"), \
- patch.dict(sys.modules, {"elevenlabs": None,
- "elevenlabs.client": None}):
- from tools.tts_tool import _import_elevenlabs
- with pytest.raises(ImportError):
- _import_elevenlabs()
-
-
-class TestMistralPythonpathFallback:
- def test_falls_through_on_install_failure(self):
- """FeatureUnavailable from ensure() must not prevent raw import."""
- mock_cls = MagicMock()
- mock_mistralai = MagicMock()
- mock_mistralai.Mistral = mock_cls
- with patch.dict(sys.modules, {
- "mistralai": mock_mistralai,
- "mistralai.client": mock_mistralai,
- }), patch("pm.ensure_import",
- side_effect=FeatureUnavailable("mistral", "test")):
- from tools.tts_tool import _import_mistral_client
- result = _import_mistral_client()
- assert result is mock_cls
-
- def test_raises_when_package_truly_missing(self):
- """When the package is truly absent, ImportError must propagate."""
- with patch("pm.ensure_import"), \
- patch.dict(sys.modules, {"mistralai": None,
- "mistralai.client": None}):
- from tools.tts_tool import _import_mistral_client
- with pytest.raises(ImportError):
- _import_mistral_client()
-
-
-# ── STT: _transcribe_mistral fallthrough ───────────────────────────────────
-
-
-class TestMistralSttPythonpathFallback:
- def test_transcribe_mistral_falls_through_on_install_failure(
- self, tmp_path,
- ):
- """InstallError from ensure_import('mistral') must not block
- transcription when mistralai is importable via PYTHONPATH."""
- from tools.transcription_tools import _transcribe_mistral
-
- audio_file = tmp_path / "audio.wav"
- audio_file.write_bytes(b"fake-audio")
-
- mock_client_cls = MagicMock()
- mock_result = MagicMock()
- mock_result.text = "hello world"
- mock_client_cls.return_value.__enter__ = MagicMock(
- return_value=MagicMock(
- audio=MagicMock(
- transcriptions=MagicMock(
- complete=MagicMock(return_value=mock_result),
- ),
- ),
- ),
- )
- mock_client_cls.return_value.__exit__ = MagicMock(return_value=False)
-
- mock_mistralai = MagicMock()
- mock_mistralai.Mistral = mock_client_cls
-
- with patch.dict(sys.modules, {
- "mistralai": mock_mistralai,
- "mistralai.client": mock_mistralai,
- }), patch("pm.ensure_import",
- side_effect=FeatureUnavailable("mistral", "test")), \
- patch("tools.transcription_tools.get_env_value",
- return_value="test-key"):
- result = _transcribe_mistral(str(audio_file), "mistral-large-latest")
-
- assert result["success"] is True
- assert result["transcript"] == "hello world"
diff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.py
index 039004921b3..cf0801fb1e9 100644
--- a/tests/tools/test_wake_word.py
+++ b/tests/tools/test_wake_word.py
@@ -450,74 +450,6 @@ def test_bundled_hey_hermes_model_ships_on_disk():
assert os.path.getsize(path) > 1024, path
-# ── sherpa-onnx open-vocabulary engine ───────────────────────────────────
-
-
-def _install_fake_sherpa(monkeypatch, tmp_path):
- """Fake sherpa_onnx + a fake model dir so the engine builds offline."""
- calls = {"text2token": [], "spotter": [], "results": []}
-
- model_dir = tmp_path / "kws-model"
- model_dir.mkdir()
- for name in (
- "tokens.txt",
- "bpe.model",
- "encoder-epoch-12-avg-2-chunk-16-left-64.onnx",
- "decoder-epoch-12-avg-2-chunk-16-left-64.onnx",
- "joiner-epoch-12-avg-2-chunk-16-left-64.onnx",
- ):
- (model_dir / name).write_bytes(b"x")
-
- class _FakeStream:
- def accept_waveform(self, sample_rate, samples):
- pass
-
- class _FakeSpotter:
- def __init__(self, **kwargs):
- calls["spotter"].append(kwargs)
-
- def create_stream(self):
- return _FakeStream()
-
- def is_ready(self, stream):
- return bool(calls["results"])
-
- def decode_stream(self, stream):
- pass
-
- def get_result(self, stream):
- return calls["results"].pop(0) if calls["results"] else ""
-
- def reset_stream(self, stream):
- pass
-
- def _fake_text2token(phrases, tokens, tokens_type, bpe_model):
- calls["text2token"].append(list(phrases))
- return [p.split() for p in phrases]
-
- sherpa = types.ModuleType("sherpa_onnx")
- sherpa.KeywordSpotter = _FakeSpotter
- sherpa.text2token = _fake_text2token
- monkeypatch.setitem(sys.modules, "sherpa_onnx", sherpa)
- monkeypatch.setattr(pm, "ensure_import", lambda *a, **k: None)
-
- # numpy is an optional voice-extra dep, lazy-installed at runtime — CI's
- # hermetic slices don't have it. process() only calls asarray(...)/32768,
- # so a minimal stub keeps these tests runnable without the real package.
- if "numpy" not in sys.modules:
- class _FakeArr(list):
- def __truediv__(self, other):
- return self
-
- np_stub = types.ModuleType("numpy")
- np_stub.float32 = "float32"
- np_stub.asarray = lambda x, dtype=None: _FakeArr(x)
- monkeypatch.setitem(sys.modules, "numpy", np_stub)
- return calls, model_dir
-
-
-# ── Multi-profile phrase routing ─────────────────────────────────────────
-
# ── Detector loop ────────────────────────────────────────────────────────
diff --git a/tests/tools/test_zombie_process_cleanup.py b/tests/tools/test_zombie_process_cleanup.py
index 45d761280d3..71a47726e9c 100644
--- a/tests/tools/test_zombie_process_cleanup.py
+++ b/tests/tools/test_zombie_process_cleanup.py
@@ -31,69 +31,6 @@ def _pid_alive(pid: int) -> bool:
return False
-class TestZombieReproduction:
- """Demonstrate that subprocesses survive when cleanup is not called."""
-
- @pytest.mark.platforms("linux")
- def test_orphaned_processes_survive_without_cleanup(self):
- """REPRODUCTION: processes spawned directly survive if no one kills
- them — this models the gap that causes zombie accumulation when
- the gateway drops agent references without calling close()."""
- pids = []
-
- try:
- for _ in range(3):
- proc = _spawn_sleep(60)
- pids.append(proc.pid)
-
- for pid in pids:
- assert _pid_alive(pid), f"PID {pid} should be alive after spawn"
-
- # Simulate "session end" by just dropping the reference
- del proc # noqa: F821
-
- # BUG: processes are still alive after reference is dropped
- for pid in pids:
- assert _pid_alive(pid), (
- f"PID {pid} died after ref drop — "
- f"expected it to survive (demonstrating the bug)"
- )
- finally:
- for pid in pids:
- try:
- os.kill(pid, signal.SIGKILL)
- except (ProcessLookupError, PermissionError):
- pass
-
- def test_explicit_terminate_reaps_processes(self):
- """Explicitly terminating+waiting on Popen handles works.
- This models what ProcessRegistry.kill_process does internally."""
- procs = []
-
- try:
- for _ in range(3):
- proc = _spawn_sleep(60)
- procs.append(proc)
-
- for proc in procs:
- assert _pid_alive(proc.pid)
-
- for proc in procs:
- proc.terminate()
- proc.wait(timeout=5)
-
- for proc in procs:
- assert proc.returncode is not None, (
- f"PID {proc.pid} should have exited after terminate+wait"
- )
- finally:
- for proc in procs:
- try:
- proc.kill()
- proc.wait(timeout=1)
- except Exception:
- pass
-
class TestAgentCloseMethod:
"""Verify AIAgent.close() exists, is idempotent, and calls cleanup."""
@@ -482,7 +419,7 @@ class TestDelegationCleanup:
parent._active_children.append(child)
relay_host = MagicMock()
monkeypatch.setattr(relay_runtime, "get_runtime", lambda **_kwargs: relay_host)
- monkeypatch.setattr("tools.delegate_tool._get_child_timeout", lambda: 0.1)
+ monkeypatch.setattr("tools.delegate_tool._get_child_timeout", lambda: 2)
def run_conversation(**kwargs):
lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation(
@@ -497,7 +434,7 @@ class TestDelegationCleanup:
)
child_started.set()
try:
- release_child.wait(timeout=5)
+ assert release_child.wait(timeout=30), "test did not release the child"
return {
"final_response": "late result",
"completed": True,
@@ -538,5 +475,7 @@ class TestDelegationCleanup:
)
finally:
release_child.set()
+ if child_started.is_set():
+ assert child_finished.wait(timeout=10)
reset_hermes_home_override(profile_token)
relay_runtime._reset_for_tests()