AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): install a marketplace skill straight onto one of your experts (#14559)
Reinier van der Leer93926246f2d6
diff --git a/autogpt_platform/backend/backend/api/features/store/skill_db_test.py b/autogpt_platform/backend/backend/api/features/store/skill_db_test.pyindex 17a8408238..23bd428d05 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_db_test.py@@ -1,10 +1,12 @@import datetimefrom types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMockimport prisma.enumsimport prisma.modelsimport pytest+from backend.copilot.tools.skills_test import _FakeWorkspaceManager, _patch_skills_pathfrom backend.util.exceptions import NotFoundErrorfrom backend.util.test import SpinTestServer@@ -210,6 +212,46 @@ async def test_install_stores_under_the_listing_slug_and_counts(mocker, expert_iassert refreshed.installCount == 1+ "expert_id, folder",+ [(None, "/skills"), ("expert-a", "/experts/expert-a/skills")],+ ids=["library", "expert"],+)+async def test_install_writes_into_the_target_owners_folder_and_no_other(+ mocker, expert_id, folder+):+ """The test above proves the id reaches ``store_user_skill``; this one runs+ the real write, so a folder that ignored it would show up here."""+ listing = await _make_listing(f"folder-one-{expert_id or 'library'}")+ workspace = _FakeWorkspaceManager()+ experts = MagicMock()+ experts.add_expert_skill_name = AsyncMock()+ mocker.patch("backend.copilot.tools.skills.experts_db", return_value=experts)++ with _patch_skills_path(workspace):+ await skill_db.install_marketplace_skill(+ "user-1", listing.slug, expert_id=expert_id+ )+ # A second install of the same skill overwrites its copy rather than+ # leaving a second one behind.+ await skill_db.install_marketplace_skill(+ "user-1", listing.slug, expert_id=expert_id+ )++ assert list(workspace.files) == [f"{folder}/{listing.slug}/SKILL.md"]+ refreshed = await prisma.models.SkillListing.prisma().find_unique(+ where={"id": listing.id}+ )+ assert refreshed is not None+ assert refreshed.installCount == 1+ if expert_id is None:+ experts.add_expert_skill_name.assert_not_awaited()+ else:+ experts.add_expert_skill_name.assert_awaited_with(+ "user-1", expert_id, listing.slug+ )++async def test_reinstalling_stores_again_but_does_not_count_again(mocker):listing = await _make_listing("install-twice", body="# do this\n")stored = mocker.patch.object(skill_db, "store_user_skill")diff --git a/autogpt_platform/backend/backend/api/features/store/skill_routes.py b/autogpt_platform/backend/backend/api/features/store/skill_routes.pyindex 246a39a19d..29fb5bafa5 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_routes.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_routes.py@@ -4,6 +4,7 @@ import autogpt_libs.authimport fastapifrom fastapi import Depends, Path, Query, Security+from backend.api.features.experts import experts_dbfrom backend.copilot.tools.skills import SkillLimitErrorfrom backend.util.feature_flag import Flag, is_feature_enabled@@ -121,19 +122,37 @@ async def get_marketplace_skill(summary="Install marketplace skill",tags=["store", "private"],responses={- 404: {"description": "Skill not found"},+ 404: {"description": "Skill or expert not found"},409: {"description": "Per-user skill limit reached"},},dependencies=[Security(autogpt_libs.auth.requires_user)],)async def install_marketplace_skill(slug: str = Path(..., description="Slug of the skill listing"),+ expert_id: str | None = Query(+ default=None,+ description="Install into this expert's skills instead of the caller's own.",+ ),user_id: str = Security(autogpt_libs.auth.get_user_id),) -> skill_model.InstalledSkill:- """Copy the listing's skill into the caller's skill library."""+ """Copy the listing's skill into an expert's skills, or the caller's own."""+ await _require_install_target(user_id, expert_id)try:- return await skill_db.install_marketplace_skill(user_id, slug)+ return await skill_db.install_marketplace_skill(+ user_id, slug, expert_id=expert_id+ )except SkillLimitError as exc:raise fastapi.HTTPException(status_code=409, detail=str(exc))except ValueError as exc:raise fastapi.HTTPException(status_code=400, detail=str(exc))+++async def _require_install_target(user_id: str, expert_id: str | None) -> None:+ """An expert named by the client must be one of the caller's own active+ hires; someone else's answers 404, which a 403 would confirm exists."""+ if expert_id is None:+ return+ if not await experts_db.owns_private_active_expert(user_id, expert_id):+ raise fastapi.HTTPException(+ status_code=404, detail=f"Expert '{expert_id}' not found"+ )diff --git a/autogpt_platform/backend/backend/api/features/store/skill_routes_test.py b/autogpt_platform/backend/backend/api/features/store/skill_routes_test.pyindex 926ce4f442..75db424795 100644--- a/autogpt_platform/backend/backend/api/features/store/skill_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/store/skill_routes_test.py@@ -4,7 +4,7 @@ import fastapiimport fastapi.testclientimport pytest-from . import skill_routes, skill_submission_db+from . import skill_model, skill_routes, skill_submission_dbapp = fastapi.FastAPI()app.include_router(skill_routes.router, prefix="/api/store/skills")@@ -86,3 +86,46 @@ def test_submissions_is_a_route_of_its_own_not_a_skill_slug(assert response.status_code == 200listed.assert_awaited_once()detail.assert_not_called()++[email protected]("expert_id", [None, "expert-1"], ids=["library", "expert"])+def test_install_targets_the_expert_the_caller_named(+ monkeypatch: pytest.MonkeyPatch, mocker, authenticated, test_user_id, expert_id+):+ monkeypatch.setenv(FLAG_ENV_VAR, "true")+ mocker.patch.object(+ skill_routes.experts_db, "owns_private_active_expert", return_value=True+ )+ install = mocker.patch.object(+ skill_routes.skill_db,+ "install_marketplace_skill",+ return_value=skill_model.InstalledSkill(name="a-skill", required_providers=[]),+ )++ response = client.post(+ "/api/store/skills/a-skill/install",+ params={"expert_id": expert_id} if expert_id else {},+ )++ assert response.status_code == 200+ install.assert_awaited_once_with(test_user_id, "a-skill", expert_id=expert_id)+++def test_install_onto_someone_elses_expert_is_a_404_that_writes_nothing(+ monkeypatch: pytest.MonkeyPatch, mocker, authenticated, test_user_id+):+ """A 403 would confirm the expert exists, so an unowned id reads as missing."""+ monkeypatch.setenv(FLAG_ENV_VAR, "true")+ owns = mocker.patch.object(+ skill_routes.experts_db, "owns_private_active_expert", return_value=False+ )+ install = mocker.patch.object(skill_routes.skill_db, "install_marketplace_skill")++ response = client.post(+ "/api/store/skills/a-skill/install", params={"expert_id": "not-mine"}+ )++ assert response.status_code == 404+ assert response.json()["detail"] == "Expert 'not-mine' not found"+ owns.assert_awaited_once_with(test_user_id, "not-mine")+ install.assert_not_awaited()diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/install-to-expert.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/install-to-expert.test.tsxnew file mode 100644index 0000000000..2fcd530ae6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/__tests__/install-to-expert.test.tsx@@ -0,0 +1,139 @@+import { getListExpertsMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";+import { getGetV1ListCredentialsMockHandler200 } from "@/app/api/__generated__/endpoints/integrations/integrations.msw";+import {+ getGetV2GetMarketplaceSkillMockHandler200,+ getPostV2InstallMarketplaceSkillMockHandler200,+} from "@/app/api/__generated__/endpoints/store/store.msw";+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { MarketplaceSkillDetails } from "@/app/api/__generated__/models/marketplaceSkillDetails";+import { Toaster } from "@/components/molecules/Toast/toaster";+import { server } from "@/mocks/mock-server";+import {+ configure,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { HttpResponse, http } from "msw";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { SkillPage } from "../components/SkillPage";++configure({ asyncUtilTimeout: 10000 });++const mockUseAuth = vi.hoisted(() => vi.fn());++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),+ usePathname: () => "/marketplace/skills/outreach-playbook",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({ slug: "outreach-playbook" }),+ notFound: vi.fn(),+}));++vi.mock("@/lib/auth/hooks/useAuth", () => ({ useAuth: mockUseAuth }));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return { ...actual, useFlagStatus: () => ({ enabled: true, ready: true }) };+});++const outreach: MarketplaceSkillDetails = {+ slug: "outreach-playbook",+ name: "Outreach playbook",+ description: "Run cold outreach that gets replies.",+ categories: ["sales"],+ required_providers: [],+ install_count: 3,+ creator: null,+ creator_avatar: null,+ skill_listing_version_id: "version-1",+ body: "# Outreach playbook\n\nFour sentences, no more.",+ triggers: [],+ updated_at: new Date("2026-09-07T00:00:00Z"),+};++const maria: Expert = {+ id: "expert-maria",+ name: "Maria",+ avatar_url: null,+ role: "Marketing Strategist",+ bio: null,+ skills: [],+ tagline: "Grows your brand while you sleep",+ identity: "You are Maria.",+ voice_preferences: "Warm and direct.",+ boundaries: "Never invent customer evidence.",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: "template-maria",+ is_archived: false,+ workflows: [],+};++/** The query string the install landed on, or null when it never ran. */+let installTarget: string | null;++function renderPage(experts: Expert[]) {+ installTarget = null;+ server.use(+ getGetV2GetMarketplaceSkillMockHandler200(outreach),+ getPostV2InstallMarketplaceSkillMockHandler200(({ request }) => {+ installTarget = new URL(request.url).searchParams.get("expert_id") ?? "";+ return { name: "outreach-playbook", required_providers: [] };+ }),+ getGetV1ListCredentialsMockHandler200([]),+ getListExpertsMockHandler(experts),+ http.get("/api/proxy/api/skills", () => HttpResponse.json([])),+ );+ render(+ <>+ <SkillPage slug="outreach-playbook" />+ <Toaster />+ </>,+ );+}++describe("Installing a marketplace skill for an expert", () => {+ beforeEach(() => {+ mockUseAuth.mockReturnValue({ user: { id: "user-1" }, isLoggedIn: true });+ });++ test("the main half of the split button installs into your own skills", async () => {+ renderPage([maria]);++ await userEvent.click(await screen.findByTestId("skill-install-button"));++ // "" is the install landing in the caller's own skills: the request ran+ // and carried no expert, which null could not tell apart from no request.+ await waitFor(() => expect(installTarget).toBe(""));+ });++ test("the dropdown installs into the expert you pick, and says so", async () => {+ renderPage([maria]);+ await screen.findByTestId("skill-install-button");++ await userEvent.click(+ screen.getByRole("button", { name: "Install for an expert" }),+ );+ await userEvent.click(+ await screen.findByRole("menuitem", { name: /Maria/ }),+ );++ expect(await screen.findByText("Installed on Maria")).toBeDefined();+ expect(installTarget).toBe("expert-maria");+ });++ test("offers no dropdown when there is no expert to install onto", async () => {+ renderPage([]);++ await screen.findByTestId("skill-install-button");+ expect(+ screen.queryByRole("button", { name: "Install for an expert" }),+ ).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/InstallSkillButton.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/InstallSkillButton.tsxnew file mode 100644index 0000000000..f14a54359d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/InstallSkillButton.tsx@@ -0,0 +1,129 @@+import { Expert } from "@/app/api/__generated__/models/expert";+import {+ Avatar,+ AvatarFallback,+ AvatarImage,+} from "@/components/atoms/Avatar/Avatar";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "@/components/molecules/DropdownMenu/DropdownMenu";+import { ArrowDown01Icon } from "@hugeicons/core-free-icons";++export const MENU_LABEL = "Install for an expert";++interface Props {+ experts: Expert[];+ isAdding: boolean;+ onAddToLibrary: () => void;+ onAddToExpert: (expert: Expert) => void;+}++/** Installing to your own skills is the main action; the dropdown hands the+ * skill to one of your experts instead. */+export function InstallSkillButton({+ experts,+ isAdding,+ onAddToLibrary,+ onAddToExpert,+}: Props) {+ if (experts.length === 0) {+ return (+ <Button+ variant="primary"+ size="small"+ onClick={onAddToLibrary}+ loading={isAdding}+ className="w-full sm:w-auto"+ data-testid="skill-install-button"+ >+ Install skill+ </Button>+ );+ }++ return (+ <div className="inline-flex w-full sm:w-auto">+ <Button+ variant="primary"+ size="small"+ onClick={onAddToLibrary}+ loading={isAdding}+ className="!rounded-r-none border-r-0 sm:w-auto"+ data-testid="skill-install-button"+ >+ Install skill+ </Button>+ <ExpertInstallMenu+ experts={experts}+ isAdding={isAdding}+ onAddToExpert={onAddToExpert}+ >+ <Button+ variant="primary"+ size="small"+ aria-label={MENU_LABEL}+ disabled={isAdding}+ className="!min-w-0 !rounded-l-none border-l border-l-white/25 px-2.5"+ >+ <Icon icon={ArrowDown01Icon} size={16} aria-hidden />+ </Button>+ </ExpertInstallMenu>+ </div>+ );+}++interface MenuProps {+ experts: Expert[];+ isAdding: boolean;+ onAddToExpert: (expert: Expert) => void;+ children: React.ReactNode;+}++export function ExpertInstallMenu({+ experts,+ isAdding,+ onAddToExpert,+ children,+}: MenuProps) {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="min-w-[15rem]">+ <DropdownMenuLabel className="text-xs font-normal text-zinc-500">+ {MENU_LABEL}+ </DropdownMenuLabel>+ {experts.map((expert) => (+ <DropdownMenuItem+ key={expert.id}+ disabled={isAdding}+ onSelect={() => onAddToExpert(expert)}+ className="gap-2.5 py-2"+ >+ <Avatar className="h-6 w-6">+ {expert.avatar_url ? (+ <AvatarImage src={expert.avatar_url} alt="" />+ ) : null}+ <AvatarFallback>{expert.name}</AvatarFallback>+ </Avatar>+ <span className="min-w-0">+ <span className="block truncate text-zinc-900">+ {expert.name}+ </span>+ {expert.role ? (+ <span className="block truncate text-xs text-zinc-500">+ {expert.role}+ </span>+ ) : null}+ </span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillActions.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillActions.tsxindex 240ce2f94a..c0638be7d8 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillActions.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillActions.tsx@@ -1,8 +1,17 @@+import { Expert } from "@/app/api/__generated__/models/expert";import { Badge } from "@/components/atoms/Badge/Badge";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";-import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";+import {+ ArrowDown01Icon,+ CheckmarkCircle02Icon,+} from "@hugeicons/core-free-icons";+import {+ ExpertInstallMenu,+ InstallSkillButton,+ MENU_LABEL,+} from "./InstallSkillButton";// Sized and shaped like the small button beside it so the pair reads as one row.const STATUS_CLASS = "h-9 rounded-full px-3.5 text-sm";@@ -16,7 +25,9 @@ interface Props {isReady: boolean;isAdded: boolean;isAdding: boolean;+ experts: Expert[];onAdd: () => void;+ onAddToExpert: (expert: Expert) => void;}/** The page's one call to action, in the header beside the title. A visitor@@ -27,7 +38,9 @@ export function SkillActions({isReady,isAdded,isAdding,+ experts,onAdd,+ onAddToExpert,}: Props) {return (<div aria-live="polite" className="w-full sm:w-auto">@@ -58,18 +71,33 @@ export function SkillActions({>Your skills</Button>+ {/* Already in your own skills is no reason not to hand it to an+ expert too, so the dropdown outlives the main action. */}+ {experts.length > 0 ? (+ <ExpertInstallMenu+ experts={experts}+ isAdding={isAdding}+ onAddToExpert={onAddToExpert}+ >+ <Button+ variant="secondary"+ size="small"+ aria-label={MENU_LABEL}+ disabled={isAdding}+ className={`!min-w-0 px-2.5 ${SECONDARY_CLASS}`}+ >+ <Icon icon={ArrowDown01Icon} size={16} aria-hidden />+ </Button>+ </ExpertInstallMenu>+ ) : null}</div>) : (- <Button- variant="primary"- size="small"- onClick={onAdd}- loading={isAdding}- className="w-full sm:w-auto"- data-testid="skill-install-button"- >- Install skill- </Button>+ <InstallSkillButton+ experts={experts}+ isAdding={isAdding}+ onAddToLibrary={onAdd}+ onAddToExpert={onAddToExpert}+ />)}</div>);diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsxindex 0dcc28a373..16ebc03b95 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/SkillPage.tsx@@ -45,7 +45,9 @@ export function SkillPage({ slug }: Props) {flagReady,isAdded,isAdding,+ experts,addToAutoPilot,+ addToExpert,pendingConnections,moreSkills,isConnectOpen,@@ -116,7 +118,9 @@ export function SkillPage({ slug }: Props) {isReady={isReady}isAdded={isAdded}isAdding={isAdding}+ experts={experts}onAdd={addToAutoPilot}+ onAddToExpert={addToExpert}/></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.tsindex f202428136..e08e5cea22 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/skills/[slug]/components/useSkillPage.ts@@ -1,3 +1,7 @@+import {+ getGetExpertQueryKey,+ useListExperts,+} from "@/app/api/__generated__/endpoints/experts/experts";import {getGetV1ListCredentialsQueryKey,useGetV1ListCredentials,@@ -11,6 +15,7 @@ import {useGetV2ListMarketplaceSkills,usePostV2InstallMarketplaceSkill,} from "@/app/api/__generated__/endpoints/store/store";+import { Expert } from "@/app/api/__generated__/models/expert";import { okData } from "@/app/api/helpers";import { formatProviderName } from "@/components/contextual/IntegrationsPanel/helpers";import { useToast } from "@/components/molecules/Toast/use-toast";@@ -43,6 +48,13 @@ export function useSkillPage(slug: string) {(skill) => skill.name === slug,);+ const expertsQuery = useListExperts({+ query: { select: (res) => res.data as Expert[], enabled: isLoggedIn },+ });+ const experts = (expertsQuery.data ?? []).filter(+ (expert) => !expert.is_template && !expert.is_archived,+ );+const credentials = useGetV1ListCredentials({query: {enabled: isLoggedIn,@@ -61,16 +73,27 @@ export function useSkillPage(slug: string) {const { mutate: install, isPending: isAdding } =usePostV2InstallMarketplaceSkill({mutation: {- onSuccess: (response) => {+ onSuccess: (response, variables) => {if (response.status !== 200) return;+ const expert = findExpert(variables.params?.expert_id);queryClient.invalidateQueries({- queryKey: getListCopilotSkillsQueryKey(),+ queryKey: getListCopilotSkillsQueryKey(+ expert ? { expert_id: expert.id } : undefined,+ ),});+ if (!expert) return;+ queryClient.invalidateQueries({+ queryKey: getGetExpertQueryKey(expert.id),+ });+ toast({ title: `Installed on ${expert.name}`, variant: "success" });},- onError: (error) => {+ onError: (error, variables) => {const status = (error as { status?: number }).status;+ const expert = findExpert(variables.params?.expert_id);toast({- title: "Couldn't add this skill",+ title: expert+ ? `Couldn't add this skill to ${expert.name}`+ : "Couldn't add this skill",description:status === 401? "Sign in and try again."@@ -83,6 +106,10 @@ export function useSkillPage(slug: string) {},});+ function findExpert(expertId: string | null | undefined) {+ return experts.find((expert) => expert.id === expertId) ?? null;+ }+const requiredProviders = query.data?.required_providers ?? [];return {@@ -92,17 +119,21 @@ export function useSkillPage(slug: string) {isError: query.isError,isNotFound: (query.error as { status?: number } | null)?.status === 404,refetch: query.refetch,- // Nothing renders "Add" before auth, the flag and the user's own skills- // have all answered, so it never flashes into "Added".+ // Nothing renders before auth, the flag, the user's own skills and the+ // roster have all answered, so the button never flashes into "Added" nor+ // grows its dropdown half under the pointer.isReady:!isUserLoading &&flag.ready &&- (!isLoggedIn || !installedSkills.isLoading),+ (!isLoggedIn || (!installedSkills.isLoading && !expertsQuery.isLoading)),flagEnabled: flag.enabled,flagReady: flag.ready,isAdded,isAdding,+ experts,addToAutoPilot: () => install({ slug }),+ addToExpert: (expert: Expert) =>+ install({ slug, params: { expert_id: expert.id } }),// Connecting is a next step, never a precondition: the list only offers// what is still worth setting up, after the install landed.pendingConnections: requiredProvidersdiff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsxindex 7313b72c31..4ba9fd1842 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx@@ -47,7 +47,10 @@ import {getGetHomeDashboardResponseMock200,} from "@/app/api/__generated__/endpoints/home/home.msw";import { HomeAttentionItem } from "@/app/api/__generated__/models/homeAttentionItem";-import { getGetV2ListStoreAgentsMockHandler200 } from "@/app/api/__generated__/endpoints/store/store.msw";+import {+ getGetV2ListMarketplaceSkillsMockHandler200,+ getPostV2InstallMarketplaceSkillMockHandler200,+} from "@/app/api/__generated__/endpoints/store/store.msw";import { server } from "@/mocks/mock-server";import {fireEvent,@@ -85,8 +88,9 @@ vi.mock("framer-motion", async (importActual) => {return { ...actual, useReducedMotion: () => true };});-const { setFlagStatusMock } = vi.hoisted(() => ({+const { setFlagStatusMock, skillsHubFlag } = vi.hoisted(() => ({setFlagStatusMock: vi.fn(() => ({ enabled: true, ready: true })),+ skillsHubFlag: { enabled: true, ready: true },}));vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {@@ -99,7 +103,9 @@ vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {useFlagStatus: (flag: string) =>flag === "hire-experts"? setFlagStatusMock()- : actual.useFlagStatus(flag as never),+ : flag === "skills-hub"+ ? skillsHubFlag+ : actual.useFlagStatus(flag as never),};});@@ -280,6 +286,7 @@ beforeEach(() => {});afterEach(() => {+ skillsHubFlag.enabled = true;resetCopilotChatRegistry();window.localStorage.removeItem("team-workflows-view");setFlagStatusMock.mockReturnValue({ enabled: true, ready: true });@@ -720,23 +727,20 @@ describe("ExpertDetailPage", () => {expect(await within(list).findByText("Deep Research")).toBeDefined();});- test("offers marketplace skills as a second source in the add dialog", async () => {- const user = userEvent.setup();- server.use(+ function hubSkillHandlers(installs: string[], onInstalled = () => {}) {+ return [getListCopilotSkillsMockHandler200([]),- getGetV2ListStoreAgentsMockHandler200({- agents: [+ getGetV2ListMarketplaceSkillsMockHandler200({+ skills: [{slug: "seo-audit",- agent_name: "SEO Audit Pro",- agent_image: "",+ name: "SEO audit",+ description: "Audit any page for SEO gaps",+ categories: ["marketing"],+ required_providers: [],+ install_count: 3,creator: "acme",- creator_avatar: "",- sub_heading: "Audit any page for SEO gaps",- description: "",- runs: 3,- rating: 4.5,- agent_graph_id: "graph-seo",+ creator_avatar: null,},],pagination: {@@ -746,6 +750,26 @@ describe("ExpertDetailPage", () => {page_size: 20,},}),+ getPostV2InstallMarketplaceSkillMockHandler200(({ request, params }) => {+ const expertId = new URL(request.url).searchParams.get("expert_id");+ installs.push(`${params.slug as string}@${expertId}`);+ onInstalled();+ return { name: "seo-audit", required_providers: [] };+ }),+ ];+ }++ test("installs a marketplace skill onto the expert being viewed", async () => {+ const user = userEvent.setup();+ const installs: string[] = [];+ // The install writes the name onto the row server-side, so the expert+ // read after it is what the list must pick up.+ let skills: string[] = [];+ server.use(+ ...hubSkillHandlers(installs, () => {+ skills = ["seo-audit"];+ }),+ getGetExpertMockHandler(() => ({ ...maria, skills })),);render(<ExpertDetailPage />);@@ -757,7 +781,32 @@ describe("ExpertDetailPage", () => {const list = await within(dialog).findByRole("list", {name: "Marketplace skills",});- expect(within(list).getByText("SEO Audit Pro")).toBeDefined();+ expect(within(list).getByText("SEO audit")).toBeDefined();+ await user.click(within(list).getByRole("button", { name: "Add" }));++ // The expert's own id, not the caller's library: this is the whole+ // difference from the old tab, which only recorded the listing's name.+ await waitFor(() => expect(installs).toEqual(["seo-audit@expert-maria"]));+ const attached = await screen.findByRole("list", { name: "Expert skills" });+ expect(await within(attached).findByText("seo-audit")).toBeDefined();+ });++ test("hides the marketplace tab when the skills hub is off", async () => {+ const user = userEvent.setup();+ skillsHubFlag.enabled = false;+ server.use(...hubSkillHandlers([]));+ render(<ExpertDetailPage />);++ await openTab("Skills");+ await user.click(screen.getByRole("button", { name: "Add skill" }));+ const dialog = await screen.findByRole("dialog", { name: "Add a skill" });++ expect(+ within(dialog).queryByRole("tab", { name: "Marketplace" }),+ ).toBeNull();+ // The dialog must not promise a source it cannot show either.+ expect(dialog.textContent).toContain("Pick one from your library.");+ expect(dialog.textContent).not.toMatch(/marketplace/i);});test("removes a skill from the expert", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/AddSkillDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/AddSkillDialog.tsxindex d60e7bc8e6..a3b8e37984 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/AddSkillDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/AddSkillDialog.tsx@@ -1,7 +1,7 @@"use client";import { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkillInfo";-import { StoreAgent } from "@/app/api/__generated__/models/storeAgent";+import { MarketplaceSkill } from "@/app/api/__generated__/models/marketplaceSkill";import { Button } from "@/components/atoms/Button/Button";import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";@@ -31,11 +31,12 @@ interface Props {isLoading: boolean;marketQuery: string;onMarketQueryChange: (query: string) => void;- marketplaceSkills: StoreAgent[];+ marketplaceSkills: MarketplaceSkill[];isMarketplaceLoading: boolean;+ hasMarketplace: boolean;isSaving: boolean;onAdd: (name: string) => void;- onAddMarketplace: (agent: StoreAgent) => void;+ onAddMarketplace: (skill: MarketplaceSkill) => void;onClose: () => void;}@@ -49,6 +50,7 @@ export function AddSkillDialog({onMarketQueryChange,marketplaceSkills,isMarketplaceLoading,+ hasMarketplace,isSaving,onAdd,onAddMarketplace,@@ -81,24 +83,27 @@ export function AddSkillDialog({<div className="flex flex-col gap-3"><Text variant="body" tone="muted">Skills are reusable instructions this expert follows for a specific- job. Pick one from your library or install one from the marketplace.+ job. Pick one from your library+ {hasMarketplace ? " or install one from the marketplace" : ""}.</Text>- <TabsLine- variant="compact"- value={source}- onValueChange={(next) => onSourceChange(next as Source)}- >- <TabsLineList>- <TabsLineTrigger value="library" icon={BookOpen01Icon}>- Library- </TabsLineTrigger>- <TabsLineTrigger value="marketplace" icon={Store01Icon}>- Marketplace- </TabsLineTrigger>- </TabsLineList>- </TabsLine>+ {hasMarketplace ? (+ <TabsLine+ variant="compact"+ value={source}+ onValueChange={(next) => onSourceChange(next as Source)}+ >+ <TabsLineList>+ <TabsLineTrigger value="library" icon={BookOpen01Icon}>+ Library+ </TabsLineTrigger>+ <TabsLineTrigger value="marketplace" icon={Store01Icon}>+ Marketplace+ </TabsLineTrigger>+ </TabsLineList>+ </TabsLine>+ ) : null}- {source === "library" ? (+ {!hasMarketplace || source === "library" ? (<><SearchInputsize="small"@@ -167,14 +172,14 @@ export function AddSkillDialog({className="flex flex-col gap-2 overflow-y-auto pr-1"aria-label="Marketplace skills">- {marketplaceSkills.map((agent) => (+ {marketplaceSkills.map((skill) => (<SkillOption- key={`${agent.creator}/${agent.slug}`}- name={agent.agent_name}- description={agent.sub_heading || agent.description}+ key={skill.slug}+ name={skill.name}+ description={skill.description}icon={Store01Icon}disabled={isSaving}- onAdd={() => onAddMarketplace(agent)}+ onAdd={() => onAddMarketplace(skill)}/>))}</ul>diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillsSection.tsxindex e6f7857fc4..108b11b486 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillsSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertSkillsSection.tsx@@ -31,6 +31,7 @@ export function ExpertSkillsSection({ expert, accentClassName }: Props) {setMarketQuery,marketplaceSkills,isMarketplaceLoading,+ hasMarketplace,addSkill,addMarketplaceSkill,removeSkill,@@ -94,6 +95,7 @@ export function ExpertSkillsSection({ expert, accentClassName }: Props) {onMarketQueryChange={setMarketQuery}marketplaceSkills={marketplaceSkills}isMarketplaceLoading={isMarketplaceLoading}+ hasMarketplace={hasMarketplace}isSaving={isSaving}onAdd={addSkill}onAddMarketplace={addMarketplaceSkill}diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.tsindex d51e0ef7c0..1195521da8 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/useExpertSkills.ts@@ -7,16 +7,17 @@ import {useListCopilotSkills,} from "@/app/api/__generated__/endpoints/skills/skills";import {- getV2GetSpecificAgent,- useGetV2ListStoreAgents,+ useGetV2ListMarketplaceSkills,+ usePostV2InstallMarketplaceSkill,} from "@/app/api/__generated__/endpoints/store/store";-import { StoreAgent } from "@/app/api/__generated__/models/storeAgent";+import { MarketplaceSkill } from "@/app/api/__generated__/models/marketplaceSkill";import { useDebouncedValue } from "@/hooks/useDebouncedValue";import { CopilotSkillInfo } from "@/app/api/__generated__/models/copilotSkillInfo";import { Expert } from "@/app/api/__generated__/models/expert";import { okData } from "@/app/api/helpers";import { ApiError } from "@/lib/autogpt-server-api/helpers";import { useToast } from "@/components/molecules/Toast/use-toast";+import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";import { invalidateExpertRosterQueries } from "@/services/experts/invalidate-experts";import { useQueryClient } from "@tanstack/react-query";import { useState } from "react";@@ -35,15 +36,18 @@ export function useExpertSkills(expert: Expert) {const [source, setSource] = useState<"library" | "marketplace">("library");const [marketQuery, setMarketQuery] = useState("");const debouncedMarketQuery = useDebouncedValue(marketQuery, 250);- const marketplaceSkills = useGetV2ListStoreAgents(+ const hub = useFlagStatus(Flag.SKILLS_HUB);+ const marketplaceSkills = useGetV2ListMarketplaceSkills({ search_query: debouncedMarketQuery.trim(), page_size: 20 },{query: {- enabled: isAddOpen && source === "marketplace",- select: (res) => okData(res)?.agents ?? [],+ enabled: hub.enabled && isAddOpen && source === "marketplace",+ select: (res) => okData(res)?.skills ?? [],},},);+ const { mutateAsync: installHubSkill, isPending: isInstalling } =+ usePostV2InstallMarketplaceSkill();const librarySkills = useListCopilotSkills(undefined, {query: { select: (res) => okData(res) ?? [] },});@@ -84,25 +88,10 @@ export function useExpertSkills(expert: Expert) {): attached;- async function save(- skills: string[],- successTitle: string,- marketplaceListingIds: string[] = [],- ) {+ async function save(skills: string[], successTitle: string) {try {- await updateSkills({- expertId: expert.id,- data: { skills, marketplace_listing_ids: marketplaceListingIds },- });- await Promise.all([- queryClient.invalidateQueries({- queryKey: getGetExpertQueryKey(expert.id),- }),- queryClient.invalidateQueries({- queryKey: getListCopilotSkillsQueryKey({ expert_id: expert.id }),- }),- invalidateExpertRosterQueries(queryClient),- ]);+ await updateSkills({ expertId: expert.id, data: { skills } });+ await refreshExpert();toast({ title: successTitle, variant: "success" });return true;} catch (error) {@@ -120,17 +109,18 @@ export function useExpertSkills(expert: Expert) {if (saved) setIsAddOpen(false);}- async function addMarketplaceSkill(agent: StoreAgent) {+ /** Copies the Hub skill's instructions into this expert's own folder, so+ * the expert runs it rather than only listing its name. */+ async function addMarketplaceSkill(skill: MarketplaceSkill) {try {- const details = await getV2GetSpecificAgent(- agent.creator.toLowerCase(),- agent.slug,- );- if (details.status !== 200) throw new Error("listing unavailable");- const saved = await save(expert.skills, `Added ${agent.agent_name}`, [- details.data.store_listing_version_id,- ]);- if (saved) setIsAddOpen(false);+ const response = await installHubSkill({+ slug: skill.slug,+ params: { expert_id: expert.id },+ });+ if (response.status !== 200) throw new Error("install failed");+ await refreshExpert();+ toast({ title: `Added ${skill.name}`, variant: "success" });+ setIsAddOpen(false);} catch (error) {toast({title: "Couldn't add that skill",@@ -140,6 +130,18 @@ export function useExpertSkills(expert: Expert) {}}+ function refreshExpert() {+ return Promise.all([+ queryClient.invalidateQueries({+ queryKey: getGetExpertQueryKey(expert.id),+ }),+ queryClient.invalidateQueries({+ queryKey: getListCopilotSkillsQueryKey({ expert_id: expert.id }),+ }),+ invalidateExpertRosterQueries(queryClient),+ ]);+ }+function removeSkill(name: string) {return save(expert.skills.filter((skill) => skill !== name),@@ -163,9 +165,10 @@ export function useExpertSkills(expert: Expert) {setMarketQuery,marketplaceSkills: marketplaceSkills.data ?? [],isMarketplaceLoading: marketplaceSkills.isFetching,+ hasMarketplace: hub.enabled,addSkill,addMarketplaceSkill,removeSkill,- isSaving: isPending,+ isSaving: isPending || isInstalling,};}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex b64c67a4d0..b8d0224bb6 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15186,7 +15186,7 @@"post": {"tags": ["v2", "store", "private"],"summary": "Install marketplace skill",- "description": "Copy the listing's skill into the caller's skill library.",+ "description": "Copy the listing's skill into an expert's skills, or the caller's own.","operationId": "postV2Install marketplace skill","security": [{ "HTTPBearer": [] }, { "HTTPBearerJWT": [] }],"parameters": [@@ -15200,6 +15200,17 @@"title": "Slug"},"description": "Slug of the skill listing"+ },+ {+ "name": "expert_id",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "description": "Install into this expert's skills instead of the caller's own.",+ "title": "Expert Id"+ },+ "description": "Install into this expert's skills instead of the caller's own."}],"responses": {@@ -15214,7 +15225,7 @@"401": {"$ref": "#/components/responses/HTTP401NotAuthenticatedError"},- "404": { "description": "Skill not found" },+ "404": { "description": "Skill or expert not found" },"409": { "description": "Per-user skill limit reached" },"422": {"description": "Validation Error",