fix(webui): avoid blocking the gateway on skill loading
This commit is contained in:
1 parent
a721eb8476
commit
aeca1c0f1a
4 files changed
+145
-54
No files matched your search
@@ -7,12 +7,14 @@ import socket
|
|||||||
import time
|
import time
|
||||||
from contextlib import suppress
|
from contextlib import suppress
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from threading import Event
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.agent.skills import SkillsLoader
|
||||||
from nanobot.bus.events import OutboundMessage
|
from nanobot.bus.events import OutboundMessage
|
||||||
from nanobot.channels.base import BaseChannel
|
from nanobot.channels.base import BaseChannel
|
||||||
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
|
||||||
@@ -610,6 +612,60 @@ async def test_webui_skills_route_requires_token_and_hides_paths(
|
|||||||
await server_task
|
await server_task
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize("suffix", ["", "/workspace-skill"], ids=["list", "detail"])
|
||||||
|
async def test_webui_skill_reads_do_not_block_other_http_routes(
|
||||||
|
bus: MagicMock,
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
suffix: str,
|
||||||
|
) -> None:
|
||||||
|
skill_dir = tmp_path / "skills" / "workspace-skill"
|
||||||
|
skill_dir.mkdir(parents=True)
|
||||||
|
(skill_dir / "SKILL.md").write_text(
|
||||||
|
"---\nname: workspace-skill\ndescription: Workspace skill.\n---\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
entered = asyncio.Event()
|
||||||
|
release = Event()
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
discover = SkillsLoader._discover_skills
|
||||||
|
|
||||||
|
def slow_discovery(loader: SkillsLoader) -> list[dict[str, str]]:
|
||||||
|
loop.call_soon_threadsafe(entered.set)
|
||||||
|
if not release.wait(3.0):
|
||||||
|
raise TimeoutError("skill scan was not released")
|
||||||
|
return discover(loader)
|
||||||
|
|
||||||
|
monkeypatch.setattr(SkillsLoader, "_discover_skills", slow_discovery)
|
||||||
|
port = _free_port()
|
||||||
|
channel = _ch(
|
||||||
|
bus, session_manager=_seed_session(tmp_path), workspace_path=tmp_path, port=port,
|
||||||
|
)
|
||||||
|
server_task = asyncio.create_task(channel.start())
|
||||||
|
token = channel.gateway.tokens.issue_api_token(300)
|
||||||
|
auth = {"Authorization": f"Bearer {token}"}
|
||||||
|
skills_task = asyncio.create_task(
|
||||||
|
_http_get(f"http://127.0.0.1:{port}/api/webui/skills{suffix}", headers=auth)
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(entered.wait(), 2.0)
|
||||||
|
workspaces = await asyncio.wait_for(
|
||||||
|
_http_get(f"http://127.0.0.1:{port}/api/workspaces", headers=auth), 1.0,
|
||||||
|
)
|
||||||
|
assert workspaces.status_code == 200
|
||||||
|
assert not skills_task.done()
|
||||||
|
|
||||||
|
release.set()
|
||||||
|
skills = await skills_task
|
||||||
|
assert skills.status_code == 200
|
||||||
|
finally:
|
||||||
|
release.set()
|
||||||
|
await asyncio.gather(skills_task, return_exceptions=True)
|
||||||
|
await channel.stop()
|
||||||
|
await server_task
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_webui_skill_management_routes(
|
async def test_webui_skill_management_routes(
|
||||||
bus: MagicMock,
|
bus: MagicMock,
|
||||||
|
|||||||
+28
-26
@@ -29,16 +29,17 @@ def webui_skills_payload(
|
|||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
"""Return agent skills without leaking local filesystem paths."""
|
"""Return agent skills without leaking local filesystem paths."""
|
||||||
loader = SkillsLoader(workspace_path)
|
loader = SkillsLoader(workspace_path)
|
||||||
entries = sorted(
|
with loader.snapshot():
|
||||||
loader.list_skills(filter_unavailable=False),
|
entries = sorted(
|
||||||
key=lambda entry: (entry.get("source") != "workspace", entry["name"]),
|
loader.list_skills(filter_unavailable=False),
|
||||||
)
|
key=lambda entry: (entry.get("source") != "workspace", entry["name"]),
|
||||||
return {
|
)
|
||||||
"skills": [
|
return {
|
||||||
_skill_payload(loader, entry, disabled_skills=disabled_skills)
|
"skills": [
|
||||||
for entry in entries
|
_skill_payload(loader, entry, disabled_skills=disabled_skills)
|
||||||
]
|
for entry in entries
|
||||||
}
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def webui_skill_detail_payload(
|
def webui_skill_detail_payload(
|
||||||
@@ -49,22 +50,23 @@ def webui_skill_detail_payload(
|
|||||||
) -> dict[str, Any] | None:
|
) -> dict[str, Any] | None:
|
||||||
"""Return a single skill's safe detail payload."""
|
"""Return a single skill's safe detail payload."""
|
||||||
loader = SkillsLoader(workspace_path)
|
loader = SkillsLoader(workspace_path)
|
||||||
entries = loader.list_skills(filter_unavailable=False)
|
with loader.snapshot():
|
||||||
entry = next((item for item in entries if item["name"] == name), None)
|
entries = loader.list_skills(filter_unavailable=False)
|
||||||
if entry is None:
|
entry = next((item for item in entries if item["name"] == name), None)
|
||||||
return None
|
if entry is None:
|
||||||
metadata = loader.get_skill_metadata(name)
|
return None
|
||||||
return {
|
metadata = loader.get_skill_metadata(name)
|
||||||
**_skill_payload(
|
return {
|
||||||
loader,
|
**_skill_payload(
|
||||||
entry,
|
loader,
|
||||||
metadata=metadata,
|
entry,
|
||||||
disabled_skills=disabled_skills,
|
metadata=metadata,
|
||||||
),
|
disabled_skills=disabled_skills,
|
||||||
"requirements": loader.get_skill_requirements(name),
|
),
|
||||||
"install_options": _install_options(metadata),
|
"requirements": loader.get_skill_requirements(name),
|
||||||
"raw_markdown": loader.load_skill(name) or "",
|
"install_options": _install_options(metadata),
|
||||||
}
|
"raw_markdown": loader.load_skill(name) or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def set_webui_skill_enabled(
|
def set_webui_skill_enabled(
|
||||||
|
|||||||
+22
-28
@@ -1627,14 +1627,14 @@ class GatewayHTTPHandler:
|
|||||||
if got == "/api/webui/skills/install":
|
if got == "/api/webui/skills/install":
|
||||||
return await self._handle_webui_skill_install(connection, request)
|
return await self._handle_webui_skill_install(connection, request)
|
||||||
if got == "/api/webui/skills/update":
|
if got == "/api/webui/skills/update":
|
||||||
return self._handle_webui_skill_update(request)
|
return await self._handle_webui_skill_update(request)
|
||||||
if got == "/api/webui/skills/delete":
|
if got == "/api/webui/skills/delete":
|
||||||
return self._handle_webui_skill_delete(connection, request)
|
return await self._handle_webui_skill_delete(connection, request)
|
||||||
if got == "/api/webui/skills":
|
if got == "/api/webui/skills":
|
||||||
return self._handle_webui_skills(request)
|
return await self._handle_webui_skills(request)
|
||||||
m = re.match(r"^/api/webui/skills/([^/]+)$", got)
|
m = re.match(r"^/api/webui/skills/([^/]+)$", got)
|
||||||
if m:
|
if m:
|
||||||
return self._handle_webui_skill_detail(request, m.group(1))
|
return await self._handle_webui_skill_detail(request, m.group(1))
|
||||||
if got in {"/api/webui/star-prompt/claim", "/api/webui/star-prompt/dismiss"}:
|
if got in {"/api/webui/star-prompt/claim", "/api/webui/star-prompt/dismiss"}:
|
||||||
if not self.check_api_token(request):
|
if not self.check_api_token(request):
|
||||||
return _http_error(401, "Unauthorized")
|
return _http_error(401, "Unauthorized")
|
||||||
@@ -1709,15 +1709,17 @@ class GatewayHTTPHandler:
|
|||||||
return _http_error(exc.status, exc.message)
|
return _http_error(exc.status, exc.message)
|
||||||
return _http_json_response(dict(payload))
|
return _http_json_response(dict(payload))
|
||||||
|
|
||||||
def _handle_webui_skills(self, request: WsRequest) -> Response:
|
async def _load_webui_skills(self) -> dict[str, Any]:
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
webui_skills_payload,
|
||||||
|
self.skills_workspace_path,
|
||||||
|
disabled_skills=set(self.disabled_skills),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _handle_webui_skills(self, request: WsRequest) -> Response:
|
||||||
if not self.check_api_token(request):
|
if not self.check_api_token(request):
|
||||||
return _http_error(401, "Unauthorized")
|
return _http_error(401, "Unauthorized")
|
||||||
return _http_json_response(
|
return _http_json_response(await self._load_webui_skills())
|
||||||
webui_skills_payload(
|
|
||||||
self.skills_workspace_path,
|
|
||||||
disabled_skills=self.disabled_skills,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
async def _handle_webui_skills_search(self, request: WsRequest) -> Response:
|
async def _handle_webui_skills_search(self, request: WsRequest) -> Response:
|
||||||
if not self.check_api_token(request):
|
if not self.check_api_token(request):
|
||||||
@@ -1797,10 +1799,7 @@ class GatewayHTTPHandler:
|
|||||||
self._log.exception("skill installation failed")
|
self._log.exception("skill installation failed")
|
||||||
return _http_error(500, "skill installation failed")
|
return _http_error(500, "skill installation failed")
|
||||||
return _http_json_response({
|
return _http_json_response({
|
||||||
**webui_skills_payload(
|
**(await self._load_webui_skills()),
|
||||||
self.skills_workspace_path,
|
|
||||||
disabled_skills=self.disabled_skills,
|
|
||||||
),
|
|
||||||
"last_action": action,
|
"last_action": action,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1815,7 +1814,7 @@ class GatewayHTTPHandler:
|
|||||||
self._log.exception("failed to load remote package install policy")
|
self._log.exception("failed to load remote package install policy")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _handle_webui_skill_update(self, request: WsRequest) -> Response:
|
async def _handle_webui_skill_update(self, request: WsRequest) -> Response:
|
||||||
if not self.check_api_token(request):
|
if not self.check_api_token(request):
|
||||||
return _http_error(401, "Unauthorized")
|
return _http_error(401, "Unauthorized")
|
||||||
query = _request_query(request)
|
query = _request_query(request)
|
||||||
@@ -1837,14 +1836,11 @@ class GatewayHTTPHandler:
|
|||||||
return _http_error(exc.status, exc.message)
|
return _http_error(exc.status, exc.message)
|
||||||
self._apply_skill_state()
|
self._apply_skill_state()
|
||||||
return _http_json_response({
|
return _http_json_response({
|
||||||
**webui_skills_payload(
|
**(await self._load_webui_skills()),
|
||||||
self.skills_workspace_path,
|
|
||||||
disabled_skills=self.disabled_skills,
|
|
||||||
),
|
|
||||||
"last_action": action,
|
"last_action": action,
|
||||||
})
|
})
|
||||||
|
|
||||||
def _handle_webui_skill_delete(
|
async def _handle_webui_skill_delete(
|
||||||
self,
|
self,
|
||||||
connection: Any,
|
connection: Any,
|
||||||
request: WsRequest,
|
request: WsRequest,
|
||||||
@@ -1867,10 +1863,7 @@ class GatewayHTTPHandler:
|
|||||||
return _http_error(exc.status, exc.message)
|
return _http_error(exc.status, exc.message)
|
||||||
self._apply_skill_state()
|
self._apply_skill_state()
|
||||||
return _http_json_response({
|
return _http_json_response({
|
||||||
**webui_skills_payload(
|
**(await self._load_webui_skills()),
|
||||||
self.skills_workspace_path,
|
|
||||||
disabled_skills=self.disabled_skills,
|
|
||||||
),
|
|
||||||
"last_action": action,
|
"last_action": action,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -1878,7 +1871,7 @@ class GatewayHTTPHandler:
|
|||||||
if self.skill_state_action is not None:
|
if self.skill_state_action is not None:
|
||||||
self.skill_state_action(set(self.disabled_skills))
|
self.skill_state_action(set(self.disabled_skills))
|
||||||
|
|
||||||
def _handle_webui_skill_detail(self, request: WsRequest, raw_name: str) -> Response:
|
async def _handle_webui_skill_detail(self, request: WsRequest, raw_name: str) -> Response:
|
||||||
if not self.check_api_token(request):
|
if not self.check_api_token(request):
|
||||||
return _http_error(401, "Unauthorized")
|
return _http_error(401, "Unauthorized")
|
||||||
from urllib.parse import unquote
|
from urllib.parse import unquote
|
||||||
@@ -1886,10 +1879,11 @@ class GatewayHTTPHandler:
|
|||||||
name = unquote(raw_name)
|
name = unquote(raw_name)
|
||||||
if not name or "/" in name or "\\" in name:
|
if not name or "/" in name or "\\" in name:
|
||||||
return _http_error(400, "invalid skill name")
|
return _http_error(400, "invalid skill name")
|
||||||
payload = webui_skill_detail_payload(
|
payload = await asyncio.to_thread(
|
||||||
|
webui_skill_detail_payload,
|
||||||
self.skills_workspace_path,
|
self.skills_workspace_path,
|
||||||
name,
|
name,
|
||||||
disabled_skills=self.disabled_skills,
|
disabled_skills=set(self.disabled_skills),
|
||||||
)
|
)
|
||||||
if payload is None:
|
if payload is None:
|
||||||
return _http_error(404, "skill not found")
|
return _http_error(404, "skill not found")
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.agent import plugins as agent_plugins
|
||||||
from nanobot.config.loader import load_config, save_config
|
from nanobot.config.loader import load_config, save_config
|
||||||
from nanobot.config.schema import Config
|
from nanobot.config.schema import Config
|
||||||
from nanobot.webui.skills_api import (
|
from nanobot.webui.skills_api import (
|
||||||
@@ -74,6 +77,42 @@ def test_skill_detail_exposes_copyable_install_commands(tmp_path: Path) -> None:
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("detail", [False, True], ids=["list", "detail"])
|
||||||
|
def test_skill_payload_verifies_plugins_once_per_request(
|
||||||
|
tmp_path: Path,
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
detail: bool,
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setattr(agent_plugins, "get_config_path", lambda: tmp_path / "config.json")
|
||||||
|
workspace_skill = _write_skill(tmp_path, "custom-skill") / "SKILL.md"
|
||||||
|
plugin = tmp_path / "plugins" / "demo"
|
||||||
|
_write_skill(plugin, "plugin-skill")
|
||||||
|
(plugin / "plugin.json").write_text(
|
||||||
|
json.dumps({"$schema": agent_plugins.AGENT_PLUGIN_SCHEMA, "name": "demo"}),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
agent_plugins.set_agent_plugin_enabled(tmp_path, "demo", True)
|
||||||
|
fingerprint = Mock(wraps=agent_plugins._package_fingerprint)
|
||||||
|
monkeypatch.setattr(agent_plugins, "_package_fingerprint", fingerprint)
|
||||||
|
|
||||||
|
for expected_calls, description in enumerate(["Original", "Updated"], start=1):
|
||||||
|
workspace_skill.write_text(
|
||||||
|
f"---\nname: custom-skill\ndescription: {description}\n---\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
if detail:
|
||||||
|
payload = webui_skill_detail_payload(tmp_path, "custom-skill")
|
||||||
|
assert payload is not None
|
||||||
|
skill = payload
|
||||||
|
else:
|
||||||
|
payload = webui_skills_payload(tmp_path)
|
||||||
|
skill = next(item for item in payload["skills"] if item["name"] == "custom-skill")
|
||||||
|
assert any(item["source"] == "plugin" for item in payload["skills"])
|
||||||
|
|
||||||
|
assert skill["description"] == description
|
||||||
|
assert fingerprint.call_count == expected_calls
|
||||||
|
|
||||||
|
|
||||||
def test_set_webui_skill_enabled_persists_and_updates_runtime(
|
def test_set_webui_skill_enabled_persists_and_updates_runtime(
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
|||||||
Reference in new issue
Block a user