From 70eca8343b8be26572b66712b7b6daa2209d970b Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:47:51 +0800 Subject: [PATCH] fix(skills): distinguish marketplace installation sources --- docs/webui.md | 2 + nanobot/webui/skills_marketplace.py | 235 +++++++++++------- tests/webui/test_skills_marketplace.py | 14 +- .../webui/test_skills_marketplace_identity.py | 199 +++++++++++++++ .../components/settings/SkillsMarketplace.tsx | 84 ++++--- webui/src/i18n/locales/en/common.json | 4 + webui/src/i18n/locales/es/common.json | 4 + webui/src/i18n/locales/fr/common.json | 4 + webui/src/i18n/locales/id/common.json | 4 + webui/src/i18n/locales/ja/common.json | 4 + webui/src/i18n/locales/ko/common.json | 4 + webui/src/i18n/locales/pt-BR/common.json | 4 + webui/src/i18n/locales/vi/common.json | 4 + webui/src/i18n/locales/zh-CN/common.json | 4 + webui/src/i18n/locales/zh-TW/common.json | 4 + webui/src/lib/types.ts | 1 + webui/src/tests/skills-marketplace.test.tsx | 78 ++++++ 17 files changed, 518 insertions(+), 135 deletions(-) create mode 100644 tests/webui/test_skills_marketplace_identity.py diff --git a/docs/webui.md b/docs/webui.md index 6c9a86b2d..a26d7e17a 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -249,6 +249,8 @@ Open **Skills → Discover** to browse or search skills from skills.sh and Skill Marketplace skills are third-party instructions and may include executable scripts. Review the source and instructions before installing one, and enable only skills you trust with the same files, tools, and credentials available to your agent. +Discover marks a skill as installed only when its recorded marketplace source matches. A skill with the same name from another source is a name conflict, not another installed copy. Older or manually copied skills without a source record remain usable and show “Installed source unknown.” Review the existing skill in **Installed** before removing it if you want a different source; installation never replaces it automatically. New installs keep a small `.nanobot-origin.json` receipt beside `SKILL.md`. Keep that receipt with the skill when moving or backing up the workspace. Older nanobot versions ignore it; no skill-directory rename or history migration is required. + ## Automations Automations are agent turns that run later in a linked topic. Create them from the topic or channel where they are supposed to run so nanobot keeps the correct target context. When an automation runs, it normally delivers the result back to that topic. diff --git a/nanobot/webui/skills_marketplace.py b/nanobot/webui/skills_marketplace.py index bbc09fd07..2ad4cdb10 100644 --- a/nanobot/webui/skills_marketplace.py +++ b/nanobot/webui/skills_marketplace.py @@ -2,6 +2,7 @@ from __future__ import annotations import asyncio import hashlib +import json import os import re import shutil @@ -18,6 +19,7 @@ import httpx from nanobot.agent.skills import SkillsLoader from nanobot.security.network import PinnedDNSAsyncTransport from nanobot.security.workspace_policy import WorkspaceBoundaryError, require_path_within +from nanobot.utils.atomic_file import atomic_write_text _PROVIDER_ALL = "all" _PROVIDER_SKILLS_SH = "skills_sh" @@ -50,6 +52,7 @@ _SKILLHUB_MAX_UNPACKED_BYTES = 100 * 1024 * 1024 _SKILLHUB_MAX_FILES = 1_000 # The skills CLI's OpenClaw adapter copies into /skills, nanobot's layout too. _CLI_AGENT = "openclaw" +_ORIGIN_FILE = ".nanobot-origin.json" _weekly_cache: dict[tuple[str, str], list[int]] = {} _weekly_cache_expires_at = 0.0 @@ -126,7 +129,7 @@ async def _trending_skills_sh_skills( status=502, ) from exc - installed = _installed_skill_names(workspace_path) + installed = _installed_skill_origins(workspace_path) rows = payload.get("skills", []) skills: list[dict[str, Any]] = [] seen_sources: set[str] = set() @@ -217,7 +220,7 @@ async def _search_skills_sh_skills( status=502, ) from exc - installed = _installed_skill_names(workspace_path) + installed = _installed_skill_origins(workspace_path) rows = payload.get("skills", []) skills: list[dict[str, Any]] = [] for row in rows: @@ -255,7 +258,7 @@ async def _search_skillhub_skills( status=502, ) from exc - installed = _installed_skill_names(workspace_path) + installed = _installed_skill_origins(workspace_path) rows = payload.get("results", []) skills = [ skill @@ -287,7 +290,7 @@ async def _trending_skillhub_skills( status=502, ) from exc - installed = _installed_skill_names(workspace_path) + installed = _installed_skill_origins(workspace_path) rows = payload.get("skills", []) skills: list[dict[str, Any]] = [] for rank, row in enumerate(rows, start=1): @@ -352,21 +355,10 @@ async def _install_skills_sh_skill( if not _valid_skill_id(skill_id): raise SkillsMarketplaceError("invalid skill name") - loader = SkillsLoader(workspace_path) - existing = {entry["name"]: entry for entry in loader.list_skills(filter_unavailable=False)} - if skill_id in existing: + if _already_installed(workspace_path, skill_id, _PROVIDER_SKILLS_SH, source): return {"installed": True, "already_installed": True, "name": skill_id} - workspace = workspace_path.expanduser().resolve() - workspace.mkdir(parents=True, exist_ok=True) - try: - require_path_within( - workspace / "skills", - workspace, - message="skills directory must stay inside the workspace", - ) - except WorkspaceBoundaryError as exc: - raise SkillsMarketplaceError(str(exc), status=403) from exc + target = _install_target(workspace_path, skill_id) npx = shutil.which("npx") if npx is None: @@ -391,42 +383,41 @@ async def _install_skills_sh_skill( "--yes", ) - process = await asyncio.create_subprocess_exec( - *command, - cwd=str(workspace), - env=env, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.STDOUT, - ) - try: - output, _ = await asyncio.wait_for( - process.communicate(), - timeout=_INSTALL_TIMEOUT_SECONDS, + # Stage the CLI's output too: it must not overwrite a same-name installation. + with tempfile.TemporaryDirectory(prefix=".nanobot-install-", dir=target.parent) as temporary: + process = await asyncio.create_subprocess_exec( + *command, + cwd=temporary, + env=env, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, ) - except TimeoutError as exc: - process.kill() - await process.communicate() - raise SkillsMarketplaceError("skill installation timed out", status=504) from exc + try: + output, _ = await asyncio.wait_for( + process.communicate(), timeout=_INSTALL_TIMEOUT_SECONDS, + ) + except (TimeoutError, asyncio.CancelledError) as exc: + process.kill() + await process.communicate() + if isinstance(exc, asyncio.CancelledError): + raise + raise SkillsMarketplaceError("skill installation timed out", status=504) from exc - if process.returncode != 0: - detail = _safe_output_tail(output) - message = "skill installation failed" - if detail: - message = f"{message}: {detail}" - raise SkillsMarketplaceError(message, status=502) + if process.returncode != 0: + detail = _safe_output_tail(output) + message = "skill installation failed" + if detail: + message = f"{message}: {detail}" + raise SkillsMarketplaceError(message, status=502) - installed = next( - ( - entry - for entry in loader.list_skills(filter_unavailable=False) - if entry["source"] == "workspace" and entry["name"] == skill_id - ), - None, - ) - if installed is None: - raise SkillsMarketplaceError( - "installer completed but the skill was not found in this workspace", - status=502, + stage = Path(temporary) / "skills" / skill_id + try: + require_path_within(stage, Path(temporary)) + require_path_within(stage / "SKILL.md", stage) + except WorkspaceBoundaryError as exc: + raise SkillsMarketplaceError("installer returned an unsafe skill path", status=403) from exc + _publish_skill( + stage, target, provider=_PROVIDER_SKILLS_SH, source=source, skill_id=skill_id, ) return {"installed": True, "already_installed": False, "name": skill_id} @@ -441,9 +432,7 @@ async def _install_skillhub_skill( if requested_version and _VERSION_RE.fullmatch(requested_version) is None: raise SkillsMarketplaceError("invalid SkillHub skill version") - loader = SkillsLoader(workspace_path) - existing = {entry["name"]: entry for entry in loader.list_skills(filter_unavailable=False)} - if skill_id in existing: + if _already_installed(workspace_path, skill_id, _PROVIDER_SKILLHUB): return { "installed": True, "already_installed": True, @@ -451,18 +440,7 @@ async def _install_skillhub_skill( "provider": _PROVIDER_SKILLHUB, } - workspace = workspace_path.expanduser().resolve() - workspace.mkdir(parents=True, exist_ok=True) - try: - skills_root = require_path_within( - workspace / "skills", - workspace, - message="skills directory must stay inside the workspace", - ) - except WorkspaceBoundaryError as exc: - raise SkillsMarketplaceError(str(exc), status=403) from exc - skills_root.mkdir(parents=True, exist_ok=True) - target = skills_root / skill_id + target = _install_target(workspace_path, skill_id) try: async with _skillhub_client() as client: @@ -480,7 +458,7 @@ async def _install_skillhub_skill( with tempfile.TemporaryDirectory( prefix=".skillhub-install-", - dir=skills_root, + dir=target.parent, ) as temporary: temporary_path = Path(temporary) archive_path = temporary_path / f"{skill_id}.zip" @@ -498,14 +476,9 @@ async def _install_skillhub_skill( status=502, ) _extract_skillhub_archive(archive_path, stage_path) - if target.exists(): - return { - "installed": True, - "already_installed": True, - "name": skill_id, - "provider": _PROVIDER_SKILLHUB, - } - os.replace(stage_path, target) + _publish_skill( + stage_path, target, provider=_PROVIDER_SKILLHUB, source="", skill_id=skill_id, + ) except SkillsMarketplaceError: raise except (httpx.HTTPError, OSError, zipfile.BadZipFile) as exc: @@ -514,19 +487,6 @@ async def _install_skillhub_skill( status=502, ) from exc - installed = next( - ( - entry - for entry in loader.list_skills(filter_unavailable=False) - if entry["source"] == "workspace" and entry["name"] == skill_id - ), - None, - ) - if installed is None: - raise SkillsMarketplaceError( - "installer completed but the skill was not found in this workspace", - status=502, - ) return { "installed": True, "already_installed": False, @@ -736,16 +696,95 @@ def _skillhub_client() -> httpx.AsyncClient: ) -def _installed_skill_names(workspace_path: Path) -> set[str]: - return { - entry["name"] - for entry in SkillsLoader(workspace_path).list_skills(filter_unavailable=False) - } +def _installed_skill_origins(workspace_path: Path) -> dict[str, tuple[str, str] | None]: + """Read optional installation receipts, never infer origin from a skill name.""" + installed: dict[str, tuple[str, str] | None] = {} + for entry in SkillsLoader(workspace_path).list_skills(filter_unavailable=False): + name = entry["name"] + installed[name] = None + if entry["source"] != "workspace": + continue + try: + receipt = require_path_within( + Path(entry["path"]).parent / _ORIGIN_FILE, workspace_path.expanduser().resolve(), + ) + with receipt.open(encoding="utf-8") as handle: + raw: object = json.loads(handle.read(4097)) + except (OSError, ValueError, WorkspaceBoundaryError): + continue + if not isinstance(raw, dict): + continue + data = cast(dict[str, object], raw) + if data.get("skill_id") != name: + continue + provider, source = data.get("provider"), data.get("source") + if provider == _PROVIDER_SKILLS_SH and isinstance(source, str) and _SOURCE_RE.fullmatch(source): + installed[name] = (_PROVIDER_SKILLS_SH, source.lower()) + elif provider == _PROVIDER_SKILLHUB and source == "": + # SkillHub's download API addresses a globally unique slug, not its display handle. + installed[name] = (_PROVIDER_SKILLHUB, "") + return installed + + +def _installation_status( + installed: dict[str, tuple[str, str] | None], + skill_id: str, + provider: str, + source: str = "", +) -> str: + if skill_id not in installed: + return "available" + origin = installed[skill_id] + if origin is None: + return "unknown" + return "installed" if origin == (provider, source.lower()) else "conflict" + + +def _already_installed(workspace: Path, skill_id: str, provider: str, source: str = "") -> bool: + status = _installation_status(_installed_skill_origins(workspace), skill_id, provider, source) + if status in {"conflict", "unknown"}: + raise SkillsMarketplaceError( + "a skill with this name already exists; review it in Installed before removing it", + status=409, + ) + return status == "installed" + + +def _install_target(workspace_path: Path, skill_id: str) -> Path: + workspace = workspace_path.expanduser().resolve() + try: + root = require_path_within( + workspace / "skills", workspace, + message="skills directory must stay inside the workspace", + ) + except WorkspaceBoundaryError as exc: + raise SkillsMarketplaceError(str(exc), status=403) from exc + root.mkdir(parents=True, exist_ok=True) + target = root / skill_id + if os.path.lexists(target): + raise SkillsMarketplaceError("skill directory already exists; no files were replaced", status=409) + return target + + +def _publish_skill(stage: Path, target: Path, *, provider: str, source: str, skill_id: str) -> None: + if not (stage / "SKILL.md").is_file(): + raise SkillsMarketplaceError("installer completed but the skill was not found in this workspace", status=502) + atomic_write_text(stage / _ORIGIN_FILE, json.dumps({ + "provider": provider, "source": source, "skill_id": skill_id, + })) + if os.path.lexists(target): + raise SkillsMarketplaceError("skill directory already exists; no files were replaced", status=409) + try: + stage.rename(target) + except OSError as exc: + if os.path.lexists(target): + raise SkillsMarketplaceError("skill directory already exists; no files were replaced", status=409) from exc + raise def _marketplace_skill( row: dict[str, Any], - installed: set[str], + installed: dict[str, tuple[str, str] | None], *, rank: int | None = None, ) -> dict[str, Any] | None: @@ -759,6 +798,7 @@ def _marketplace_skill( if not isinstance(display_name, str) or not display_name.strip(): display_name = skill_id installs = row.get("installs") + status = _installation_status(installed, skill_id, _PROVIDER_SKILLS_SH, source) skill: dict[str, Any] = { "id": f"{source}/{skill_id}", "skill_id": skill_id, @@ -767,7 +807,8 @@ def _marketplace_skill( "provider": _PROVIDER_SKILLS_SH, "installs": installs if isinstance(installs, int) and installs >= 0 else 0, "url": f"https://skills.sh/{source}/{skill_id}", - "installed": skill_id in installed, + "installed": status == "installed", + "installation_status": status, "install_supported": skills_install_supported(), "metric": "installs_24h" if rank is not None else "installs_total", } @@ -778,7 +819,7 @@ def _marketplace_skill( def _skillhub_skill( row: dict[str, Any], - installed: set[str], + installed: dict[str, tuple[str, str] | None], *, rank: int | None = None, ) -> dict[str, Any] | None: @@ -809,6 +850,7 @@ def _skillhub_skill( if not isinstance(version, str) or _VERSION_RE.fullmatch(version) is None: version = "" + status = _installation_status(installed, skill_id, _PROVIDER_SKILLHUB) skill: dict[str, Any] = { "id": f"{_PROVIDER_SKILLHUB}:{skill_id}", "skill_id": skill_id, @@ -819,7 +861,8 @@ def _skillhub_skill( "downloads": downloads if isinstance(downloads, int) and downloads >= 0 else 0, "url": f"{_SKILLHUB_PAGE_BASE_URL}/skills/{quote(handle.strip(), safe='')}/" f"{quote(skill_id, safe='')}", - "installed": skill_id in installed, + "installed": status == "installed", + "installation_status": status, "install_supported": True, "metric": "installs_total", "version": version, diff --git a/tests/webui/test_skills_marketplace.py b/tests/webui/test_skills_marketplace.py index cb549f17e..9f671760f 100644 --- a/tests/webui/test_skills_marketplace.py +++ b/tests/webui/test_skills_marketplace.py @@ -1,5 +1,6 @@ import hashlib import io +import json import zipfile from pathlib import Path from typing import Any @@ -88,7 +89,8 @@ async def test_search_marketplace_skills_filters_and_marks_installed( "provider": "skills_sh", "installs": 42, "url": "https://skills.sh/acme/agent-skills/react-testing", - "installed": True, + "installed": False, + "installation_status": "unknown", "install_supported": True, "metric": "installs_total", } @@ -162,6 +164,7 @@ async def test_search_skillhub_skills_normalizes_provider_metadata( "downloads": 142525, "url": "https://skillhub.cn/skills/tencent-adm/ima-skills", "installed": False, + "installation_status": "available", "install_supported": True, "metric": "installs_total", "version": "1.1.8", @@ -355,7 +358,7 @@ async def test_install_marketplace_skill_uses_official_cli_and_workspace( returncode = 0 async def communicate(self) -> tuple[bytes, None]: - skill_dir = tmp_path / "skills" / "react-testing" + skill_dir = Path(seen["cwd"]) / "skills" / "react-testing" skill_dir.mkdir(parents=True) (skill_dir / "SKILL.md").write_text( "---\nname: react-testing\n---\n", @@ -403,7 +406,9 @@ async def test_install_marketplace_skill_uses_official_cli_and_workspace( "--copy", "--yes", ) - assert seen["cwd"] == str(tmp_path.resolve()) + assert Path(seen["cwd"]).parent == tmp_path.resolve() / "skills" + assert not Path(seen["cwd"]).exists() + assert (tmp_path / "skills" / "react-testing" / "SKILL.md").is_file() assert seen["env"]["DISABLE_TELEMETRY"] == "1" @@ -560,6 +565,9 @@ async def test_install_marketplace_skill_is_idempotent( skill_dir = tmp_path / "skills" / "already-here" skill_dir.mkdir(parents=True) (skill_dir / "SKILL.md").write_text("---\nname: already-here\n---\n", encoding="utf-8") + (skill_dir / ".nanobot-origin.json").write_text(json.dumps({ + "provider": "skills_sh", "source": "acme/agent-skills", "skill_id": "already-here", + }), encoding="utf-8") launch = pytest.fail monkeypatch.setattr( "nanobot.webui.skills_marketplace.asyncio.create_subprocess_exec", diff --git a/tests/webui/test_skills_marketplace_identity.py b/tests/webui/test_skills_marketplace_identity.py new file mode 100644 index 000000000..5c37fedc0 --- /dev/null +++ b/tests/webui/test_skills_marketplace_identity.py @@ -0,0 +1,199 @@ +"""Marketplace identity must not be confused with the loader's local skill name.""" + +import asyncio +import json +from pathlib import Path + +import httpx +import pytest + +from nanobot.agent.skills import SkillsLoader +from nanobot.config.loader import save_config +from nanobot.config.schema import Config +from nanobot.webui.skills_api import ( + delete_webui_skill, + webui_skill_detail_payload, + webui_skills_payload, +) +from nanobot.webui.skills_marketplace import ( + SkillsMarketplaceError, + install_marketplace_skill, + search_marketplace_skills, + trending_marketplace_skills, +) + +NAME = "agent-browser" +SOURCE = "vercel-labs/agent-browser" + + +@pytest.fixture +def catalog(monkeypatch: pytest.MonkeyPatch) -> None: + def respond(request: httpx.Request) -> httpx.Response: + rows = [ + {"skillId": NAME, "source": SOURCE}, + {"skillId": NAME, "source": "101-skills/superpowers"}, + ] + if request.url.host == "api.skillhub.cn": + rows = [{"slug": NAME, "namespace": {"handle": "someone"}}] + key = "results" if request.url.path.endswith("search") else "skills" + else: + key = "skills" + return httpx.Response(200, json={key: rows}) + + for client in ("_skills_client", "_skillhub_client"): + monkeypatch.setattr( + f"nanobot.webui.skills_marketplace.{client}", + lambda: httpx.AsyncClient(transport=httpx.MockTransport(respond)), + ) + + +@pytest.fixture +def installer(monkeypatch: pytest.MonkeyPatch) -> list[Path]: + stages: list[Path] = [] + + async def launch(*command: str, cwd: str, **_kwargs: object): + stage = Path(cwd) / "skills" / NAME + stages.append(stage) + + class Process: + returncode = 0 + + async def communicate(self): + stage.mkdir(parents=True) + (stage / "SKILL.md").write_text( + f"---\nname: {NAME}\ndescription: Browser skill\n---\n{command[4]}\n", + encoding="utf-8", + ) + return b"installed", None + + return Process() + + monkeypatch.setattr("nanobot.webui.skills_marketplace.shutil.which", lambda _: "npx") + monkeypatch.setattr("nanobot.webui.skills_marketplace.asyncio.create_subprocess_exec", launch) + return stages + + +@pytest.mark.asyncio +async def test_source_identity_survives_restart_move_delete_and_reinstall( + tmp_path: Path, catalog: None, installer: list[Path], +) -> None: + workspace = tmp_path / "workspace" + await install_marketplace_skill(SOURCE, NAME, workspace) + original = webui_skill_detail_payload(workspace, NAME) + assert original and SOURCE in original["raw_markdown"] + assert any(skill["name"] == NAME for skill in webui_skills_payload(workspace)["skills"]) + + for payload in ( + await search_marketplace_skills(NAME, workspace), + await trending_marketplace_skills(workspace), + ): + assert [skill["installation_status"] for skill in payload["skills"]] == [ + "installed", "conflict", "conflict", + ] + assert [skill["installed"] for skill in payload["skills"]] == [True, False, False] + assert (await install_marketplace_skill(SOURCE.upper(), NAME, workspace))["already_installed"] + for source, provider in (("101-skills/superpowers", "skills_sh"), ("", "skillhub")): + with pytest.raises(SkillsMarketplaceError) as error: + await install_marketplace_skill(source, NAME, workspace, provider=provider) + assert error.value.status == 409 + assert len(installer) == 1 + assert webui_skill_detail_payload(workspace, NAME) == original + + moved = tmp_path / "moved" + workspace.rename(moved) + assert (await search_marketplace_skills(NAME, moved))["skills"][0]["installed"] + # The original loader ignores the receipt: skill content and model-visible summary stay stable. + loader = SkillsLoader(moved) + summary = loader.build_skills_summary() + receipt = moved / "skills" / NAME / ".nanobot-origin.json" + saved_receipt = receipt.read_bytes() + receipt.unlink() + assert SkillsLoader(moved).build_skills_summary() == summary + assert webui_skill_detail_payload(moved, NAME) == original + receipt.write_bytes(saved_receipt) + + config_path = tmp_path / "instance" / "config.json" + save_config(Config(), config_path) + delete_webui_skill(moved, NAME, disabled_skills=set(), config_path=config_path) + assert not receipt.exists() + assert all(not skill["installed"] for skill in (await search_marketplace_skills(NAME, moved))["skills"]) + await install_marketplace_skill("101-skills/superpowers", NAME, moved) + rows = (await search_marketplace_skills(NAME, moved))["skills"] + assert [skill["installation_status"] for skill in rows] == ["conflict", "installed", "conflict"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("receipt", [None, "{broken", '{"provider":"skills_sh"}']) +async def test_legacy_or_damaged_receipt_preserves_skill_without_claiming_origin( + tmp_path: Path, catalog: None, installer: list[Path], receipt: str | None, +) -> None: + directory = tmp_path / "skills" / NAME + directory.mkdir(parents=True) + content = "---\nname: agent-browser\n---\nLocal instructions\n" + (directory / "SKILL.md").write_text(content, encoding="utf-8") + if receipt is not None: + (directory / ".nanobot-origin.json").write_text(receipt, encoding="utf-8") + for _ in range(2): + rows = (await search_marketplace_skills(NAME, tmp_path))["skills"] + assert all(row["installation_status"] == "unknown" and not row["installed"] for row in rows) + assert webui_skill_detail_payload(tmp_path, NAME)["raw_markdown"] == content + with pytest.raises(SkillsMarketplaceError) as error: + await install_marketplace_skill(SOURCE, NAME, tmp_path) + assert error.value.status == 409 + assert not installer + assert (directory / "SKILL.md").read_text(encoding="utf-8") == content + + +@pytest.mark.asyncio +async def test_skillhub_receipt_does_not_mark_same_name_github_skill_installed( + tmp_path: Path, catalog: None, +) -> None: + directory = tmp_path / "skills" / NAME + directory.mkdir(parents=True) + (directory / "SKILL.md").write_text("---\nname: agent-browser\n---\n", encoding="utf-8") + (directory / ".nanobot-origin.json").write_text(json.dumps({ + "provider": "skillhub", "source": "", "skill_id": NAME, + }), encoding="utf-8") + assert (await install_marketplace_skill("", NAME, tmp_path, provider="skillhub"))["already_installed"] + rows = (await search_marketplace_skills(NAME, tmp_path))["skills"] + assert [row["installation_status"] for row in rows] == ["conflict", "conflict", "installed"] + + +@pytest.mark.asyncio +async def test_two_installers_cannot_replace_the_winning_source( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, catalog: None, +) -> None: + ready = asyncio.Event() + launches = 0 + + async def launch(*command: str, cwd: str, **_kwargs: object): + nonlocal launches + launches += 1 + if launches == 2: + ready.set() + + class Process: + returncode = 0 + + async def communicate(self): + await ready.wait() + stage = Path(cwd) / "skills" / NAME + stage.mkdir(parents=True) + (stage / "SKILL.md").write_text(command[4], encoding="utf-8") + return b"ok", None + + return Process() + + monkeypatch.setattr("nanobot.webui.skills_marketplace.shutil.which", lambda _: "npx") + monkeypatch.setattr("nanobot.webui.skills_marketplace.asyncio.create_subprocess_exec", launch) + results = await asyncio.gather( + install_marketplace_skill(SOURCE, NAME, tmp_path), + install_marketplace_skill("101-skills/superpowers", NAME, tmp_path), + return_exceptions=True, + ) + assert sum(isinstance(result, dict) for result in results) == 1 + error = next(result for result in results if isinstance(result, SkillsMarketplaceError)) + assert error.status == 409 + rows = (await search_marketplace_skills(NAME, tmp_path))["skills"] + winner = next(row for row in rows if row["installed"]) + assert (tmp_path / "skills" / NAME / "SKILL.md").read_text() == winner["source"] diff --git a/webui/src/components/settings/SkillsMarketplace.tsx b/webui/src/components/settings/SkillsMarketplace.tsx index dd77707da..5e36597ef 100644 --- a/webui/src/components/settings/SkillsMarketplace.tsx +++ b/webui/src/components/settings/SkillsMarketplace.tsx @@ -1,6 +1,7 @@ import { useEffect, useMemo, useState } from "react"; import { Check, + Info, ExternalLink, Loader2, PackagePlus, @@ -24,6 +25,7 @@ import { Button } from "@/components/ui/button"; import { SearchInput } from "@/components/ui/input"; import { SegmentedControl } from "@/components/ui/segmented-control"; import { + ApiError, fetchMarketplaceSkillTrends, fetchTrendingMarketplaceSkills, installMarketplaceSkill, @@ -56,12 +58,12 @@ export function SkillsMarketplace({ const [loading, setLoading] = useState(false); const [trendingLoading, setTrendingLoading] = useState(true); const [error, setError] = useState(""); + const [installError, setInstallError] = useState(""); const [provider, setProvider] = useState("all"); const [selected, setSelected] = useState(null); - const installedNames = useMemo( - () => new Set(installedSkills.map((skill) => skill.name)), - [installedSkills], - ); + // Refresh server-owned installation facts only when the local inventory changes. + const inventory = installedSkills.map((skill) => `${skill.source}:${skill.name}`).sort().join("\n"); + const [installRevision, setInstallRevision] = useState(0); const visibleTrending = useMemo( () => provider === "all" @@ -94,7 +96,7 @@ export function SkillsMarketplace({ return () => { cancelled = true; }; - }, [getToken]); + }, [getToken, inventory, installRevision]); useEffect(() => { const skills = query.trim().length < 2 ? trending : results; @@ -107,7 +109,10 @@ export function SkillsMarketplace({ fetchMarketplaceSkillTrends(getToken(), unresolved.map((skill) => skill.id)) .then((payload) => { if (!cancelled) { - setTrends((current) => ({ ...current, ...payload.trends })); + setTrends((current) => ({ + ...current, + ...Object.fromEntries(unresolved.map((skill) => [skill.id, payload.trends[skill.id] ?? []])), + })); } }) .catch(() => undefined); @@ -154,12 +159,12 @@ export function SkillsMarketplace({ cancelled = true; window.clearTimeout(timer); }; - }, [getToken, query, t]); + }, [getToken, query, t, inventory, installRevision]); const install = async (skill: MarketplaceSkillSummary) => { setSelected(null); onInstallingChange(skill.id); - setError(""); + setInstallError(""); try { const payload = await installMarketplaceSkill( client, @@ -169,25 +174,18 @@ export function SkillsMarketplace({ skill.version, ); notifySkillsChanged(payload); - setResults((current) => - current.map((item) => - item.id === skill.id ? { ...item, installed: true } : item, - ), - ); - setTrending((current) => - current.map((item) => - item.id === skill.id ? { ...item, installed: true } : item, - ), - ); } catch (reason) { - setError( - reason instanceof Error + setInstallError( + reason instanceof ApiError && reason.status === 409 + ? t("settings.skills.marketplaceInstallConflict") + : reason instanceof Error ? reason.message : t("settings.skills.marketplaceInstallFailed", { defaultValue: "Could not install this skill.", }), ); } finally { + setInstallRevision((revision) => revision + 1); onInstallingChange(""); } }; @@ -226,12 +224,21 @@ export function SkillsMarketplace({ - {error ? ( -
- {error} + {error || installError ? ( +
+ {installError || error}
) : null} + {(query.trim().length < 2 ? visibleTrending : visibleResults).some((skill) => + skill.installation_status === "conflict" || skill.installation_status === "unknown" + || (!skill.installation_status && skill.installed), + ) ? ( +

+ {t("settings.skills.marketplaceConflictHelp")} +

+ ) : null} + {query.trim().length < 2 ? (
@@ -257,7 +264,6 @@ export function SkillsMarketplace({ ) : visibleTrending.length ? ( ; installing: string; trends: Record; grouped: boolean; @@ -406,7 +409,6 @@ function MarketplaceSkillGroups({ return ( ; installing: string; trends: Record; onSelect: (skill: MarketplaceSkillSummary) => void; @@ -468,7 +467,6 @@ function MarketplaceSkillList({ void; }) { const { t } = useTranslation(); + // Older hosts only know the name, so their boolean cannot prove a source match. + const status = skill.installation_status ?? (skill.installed ? "unknown" : "available"); + const installed = status === "installed"; + const conflict = status === "conflict" || status === "unknown"; + const conflictLabel = t(status === "unknown" + ? "settings.skills.marketplaceOriginUnknown" + : "settings.skills.marketplaceNameConflict"); const actionLabel = t( isInstalling ? "settings.skills.marketplaceInstalling" : installed ? "settings.skills.marketplaceInstalled" - : "settings.skills.marketplaceInstall", + : conflict + ? "settings.skills.marketplaceNameConflict" + : "settings.skills.marketplaceInstall", ); return ( @@ -548,6 +553,11 @@ function MarketplaceSkillRow({ ) : null}
+ {conflict ? ( +

+ {conflictLabel} +

+ ) : null}
{skill.provider === "skills_sh" ? : null}