Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(tools): unbreak verify-tool error paths and stop event-loop blocking

Ruben Lütke421a5ff2639c
diff --git a/jarvis/plugins/tool/verify_localhost.py b/jarvis/plugins/tool/verify_localhost.py
index dc06e6b501..db95091b91 100644
--- a/jarvis/plugins/tool/verify_localhost.py
+++ b/jarvis/plugins/tool/verify_localhost.py
@@ -1,6 +1,7 @@
"""VerifyLocalhostTool — HTTP check against localhost with an optional screenshot."""
from __future__ import annotations
+import asyncio
from typing import Any
from jarvis.core.protocols import ExecutionContext, ToolResult
@@ -39,7 +40,7 @@ class VerifyLocalhostTool:
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
port = int(args.get("port") or 0)
if not port:
- return ToolResult(success=False, error="port is 0 or empty")
+ return ToolResult(success=False, output=None, error="port is 0 or empty")
path = (args.get("path") or "/").strip()
if not path.startswith("/"):
path = "/" + path
@@ -52,7 +53,11 @@ class VerifyLocalhostTool:
try:
import httpx
- r = httpx.get(url, timeout=5.0, follow_redirects=True)
+ # httpx.get is synchronous — run it off the event loop so a slow/
+ # hung localhost server cannot block every other in-flight task.
+ r = await asyncio.to_thread(
+ httpx.get, url, timeout=5.0, follow_redirects=True
+ )
ok = r.status_code == 200
if ok and substring and substring not in r.text:
ok = False
@@ -62,7 +67,9 @@ class VerifyLocalhostTool:
else:
msg = f"HTTP 200 OK ({url})"
except Exception as exc: # noqa: BLE001
- return ToolResult(success=False, error=f"Connection to {url} failed: {exc}")
+ return ToolResult(
+ success=False, output=None, error=f"Connection to {url} failed: {exc}"
+ )
if take_screenshot:
try:
diff --git a/jarvis/plugins/tool/verify_via_curl.py b/jarvis/plugins/tool/verify_via_curl.py
index 6d4a7e99cc..c62a8aaec8 100644
--- a/jarvis/plugins/tool/verify_via_curl.py
+++ b/jarvis/plugins/tool/verify_via_curl.py
@@ -1,6 +1,7 @@
"""VerifyViaCurlTool — HTTP check for Jarvis-Agent worker verification."""
from __future__ import annotations
+import asyncio
from typing import Any
from jarvis.core.protocols import ExecutionContext, ToolResult
@@ -34,14 +35,21 @@ class VerifyViaCurlTool:
async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
url = (args.get("url") or "").strip()
if not url:
- return ToolResult(success=False, error="url is empty")
+ return ToolResult(success=False, output=None, error="url is empty")
substring = (args.get("expected_substring") or "").strip()
- timeout = float(args.get("timeout_s") or 5.0)
+ # Clamp the model-controlled timeout to a sane range: a 0/negative
+ # value would hang forever, an unbounded huge one lets a single call
+ # wedge the caller for arbitrarily long.
+ timeout = min(max(float(args.get("timeout_s") or 5.0), 0.5), 30.0)
try:
import httpx
- r = httpx.get(url, timeout=timeout, follow_redirects=True)
+ # httpx.get is synchronous — run it off the event loop so a slow/
+ # unreachable host cannot block every other in-flight task.
+ r = await asyncio.to_thread(
+ httpx.get, url, timeout=timeout, follow_redirects=True
+ )
if r.status_code != 200:
return ToolResult(
success=False,
@@ -57,4 +65,4 @@ class VerifyViaCurlTool:
output=f"HTTP 200 OK ({url})" + (f" — '{substring}' found" if substring else ""),
)
except Exception as exc: # noqa: BLE001
- return ToolResult(success=False, error=f"Request failed: {exc}")
+ return ToolResult(success=False, output=None, error=f"Request failed: {exc}")
diff --git a/tests/unit/plugins/tool/test_verify_localhost.py b/tests/unit/plugins/tool/test_verify_localhost.py
new file mode 100644
index 0000000000..cc2d400331
--- /dev/null
+++ b/tests/unit/plugins/tool/test_verify_localhost.py
@@ -0,0 +1,105 @@
+"""Tests for VerifyLocalhostTool's error-path contract and threading.
+
+Two regressions pinned here:
+ 1. Every error-path ``ToolResult`` construction must pass ``output=`` — the
+ dataclass has no default for it, so omitting it raised a ``TypeError``
+ from inside ``execute()`` instead of returning an honest failed result.
+ 2. The synchronous ``httpx.get`` call must be offloaded via
+ ``asyncio.to_thread`` so a slow/hung localhost server cannot block the
+ event loop.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+from jarvis.plugins.tool.verify_localhost import VerifyLocalhostTool
+
+
+@dataclass
+class _FakeResponse:
+ status_code: int
+ text: str = ""
+
+
+@dataclass
+class _CallRecorder:
+ calls: list[tuple[Any, tuple, dict]] = field(default_factory=list)
+
+
+async def test_zero_port_returns_error_result_without_raising() -> None:
+ tool = VerifyLocalhostTool()
+ result = await tool.execute({"port": 0}, ctx=None)
+ assert result.success is False
+ assert result.output is None
+ assert "port" in (result.error or "").lower()
+
+
+async def test_connection_failure_returns_error_result_without_raising(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import httpx
+
+ def _raise(*_args: Any, **_kwargs: Any) -> Any:
+ raise httpx.ConnectError("refused")
+
+ monkeypatch.setattr(httpx, "get", _raise)
+
+ tool = VerifyLocalhostTool()
+ result = await tool.execute({"port": 5173}, ctx=None)
+
+ assert result.success is False
+ assert result.output is None
+ assert "connection" in (result.error or "").lower()
+
+
+async def test_success_reports_http_200(monkeypatch: pytest.MonkeyPatch) -> None:
+ import httpx
+
+ monkeypatch.setattr(
+ httpx, "get", lambda *_a, **_k: _FakeResponse(status_code=200, text="hi")
+ )
+
+ tool = VerifyLocalhostTool()
+ result = await tool.execute({"port": 5173}, ctx=None)
+
+ assert result.success is True
+ assert "200" in (result.output or "")
+
+
+async def test_http_call_is_offloaded_via_to_thread(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The synchronous ``httpx.get`` must run through ``asyncio.to_thread``,
+ not directly on the event loop."""
+ import asyncio
+
+ import httpx
+
+ recorder = _CallRecorder()
+ real_to_thread = asyncio.to_thread
+
+ async def _recording_to_thread(func: Any, *args: Any, **kwargs: Any) -> Any:
+ recorder.calls.append((func, args, kwargs))
+ return await real_to_thread(func, *args, **kwargs)
+
+ monkeypatch.setattr(
+ "jarvis.plugins.tool.verify_localhost.asyncio.to_thread",
+ _recording_to_thread,
+ )
+ monkeypatch.setattr(
+ httpx, "get", lambda *_a, **_k: _FakeResponse(status_code=200, text="hi")
+ )
+
+ tool = VerifyLocalhostTool()
+ result = await tool.execute({"port": 5173}, ctx=None)
+
+ assert result.success is True
+ assert len(recorder.calls) == 1
+ assert recorder.calls[0][0] is httpx.get
diff --git a/tests/unit/plugins/tool/test_verify_via_curl.py b/tests/unit/plugins/tool/test_verify_via_curl.py
new file mode 100644
index 0000000000..2a2a154a33
--- /dev/null
+++ b/tests/unit/plugins/tool/test_verify_via_curl.py
@@ -0,0 +1,152 @@
+"""Tests for VerifyViaCurlTool's error-path contract, timeout clamp, and
+threading.
+
+Three regressions pinned here:
+ 1. Every error-path ``ToolResult`` construction must pass ``output=`` — the
+ dataclass has no default for it, so omitting it raised a ``TypeError``
+ from inside ``execute()`` instead of returning an honest failed result.
+ 2. ``timeout_s`` is model-controlled and must be clamped to a sane range —
+ an unbounded value would let a single call wedge the caller for
+ arbitrarily long; a zero/negative value would hang forever.
+ 3. The synchronous ``httpx.get`` call must be offloaded via
+ ``asyncio.to_thread`` so an unreachable host cannot block the event loop.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+from jarvis.plugins.tool.verify_via_curl import VerifyViaCurlTool
+
+
+@dataclass
+class _FakeResponse:
+ status_code: int
+ text: str = ""
+
+
+@dataclass
+class _CallRecorder:
+ calls: list[tuple[Any, tuple, dict]] = field(default_factory=list)
+
+
+async def test_empty_url_returns_error_result_without_raising() -> None:
+ tool = VerifyViaCurlTool()
+ result = await tool.execute({"url": ""}, ctx=None)
+ assert result.success is False
+ assert result.output is None
+ assert "url" in (result.error or "").lower()
+
+
+async def test_request_failure_returns_error_result_without_raising(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import httpx
+
+ def _raise(*_args: Any, **_kwargs: Any) -> Any:
+ raise httpx.ConnectTimeout("timed out")
+
+ monkeypatch.setattr(httpx, "get", _raise)
+
+ tool = VerifyViaCurlTool()
+ result = await tool.execute({"url": "https://example.invalid"}, ctx=None)
+
+ assert result.success is False
+ assert result.output is None
+ assert "request failed" in (result.error or "").lower()
+
+
+async def test_success_reports_http_200(monkeypatch: pytest.MonkeyPatch) -> None:
+ import httpx
+
+ monkeypatch.setattr(
+ httpx, "get", lambda *_a, **_k: _FakeResponse(status_code=200, text="hi")
+ )
+
+ tool = VerifyViaCurlTool()
+ result = await tool.execute({"url": "https://example.com"}, ctx=None)
+
+ assert result.success is True
+ assert "200" in (result.output or "")
+
+
+async def test_timeout_is_clamped_to_lower_bound(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import httpx
+
+ recorder = _CallRecorder()
+
+ def _capture(*args: Any, **kwargs: Any) -> Any:
+ recorder.calls.append((None, args, kwargs))
+ return _FakeResponse(status_code=200, text="hi")
+
+ monkeypatch.setattr(httpx, "get", _capture)
+
+ tool = VerifyViaCurlTool()
+ # 0 is falsy and would trigger the "or 5.0" default before ever reaching
+ # the clamp, so use a truthy below-floor value to exercise the min-bound.
+ await tool.execute({"url": "https://example.com", "timeout_s": 0.1}, ctx=None)
+
+ assert recorder.calls[0][2]["timeout"] == pytest.approx(0.5)
+
+
+async def test_timeout_is_clamped_to_upper_bound(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import httpx
+
+ recorder = _CallRecorder()
+
+ def _capture(*args: Any, **kwargs: Any) -> Any:
+ recorder.calls.append((None, args, kwargs))
+ return _FakeResponse(status_code=200, text="hi")
+
+ monkeypatch.setattr(httpx, "get", _capture)
+
+ tool = VerifyViaCurlTool()
+ await tool.execute(
+ {"url": "https://example.com", "timeout_s": 999_999}, ctx=None
+ )
+
+ assert recorder.calls[0][2]["timeout"] == pytest.approx(30.0)
+
+
+async def test_http_call_is_offloaded_via_to_thread(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The synchronous ``httpx.get`` must run through ``asyncio.to_thread``,
+ not directly on the event loop."""
+ import asyncio
+
+ import httpx
+
+ recorder = _CallRecorder()
+ real_to_thread = asyncio.to_thread
+
+ async def _recording_to_thread(func: Any, *args: Any, **kwargs: Any) -> Any:
+ recorder.calls.append((func, args, kwargs))
+ return await real_to_thread(func, *args, **kwargs)
+
+ monkeypatch.setattr(
+ "jarvis.plugins.tool.verify_via_curl.asyncio.to_thread",
+ _recording_to_thread,
+ )
+ monkeypatch.setattr(
+ httpx, "get", lambda *_a, **_k: _FakeResponse(status_code=200, text="hi")
+ )
+
+ tool = VerifyViaCurlTool()
+ result = await tool.execute({"url": "https://example.com"}, ctx=None)
+
+ assert result.success is True
+ assert len(recorder.calls) == 1
+ assert recorder.calls[0][0] is httpx.get