Skip to content

The agent that grows with you

test: restore tools regression guards dropped by #120071

teknium14ebda1dddb11
diff --git a/tests/tools/test_code_kernel.py b/tests/tools/test_code_kernel.py
index 0b768da7c09..c3225df3217 100644
--- a/tests/tools/test_code_kernel.py
+++ b/tests/tools/test_code_kernel.py
@@ -179,6 +179,24 @@ class TestKernelLifecycle(unittest.TestCase):
self.assertIn("raw-passthrough", result["output"])
+class TestModelFacingReset(unittest.TestCase):
+ def test_reset_is_reachable_from_a_model_call_despite_stale_kernel_mode(self):
+ """Session kernels are always on (#96787), so ``reset`` is the model's only
+ way out of poisoned state. A stale ``kernel_mode: per-call`` key must not
+ drop it from the schema, and a model-shaped call routed through the
+ registered handler must actually discard the kernel's state."""
+ from tools.code_execution_tool import _execute_code_handler, build_execute_code_schema
+
+ with _kernel_config(kernel_mode="per-call"):
+ schema = build_execute_code_schema(mode="strict")
+ self.assertEqual(schema["parameters"]["properties"]["reset"]["type"], "boolean")
+ _execute_code_handler({"code": "x = 41"}, task_id="kernel-test")
+ kept = json.loads(_execute_code_handler({"code": "print(x + 1)"}, task_id="kernel-test"))
+ self.assertIn("42", kept["output"], kept)
+ reset = json.loads(_execute_code_handler(
+ {"code": "print(x + 1)", "reset": True}, task_id="kernel-test"))
+ self.assertEqual(reset["status"], "error", reset)
+ self.assertIn("NameError", reset.get("error", ""))
if __name__ == "__main__":
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index c4f822b5a2c..835c7c5cdad 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -2337,6 +2337,55 @@ class TestCuaToolCoverageExpansion:
assert args["session"] == "harness-1"
+class TestStartupTimeoutPhaseDetail:
+ """Issue #57025: the ready-timeout error must report which startup phase
+ wedged, so 'doctor passes but wrapper times out' reports are diagnosable."""
+
+ def test_timeout_error_reports_the_wedged_phase(self):
+ import asyncio
+ import threading
+
+ from tools.computer_use import cua_backend_session as cbs
+
+ phase_reached = threading.Event()
+
+ async def _wedged_lifecycle(self):
+ # Real lifecycle shape: shutdown event on the loop, phase marker,
+ # then block — here at MCP initialize, as a wedged driver does.
+ self._shutdown_event = asyncio.Event()
+ self._startup_phase = "mcp-initialize"
+ phase_reached.set()
+ await self._shutdown_event.wait()
+
+ class _FastReadyEvent(threading.Event):
+ """Shrinks only the 30s ready wait, and only once the lifecycle
+ coroutine has provably recorded its phase (no timing race)."""
+
+ def wait(self, timeout=None):
+ if timeout is not None:
+ assert phase_reached.wait(10), "lifecycle coroutine never ran"
+ timeout = min(timeout, 0.05)
+ return super().wait(timeout)
+
+ bridge = cbs._AsyncBridge()
+ session = cbs._CuaDriverSession(bridge)
+ bridge.start() # before the Event patch, so only the ready wait sees it
+ try:
+ with patch.object(cbs._CuaDriverSession, "_lifecycle_coro", _wedged_lifecycle), \
+ patch.object(cbs.threading, "Event", _FastReadyEvent):
+ with pytest.raises(RuntimeError) as excinfo:
+ session.start()
+ msg = str(excinfo.value)
+ assert "stuck in phase: mcp-initialize" in msg
+ assert "computer-use doctor" in msg
+ # The timeout path signals the wedged lifecycle to shut down, and
+ # the session stays un-started so the next call rebuilds it.
+ session._lifecycle_future.result(timeout=5)
+ assert session._started is False
+ finally:
+ bridge.stop()
+
+
class TestCapturePayloadBudget:
"""Element labels and the aux-vision branch must respect response budgets.
diff --git a/tests/tools/test_file_operations.py b/tests/tools/test_file_operations.py
index 1e73a978dd8..530ee8af485 100644
--- a/tests/tools/test_file_operations.py
+++ b/tests/tools/test_file_operations.py
@@ -768,3 +768,50 @@ class TestEscapeNativeToolArg:
"""Multi-segment POSIX paths (/home/x, /tmp/y) are not drive paths."""
ops = self._ops(mock_env)
assert ops._escape_native_tool_arg("/tmp/workdir") == "'/tmp/workdir'"
+
+ @pytest.mark.windows_only
+ def test_rg_content_search_uses_native_form(self, mock_env):
+ """The call site, not just the helper: search must hand the native rg
+ binary C:/..., never the MSYS /c/... form (the live os-error-3 failure)."""
+ commands = []
+
+ def side_effect(command, **kwargs):
+ commands.append(command)
+ if "test -e" in command:
+ return {"output": "exists", "returncode": 0}
+ if "command -v" in command:
+ return {"output": "yes", "returncode": 0}
+ return {"output": "", "returncode": 0}
+
+ mock_env.execute.side_effect = side_effect
+ ops = self._ops(mock_env)
+ ops.search("needle", path=r"C:\Users\alice\project")
+ rg_cmds = [c for c in commands if "rg " in c or c.startswith("rg")]
+ assert rg_cmds, f"no rg command captured in: {commands}"
+ assert any("'C:/Users/alice/project'" in c for c in rg_cmds), rg_cmds
+ assert all("/c/Users" not in c for c in rg_cmds), rg_cmds
+
+ @pytest.mark.windows_only
+ def test_shell_linter_uses_native_form(self, mock_env):
+ """_check_lint must hand node/python/etc. the native C:/ path.
+
+ Regression for the double-prefix failure (#84303): node given the
+ MSYS /c/Users/... form resolves it as C:\\c\\Users\\... and every
+ .js write reports a phantom ENOENT lint error.
+ """
+ commands = []
+
+ def side_effect(command, **kwargs):
+ commands.append(command)
+ if "command -v" in command:
+ return {"output": "yes", "returncode": 0}
+ return {"output": "", "returncode": 0}
+
+ mock_env.execute.side_effect = side_effect
+ ops = self._ops(mock_env)
+ result = ops._check_lint(r"C:\Users\alice\app\main.js")
+ assert result.skipped is False
+ node_cmds = [c for c in commands if "node --check" in c]
+ assert node_cmds, f"no node command captured in: {commands}"
+ assert "'C:/Users/alice/app/main.js'" in node_cmds[0]
+ assert "/c/Users" not in node_cmds[0]
diff --git a/tests/tools/test_file_tools.py b/tests/tools/test_file_tools.py
index 9cbd07912f6..fe4217ff093 100644
--- a/tests/tools/test_file_tools.py
+++ b/tests/tools/test_file_tools.py
@@ -890,6 +890,35 @@ class TestNotFoundCache:
+class TestSSHConfigWriteGate:
+ """~/.ssh/config can run commands (ProxyCommand / Match exec), so a write
+ routes through the approval gate and fails closed with nobody to approve.
+ #93201: the gate call once raised TypeError (missing required kwarg)
+ instead of returning an approval decision — drive the real gate end to end."""
+
+ @pytest.fixture()
+ def ssh_config(self, tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ return tmp_path / ".ssh" / "config"
+
+ def test_no_human_present_blocks_and_writes_nothing(self, ssh_config):
+ from tools.file_tools import write_file_tool
+
+ result = json.loads(write_file_tool(str(ssh_config), "Host x\n ProxyCommand evil\n"))
+ assert "BLOCKED" in result["error"]
+ assert not ssh_config.exists()
+
+ def test_single_query_session_denies_with_the_q_mode_message(self, ssh_config, monkeypatch):
+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")
+ monkeypatch.setenv("HERMES_INTERACTIVE", "1") # `hermes chat -q` exports it too
+ from tools.file_tools import write_file_tool
+
+ result = json.loads(write_file_tool(str(ssh_config), "Host x\n ProxyCommand evil\n"))
+ assert "BLOCKED" in result["error"]
+ assert "single-query" in result["error"]
+ assert not ssh_config.exists()
+
+
class TestSecretFileReadRedaction:
"""#110567: read_file / search_files must classify the RESOLVED path and run the
assignment passes for a secret-bearing file, instead of returning an opaque
diff --git a/tests/tools/test_lazy_deps.py b/tests/tools/test_lazy_deps.py
index a9caa180467..af177e1b453 100644
--- a/tests/tools/test_lazy_deps.py
+++ b/tests/tools/test_lazy_deps.py
@@ -218,6 +218,12 @@ class TestIsSatisfiedVersionAware:
self._fake_version(monkeypatch, {"mautrix": "0.20.0"})
assert ld._is_satisfied("mautrix[encryption]==0.21.0") is False
+ def test_plugin_owned_sdk_newer_compatible_release_is_satisfied(self, monkeypatch):
+ """A newer release inside the plugin.yaml range must not be re-pinned downward on refresh
+ (#98407 mem0ai 2.0.19 -> 2.0.10; the same class hit the former hindsight extra, #86992)."""
+ self._fake_version(monkeypatch, {"mem0ai": "2.0.19"})
+ assert ld.feature_missing("memory.mem0") == ()
+
# ---------------------------------------------------------------------------
# active_features + refresh_active_features (Piece A — hermes update wiring)
@@ -273,6 +279,15 @@ class TestRefreshActiveFeatures:
assert result["platform.matrix"].startswith("skipped:")
assert "unsupported on Windows" in result["platform.matrix"]
+ @pytest.mark.windows_only
+ def test_matrix_probe_reports_unsupported_on_real_windows(self):
+ # The consumer test above stubs the probe; this proves the real probe
+ # actually fires on a real Windows host, so `hermes update` skips the
+ # doomed python-olm install instead of retrying it every run.
+ assert "unsupported on Windows" in (
+ ld._unsupported_feature_reason("platform.matrix") or ""
+ )
+
def test_restore_snapshot_skips_telegram_with_lazy_installs_disabled(
self, monkeypatch
diff --git a/tests/tools/test_mcp_empty_error_message.py b/tests/tools/test_mcp_empty_error_message.py
new file mode 100644
index 00000000000..fb852636a32
--- /dev/null
+++ b/tests/tools/test_mcp_empty_error_message.py
@@ -0,0 +1,33 @@
+"""Regression tests for MCP error messages when str(exc) is empty.
+
+Issue #19417: ClosedResourceError (and similar exceptions raised without a
+message argument) produced ``MCP call failed: ClosedResourceError: `` with
+nothing after the colon, making debugging impossible.
+
+Fix: ``_exc_str()`` falls back to ``repr(exc)`` when ``str(exc)`` is empty.
+"""
+
+from tools.mcp_tool_common import _exc_str
+
+
+class _EmptyMessageError(Exception):
+ """Exception whose __str__ returns empty string (like anyio.ClosedResourceError)."""
+
+ def __str__(self):
+ return ""
+
+
+def test_exc_str_falls_back_to_repr_when_message_is_empty():
+ """The #19417 shape: an empty-message exception must still yield diagnostics."""
+ text = _exc_str(_EmptyMessageError())
+ assert text.strip(), "empty exception message must not produce an empty diagnostic"
+ assert "_EmptyMessageError" in text
+
+
+def test_exc_str_falls_back_for_whitespace_only_message():
+ text = _exc_str(RuntimeError(" "))
+ assert "RuntimeError" in text
+
+
+def test_exc_str_keeps_real_message():
+ assert _exc_str(ValueError("connection refused")) == "connection refused"
diff --git a/tests/tools/test_mcp_stdio_children_dead.py b/tests/tools/test_mcp_stdio_children_dead.py
index 40844476edf..9679e4fc917 100644
--- a/tests/tools/test_mcp_stdio_children_dead.py
+++ b/tests/tools/test_mcp_stdio_children_dead.py
@@ -94,5 +94,35 @@ def test_watcher_resolves_when_all_children_are_dead():
asyncio.run(_run())
-
-
+def test_fast_fail_probe_never_calls_the_watcher_on_the_plain_path():
+ """The fast-fail gate must inspect the watcher, not call it (#96044).
+
+ The old probe, ``inspect.isawaitable(_watch_children())``, created a fresh
+ watcher coroutine on every stdio tool call and dropped it unawaited on the
+ plain-await path ("coroutine ... was never awaited" under -W error, GC churn).
+ Drive the real call path with a stubbed (non-coroutine) session result and
+ assert the async watcher is never invoked.
+ """
+ import gc
+ import warnings
+ from types import SimpleNamespace
+ from unittest.mock import AsyncMock
+
+ from tools.mcp_tool_handlers import _call_tool_racing_stdio_death
+
+ # AsyncMock qualifies as a coroutine function (like the real async method)
+ # and counts calls even when the returned coroutine is never awaited.
+ watcher = AsyncMock()
+ server = SimpleNamespace(
+ session=SimpleNamespace(call_tool=lambda name, arguments: {"ok": name}),
+ _watch_stdio_children=watcher,
+ )
+
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ result = asyncio.run(_call_tool_racing_stdio_death(server, "srv", "tool", {}))
+ gc.collect()
+
+ assert result == {"ok": "tool"}
+ assert watcher.call_count == 0, "fast-fail probe called the watcher (leaks a coroutine per call)"
+ assert not [w for w in caught if "never awaited" in str(w.message)]
diff --git a/tests/tools/test_subprocess_utf8_encoding.py b/tests/tools/test_subprocess_utf8_encoding.py
new file mode 100644
index 00000000000..5a59f848d32
--- /dev/null
+++ b/tests/tools/test_subprocess_utf8_encoding.py
@@ -0,0 +1,35 @@
+"""Regression test for #53428 (fix PR #55339): ``subprocess.run(text=True)``
+decoding of secret-manager CLI output must never crash on undecodable bytes.
+
+On Chinese Windows (cp936/GBK) ``text=True`` without ``encoding=`` decodes with
+the locale codepage and crashes on non-GBK bytes (#47939, #53428, #57238);
+``encoding='utf-8'`` alone still raises on non-UTF-8 bytes emitted by
+Windows-native CLIs. ``scripts/check-windows-footguns.py`` enforces the
+``encoding=`` half repo-wide; this drives the real ``_op_whoami`` against a
+child that emits invalid UTF-8 so the ``errors='replace'`` half is exercised
+on every host.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+
+def test_op_whoami_survives_non_utf8_cli_output(tmp_path, monkeypatch):
+ from hermes_cli import onepassword_secrets_cli as op_cli
+
+ # _op_whoami runs ``[binary, "whoami"]``. Using the interpreter as the
+ # binary makes that ``python whoami``, i.e. run ./whoami from the cwd:
+ # a portable stand-in for an ``op`` that prints a non-UTF-8 account name.
+ (tmp_path / "whoami").write_text(
+ "import sys\n"
+ "sys.stdout.buffer.write(b'\\xff\\xfe caf\\xc3\\[email protected]\\n')\n",
+ encoding="utf-8",
+ )
+ monkeypatch.chdir(tmp_path)
+
+ identity = op_cli._op_whoami(Path(sys.executable), account="")
+
+ assert identity is not None
+ assert "café@example.com" in identity
diff --git a/tests/tools/test_tts_output_timestamp.py b/tests/tools/test_tts_output_timestamp.py
new file mode 100644
index 00000000000..5fc13133c72
--- /dev/null
+++ b/tests/tools/test_tts_output_timestamp.py
@@ -0,0 +1,33 @@
+"""Regression test for salvaged PR #43911 — microsecond TTS output timestamps.
+
+Default output paths used second-resolution ``%Y%m%d_%H%M%S`` timestamps, so
+two text_to_speech_tool calls landing in the same wall-clock second produced
+the same filename and the second synthesis overwrote the first.
+"""
+
+import datetime as real_datetime
+from types import SimpleNamespace
+
+from tools import tts_tool
+
+
+def test_default_output_paths_differ_within_the_same_second(tmp_path, monkeypatch):
+ stamps = iter([
+ real_datetime.datetime(2026, 9, 23, 12, 0, 0, 1000),
+ real_datetime.datetime(2026, 9, 23, 12, 0, 0, 2000),
+ ])
+
+ class _FrozenDateTime:
+ @staticmethod
+ def now():
+ return next(stamps)
+
+ monkeypatch.setattr(tts_tool, "datetime", SimpleNamespace(datetime=_FrozenDateTime))
+ monkeypatch.setattr(tts_tool, "_default_output_dir", lambda: str(tmp_path))
+
+ first, err1 = tts_tool._resolve_output_base(None, "edge", None, False)
+ second, err2 = tts_tool._resolve_output_base(None, "edge", None, False)
+
+ assert err1 is None and err2 is None
+ assert first.parent == tmp_path and second.parent == tmp_path
+ assert first != second, "same-second TTS calls must not share an output file (#43911)"
diff --git a/tests/tools/test_windows_agent_loop_papercuts.py b/tests/tools/test_windows_agent_loop_papercuts.py
index d6023384ebd..01f0f9877cd 100644
--- a/tests/tools/test_windows_agent_loop_papercuts.py
+++ b/tests/tools/test_windows_agent_loop_papercuts.py
@@ -75,7 +75,40 @@ class TestWindowsMarketingVersion:
assert _windows_marketing_version() == expected
+class TestAutocompleteDevicePaths:
+ """#42016 — a relpath ValueError on a device path must not escape the completer."""
+
+ def test_relpath_valueerror_is_skipped_not_raised(self, tmp_path, monkeypatch):
+ import os
+ import subprocess
+
+ from hermes_cli import commands_completion as cc
+
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ # An absolute path relpath cannot express relative to cwd (Windows: a
+ # device path such as \\.\nul, or another drive letter).
+ device = os.path.abspath(os.path.join(os.sep, "nul-device"))
+ real = os.path.join(cwd, "real.txt")
+
+ monkeypatch.setattr(cc.shutil, "which", lambda name: "/fake/rg" if name == "rg" else None)
+ monkeypatch.setattr(
+ cc.subprocess, "run",
+ lambda cmd, **kw: subprocess.CompletedProcess(cmd, 0, f"{device}\n{real}\n", ""),
+ )
+ real_relpath = os.path.relpath
+
+ def _relpath(path, start=None):
+ # Windows raises ValueError for device paths / paths on another drive.
+ if path == device:
+ raise ValueError("path is on a different mount than start")
+ return real_relpath(path, start)
+
+ monkeypatch.setattr(cc.os.path, "relpath", _relpath)
+
+ files = cc.SlashCommandCompleter()._get_project_files()
+ assert files == ["real.txt"]
class TestBrowserScreenshotPathRegex:
diff --git a/tests/tools/test_windows_native_support.py b/tests/tools/test_windows_native_support.py
index c002bf826f0..ff6eab4d6a0 100644
--- a/tests/tools/test_windows_native_support.py
+++ b/tests/tools/test_windows_native_support.py
@@ -674,3 +674,43 @@ class TestGatewayRunRestartWatcherOuterPopenFallback:
assert argv_used[2] not in rendered # watcher script body
assert "argv" not in fmt.lower()
assert "env=" not in fmt.lower()
+
+
+# ---------------------------------------------------------------------------
+# cron pre-run scripts resolve bash dynamically (Git Bash on Windows)
+# ---------------------------------------------------------------------------
+
+
+class TestCronSchedulerBashResolution:
+ """cron.scheduler_script must resolve bash via PATH (Git Bash on Windows) and,
+ when no bash exists, return an actionable error instead of a [WinError 2] crash."""
+
+ def test_sh_script_uses_bash_found_on_path(self, tmp_path, monkeypatch):
+ from cron import scheduler_script
+
+ script = tmp_path / "job.sh"
+ script.write_text("echo hi\n", encoding="utf-8")
+ found = str(tmp_path / "git" / "bin" / "bash.exe")
+ monkeypatch.setattr(scheduler_script.shutil, "which",
+ lambda name: found if name == "bash" else None)
+
+ argv, _overlay, error = scheduler_script._script_argv(script)
+
+ assert error is None
+ assert argv == [found, str(script)]
+
+ def test_missing_bash_returns_actionable_error(self, tmp_path, monkeypatch):
+ from cron import scheduler_script
+
+ script = tmp_path / "job.sh"
+ script.write_text("echo hi\n", encoding="utf-8")
+ real_isfile = os.path.isfile
+ monkeypatch.setattr(scheduler_script.shutil, "which", lambda name: None)
+ monkeypatch.setattr(scheduler_script.os.path, "isfile",
+ lambda p: False if p == "/bin/bash" else real_isfile(p))
+
+ argv, _overlay, error = scheduler_script._script_argv(script)
+
+ assert argv is None
+ assert "bash not found" in error
+ assert "job.sh" in error