From a14cd65e60cc3e2a70896a5ce2529badf6aae72f Mon Sep 17 00:00:00 2001 From: fangliquanflq Date: Fri, 14 Aug 2026 18:28:51 +0800 Subject: [PATCH 1/6] fix(web): avoid DDGS native crash on Termux --- plugins/web/ddgs/__init__.py | 6 +- plugins/web/ddgs/plugin.yaml | 2 +- plugins/web/ddgs/provider.py | 117 +++++++++++++++++++++---- tests/tools/test_web_providers_ddgs.py | 66 ++++++++++++++ tools/web_tools.py | 12 +-- 5 files changed, 178 insertions(+), 25 deletions(-) diff --git a/plugins/web/ddgs/__init__.py b/plugins/web/ddgs/__init__.py index 26eb6407ef8d0..daaee52e710b3 100644 --- a/plugins/web/ddgs/__init__.py +++ b/plugins/web/ddgs/__init__.py @@ -1,8 +1,8 @@ """DuckDuckGo search plugin — bundled, auto-loaded. -Backed by the community ``ddgs`` Python package which scrapes DDG's HTML -results page. No API key required, but the package itself must be installed -(it's an optional dep — gated via :meth:`is_available`). +Backed by the community ``ddgs`` package on desktop platforms and a core-httpx +HTML fallback on Termux, where ddgs's native transport cannot run. No API key +is required. """ from __future__ import annotations diff --git a/plugins/web/ddgs/plugin.yaml b/plugins/web/ddgs/plugin.yaml index e85236c14cf12..010ca9a7ee059 100644 --- a/plugins/web/ddgs/plugin.yaml +++ b/plugins/web/ddgs/plugin.yaml @@ -1,6 +1,6 @@ name: web-ddgs version: 1.0.0 -description: "DuckDuckGo web search via the ddgs Python package — no API key required. Install with `pip install ddgs`." +description: "DuckDuckGo web search without an API key; includes a Termux-compatible HTTP fallback." author: NousResearch kind: backend provides_web_providers: diff --git a/plugins/web/ddgs/provider.py b/plugins/web/ddgs/provider.py index 824f3edba6d64..36ea56e790c30 100644 --- a/plugins/web/ddgs/provider.py +++ b/plugins/web/ddgs/provider.py @@ -25,9 +25,12 @@ import os import subprocess import sys import time +from html.parser import HTMLParser from typing import Any, Dict, Optional +from urllib.parse import parse_qs, urljoin, urlparse from agent.web_search_provider import WebSearchProvider +from hermes_constants import is_termux logger = logging.getLogger(__name__) @@ -49,6 +52,81 @@ class _SearchInterrupted(Exception): """Raised when tools.interrupt.is_interrupted() trips during a search wait.""" +_DDG_HTML_ENDPOINT = "https://html.duckduckgo.com/html/" + + +def _decode_ddg_url(href: str) -> str: + """Return the destination hidden inside DDG's redirect wrapper.""" + absolute = urljoin(_DDG_HTML_ENDPOINT, href) + parsed = urlparse(absolute) + if parsed.hostname in {"duckduckgo.com", "www.duckduckgo.com"}: + destination = parse_qs(parsed.query).get("uddg") + if destination: + return destination[0] + return absolute + + +class _DDGHTMLParser(HTMLParser): + """Extract the result fields emitted by DuckDuckGo's HTML endpoint.""" + + def __init__(self, limit: int) -> None: + super().__init__(convert_charrefs=True) + self.limit = limit + self.results: list[dict[str, Any]] = [] + self._field: Optional[str] = None + self._depth = 0 + self._current: Optional[dict[str, Any]] = None + + def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: + attributes = dict(attrs) + classes = set((attributes.get("class") or "").split()) + if tag == "a" and "result__a" in classes and len(self.results) < self.limit: + href = attributes.get("href") or "" + self._current = { + "title": "", + "url": _decode_ddg_url(href), + "description": "", + "position": len(self.results) + 1, + } + self.results.append(self._current) + self._field = "title" + self._depth = 1 + elif "result__snippet" in classes and self._current is not None: + self._field = "description" + self._depth = 1 + elif self._field: + self._depth += 1 + + def handle_endtag(self, tag: str) -> None: + if not self._field: + return + self._depth -= 1 + if self._depth == 0: + self._field = None + + def handle_data(self, data: str) -> None: + if self._field and self._current is not None: + current = str(self._current[self._field]) + self._current[self._field] = f"{current} {data}".strip() + + +def _run_ddg_html_search(query: str, safe_limit: int) -> list[dict[str, Any]]: + """Search DDG without the Android-incompatible ``primp`` transport.""" + import httpx + + response = httpx.post( + _DDG_HTML_ENDPOINT, + data={"q": query}, + headers={"User-Agent": "Mozilla/5.0 (compatible; Hermes-Agent/1.0)"}, + follow_redirects=True, + timeout=10, + ) + response.raise_for_status() + parser = _DDGHTMLParser(safe_limit) + parser.feed(response.text) + return parser.results + + def _run_ddgs_search(query: str, safe_limit: int) -> list[dict[str, Any]]: """Run the blocking ddgs query and return normalized hits. @@ -57,6 +135,9 @@ def _run_ddgs_search(query: str, safe_limit: int) -> list[dict[str, Any]]: each individual HTTP request; the overall wall-clock cap is enforced by the parent via process timeout (#68096). """ + if is_termux(): + return _run_ddg_html_search(query, safe_limit) + from ddgs import DDGS # type: ignore results: list[dict[str, Any]] = [] @@ -281,12 +362,14 @@ class DDGSWebSearchProvider(WebSearchProvider): return "DuckDuckGo (ddgs)" def is_available(self) -> bool: - """Return True when the ``ddgs`` package is importable. + """Return True when the active platform's transport is available. - Probes the import once; cheap because Python caches the import. Must - NOT perform network I/O — runs at tool-registration time and on every - ``hermes tools`` paint. + Termux uses core ``httpx``; other platforms probe ``ddgs`` once. Must + not perform network I/O because this runs during tool registration and + on every ``hermes tools`` paint. """ + if is_termux(): + return True try: import ddgs # noqa: F401 @@ -307,13 +390,14 @@ class DDGSWebSearchProvider(WebSearchProvider): a hard wall-clock timeout (``_SEARCH_TIMEOUT_SECS``) so a hung native ``primp`` call cannot freeze the Hermes process (#36776, #68096). """ - try: - import ddgs # type: ignore # noqa: F401 — availability probe - except ImportError: - return { - "success": False, - "error": "ddgs package is not installed — run `pip install ddgs`", - } + if not is_termux(): + try: + import ddgs # type: ignore # noqa: F401 — availability probe + except ImportError: + return { + "success": False, + "error": "ddgs package is not installed — run `pip install ddgs`", + } # DDGS().text yields at most `max_results` items; we cap defensively # in case the package ignores the hint. @@ -351,12 +435,13 @@ class DDGSWebSearchProvider(WebSearchProvider): return {"success": True, "data": {"web": web_results}} def get_setup_schema(self) -> Dict[str, Any]: - return { + schema = { "name": "DuckDuckGo (ddgs)", "badge": "free · no key · search only", - "tag": "Search via the ddgs Python package — no API key (pair with any extract provider)", + "tag": "Search DuckDuckGo without an API key (pair with any extract provider)", "env_vars": [], - # Trigger `_run_post_setup("ddgs")` after the user picks this row - # so the ddgs Python package gets pip-installed on first selection. - "post_setup": "ddgs", } + if not is_termux(): + # The Android fallback uses core httpx; primp aborts under Termux. + schema["post_setup"] = "ddgs" + return schema diff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.py index 959f3c703b7c9..eb4b3bd26b169 100644 --- a/tests/tools/test_web_providers_ddgs.py +++ b/tests/tools/test_web_providers_ddgs.py @@ -88,8 +88,65 @@ class TestDDGSProviderIsConfigured: from plugins.web.ddgs.provider import DDGSWebSearchProvider assert issubclass(DDGSWebSearchProvider, WebSearchProvider) + def test_termux_is_available_without_ddgs_and_skips_installer(self, monkeypatch): + import plugins.web.ddgs.provider as prov + + monkeypatch.setattr(prov, "is_termux", lambda: True) + + provider = prov.DDGSWebSearchProvider() + assert provider.is_available() is True + assert "post_setup" not in provider.get_setup_schema() + class TestDDGSProviderSearch: + def test_termux_uses_html_transport_without_importing_ddgs(self, monkeypatch): + import plugins.web.ddgs.provider as prov + + monkeypatch.setattr(prov, "is_termux", lambda: True) + monkeypatch.setitem(sys.modules, "ddgs", None) + monkeypatch.setattr( + prov, + "_run_ddgs_search_bounded", + lambda query, safe_limit: [{"title": query, "position": safe_limit}], + ) + + result = prov.DDGSWebSearchProvider().search("termux query", limit=3) + + assert result == { + "success": True, + "data": {"web": [{"title": "termux query", "position": 3}]}, + } + + def test_html_parser_decodes_redirects_and_normalizes_text(self): + from plugins.web.ddgs.provider import _DDGHTMLParser + + parser = _DDGHTMLParser(limit=1) + parser.feed( + '
' + 'Example & result' + 'A useful description.
' + 'Ignored' + ) + + assert parser.results == [{ + "title": "Example & result", + "url": "https://example.com/a?x=1", + "description": "A useful description.", + "position": 1, + }] + + def test_termux_worker_dispatches_to_html_transport(self, monkeypatch): + import plugins.web.ddgs.provider as prov + + expected = [{"title": "hit"}] + monkeypatch.setattr(prov, "is_termux", lambda: True) + monkeypatch.setattr( + prov, "_run_ddg_html_search", lambda query, limit: expected + ) + + assert prov._run_ddgs_search("q", 2) is expected + def test_happy_path_normalizes_results(self, monkeypatch): _install_fake_ddgs(monkeypatch, text_results=[ {"title": "A", "href": "https://a.example.com", "body": "desc A"}, @@ -233,6 +290,15 @@ class TestDDGSProcessIsolation: class TestDDGSBackendWiring: + def test_termux_backend_available_without_ddgs(self, monkeypatch): + from tools import web_tools + + monkeypatch.setitem(sys.modules, "ddgs", None) + monkeypatch.setattr("hermes_constants.is_termux", lambda: True) + + assert web_tools._ddgs_package_importable() is True + assert web_tools._is_backend_available("ddgs") is True + def test_is_backend_available_true_when_package_importable(self, monkeypatch): from tools import web_tools monkeypatch.setattr(web_tools, "_ddgs_package_importable", lambda: True) diff --git a/tools/web_tools.py b/tools/web_tools.py index e8c62142af8b9..6b208307dcda4 100644 --- a/tools/web_tools.py +++ b/tools/web_tools.py @@ -353,13 +353,15 @@ def _is_backend_available(backend: str) -> bool: def _ddgs_package_importable() -> bool: - """Return True when the ``ddgs`` Python package can be imported. + """Return True when the platform's bundled DDG transport is available. - ddgs is the only backend whose availability is driven by a package - presence rather than an env var / config entry. Wrapped in a helper - so auto-detect and ``_is_backend_available`` share the same check - (and tests can monkeypatch a single symbol). + Termux uses the provider's core-httpx fallback because ``ddgs`` aborts in + native ``primp`` code there. Other platforms require the optional package. """ + from hermes_constants import is_termux + + if is_termux(): + return True try: import ddgs # noqa: F401 return True From 76297d845c69c8d25c8fc1deb5cf8cb491a0f28f Mon Sep 17 00:00:00 2001 From: fangliquanflq Date: Fri, 14 Aug 2026 18:36:33 +0800 Subject: [PATCH 2/6] fix(web): normalize DDG HTML result text --- plugins/web/ddgs/provider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/web/ddgs/provider.py b/plugins/web/ddgs/provider.py index 36ea56e790c30..bd747cf674536 100644 --- a/plugins/web/ddgs/provider.py +++ b/plugins/web/ddgs/provider.py @@ -107,7 +107,7 @@ class _DDGHTMLParser(HTMLParser): def handle_data(self, data: str) -> None: if self._field and self._current is not None: current = str(self._current[self._field]) - self._current[self._field] = f"{current} {data}".strip() + self._current[self._field] = " ".join(f"{current} {data}".split()) def _run_ddg_html_search(query: str, safe_limit: int) -> list[dict[str, Any]]: From ba7058eab968d7f7f69a87f9f224efb0d003f0b5 Mon Sep 17 00:00:00 2001 From: fangliquanflq Date: Fri, 14 Aug 2026 18:44:51 +0800 Subject: [PATCH 3/6] fix(web): reap DDGS communicator threads --- plugins/web/ddgs/provider.py | 47 +++++++++++++++++++------- tests/tools/test_web_providers_ddgs.py | 5 ++- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/plugins/web/ddgs/provider.py b/plugins/web/ddgs/provider.py index bd747cf674536..c18b00c3ce1d5 100644 --- a/plugins/web/ddgs/provider.py +++ b/plugins/web/ddgs/provider.py @@ -18,12 +18,13 @@ therefore runs in a disposable child process the parent can terminate/kill. from __future__ import annotations -import concurrent.futures as cf import json import logging import os +import queue import subprocess import sys +import threading import time from html.parser import HTMLParser from typing import Any, Dict, Optional @@ -163,6 +164,7 @@ _test_hook: Optional[str] = None # Last worker Popen started by ``_run_ddgs_search_bounded`` (test reap checks). _last_worker_proc: Optional[subprocess.Popen] = None +_last_worker_thread: Optional[threading.Thread] = None def _plugins_path_entry() -> str: @@ -231,7 +233,7 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] # Imported lazily so plugin import stays light for ``hermes tools`` probes. from tools.interrupt import is_interrupted - global _last_worker_proc + global _last_worker_proc, _last_worker_thread request: dict[str, Any] = {"query": query, "safe_limit": safe_limit} if _test_hook: @@ -280,13 +282,29 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] ) _last_worker_proc = proc - # ``communicate`` runs in a side thread so the parent can poll interrupt / - # deadline without blocking. Killing the child unblocks communicate. - pool = cf.ThreadPoolExecutor(max_workers=1) - fut = pool.submit(proc.communicate, json.dumps(request)) + # ``communicate`` runs in a daemon thread so the parent can poll interrupt / + # deadline without blocking. A daemon avoids trapping interpreter shutdown + # if a native worker dies while an inherited pipe remains open. + completed: queue.Queue[tuple[Optional[str], Optional[BaseException]]] = queue.Queue(maxsize=1) + + def _communicate() -> None: + try: + out, _err = proc.communicate(json.dumps(request)) + completed.put((out or "", None)) + except BaseException as exc: # noqa: BLE001 — forward into caller thread + completed.put((None, exc)) + + communicator = threading.Thread( + target=_communicate, + name=f"ddgs-worker-{proc.pid}", + daemon=True, + ) + communicator.start() + _last_worker_thread = communicator timed_out = False interrupted = False raw = "" + communicate_error: Optional[BaseException] = None try: deadline = time.monotonic() + _SEARCH_TIMEOUT_SECS while True: @@ -298,22 +316,23 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] timed_out = True break try: - out, _err = fut.result(timeout=min(_POLL_INTERVAL_SECS, remaining)) + out, communicate_error = completed.get( + timeout=min(_POLL_INTERVAL_SECS, remaining) + ) raw = out or "" break - except cf.TimeoutError: + except queue.Empty: continue finally: _terminate_and_reap(proc) - # After kill, communicate should return promptly; don't block forever. - if not fut.done(): + communicator.join(timeout=_TERMINATE_GRACE_SECS) + if not communicator.is_alive() and completed.qsize(): try: - out, _err = fut.result(timeout=_TERMINATE_GRACE_SECS) + out, communicate_error = completed.get_nowait() if not raw: raw = out or "" - except Exception: # noqa: BLE001 + except queue.Empty: pass - pool.shutdown(wait=False, cancel_futures=True) if interrupted: raise _SearchInterrupted("DuckDuckGo search interrupted") @@ -321,6 +340,8 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] raise TimeoutError( f"DuckDuckGo search timed out after {_SEARCH_TIMEOUT_SECS}s" ) + if communicate_error is not None: + raise RuntimeError(f"DDGS worker communication failed: {communicate_error}") raw = raw.strip() if not raw: diff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.py index eb4b3bd26b169..e1655d43c0efd 100644 --- a/tests/tools/test_web_providers_ddgs.py +++ b/tests/tools/test_web_providers_ddgs.py @@ -217,12 +217,15 @@ class TestDDGSProviderSearch: def _assert_worker_reaped(prov) -> None: - """Assert the last DDGS worker process has exited.""" + """Assert the last DDGS worker process and communicator have exited.""" proc = prov._last_worker_proc assert proc is not None, "expected a DDGS worker process to have been started" assert proc.poll() is not None, ( f"DDGS worker still alive (pid={proc.pid}, returncode={proc.returncode})" ) + thread = prov._last_worker_thread + assert thread is not None, "expected a DDGS communicator thread" + assert not thread.is_alive(), "DDGS communicator thread still alive" @pytest.mark.live_system_guard_bypass From 73007b43312f27271393eac655cb8ac2a7965db3 Mon Sep 17 00:00:00 2001 From: fangliquanflq Date: Fri, 14 Aug 2026 18:46:40 +0800 Subject: [PATCH 4/6] fix(web): poll DDGS worker without executor leaks --- plugins/web/ddgs/provider.py | 50 ++++++++------------------ tests/tools/test_web_providers_ddgs.py | 5 +-- 2 files changed, 15 insertions(+), 40 deletions(-) diff --git a/plugins/web/ddgs/provider.py b/plugins/web/ddgs/provider.py index c18b00c3ce1d5..0609608b30ee2 100644 --- a/plugins/web/ddgs/provider.py +++ b/plugins/web/ddgs/provider.py @@ -21,10 +21,8 @@ from __future__ import annotations import json import logging import os -import queue import subprocess import sys -import threading import time from html.parser import HTMLParser from typing import Any, Dict, Optional @@ -164,7 +162,6 @@ _test_hook: Optional[str] = None # Last worker Popen started by ``_run_ddgs_search_bounded`` (test reap checks). _last_worker_proc: Optional[subprocess.Popen] = None -_last_worker_thread: Optional[threading.Thread] = None def _plugins_path_entry() -> str: @@ -233,7 +230,7 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] # Imported lazily so plugin import stays light for ``hermes tools`` probes. from tools.interrupt import is_interrupted - global _last_worker_proc, _last_worker_thread + global _last_worker_proc request: dict[str, Any] = {"query": query, "safe_limit": safe_limit} if _test_hook: @@ -282,29 +279,10 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] ) _last_worker_proc = proc - # ``communicate`` runs in a daemon thread so the parent can poll interrupt / - # deadline without blocking. A daemon avoids trapping interpreter shutdown - # if a native worker dies while an inherited pipe remains open. - completed: queue.Queue[tuple[Optional[str], Optional[BaseException]]] = queue.Queue(maxsize=1) - - def _communicate() -> None: - try: - out, _err = proc.communicate(json.dumps(request)) - completed.put((out or "", None)) - except BaseException as exc: # noqa: BLE001 — forward into caller thread - completed.put((None, exc)) - - communicator = threading.Thread( - target=_communicate, - name=f"ddgs-worker-{proc.pid}", - daemon=True, - ) - communicator.start() - _last_worker_thread = communicator timed_out = False interrupted = False raw = "" - communicate_error: Optional[BaseException] = None + input_payload: Optional[str] = json.dumps(request) try: deadline = time.monotonic() + _SEARCH_TIMEOUT_SECS while True: @@ -316,22 +294,25 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] timed_out = True break try: - out, communicate_error = completed.get( - timeout=min(_POLL_INTERVAL_SECS, remaining) + out, _err = proc.communicate( + input_payload, + timeout=min(_POLL_INTERVAL_SECS, remaining), ) + input_payload = None raw = out or "" break - except queue.Empty: + except subprocess.TimeoutExpired: + # communicate() retains its input after a timeout; subsequent + # calls must pass None and continue draining the same pipes. + input_payload = None continue finally: _terminate_and_reap(proc) - communicator.join(timeout=_TERMINATE_GRACE_SECS) - if not communicator.is_alive() and completed.qsize(): + if not raw: try: - out, communicate_error = completed.get_nowait() - if not raw: - raw = out or "" - except queue.Empty: + out, _err = proc.communicate(timeout=_TERMINATE_GRACE_SECS) + raw = out or "" + except (subprocess.TimeoutExpired, ValueError): pass if interrupted: @@ -340,9 +321,6 @@ def _run_ddgs_search_bounded(query: str, safe_limit: int) -> list[dict[str, Any] raise TimeoutError( f"DuckDuckGo search timed out after {_SEARCH_TIMEOUT_SECS}s" ) - if communicate_error is not None: - raise RuntimeError(f"DDGS worker communication failed: {communicate_error}") - raw = raw.strip() if not raw: raise RuntimeError( diff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.py index e1655d43c0efd..eb4b3bd26b169 100644 --- a/tests/tools/test_web_providers_ddgs.py +++ b/tests/tools/test_web_providers_ddgs.py @@ -217,15 +217,12 @@ class TestDDGSProviderSearch: def _assert_worker_reaped(prov) -> None: - """Assert the last DDGS worker process and communicator have exited.""" + """Assert the last DDGS worker process has exited.""" proc = prov._last_worker_proc assert proc is not None, "expected a DDGS worker process to have been started" assert proc.poll() is not None, ( f"DDGS worker still alive (pid={proc.pid}, returncode={proc.returncode})" ) - thread = prov._last_worker_thread - assert thread is not None, "expected a DDGS communicator thread" - assert not thread.is_alive(), "DDGS communicator thread still alive" @pytest.mark.live_system_guard_bypass From 752cf0e78de75b0629b7e471c25572f378e348ee Mon Sep 17 00:00:00 2001 From: fangliquanflq Date: Fri, 14 Aug 2026 19:00:11 +0800 Subject: [PATCH 5/6] fix(web): isolate discarded DDG snippets --- plugins/web/ddgs/provider.py | 9 ++++++++- tests/tools/test_web_providers_ddgs.py | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/plugins/web/ddgs/provider.py b/plugins/web/ddgs/provider.py index 0609608b30ee2..42096e26629d6 100644 --- a/plugins/web/ddgs/provider.py +++ b/plugins/web/ddgs/provider.py @@ -79,7 +79,14 @@ class _DDGHTMLParser(HTMLParser): def handle_starttag(self, tag: str, attrs: list[tuple[str, Optional[str]]]) -> None: attributes = dict(attrs) classes = set((attributes.get("class") or "").split()) - if tag == "a" and "result__a" in classes and len(self.results) < self.limit: + if tag == "a" and "result__a" in classes: + if len(self.results) >= self.limit: + # A skipped result must also sever the previous result's + # snippet target; otherwise its snippet is appended there. + self._current = None + self._field = None + self._depth = 0 + return href = attributes.get("href") or "" self._current = { "title": "", diff --git a/tests/tools/test_web_providers_ddgs.py b/tests/tools/test_web_providers_ddgs.py index eb4b3bd26b169..656871cd37a71 100644 --- a/tests/tools/test_web_providers_ddgs.py +++ b/tests/tools/test_web_providers_ddgs.py @@ -127,6 +127,7 @@ class TestDDGSProviderSearch: 'Example & result' 'A useful description.' 'Ignored' + 'Discarded description.' ) assert parser.results == [{ From d58e2f2ede40861565dce57c0445868bb09958c9 Mon Sep 17 00:00:00 2001 From: fangliquanflq Date: Fri, 14 Aug 2026 13:43:34 +0000 Subject: [PATCH 6/6] test(tui_gateway): return Path from get_hermes_home mock in slash_worker profile test hermes_state evaluates get_hermes_home() / state.db at import time; a bare str mock raises TypeError under per-file subprocess isolation (CI slice 3/12). --- .../test_slash_worker_profile_home.py | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/tui_gateway/test_slash_worker_profile_home.py b/tests/tui_gateway/test_slash_worker_profile_home.py index e8589c7861959..29b3e7b77e3ed 100644 --- a/tests/tui_gateway/test_slash_worker_profile_home.py +++ b/tests/tui_gateway/test_slash_worker_profile_home.py @@ -1,37 +1,37 @@ """Tests for TUI gateway slash_worker profile_home propagation (#40677).""" -import os -import subprocess -import sys -from unittest.mock import MagicMock, patch, call - -import pytest +from pathlib import Path +from unittest.mock import MagicMock, patch def test_slash_worker_accepts_profile_home(): """_SlashWorker.__init__ accepts profile_home parameter.""" + # hermes_state evaluates get_hermes_home() / "state.db" at import time, so + # the mock must return a Path (a bare str raises TypeError under per-file + # subprocess isolation). with patch.dict("sys.modules", { - "hermes_constants": MagicMock(get_hermes_home=MagicMock(return_value="/tmp/hermes_test")), + "hermes_constants": MagicMock( + get_hermes_home=MagicMock(return_value=Path("/tmp/hermes_test")), + ), }): with patch("subprocess.Popen") as mock_popen: mock_popen.return_value.stdout = MagicMock() mock_popen.return_value.stderr = MagicMock() - + from tui_gateway.server import _SlashWorker - + # Test initialization with profile_home worker = _SlashWorker( session_key="test_key", model="test-model", profile_home="/home/luke/.hermes/profiles/work" ) - + # Verify Popen was called assert mock_popen.called - + # Check that HERMES_HOME was set in the environment call_kwargs = mock_popen.call_args[1] assert "env" in call_kwargs assert call_kwargs["env"]["HERMES_HOME"] == "/home/luke/.hermes/profiles/work" -