Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
test(skills): verify source identity across public API and browser
Xubin Ren112ea9d17461
diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.pyindex 75f8b8f76..9dc680dd7 100644--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py@@ -879,6 +879,53 @@ async def test_webui_skills_marketplace_routes_search_and_install(await server_task+async def test_webui_skill_source_identity_reaches_public_reads_and_mutations(+ bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,+) -> None:+ directory = tmp_path / "skills" / "agent-browser"+ directory.mkdir(parents=True)+ content = "---\nname: agent-browser\n---\nKeep my local skill.\n"+ (directory / "SKILL.md").write_text(content, encoding="utf-8")+ (directory / ".nanobot-origin.json").write_text(json.dumps({+ "provider": "skills_sh", "source": "vercel-labs/agent-browser", "skill_id": "agent-browser",+ }), encoding="utf-8")++ def respond(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"skills": [+ {"skillId": "agent-browser", "source": "vercel-labs/agent-browser"},+ {"skillId": "agent-browser", "source": "101-skills/superpowers"},+ ]})++ monkeypatch.setattr("nanobot.webui.skills_marketplace._skills_client", lambda: httpx.AsyncClient(+ transport=httpx.MockTransport(respond),+ ))+ 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())+ try:+ headers = {"Authorization": f"Bearer {channel.gateway.tokens.issue_api_token(300)}"}+ for endpoint in ("search?q=agent-browser&provider=skills_sh", "trending?provider=skills_sh"):+ response = await _http_get(f"http://127.0.0.1:{port}/api/webui/skills/{endpoint}", headers=headers)+ assert response.status_code == 200+ assert [row["installation_status"] for row in response.json()["skills"]] == ["installed", "conflict"]+ # Old callers send no provider or new status fields; the host still enforces identity.+ wrong = await _webui_mutate(channel, "skill.install", {+ "source": "101-skills/superpowers", "skill": "agent-browser",+ }, headers=headers)+ assert wrong.status_code == 409+ same = await _webui_mutate(channel, "skill.install", {+ "source": "vercel-labs/agent-browser", "skill": "agent-browser",+ }, headers=headers)+ assert same.status_code == 200+ assert same.json()["last_action"]["already_installed"] is True+ assert any(skill["name"] == "agent-browser" for skill in same.json()["skills"])+ assert (directory / "SKILL.md").read_text(encoding="utf-8") == content+ finally:+ await channel.stop()+ await server_task++@pytest.mark.asyncioasync def test_webui_skill_install_rejects_overlapping_requests(bus: MagicMock,diff --git a/tests/webui/test_skills_marketplace.py b/tests/webui/test_skills_marketplace.pyindex 9f671760f..2dfb16d19 100644--- a/tests/webui/test_skills_marketplace.py+++ b/tests/webui/test_skills_marketplace.py@@ -524,6 +524,10 @@ async def test_install_skillhub_skill_checks_fingerprint_and_extracts_safely("version": "1.1.8",}assert (tmp_path / "skills" / "ima-skills" / "SKILL.md").read_bytes() == skill_content+ assert json.loads((tmp_path / "skills" / "ima-skills" / ".nanobot-origin.json").read_text()) == {+ "provider": "skillhub", "source": "", "skill_id": "ima-skills",+ }+ assert (await install_marketplace_skill("", "ima-skills", tmp_path, provider="skillhub"))["already_installed"]@pytest.mark.parametrize(diff --git a/tests/webui/test_skills_marketplace_identity.py b/tests/webui/test_skills_marketplace_identity.pyindex 5c37fedc0..7ff116779 100644--- a/tests/webui/test_skills_marketplace_identity.py+++ b/tests/webui/test_skills_marketplace_identity.py@@ -197,3 +197,19 @@ async def test_two_installers_cannot_replace_the_winning_source(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"]+++async def test_receipt_write_failure_leaves_no_partial_install_and_retry_works(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, installer: list[Path], catalog: None,+) -> None:+ with monkeypatch.context() as failure:+ def fail_write(*_args: object) -> None:+ raise OSError("disk full")++ failure.setattr("nanobot.webui.skills_marketplace.atomic_write_text", fail_write)+ with pytest.raises(OSError, match="disk full"):+ await install_marketplace_skill(SOURCE, NAME, tmp_path)+ assert list((tmp_path / "skills").iterdir()) == []+ assert all(not row["installed"] for row in (await search_marketplace_skills(NAME, tmp_path))["skills"])+ assert (await install_marketplace_skill(SOURCE, NAME, tmp_path))["installed"]diff --git a/webui/browser/skills-marketplace-identity.spec.ts b/webui/browser/skills-marketplace-identity.spec.tsnew file mode 100644index 000000000..2811d9d0a--- /dev/null+++ b/webui/browser/skills-marketplace-identity.spec.ts@@ -0,0 +1,50 @@+import { expect, test } from "@playwright/test";++for (const width of [390, 1440]) {+ for (const theme of ["light", "dark"]) {+ for (const locale of ["en", "zh-CN"]) {+ test(`marketplace source states remain distinct at ${width}px in ${theme} ${locale}`, async ({ page }, testInfo) => {+ await page.setViewportSize({ width, height: 900 });+ await page.addInitScript((language) => localStorage.setItem("nanobot.locale", language), locale);+ const labels = locale === "en"+ ? { installed: "Installed", conflict: "Name already in use", unknown: "Installed source unknown", search: "Search skills", trending: "Popular skills", install: "Install", cancel: "Cancel" }+ : { installed: "已安装", conflict: "技能名称已占用", unknown: "已装技能来源未知", search: "搜索技能", trending: "热门技能", install: "安装", cancel: "取消" };+ const rows = ["installed", "conflict", "unknown", "available"].map((status, index) => ({+ id: `owner-${index}/skills/agent-browser`, skill_id: "agent-browser", name: "agent-browser",+ source: `owner-${index}/skills`, provider: "skills_sh", installs: 120,+ url: `https://skills.sh/owner-${index}/skills/agent-browser`,+ installed: status === "installed", installation_status: status,+ install_supported: true, metric: "installs_total",+ }));+ let trendReads = 0;+ await page.route("**/api/webui/skills/trending?**", (route) => route.fulfill({+ json: { period: "mixed", provider: "all", install_supported: true, skills: rows },+ }));+ await page.route("**/api/webui/skills/search?**", (route) => route.fulfill({+ json: { query: "agent-browser", provider: "all", install_supported: true, skills: rows },+ }));+ await page.route("**/api/webui/skills/trends?**", (route) => {+ trendReads += 1;+ return route.fulfill({ json: { trends: {} } });+ });+ await page.goto("/browser/fixture.html?case=skeleton&surface=marketplace");+ await page.locator("html").evaluate((element, dark) => element.classList.toggle("dark", dark), theme === "dark");+ expect(await page.locator("html").evaluate((element) => element.classList.contains("dark"))).toBe(theme === "dark");+ await expect(page.getByRole("button", { name: `${labels.installed} agent-browser`, exact: true })).toHaveCount(1);+ await expect(page.getByRole("button", { name: `${labels.conflict} agent-browser` })).toHaveCount(2);+ await expect(page.getByText(labels.unknown, { exact: true })).toBeVisible();+ await page.getByRole("textbox", { name: labels.search }).fill("agent-browser");+ await expect(page.getByRole("heading", { name: labels.trending })).toHaveCount(0);+ await page.getByRole("button", { name: `${labels.install} agent-browser`, exact: true }).click();+ await expect(page.getByRole("alertdialog")).toContainText("owner-3/skills");+ await page.getByRole("button", { name: labels.cancel, exact: true }).click();+ await expect(page.getByRole("alertdialog")).toHaveCount(0);+ await expect(page.locator('.fixed[data-state="closed"]')).toHaveCount(0);+ await expect(page.getByRole("button", { name: `${labels.install} agent-browser`, exact: true })).toBeFocused();+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);+ expect(trendReads).toBe(1);+ await page.screenshot({ path: testInfo.outputPath("marketplace.png"), fullPage: true });+ });+ }+ }+}diff --git a/webui/src/components/settings/SkillsMarketplace.tsx b/webui/src/components/settings/SkillsMarketplace.tsxindex 5e36597ef..3b48a413d 100644--- a/webui/src/components/settings/SkillsMarketplace.tsx+++ b/webui/src/components/settings/SkillsMarketplace.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import {Check,Info,@@ -61,6 +61,11 @@ export function SkillsMarketplace({const [installError, setInstallError] = useState("");const [provider, setProvider] = useState<MarketplaceProvider>("all");const [selected, setSelected] = useState<MarketplaceSkillSummary | null>(null);+ const installTrigger = useRef<HTMLElement | null>(null);+ const selectSkill = (skill: MarketplaceSkillSummary) => {+ installTrigger.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ setSelected(skill);+ };// 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);@@ -267,7 +272,7 @@ export function SkillsMarketplace({installing={installing}trends={trends}grouped={provider === "all"}- onSelect={setSelected}+ onSelect={selectSkill}/>) : (<div className="px-5 py-10 text-center text-[13px] text-muted-foreground">@@ -294,7 +299,7 @@ export function SkillsMarketplace({installing={installing}trends={trends}grouped={provider === "all"}- onSelect={setSelected}+ onSelect={selectSkill}/>)}</div>@@ -306,7 +311,10 @@ export function SkillsMarketplace({if (!open) setSelected(null);}}>- <AlertDialogContent>+ <AlertDialogContent onCloseAutoFocus={(event) => {+ event.preventDefault();+ installTrigger.current?.focus();+ }}><AlertDialogHeader><div className="mb-1 flex h-10 w-10 items-center justify-center rounded-control bg-amber-500/10 text-amber-700 dark:text-amber-300"><ShieldAlert className="h-5 w-5" aria-hidden />@@ -535,10 +543,10 @@ function MarketplaceSkillRow({</a></div><div className="mt-1 flex min-w-0 items-center gap-1.5 truncate text-[12px] text-muted-foreground">- {skill.source}+ <span className="truncate" title={skill.source}>{skill.source}</span>{skill.version ? <span>v{skill.version}</span> : null}{skill.provider === "skills_sh" ? (- <>+ <span className="shrink-0">{skill.metric === "installs_24h"? t("settings.skills.marketplaceInstalls24h", {count: skill.installs,@@ -550,7 +558,7 @@ function MarketplaceSkillRow({formattedCount: skill.installs.toLocaleString(),defaultValue: "{{formattedCount}} installs",})}- </>+ </span>) : null}</div>{conflict ? (