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

@@ -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",