fix(skills): distinguish marketplace installation sources

This commit is contained in:
Xubin Ren committed 2026-11-06 00:26:32 +08:00
1 parent 6a4bb4d270
commit 70eca8343b
17 files changed
+518 -135

No files matched your search

+2
View File
@@ -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.
+139 -96
View File
@@ -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 <workspace>/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,
+11 -3
View File
@@ -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",
@@ -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"]
@@ -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<MarketplaceProvider>("all");
const [selected, setSelected] = useState<MarketplaceSkillSummary | null>(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({
<ProviderFilter value={provider} onChange={setProvider} />
</div>
{error ? (
<div className="rounded-control bg-destructive/10 px-3 py-2.5 text-[13px] text-destructive">
{error}
{error || installError ? (
<div role="alert" className="rounded-control bg-destructive/10 px-3 py-2.5 text-[13px] text-destructive">
{installError || error}
</div>
) : null}
{(query.trim().length < 2 ? visibleTrending : visibleResults).some((skill) =>
skill.installation_status === "conflict" || skill.installation_status === "unknown"
|| (!skill.installation_status && skill.installed),
) ? (
<p className="px-1 text-[12px] text-muted-foreground">
{t("settings.skills.marketplaceConflictHelp")}
</p>
) : null}
{query.trim().length < 2 ? (
<section className="overflow-hidden rounded-panel bg-settings-surface">
<div className="flex flex-col items-start gap-2 px-4 pb-2 pt-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
@@ -257,7 +264,6 @@ export function SkillsMarketplace({
) : visibleTrending.length ? (
<MarketplaceSkillGroups
skills={visibleTrending}
installedNames={installedNames}
installing={installing}
trends={trends}
grouped={provider === "all"}
@@ -285,7 +291,6 @@ export function SkillsMarketplace({
) : (
<MarketplaceSkillGroups
skills={visibleResults}
installedNames={installedNames}
installing={installing}
trends={trends}
grouped={provider === "all"}
@@ -384,14 +389,12 @@ function ProviderFilter({
function MarketplaceSkillGroups({
skills,
installedNames,
installing,
trends,
grouped,
onSelect,
}: {
skills: MarketplaceSkillSummary[];
installedNames: Set<string>;
installing: string;
trends: Record<string, number[]>;
grouped: boolean;
@@ -406,7 +409,6 @@ function MarketplaceSkillGroups({
return (
<MarketplaceSkillList
skills={skills}
installedNames={installedNames}
installing={installing}
trends={trends}
onSelect={onSelect}
@@ -437,7 +439,6 @@ function MarketplaceSkillGroups({
</div>
<MarketplaceSkillList
skills={providerSkills}
installedNames={installedNames}
installing={installing}
trends={trends}
onSelect={onSelect}
@@ -451,13 +452,11 @@ function MarketplaceSkillGroups({
function MarketplaceSkillList({
skills,
installedNames,
installing,
trends,
onSelect,
}: {
skills: MarketplaceSkillSummary[];
installedNames: Set<string>;
installing: string;
trends: Record<string, number[]>;
onSelect: (skill: MarketplaceSkillSummary) => void;
@@ -468,7 +467,6 @@ function MarketplaceSkillList({
<MarketplaceSkillRow
key={skill.id}
skill={skill}
installed={skill.installed || installedNames.has(skill.skill_id)}
isInstalling={installing === skill.id}
installBusy={Boolean(installing)}
trend={trends[skill.id]}
@@ -481,26 +479,33 @@ function MarketplaceSkillList({
function MarketplaceSkillRow({
skill,
installed,
isInstalling,
installBusy,
trend,
onSelect,
}: {
skill: MarketplaceSkillSummary;
installed: boolean;
isInstalling: boolean;
installBusy: boolean;
trend?: number[];
onSelect: (skill: MarketplaceSkillSummary) => 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}
</div>
{conflict ? (
<p className="mt-1 text-[12px] text-muted-foreground">
{conflictLabel}
</p>
) : null}
</div>
{skill.provider === "skills_sh" ? <TrendSparkline values={trend} /> : null}
<Button
@@ -555,7 +565,7 @@ function MarketplaceSkillRow({
aria-label={`${actionLabel} ${skill.name}`}
size="icon"
variant="ghost"
disabled={installed || installBusy || !skill.install_supported}
disabled={installed || conflict || installBusy || !skill.install_supported}
onClick={() => onSelect(skill)}
className={cn(
"h-9 w-9 shrink-0 rounded-full bg-muted/70 text-muted-foreground transition-[opacity,color] hover:text-foreground focus-visible:bg-foreground focus-visible:text-background focus-visible:opacity-100 sm:opacity-[0.55] sm:group-hover:opacity-100",
@@ -574,6 +584,8 @@ function MarketplaceSkillRow({
<Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />
) : installed ? (
<Check className="h-4 w-4" aria-hidden />
) : conflict ? (
<Info className="h-4 w-4" aria-hidden />
) : (
<PackagePlus className="h-4 w-4" aria-hidden />
)}
+4
View File
@@ -1820,6 +1820,10 @@
"marketplaceNpxRequired": "Node.js with npx is required",
"marketplaceInstalling": "Installing",
"marketplaceInstalled": "Installed",
"marketplaceNameConflict": "Name already in use",
"marketplaceOriginUnknown": "Installed source unknown",
"marketplaceConflictHelp": "Review same-name skills in Installed before removing them to use another source.",
"marketplaceInstallConflict": "Installation conflict. Wait for any installation to finish, then review same-name skills in Installed.",
"marketplaceInstall": "Install",
"marketplaceNoTrend": "No trend yet",
"marketplaceTrendLabel": "8-week install trend",
+4
View File
@@ -1615,6 +1615,10 @@
"marketplaceNpxRequired": "Se requiere Node.js con npx",
"marketplaceInstalling": "Instalando",
"marketplaceInstalled": "Instalada",
"marketplaceNameConflict": "El nombre ya está en uso",
"marketplaceOriginUnknown": "Origen instalado desconocido",
"marketplaceConflictHelp": "Revisa las habilidades con el mismo nombre en Instaladas antes de eliminarlas para usar otro origen.",
"marketplaceInstallConflict": "Conflicto de instalación. Espera a que termine la instalación en curso y revisa las habilidades del mismo nombre en Instaladas.",
"marketplaceInstall": "Instalar",
"marketplaceNoTrend": "Sin tendencia todavía",
"marketplaceTrendLabel": "Tendencia de instalaciones de 8 semanas",
+4
View File
@@ -1614,6 +1614,10 @@
"marketplaceNpxRequired": "Node.js avec npx est requis",
"marketplaceInstalling": "Installation",
"marketplaceInstalled": "Installée",
"marketplaceNameConflict": "Nom déjà utilisé",
"marketplaceOriginUnknown": "Source installée inconnue",
"marketplaceConflictHelp": "Vérifiez les compétences du même nom dans Installées avant de les supprimer pour utiliser une autre source.",
"marketplaceInstallConflict": "Conflit d’installation. Attendez la fin de l’installation en cours, puis vérifiez les compétences du même nom dans Installées.",
"marketplaceInstall": "Installer",
"marketplaceNoTrend": "Pas encore de tendance",
"marketplaceTrendLabel": "Tendance des installations sur 8 semaines",
+4
View File
@@ -1614,6 +1614,10 @@
"marketplaceNpxRequired": "Node.js dengan npx diperlukan",
"marketplaceInstalling": "Memasang",
"marketplaceInstalled": "Terpasang",
"marketplaceNameConflict": "Nama sudah digunakan",
"marketplaceOriginUnknown": "Sumber instalasi tidak diketahui",
"marketplaceConflictHelp": "Periksa skill bernama sama di Terpasang sebelum menghapusnya untuk memakai sumber lain.",
"marketplaceInstallConflict": "Konflik instalasi. Tunggu instalasi selesai, lalu periksa skill bernama sama di Terpasang.",
"marketplaceInstall": "Pasang",
"marketplaceNoTrend": "Belum ada tren",
"marketplaceTrendLabel": "Tren pemasangan 8 minggu",
+4
View File
@@ -1614,6 +1614,10 @@
"marketplaceNpxRequired": "npx を含む Node.js が必要です",
"marketplaceInstalling": "インストール中",
"marketplaceInstalled": "インストール済み",
"marketplaceNameConflict": "同名のスキルがあります",
"marketplaceOriginUnknown": "インストール元が不明です",
"marketplaceConflictHelp": "別の提供元に変更する場合は、「インストール済み」で同名のスキルを確認してから削除してください。",
"marketplaceInstallConflict": "インストールが競合しています。処理の完了を待ってから、「インストール済み」で同名のスキルを確認してください。",
"marketplaceInstall": "インストール",
"marketplaceNoTrend": "トレンドなし",
"marketplaceTrendLabel": "8週間のインストール推移",
+4
View File
@@ -1614,6 +1614,10 @@
"marketplaceNpxRequired": "npx가 포함된 Node.js가 필요합니다",
"marketplaceInstalling": "설치 중",
"marketplaceInstalled": "설치됨",
"marketplaceNameConflict": "같은 이름의 스킬이 있음",
"marketplaceOriginUnknown": "설치 출처를 알 수 없음",
"marketplaceConflictHelp": "출처를 바꾸려면 먼저 설치됨에서 같은 이름의 스킬을 확인한 후 삭제하세요.",
"marketplaceInstallConflict": "설치가 충돌합니다. 진행 중인 설치가 끝나면 설치됨에서 같은 이름의 스킬을 확인하세요.",
"marketplaceInstall": "설치",
"marketplaceNoTrend": "추세 없음",
"marketplaceTrendLabel": "8주 설치 추이",
+4
View File
@@ -1628,6 +1628,10 @@
"marketplaceNpxRequired": "Node.js com npx é necessário",
"marketplaceInstalling": "Instalando",
"marketplaceInstalled": "Instalada",
"marketplaceNameConflict": "Nome já em uso",
"marketplaceOriginUnknown": "Origem instalada desconhecida",
"marketplaceConflictHelp": "Confira as habilidades com o mesmo nome em Instaladas antes de removê-las para usar outra origem.",
"marketplaceInstallConflict": "Conflito de instalação. Aguarde a instalação em andamento e confira as habilidades com o mesmo nome em Instaladas.",
"marketplaceInstall": "Instalar",
"marketplaceNoTrend": "Ainda sem tendência",
"marketplaceTrendLabel": "Tendência de instalações em 8 semanas",
+4
View File
@@ -1614,6 +1614,10 @@
"marketplaceNpxRequired": "Cần Node.js có npx",
"marketplaceInstalling": "Đang cài đặt",
"marketplaceInstalled": "Đã cài đặt",
"marketplaceNameConflict": "Tên đã được sử dụng",
"marketplaceOriginUnknown": "Không rõ nguồn đã cài",
"marketplaceConflictHelp": "Kiểm tra kỹ năng cùng tên trong Đã cài trước khi xóa để dùng nguồn khác.",
"marketplaceInstallConflict": "Xung đột cài đặt. Chờ quá trình cài đặt hoàn tất rồi kiểm tra kỹ năng cùng tên trong Đã cài.",
"marketplaceInstall": "Cài đặt",
"marketplaceNoTrend": "Chưa có xu hướng",
"marketplaceTrendLabel": "Xu hướng lượt cài đặt trong 8 tuần",
+4
View File
@@ -1820,6 +1820,10 @@
"marketplaceNpxRequired": "请先安装包含 npx 的 Node.js",
"marketplaceInstalling": "正在安装",
"marketplaceInstalled": "已安装",
"marketplaceNameConflict": "技能名称已占用",
"marketplaceOriginUnknown": "已装技能来源未知",
"marketplaceConflictHelp": "请先在“已安装”中检查同名技能;如需更换来源,再移除原技能。",
"marketplaceInstallConflict": "安装冲突。请等待当前安装完成,再到“已安装”中检查同名技能。",
"marketplaceInstall": "安装",
"marketplaceNoTrend": "暂无趋势",
"marketplaceTrendLabel": "近 8 周安装趋势",
+4
View File
@@ -1614,6 +1614,10 @@
"marketplaceNpxRequired": "需要安裝包含 npx 的 Node.js",
"marketplaceInstalling": "正在安裝",
"marketplaceInstalled": "已安裝",
"marketplaceNameConflict": "技能名稱已使用",
"marketplaceOriginUnknown": "已裝技能來源不明",
"marketplaceConflictHelp": "請先在「已安裝」檢查同名技能;如需更換來源,再移除原技能。",
"marketplaceInstallConflict": "安裝衝突。請等待目前的安裝完成,再到「已安裝」檢查同名技能。",
"marketplaceInstall": "安裝",
"marketplaceNoTrend": "暫無趨勢",
"marketplaceTrendLabel": "近 8 週安裝趨勢",
+1
View File
@@ -394,6 +394,7 @@ export interface MarketplaceSkillSummary {
downloads?: number;
url: string;
installed: boolean;
installation_status?: "available" | "installed" | "conflict" | "unknown";
install_supported: boolean;
metric: "installs_24h" | "installs_total";
version?: string;
@@ -5,11 +5,15 @@ import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace";
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import {
ApiError,
fetchMarketplaceSkillTrends,
fetchSkills,
fetchTrendingMarketplaceSkills,
installMarketplaceSkill,
searchMarketplaceSkills,
} from "@/lib/api";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { MarketplaceSkillSummary } from "@/lib/types";
import { requestSkillsRefresh, SKILLS_CHANGED_EVENT } from "@/lib/skill-events";
import { ClientProvider } from "@/providers/ClientProvider";
import { useSkills } from "@/hooks/useSkills";
@@ -19,7 +23,9 @@ vi.mock("@/lib/api", async (importOriginal) => {
return {
...actual,
fetchSkills: vi.fn(),
fetchMarketplaceSkillTrends: vi.fn(),
fetchTrendingMarketplaceSkills: vi.fn(),
installMarketplaceSkill: vi.fn(),
searchMarketplaceSkills: vi.fn(),
};
});
@@ -243,6 +249,8 @@ describe("useSkills", () => {
describe("SkillsMarketplace", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.mocked(fetchMarketplaceSkillTrends).mockReset().mockResolvedValue({ trends: {} });
vi.mocked(installMarketplaceSkill).mockReset();
vi.mocked(fetchTrendingMarketplaceSkills).mockReset().mockResolvedValue({
period: "mixed",
provider: "all",
@@ -263,6 +271,76 @@ describe("SkillsMarketplace", () => {
vi.useRealTimers();
});
const originSkill = (source: string, status?: MarketplaceSkillSummary["installation_status"]): MarketplaceSkillSummary => ({
id: `${source}/agent-browser`, skill_id: "agent-browser", name: "agent-browser",
source, provider: "skills_sh", installs: 42, url: `https://skills.sh/${source}/agent-browser`,
installed: status === "installed", installation_status: status,
install_supported: true, metric: "installs_total",
});
it("shows source matches, conflicts and unconfirmed legacy hosts without inferring from local names", async () => {
vi.mocked(fetchTrendingMarketplaceSkills).mockResolvedValue({
period: "mixed", provider: "all", install_supported: true,
skills: [
originSkill("vercel-labs/agent-browser", "installed"),
originSkill("101-skills/superpowers", "conflict"),
originSkill("local/unknown", "unknown"),
{ ...originSkill("legacy/host"), installed: true },
originSkill("new/source", "available"),
],
});
render(<ClientProvider client={client} token="tok"><SkillsMarketplace
installedSkills={[{ name: "agent-browser", source: "workspace", description: "Local", available: true }]}
installing="" onInstallingChange={vi.fn()}
/></ClientProvider>);
await act(async () => {});
expect(screen.getAllByRole("button", { name: "Installed agent-browser" })).toHaveLength(1);
expect(screen.getAllByRole("button", { name: "Name already in use agent-browser" })).toHaveLength(3);
expect(screen.getAllByText("Installed source unknown")).toHaveLength(2);
const available = screen.getByRole("button", { name: "Install agent-browser" });
expect(available).toBeEnabled();
fireEvent.click(available);
expect(screen.getByRole("alertdialog")).toHaveTextContent("new/source");
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(installMarketplaceSkill).not.toHaveBeenCalled();
});
it("refreshes server identity after installation instead of marking every same-name result", async () => {
const response = (installed: boolean) => ({
period: "mixed" as const, provider: "all" as const, install_supported: true,
skills: [originSkill("vercel-labs/agent-browser", installed ? "installed" : "available"),
originSkill("101-skills/superpowers", installed ? "conflict" : "available")],
});
vi.mocked(fetchTrendingMarketplaceSkills).mockResolvedValueOnce(response(false)).mockResolvedValue(response(true));
vi.mocked(installMarketplaceSkill).mockResolvedValue({
skills: [], last_action: { name: "agent-browser", installed: true, already_installed: false },
});
render(marketplace("tok"));
await act(async () => {});
fireEvent.click(screen.getAllByRole("button", { name: "Install agent-browser" })[0]);
fireEvent.click(screen.getByRole("button", { name: "Install skill" }));
await act(async () => {});
expect(installMarketplaceSkill).toHaveBeenCalledWith(client, "skills_sh", "vercel-labs/agent-browser", "agent-browser", undefined);
expect(screen.getAllByRole("button", { name: "Installed agent-browser" })).toHaveLength(1);
expect(screen.getByRole("button", { name: "Name already in use agent-browser" })).toBeDisabled();
});
it("keeps a localized conflict error visible after refreshing a stale search result", async () => {
vi.mocked(searchMarketplaceSkills).mockResolvedValue({
query: "browser", provider: "all", install_supported: true,
skills: [originSkill("vercel-labs/agent-browser", "available")],
});
vi.mocked(installMarketplaceSkill).mockRejectedValue(new ApiError(409, "a skill with this name already exists"));
render(marketplace("tok"));
fireEvent.change(screen.getByRole("textbox", { name: "Search skills" }), { target: { value: "browser" } });
await act(async () => { await vi.advanceTimersByTimeAsync(300); });
fireEvent.click(screen.getByRole("button", { name: "Install agent-browser" }));
fireEvent.click(screen.getByRole("button", { name: "Install skill" }));
await act(async () => { await vi.advanceTimersByTimeAsync(300); });
expect(screen.getByRole("alert")).toHaveTextContent("Installation conflict.");
expect(screen.queryByRole("button", { name: "Installed agent-browser" })).not.toBeInTheDocument();
});
it("shows discovery skeletons while trending or the first search is pending and keeps loaded search results", async () => {
const skill = {
id: "skillhub:react-testing", skill_id: "react-testing", name: "React Testing",