diff --git a/nanobot/apps/cli/service.py b/nanobot/apps/cli/service.py index 3131df9ef..e66147a95 100644 --- a/nanobot/apps/cli/service.py +++ b/nanobot/apps/cli/service.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import json import os import re @@ -506,7 +507,7 @@ class CliAppManager: *, force_refresh: bool = False, ) -> dict[str, Any]: - data, cached_at = self._cached_registry(cache_path) + data, cached_at = await asyncio.to_thread(self._cached_registry, cache_path) if ( not force_refresh and data is not None @@ -526,7 +527,7 @@ class CliAppManager: return data raise - _write_json(cache_path, {"_cached_at": _now(), "data": fetched}) + await asyncio.to_thread(_write_json, cache_path, {"_cached_at": _now(), "data": fetched}) return fetched async def refresh_catalog_cache(self, *, force_refresh: bool = False) -> None: diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py index 8e527f6d5..5752c0d84 100644 --- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py +++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py @@ -7,7 +7,7 @@ import socket import time from contextlib import suppress from pathlib import Path -from threading import Event +from threading import Event, Timer from typing import Any from unittest.mock import AsyncMock, MagicMock @@ -2030,49 +2030,89 @@ async def test_nanobot_feature_remote_disable_does_not_need_install_policy( @pytest.mark.asyncio +@pytest.mark.parametrize("installed_only", [False, True]) async def test_cli_apps_catalog_does_not_block_other_webui_http_routes( bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, + installed_only: bool, ) -> None: - entered = asyncio.Event() - release = asyncio.Event() + from nanobot.apps.cli import service as cli_service + from nanobot.config import loader + from nanobot.config.schema import Config - async def slow_payload( - *, - installed_only: bool = False, - config_path: Path | None = None, - ) -> dict[str, Any]: - assert installed_only is False - entered.set() - with suppress(asyncio.TimeoutError): - await asyncio.wait_for(release.wait(), 2.0) - return {"apps": [], "installed_count": 0, "catalog_updated_at": None} - - monkeypatch.setattr("nanobot.webui.settings_routes.cli_apps_payload", slow_payload) - channel = _ch(bus, session_manager=_seed_session(tmp_path), port=29935) - server_task = asyncio.create_task(channel.start()) - try: - token = channel.gateway.tokens.issue_api_token(300) - auth = {"Authorization": f"Bearer {token}"} - - catalog_task = asyncio.create_task( - _http_get("http://127.0.0.1:29935/api/settings/cli-apps", headers=auth) + workspace = tmp_path / "workspace" + config = Config() + config.agents.defaults.workspace = str(workspace) + config_path = tmp_path / "config.json" + loader.save_config(config, config_path) + monkeypatch.setattr(loader, "_current_config_path", config_path) + monkeypatch.setenv("PATH", str(tmp_path / "empty-bin")) + manager = cli_service.CliAppManager(workspace=workspace) + app = {"name": "blocked", "entry_point": "nanobot-blocked-cli", "package_manager": "bundled"} + for source, *_ in cli_service._CATALOG_SOURCES: + manager._cache_path(source).write_text( + json.dumps({"_cached_at": time.time(), "data": {"clis": [app]}}), + encoding="utf-8", ) + manager._save_installed({"blocked": {"entry_point": app["entry_point"], "strategy": "bundled"}}) + + loop = asyncio.get_running_loop() + entered = asyncio.Event() + release = Event() + watchdog_fired = Event() + native_which = cli_service.shutil.which + + def slow_which(command: str, *args: Any, **kwargs: Any) -> str | None: + if command == app["entry_point"]: + loop.call_soon_threadsafe(entered.set) + release.wait() + return native_which(command, *args, **kwargs) + + def unblock() -> None: + watchdog_fired.set() + release.set() + + monkeypatch.setattr(cli_service.shutil, "which", slow_which) + watchdog = Timer(5.0, unblock) + watchdog.daemon = True + port = _free_port() + cfg = {"host": "127.0.0.1", "port": port, "allowFrom": ["*"], "websocketRequiresToken": False} + gateway = _make_handler(cfg, bus, session_manager=_seed_session(workspace), workspace_path=workspace) + channel = WebSocketChannel(cfg, bus, gateway=gateway) + server_task = asyncio.create_task(channel.start()) + catalog_task = None + try: + token = gateway.tokens.issue_api_token(300) + auth = {"Authorization": f"Bearer {token}"} + url = f"http://127.0.0.1:{port}" + assert (await _http_get(f"{url}/api/workspaces", headers=auth)).status_code == 200 + watchdog.start() + query = "?installed_only=1" if installed_only else "" + catalog_task = asyncio.create_task(_http_get(f"{url}/api/settings/cli-apps{query}", headers=auth)) assert await asyncio.wait_for(entered.wait(), 2.0) assert not catalog_task.done() - workspaces_started = time.perf_counter() - workspaces = await _http_get("http://127.0.0.1:29935/api/workspaces", headers=auth) - assert time.perf_counter() - workspaces_started < 1.0 + workspaces = await asyncio.wait_for(_http_get(f"{url}/api/workspaces", headers=auth), 2.0) assert workspaces.status_code == 200 + assert not release.is_set(), "the watchdog released a probe blocking the event loop" + assert not watchdog_fired.is_set() release.set() - catalog = await catalog_task + catalog = await asyncio.wait_for(catalog_task, 2.0) assert catalog.status_code == 200 - assert catalog.json()["apps"] == [] + payload = catalog.json() + assert payload["apps"][0]["name"] == "blocked" + assert payload["apps"][0]["status"] == "missing" + assert ("catalog_refresh_pending" in payload) is not installed_only finally: release.set() + watchdog.cancel() + if watchdog.ident is not None: + watchdog.join() + if catalog_task is not None: + with suppress(Exception, asyncio.CancelledError): + await asyncio.wait_for(catalog_task, 5.0) await channel.stop() await server_task diff --git a/nanobot/webui/cli_apps_api.py b/nanobot/webui/cli_apps_api.py index 0d7e81b08..fb7bf6268 100644 --- a/nanobot/webui/cli_apps_api.py +++ b/nanobot/webui/cli_apps_api.py @@ -5,6 +5,7 @@ from __future__ import annotations import asyncio import re import time +from dataclasses import dataclass from pathlib import Path from typing import Any, cast @@ -103,24 +104,38 @@ def _manager(config_path: Path | None = None) -> CliAppManager: ) +@dataclass(frozen=True, slots=True) +class _LocalRead: + payload: dict[str, Any] + refresh_manager: CliAppManager | None = None + + +def _read_local(*, installed_only: bool, config_path: Path | None) -> _LocalRead: + manager = _manager(config_path) if config_path is not None else _manager() + if installed_only: + return _LocalRead(manager.installed_payload()) + payload = manager.payload(cache_only=True) + refresh_manager = None if manager.catalog_cache_fresh(include_optional=True) else manager + if not payload["apps"]: + installed = manager.installed_payload() + if installed["apps"]: + payload = installed + return _LocalRead(payload, refresh_manager) + + async def cli_apps_payload( *, installed_only: bool = False, config_path: Path | None = None, ) -> dict[str, Any]: - manager = _manager(config_path) if config_path is not None else _manager() - if installed_only: - return manager.installed_payload() - payload = manager.payload(cache_only=True) - refresh_pending = False - if not manager.catalog_cache_fresh(include_optional=True): - refresh_pending = _start_catalog_refresh(manager) - if not payload["apps"]: - installed = manager.installed_payload() - if installed["apps"]: - payload = installed - payload["catalog_refresh_pending"] = refresh_pending - return payload + # Configuration, cache reads and executable discovery can all block on disk. + local = await asyncio.to_thread(_read_local, installed_only=installed_only, config_path=config_path) + if not installed_only: + # Refresh task/throttle state belongs to this event loop, not the reader. + local.payload["catalog_refresh_pending"] = ( + _start_catalog_refresh(local.refresh_manager) if local.refresh_manager is not None else False + ) + return local.payload def cli_apps_action( diff --git a/tests/cli_apps/test_service.py b/tests/cli_apps/test_service.py index ebd0038aa..a546481c8 100644 --- a/tests/cli_apps/test_service.py +++ b/tests/cli_apps/test_service.py @@ -1,16 +1,20 @@ from __future__ import annotations +import asyncio import json import subprocess import sys +import threading import time from pathlib import Path from types import SimpleNamespace +import httpx import pytest from nanobot.agent import plugins as agent_plugins from nanobot.agent.skills import SkillsLoader +from nanobot.apps.cli import service as cli_service from nanobot.apps.cli.service import CliAppError, CliAppManager, CliAppsRuntimeConfig @@ -365,6 +369,64 @@ def test_catalog_cache_fresh_can_include_optional_sources(tmp_path: Path) -> Non assert manager.catalog_cache_fresh(include_optional=True) is False +def test_fetch_registry_async_offloads_cache_io_and_preserves_fallback( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + manager = _manager(tmp_path) + cache_path = manager._cache_path("harness") + _write_cache(cache_path, {"meta": {"updated": "old"}, "clis": []}) + fetched = {"meta": {"updated": "2026-10-17"}, "clis": [{"name": "gimp"}]} + loop_thread = threading.get_ident() + io_threads: list[tuple[str, int]] = [] + network_threads: list[int] = [] + real_cached_registry = manager._cached_registry + real_write = cli_service._write_json + real_client = httpx.AsyncClient + + def read(path: Path): + io_threads.append(("read", threading.get_ident())) + return real_cached_registry(path) + + def write(path: Path, data: dict) -> None: + io_threads.append(("write", threading.get_ident())) + real_write(path, data) + + async def respond(request: httpx.Request) -> httpx.Response: + network_threads.append(threading.get_ident()) + await asyncio.sleep(0) + if len(network_threads) == 1: + return httpx.Response(200, json=fetched) + raise httpx.ConnectError("offline registry", request=request) + + def no_sync_network(*args, **kwargs): + raise AssertionError("registry refresh must keep asynchronous HTTP") + + monkeypatch.setattr(manager, "_cached_registry", read) + monkeypatch.setattr(cli_service, "_write_json", write) + monkeypatch.setattr(cli_service.httpx, "get", no_sync_network) + monkeypatch.setattr( + cli_service.httpx, "AsyncClient", + lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs), + ) + + async def check() -> None: + url = "https://registry.invalid/catalog.json" + assert await manager._fetch_registry_async(url, cache_path, force_refresh=True) == fetched + writes_before_failure = [item for item in io_threads if item[0] == "write"] + assert writes_before_failure + assert await manager._fetch_registry_async(url, cache_path, force_refresh=True) == fetched + assert [item for item in io_threads if item[0] == "write"] == writes_before_failure + + asyncio.run(check()) + + assert json.loads(cache_path.read_text(encoding="utf-8"))["data"] == fetched + assert not list(cache_path.parent.glob(f".{cache_path.name}.*.tmp")) + assert network_threads == [loop_thread, loop_thread] + assert {operation for operation, _ in io_threads} == {"read", "write"} + assert all(thread != loop_thread for _, thread in io_threads), io_threads + + def test_payload_cache_only_without_cache_returns_empty(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: manager = _manager(tmp_path) diff --git a/tests/webui/test_cli_apps_api.py b/tests/webui/test_cli_apps_api.py index 4ab0a0969..d0878213e 100644 --- a/tests/webui/test_cli_apps_api.py +++ b/tests/webui/test_cli_apps_api.py @@ -1,8 +1,17 @@ from __future__ import annotations import asyncio +import json +import os +import threading +import time +from pathlib import Path from typing import Any +import pytest + +from nanobot.apps.cli import service as cli_service +from nanobot.config import home, loader from nanobot.webui import cli_apps_api @@ -166,3 +175,215 @@ def test_cli_apps_payload_reports_not_pending_when_refresh_is_throttled(monkeypa assert manager.fresh_checks == [True] assert payload["catalog_refresh_pending"] is False assert payload["apps"][0]["name"] == "gimp" + + +@pytest.fixture +def _local_cli_apps(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + instance = tmp_path / "home" / ".nanobot" + workspace = tmp_path / "workspace" + bin_dir = tmp_path / "bin" + for path in (instance, workspace, bin_dir): + path.mkdir(parents=True) + config_path = instance / "config.json" + config_path.write_text( + json.dumps({"agents": {"defaults": {"workspace": str(workspace)}}}), + encoding="utf-8", + ) + monkeypatch.setenv("HOME", str(instance.parent)) + monkeypatch.setenv("USERPROFILE", str(instance.parent)) + monkeypatch.setenv("PATH", str(bin_dir)) + monkeypatch.setenv("PATHEXT", ".COM;.EXE;.BAT;.CMD") + monkeypatch.setattr(home, "_home_path", instance) + monkeypatch.setattr(loader, "_current_config_path", config_path) + executable = bin_dir / ("fixture-slow-cli.cmd" if os.name == "nt" else "fixture-slow-cli") + executable.write_text("fixture executable; never executed\n", encoding="utf-8") + executable.chmod(0o755) + manager = cli_service.CliAppManager(workspace=workspace) + for source in ("harness", "public", "extensions"): + rows = [ + {"name": "gimp", "display_name": "GIMP", "entry_point": "fixture-slow-cli", + "package_manager": "bundled", "category": "image"}, + {"name": "other", "entry_point": "fixture-other-cli", "package_manager": "bundled"}, + ] if source == "harness" else [] + manager._cache_path(source).write_text(json.dumps({ + "_cached_at": 0 if source == "extensions" else time.time(), + "data": {"meta": {"updated": "2026-10-17"}, "clis": rows}, + }), encoding="utf-8") + manager._save_installed({ + "gimp": {"entry_point": "fixture-slow-cli", "source": "harness", "strategy": "bundled"}, + }) + skill = workspace / "skills" / "cli-app-gimp" / "SKILL.md" + skill.parent.mkdir(parents=True) + skill.write_text("# GIMP\n", encoding="utf-8") + + def no_network(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("local CLI Apps reads must not use the network") + + monkeypatch.setattr(cli_service.httpx, "get", no_network) + monkeypatch.setattr(cli_service.httpx, "AsyncClient", no_network) + return config_path + + +class _HeldProbe: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + loop = asyncio.get_running_loop() + self.entered = asyncio.Event() + self.release = threading.Event() + self.watchdog_fired = threading.Event() + self.calls: list[tuple[str, int]] = [] + real_which = cli_service.shutil.which + + def which(command: str) -> str | None: + self.calls.append((command, threading.get_ident())) + if command == "fixture-slow-cli": + loop.call_soon_threadsafe(self.entered.set) + self.release.wait() + return real_which(command) + + def watchdog_release() -> None: + self.watchdog_fired.set() + self.release.set() + + monkeypatch.setattr(cli_service.shutil, "which", which) + self.watchdog = threading.Timer(5, watchdog_release) + self.watchdog.start() + + def close(self) -> None: + self.release.set() + self.watchdog.cancel() + self.watchdog.join() + + +@pytest.mark.parametrize("installed_only", [False, True], ids=["full", "installed"]) +def test_cli_apps_payload_keeps_loop_responsive( + _local_cli_apps: Path, + monkeypatch: pytest.MonkeyPatch, + installed_only: bool, +) -> None: + observed: dict[str, list[int]] = {name: [] for name in ("config", "manager", "cache", "freshness")} + real_load = cli_apps_api.load_config + real_init = cli_service.CliAppManager.__init__ + real_read = cli_service._read_json + real_freshness = cli_service.CliAppManager.catalog_cache_fresh + + def load(config_path: Path | None = None) -> Any: + observed["config"].append(threading.get_ident()) + return real_load(config_path) + + def initialize(manager: cli_service.CliAppManager, **kwargs: Any) -> None: + observed["manager"].append(threading.get_ident()) + real_init(manager, **kwargs) + + def read(path: Path) -> Any: + observed["cache"].append(threading.get_ident()) + return real_read(path) + + def freshness(manager: cli_service.CliAppManager, *, include_optional: bool = False) -> bool: + observed["freshness"].append(threading.get_ident()) + return real_freshness(manager, include_optional=include_optional) + + refresh_threads: list[int] = [] + monkeypatch.setattr(cli_apps_api, "load_config", load) + monkeypatch.setattr(cli_service.CliAppManager, "__init__", initialize) + monkeypatch.setattr(cli_service, "_read_json", read) + monkeypatch.setattr(cli_service.CliAppManager, "catalog_cache_fresh", freshness) + monkeypatch.setattr( + cli_apps_api, "_start_catalog_refresh", + lambda manager: refresh_threads.append(threading.get_ident()) or True, + ) + + async def check() -> None: + loop_thread = threading.get_ident() + probe = _HeldProbe(monkeypatch) + + async def unrelated() -> None: + await probe.entered.wait() + await asyncio.sleep(0) + assert not probe.watchdog_fired.is_set(), "watchdog released an event-loop-blocking probe" + assert not probe.release.is_set(), "unrelated coroutine must advance before release" + + observer = asyncio.create_task(unrelated()) + request = asyncio.create_task(cli_apps_api.cli_apps_payload( + installed_only=installed_only, config_path=_local_cli_apps, + )) + try: + await asyncio.wait_for(asyncio.shield(observer), 10) + assert not request.done() + probe.release.set() + payload = await asyncio.wait_for(asyncio.shield(request), 10) + apps = {app["name"]: app for app in payload["apps"]} + assert set(apps) == ({"gimp"} if installed_only else {"gimp", "other"}) + assert payload["installed_count"] == 1 + assert apps["gimp"]["display_name"] == "GIMP" + assert apps["gimp"]["status"] == "installed" + assert apps["gimp"]["available"] is True + assert apps["gimp"]["skill_installed"] is True + if installed_only: + assert "catalog_refresh_pending" not in payload + assert [command for command, _ in probe.calls] == ["fixture-slow-cli"] + assert observed["freshness"] == [] + assert refresh_threads == [] + else: + assert payload["catalog_refresh_pending"] is True + assert observed["freshness"] + assert refresh_threads == [loop_thread] + assert all(observed[name] for name in ("config", "manager", "cache")) + assert all(thread != loop_thread for threads in observed.values() for thread in threads), observed + assert all(thread != loop_thread for _, thread in probe.calls) + finally: + probe.close() + await asyncio.wait_for(asyncio.gather(request, observer, return_exceptions=True), 10) + + asyncio.run(check()) + + +def test_cli_apps_payload_cancellation_discards_late_refresh( + _local_cli_apps: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + refreshes: list[cli_service.CliAppManager] = [] + monkeypatch.setattr( + cli_apps_api, "_start_catalog_refresh", lambda manager: refreshes.append(manager) or True, + ) + + async def check() -> None: + loop = asyncio.get_running_loop() + worker_started = threading.Event() + worker_finished = asyncio.Event() + real_to_thread = asyncio.to_thread + + async def tracked_to_thread(func: Any, /, *args: Any, **kwargs: Any) -> Any: + def run() -> Any: + worker_started.set() + try: + return func(*args, **kwargs) + finally: + loop.call_soon_threadsafe(worker_finished.set) + + return await real_to_thread(run) + + monkeypatch.setattr(cli_apps_api.asyncio, "to_thread", tracked_to_thread) + probe = _HeldProbe(monkeypatch) + request = asyncio.create_task(cli_apps_api.cli_apps_payload(config_path=_local_cli_apps)) + try: + await asyncio.wait_for(probe.entered.wait(), 10) + assert not probe.watchdog_fired.is_set(), "cancellation must run while the probe is held" + assert not probe.release.is_set() + assert worker_started.is_set() + request.cancel() + with pytest.raises(asyncio.CancelledError): + await request + assert not worker_finished.is_set(), "cancelling the waiter must not finish the worker" + assert refreshes == [] + probe.release.set() + await asyncio.wait_for(worker_finished.wait(), 10) + await asyncio.sleep(0) + assert refreshes == [], "a cancelled local read must not start a late catalog refresh" + finally: + probe.close() + request.cancel() + await asyncio.gather(request, return_exceptions=True) + if worker_started.is_set(): + await asyncio.wait_for(worker_finished.wait(), 10) + + asyncio.run(check())