Skip to content

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/marketplace): return experts from search and the category chips (#14504)

Reinier van der Leer45db96f2a014
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 5c1d2ddd0e..278c4e9ac0 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -58,6 +58,7 @@ from backend.api.features.experts.workflow_chain import (
from backend.api.features.library import db as library_db
from backend.api.features.library import model as library_model
from backend.api.features.orgs.db import get_user_default_team
+from backend.api.features.store.categories import category_match_values
from backend.blocks import get_output_block_ids
from backend.copilot.briefing.outcome import DEFAULT_AGENT_NAME, run_link
from backend.copilot.tools.skills import (
@@ -228,6 +229,7 @@ def _to_model(
tagline=row.tagline,
bio=row.bio,
skills=row.skills or [],
+ categories=row.categories or [],
identity=row.identity,
voice_preferences=voice_preferences,
voice_samples=voice_samples,
@@ -261,14 +263,35 @@ async def _latest_runs(
return {row.expertId: row for row in rows if row.expertId is not None}
-async def list_templates() -> list[Expert]:
+async def list_templates(
+ search_query: str | None = None,
+ category: str | None = None,
+) -> list[Expert]:
rows = await prisma.models.Expert.prisma().find_many(
- where={"isTemplate": True, "isArchived": False},
+ where=_template_where(search_query, category),
include=_TEMPLATE_WORKFLOW_INCLUDE,
)
return [_to_model(row) for row in rows]
+def _template_where(
+ search_query: str | None, category: str | None
+) -> prisma.types.ExpertWhereInput:
+ where: prisma.types.ExpertWhereInput = {"isTemplate": True, "isArchived": False}
+ if category:
+ # Not `category_filter_values`: with the canonical-category setting
+ # on, that one hides uncategorised experts from the unfiltered roster.
+ where["categories"] = {"has_some": category_match_values(category)}
+ if search_query and (needle := search_query.strip()):
+ where["OR"] = [
+ {"name": {"contains": needle, "mode": "insensitive"}},
+ {"role": {"contains": needle, "mode": "insensitive"}},
+ {"tagline": {"contains": needle, "mode": "insensitive"}},
+ {"bio": {"contains": needle, "mode": "insensitive"}},
+ ]
+ return where
+
+
# Ceiling on in-flight Redis reads inside ``_weekly_spends``. The roster is
# user-controlled and unbounded, so an uncapped ``gather`` would ask the shared
# Redis pool for one connection per hired expert on every team-page load.
@@ -776,6 +799,7 @@ async def hire_expert(user_id: str, template_id: str, name: str | None) -> HireR
"tagline": template.tagline,
"bio": template.bio,
"skills": template.skills or [],
+ "categories": template.categories or [],
# No dayOne: it is the template's pre-hire promise, not the hire's.
"identity": template.identity,
"voicePreferences": template_voice,
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index e9c72deced..2ffa93985d 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -28,6 +28,7 @@ from backend.api.features.experts.models import (
)
from backend.api.features.library import db as library_db
from backend.api.features.library import model as library_model
+from backend.api.features.store.categories import StoreCategory
from backend.api.model import CreateGraph
from backend.blocks.io import AgentInputBlock
from backend.copilot.model import create_chat_session
@@ -1407,6 +1408,7 @@ async def test_hire_existing_team_expert_fails_closed():
tagline=None,
bio=None,
skills=[],
+ categories=[],
identity="You are Maria.",
voicePreferences=None,
boundaries=None,
@@ -1457,6 +1459,7 @@ async def test_hire_raced_org_expert_fails_closed():
tagline=None,
bio=None,
skills=[],
+ categories=[],
identity="You are Maria.",
voicePreferences=None,
boundaries=None,
@@ -3362,6 +3365,7 @@ async def test_sync_preloads_updates_template_cadence(server: SpinTestServer):
"avatar_url": None,
"bio": "",
"skills": [],
+ "categories": [],
"identity": template.identity,
"preloads": [{"slug": listing.slug, "cron": "40 7 * * *"}],
}
@@ -3408,6 +3412,7 @@ async def test_seed_backfills_presentation_fields_onto_hired_copies(
"avatar_url": "/experts/maria.svg",
"bio": "Maria is a senior marketing strategist.",
"skills": ["Content strategy", "SEO writing"],
+ "categories": ["marketing"],
"identity": template.identity,
"voice_preferences": "Clear and confident.",
"boundaries": "Never invent customer evidence.",
@@ -3425,6 +3430,7 @@ async def test_seed_backfills_presentation_fields_onto_hired_copies(
assert refreshed.avatar_url == "/experts/maria.svg"
assert refreshed.tagline == "Refreshed tagline"
assert refreshed.bio == "Maria is a senior marketing strategist."
+ assert refreshed.categories == ["marketing"]
# A user's rename and skill list survive the refresh: the template's
# skills neither replace the owner's nor get merged back into them.
assert refreshed.skills == ["Customer interviews"]
@@ -4215,3 +4221,147 @@ def test_expert_soul_fields_patch_strips_and_preserves_none():
assert patch.voice_preferences == ""
assert patch.boundaries == "Keep it short."
assert patch.identity is None
+
+
+async def _template(name: str, **fields) -> prisma.models.Expert:
+ return await prisma.models.Expert.prisma().create(
+ data={
+ "name": name,
+ "role": fields.pop("role", "Writer"),
+ "identity": f"You are {name}.",
+ "isTemplate": True,
+ **fields,
+ }
+ )
+
+
[email protected](loop_scope="session")
+async def test_list_templates_filters_by_category(server: SpinTestServer):
+ """A category chip narrows the roster, and never widens it: an expert
+ filed under another category must not surface under an unrelated chip."""
+ suffix = uuid.uuid4().hex[:8]
+ marketer = await _template(f"Mira {suffix}", categories=["marketing"])
+ seller = await _template(f"Sal {suffix}", categories=["sales"])
+
+ listed = {t.id for t in await experts_db.list_templates(category="marketing")}
+ assert marketer.id in listed
+ assert seller.id not in listed
+
+ assert marketer.categories == ["marketing"]
+
+
[email protected](loop_scope="session")
+async def test_list_templates_category_filter_accepts_a_legacy_alias(
+ server: SpinTestServer,
+):
+ """`category_match_values` folds aliases, so a chip stored as "seo"
+ still matches an expert filed under the canonical "marketing"."""
+ suffix = uuid.uuid4().hex[:8]
+ marketer = await _template(f"Mo {suffix}", categories=["marketing"])
+ seller = await _template(f"So {suffix}", categories=["sales"])
+
+ listed = {t.id for t in await experts_db.list_templates(category="seo")}
+ assert marketer.id in listed
+ # Without the exclusion this passes on an unfiltered list, which would
+ # prove nothing about the alias.
+ assert seller.id not in listed
+
+
[email protected](loop_scope="session")
+async def test_list_templates_without_a_category_keeps_uncategorised_experts(
+ server: SpinTestServer,
+):
+ """The unfiltered roster is the whole roster. `category_filter_values`
+ would narrow it to experts that HAVE a canonical category once
+ `marketplace_require_canonical_category` is on, hiding this one."""
+ plain = await _template(f"Nil {uuid.uuid4().hex[:8]}")
+
+ assert plain.categories == []
+ assert plain.id in {t.id for t in await experts_db.list_templates()}
+
+
[email protected](loop_scope="session")
+async def test_list_templates_searches_name_role_tagline_and_bio(
+ server: SpinTestServer,
+):
+ suffix = uuid.uuid4().hex[:8]
+ by_name = await _template(f"Marigold {suffix}")
+ by_role = await _template(f"Roleful {suffix}", role=f"Podcaster {suffix}")
+ by_tagline = await _template(f"Tagged {suffix}", tagline=f"Books {suffix} tours")
+ by_bio = await _template(f"Biod {suffix}", bio=f"Fifteen years of {suffix} work")
+
+ async def ids_for(query: str) -> set[str]:
+ return {t.id for t in await experts_db.list_templates(search_query=query)}
+
+ assert by_name.id in await ids_for("marigold")
+ assert by_role.id in await ids_for(f"podcaster {suffix}")
+ assert by_tagline.id in await ids_for(f"books {suffix}")
+ assert by_bio.id in await ids_for(f"fifteen years of {suffix}")
+
+ # One term, four templates: the OR spans the four searchable columns.
+ assert await ids_for(suffix) >= {
+ by_name.id,
+ by_role.id,
+ by_tagline.id,
+ by_bio.id,
+ }
+
+
[email protected](loop_scope="session")
+async def test_list_templates_search_misses_return_nothing(server: SpinTestServer):
+ await _template(f"Quiet {uuid.uuid4().hex[:8]}")
+
+ assert await experts_db.list_templates(search_query=uuid.uuid4().hex) == []
+
+
[email protected](loop_scope="session")
+async def test_list_templates_treats_a_blank_search_as_no_filter(
+ server: SpinTestServer,
+):
+ template = await _template(f"Blank {uuid.uuid4().hex[:8]}")
+
+ listed = await experts_db.list_templates(search_query=" ")
+
+ assert template.id in {t.id for t in listed}
+
+
[email protected](loop_scope="session")
+async def test_list_templates_combines_search_and_category(server: SpinTestServer):
+ suffix = uuid.uuid4().hex[:8]
+ matching = await _template(f"Both {suffix}", categories=["marketing"])
+ wrong_category = await _template(f"Both {suffix} too", categories=["sales"])
+ # Right category, wrong name: without the search half this one leaks in,
+ # which is what makes the test load-bearing for both filters at once.
+ wrong_name = await _template(f"Neither {suffix}", categories=["marketing"])
+
+ listed = {
+ t.id
+ for t in await experts_db.list_templates(
+ search_query=f"both {suffix}", category="marketing"
+ )
+ }
+ assert listed == {matching.id}
+ assert wrong_category.id not in listed
+ assert wrong_name.id not in listed
+
+
[email protected](loop_scope="session")
+async def test_hire_copies_the_template_categories(server: SpinTestServer, test_user):
+ template = await _template(f"Cat {uuid.uuid4().hex[:8]}", categories=["operations"])
+
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ assert hired.expert.categories == ["operations"]
+
+
[email protected](loop_scope="session")
+async def test_seed_roster_files_every_template_under_a_canonical_category(
+ server: SpinTestServer,
+):
+ await _load_roster_store_assets()
+ ids = await seed.seed_roster()
+ seeded = {t.name: t for t in await experts_db.list_templates() if t.id in ids}
+
+ for entry in seed.ROSTER:
+ assert seeded[entry["name"]].categories == entry["categories"]
+ assert set(entry["categories"]) <= {c.value for c in StoreCategory}
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index b029c5cc1e..cebefcf574 100644
--- a/autogpt_platform/backend/backend/api/features/experts/models.py
+++ b/autogpt_platform/backend/backend/api/features/experts/models.py
@@ -206,6 +206,8 @@ class Expert(BaseModel):
tagline: str | None
bio: str | None
skills: list[str]
+ # Canonical marketplace categories the roster is filtered by.
+ categories: list[str] = []
identity: str
voice_preferences: str
# Populated only on roster templates so the hire flow can offer a voice
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.py
index 0407261dca..cb7ade46a9 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py
@@ -128,8 +128,15 @@ class CreateRaisedExpertRequest(BaseModel):
@public_router.get("/templates", operation_id="list_expert_templates")
-async def list_expert_templates() -> list[Expert]:
- return await experts_db.list_templates()
+async def list_expert_templates(
+ search_query: str | None = fastapi.Query(default=None),
+ category: str | None = fastapi.Query(default=None),
+) -> list[Expert]:
+ """Roster templates, narrowed by a search term and/or a marketplace category.
+
+ Unpaginated: the roster is small, and every caller reads the whole list.
+ """
+ return await experts_db.list_templates(search_query=search_query, category=category)
@router.post(
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
index 5f3868f03f..8fa1a95bfa 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
@@ -147,13 +147,31 @@ def test_list_expert_templates(
assert len(data) == 1
assert data[0]["id"] == "template-1"
assert data[0]["is_template"] is True
- mock_list.assert_awaited_once_with()
+ mock_list.assert_awaited_once_with(search_query=None, category=None)
configured_snapshot.assert_match(
json.dumps(data, indent=2, sort_keys=True), "expert_templates_list"
)
+def test_list_expert_templates_forwards_search_and_category(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """The chip and the search box only work if both reach the db layer."""
+ mock_list = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.list_templates",
+ new_callable=AsyncMock,
+ return_value=[],
+ )
+
+ response = client.get(
+ "/experts/templates", params={"search_query": "Maria", "category": "marketing"}
+ )
+
+ assert response.status_code == 200
+ mock_list.assert_awaited_once_with(search_query="Maria", category="marketing")
+
+
# ─── Hire ──────────────────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/api/features/experts/seed.py b/autogpt_platform/backend/backend/api/features/experts/seed.py
index 017065fcdf..f625480ce0 100644
--- a/autogpt_platform/backend/backend/api/features/experts/seed.py
+++ b/autogpt_platform/backend/backend/api/features/experts/seed.py
@@ -6,8 +6,8 @@ Upserts the three roster templates (Maria, Max, Frankie) by template name,
so repeated runs keep the same template ids. Preload workflows are resolved
from official store listing slugs; all listings are validated before any
template is mutated. Each upsert also refreshes the presentation fields
-(avatar, tagline, bio) on experts already hired from that template, so
-roster changes reach existing users and not just new hires.
+(avatar, tagline, bio, categories) on experts already hired from that
+template, so roster changes reach existing users and not just new hires.
"""
import asyncio
@@ -23,6 +23,7 @@ from backend.api.features.experts.models import (
encode_day_one,
encode_voice_preferences,
)
+from backend.api.features.store.categories import validate_canonical_categories
from backend.data import db as database
from backend.util.clients import get_scheduler_client
from backend.util.json import SafeJson
@@ -57,6 +58,10 @@ class RosterEntry(TypedDict):
avatar_url: str | None
bio: str
skills: list[str]
+ # Canonical marketplace categories, so the category chip narrows the roster.
+ # Declared here rather than derived from `role`: "Ops" folds onto no
+ # canonical value, and a raised expert's role is free text.
+ categories: list[str]
identity: str
voice_preferences: str
# Two writing samples in the persona's voice; the hire flow shows these as
@@ -82,6 +87,7 @@ ROSTER: list[RosterEntry] = [
"Web copy",
"Positioning",
],
+ "categories": ["marketing", "content"],
"identity": """You are Maria, a senior marketing strategist with fifteen years of experience across B2B SaaS and consumer brands. You think in terms of positioning first: before any tactic, you want to know who the customer is, what keeps them up at night, and why they would choose this product over doing nothing. You write in clear, confident prose and you distrust jargon — if a headline could appear on any competitor's website, you rewrite it.
Your day-to-day work spans content strategy, social copy, email campaigns, and SEO-aware long-form writing. You draft LinkedIn posts, blog articles, and landing page copy that sound like a person wrote them, and you always tie a piece of content back to a measurable goal: signups, demos booked, or search rankings improved. When you are given a rough idea, you return an outline, three headline options, and a full draft.
@@ -135,6 +141,7 @@ You are direct about trade-offs. If a campaign idea is clever but off-brand, you
"ICP targeting",
"Account research",
],
+ "categories": ["sales"],
"identity": """You are Max, a sales development expert who has built outbound pipelines for startups and mid-market companies. You believe pipeline problems are usually targeting problems in disguise, so you start every engagement by sharpening the ideal customer profile: industry, size, trigger events, and the specific pain your product removes. Volume without fit is noise, and you say so plainly.
Your core work is prospecting and outreach preparation. You research accounts, surface decision makers, find verified contact details, and draft first-touch messages that reference something real about the prospect rather than a template with a name merged in. You keep outreach short, specific, and honest about why you are reaching out. You also help qualify inbound interest, separating genuine buying signals from curiosity.
@@ -172,6 +179,7 @@ You are rigorous about data quality. You flag when contact information looks sta
"Scheduling",
"Checklists",
],
+ "categories": ["operations", "support"],
"identity": """You are Frankie, an operations specialist who has run the back office for fast-growing teams. Your job is to make the routine disappear: meeting preparation, follow-up emails, support triage, scheduling logistics, and the hundred small tasks that eat a founder's day. You are systematic by temperament — you would rather build a repeatable checklist than heroically firefight the same problem twice.
Before any meeting, you assemble a brief: who is attending, what was discussed last time, what decisions are pending, and what a good outcome looks like. After meetings, you turn notes into action items with owners and dates. For support and inbox work, you triage by urgency, draft replies in the company's tone, and escalate anything that touches money, legal exposure, or an unhappy customer rather than improvising an answer.
@@ -322,6 +330,7 @@ async def _upsert_template(entry: RosterEntry) -> prisma.models.Expert:
"boundaries": entry["boundaries"],
"bio": entry["bio"],
"skills": entry["skills"],
+ "categories": validate_canonical_categories(entry["categories"]),
"dayOne": SafeJson(encode_day_one(entry["day_one"])),
"isArchived": False,
}
@@ -346,9 +355,10 @@ async def _backfill_hired_copies(template: prisma.models.Expert) -> int:
A hire copies the template row, so roster updates would otherwise only
ever reach new hires and everyone who hired earlier would keep a blank
- avatar/tagline/bio forever. ``name`` is deliberately excluded — users may
- have renamed their hire — as are ``role``/``identity``, which drive live
- persona behaviour, and ``skills``, which the owner edits after hire.
+ avatar/tagline/bio/categories forever. ``name`` is deliberately excluded —
+ users may have renamed their hire — as are ``role``/``identity``, which
+ drive live persona behaviour, and ``skills``, which the owner edits after
+ hire.
"""
return await prisma.models.Expert.prisma().update_many(
where={"sourceTemplateId": template.id, "isTemplate": False},
@@ -356,6 +366,7 @@ async def _backfill_hired_copies(template: prisma.models.Expert) -> int:
"avatarUrl": template.avatarUrl,
"tagline": template.tagline,
"bio": template.bio,
+ "categories": template.categories,
},
)
diff --git a/autogpt_platform/backend/migrations/20260910180000_add_expert_categories/migration.sql b/autogpt_platform/backend/migrations/20260910180000_add_expert_categories/migration.sql
new file mode 100644
index 0000000000..367137b279
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260910180000_add_expert_categories/migration.sql
@@ -0,0 +1 @@
+ALTER TABLE "Expert" ADD COLUMN "categories" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 016bc6b0d8..e4fb472efb 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -1054,6 +1054,9 @@ model Expert {
identity String
bio String?
skills String[] @default([])
+ // Free-text `role` cannot stand in: "Ops" folds onto no canonical
+ // category, and a raised expert's role is whatever its owner typed.
+ categories String[] @default([])
voicePreferences String @default("")
boundaries String @default("")
diff --git a/autogpt_platform/backend/snapshots/expert_pod_assign b/autogpt_platform/backend/snapshots/expert_pod_assign
index 47ebc64ceb..4d675b71ab 100644
--- a/autogpt_platform/backend/snapshots/expert_pod_assign
+++ b/autogpt_platform/backend/snapshots/expert_pod_assign
@@ -2,6 +2,7 @@
"avatar_url": null,
"bio": null,
"boundaries": "Ask before external actions.",
+ "categories": [],
"color": "",
"credential_count": 0,
"credential_providers": [],
diff --git a/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure b/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure
index 82ef1dd20d..3e2455adc1 100644
--- a/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure
+++ b/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure
@@ -3,6 +3,7 @@
"avatar_url": null,
"bio": null,
"boundaries": "",
+ "categories": [],
"color": "",
"credential_count": 0,
"credential_providers": [],
diff --git a/autogpt_platform/backend/snapshots/expert_raise_attachments b/autogpt_platform/backend/snapshots/expert_raise_attachments
index 44a4e06aed..e7eddaf3c6 100644
--- a/autogpt_platform/backend/snapshots/expert_raise_attachments
+++ b/autogpt_platform/backend/snapshots/expert_raise_attachments
@@ -3,6 +3,7 @@
"avatar_url": null,
"bio": null,
"boundaries": "",
+ "categories": [],
"color": "",
"credential_count": 0,
"credential_providers": [],
diff --git a/autogpt_platform/backend/snapshots/expert_raise_default b/autogpt_platform/backend/snapshots/expert_raise_default
index 47f5f18084..966dc04e69 100644
--- a/autogpt_platform/backend/snapshots/expert_raise_default
+++ b/autogpt_platform/backend/snapshots/expert_raise_default
@@ -3,6 +3,7 @@
"avatar_url": null,
"bio": null,
"boundaries": "",
+ "categories": [],
"color": "",
"credential_count": 0,
"credential_providers": [],
diff --git a/autogpt_platform/backend/snapshots/expert_soul_update b/autogpt_platform/backend/snapshots/expert_soul_update
index 39796d079a..b4d63c17f0 100644
--- a/autogpt_platform/backend/snapshots/expert_soul_update
+++ b/autogpt_platform/backend/snapshots/expert_soul_update
@@ -2,6 +2,7 @@
"avatar_url": null,
"bio": null,
"boundaries": "Never invent customer evidence.",
+ "categories": [],
"color": "",
"credential_count": 0,
"credential_providers": [],
diff --git a/autogpt_platform/backend/snapshots/expert_templates_list b/autogpt_platform/backend/snapshots/expert_templates_list
index 239260528a..07d8cf9c1a 100644
--- a/autogpt_platform/backend/snapshots/expert_templates_list
+++ b/autogpt_platform/backend/snapshots/expert_templates_list
@@ -3,6 +3,7 @@
"avatar_url": null,
"bio": null,
"boundaries": "Ask before external actions.",
+ "categories": [],
"color": "",
"credential_count": 0,
"credential_providers": [],
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-category-filter.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-category-filter.test.tsx
new file mode 100644
index 0000000000..e04a0c3e80
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-category-filter.test.tsx
@@ -0,0 +1,218 @@
+import { getListExpertsMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { getGetV2ListStoreCategoriesMockHandler } from "@/app/api/__generated__/endpoints/store/store.msw";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { server } from "@/mocks/mock-server";
+import {
+ configure,
+ render,
+ screen,
+ waitFor,
+ within,
+} 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 { MainMarkeplacePage } from "../components/MainMarketplacePage/MainMarketplacePage";
+
+configure({ asyncUtilTimeout: 10000 });
+
+const mockUseAuth = vi.hoisted(() => vi.fn());
+const hireExpertsFlag = vi.hoisted(() => ({ enabled: true }));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ back: vi.fn(),
+ forward: vi.fn(),
+ prefetch: vi.fn(),
+ push: vi.fn(),
+ refresh: vi.fn(),
+ replace: vi.fn(),
+ }),
+ usePathname: () => "/marketplace",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+}));
+
+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,
+ useGetFlag: (flag: string) =>
+ flag === "hire-experts"
+ ? hireExpertsFlag.enabled
+ : actual.useGetFlag(flag as never),
+ };
+});
+
+const CATEGORIES = [
+ { value: "marketing", label: "Marketing", description: "Campaigns and SEO" },
+ { value: "sales", label: "Sales", description: "Leads and outreach" },
+];
+
+function template(name: string, categories: string[]): Expert {
+ return {
+ id: `template-${name.toLowerCase()}`,
+ name,
+ avatar_url: null,
+ role: categories[0],
+ bio: null,
+ skills: [],
+ categories,
+ tagline: `${name} works here`,
+ identity: `You are ${name}.`,
+ voice_preferences: "Direct.",
+ boundaries: "Ask first.",
+ protected_soul_rules: [],
+ is_template: true,
+ source_template_id: null,
+ is_archived: false,
+ workflows: [],
+ };
+}
+
+const ROSTER = [template("Maria", ["marketing"]), template("Max", ["sales"])];
+
+/** Records every ?category= the roster is asked for, and answers with the
+ * experts filed under it — the server-side filter, as the page sees it. */
+const requestedCategories: (string | null)[] = [];
+
+describe("Marketplace category filter over experts", () => {
+ beforeEach(() => {
+ requestedCategories.length = 0;
+ hireExpertsFlag.enabled = true;
+ mockUseAuth.mockReturnValue({ user: { id: "user-1" }, isLoggedIn: true });
+ server.use(
+ getListExpertsMockHandler([]),
+ getGetV2ListStoreCategoriesMockHandler(CATEGORIES),
+ http.get("/api/proxy/api/experts/templates", ({ request }) => {
+ const category = new URL(request.url).searchParams.get("category");
+ requestedCategories.push(category);
+ return HttpResponse.json(
+ category
+ ? ROSTER.filter((t) => t.categories?.includes(category))
+ : ROSTER,
+ );
+ }),
+ http.get("/api/proxy/api/store/agents", () =>
+ HttpResponse.json({
+ agents: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ ),
+ http.get("/api/proxy/api/store/creators", () =>
+ HttpResponse.json({
+ creators: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ ),
+ );
+ });
+
+ test("the chip row sits above the experts shelf it narrows", async () => {
+ render(<MainMarkeplacePage />);
+
+ const chips = await screen.findByRole("group", {
+ name: "Browse by category",
+ });
+ const shelf = await screen.findByRole("link", { name: /Maria/ });
+
+ // Node.DOCUMENT_POSITION_FOLLOWING: the shelf comes after the chips.
+ expect(chips.compareDocumentPosition(shelf) & 4).toBeTruthy();
+ });
+
+ test("picking a category narrows the roster and drops the others", async () => {
+ render(<MainMarkeplacePage />);
+
+ expect(await screen.findByRole("link", { name: /Maria/ })).toBeDefined();
+ expect(await screen.findByRole("link", { name: /Max/ })).toBeDefined();
+
+ await userEvent.click(await findCategoryChip("Marketing"));
+
+ await waitFor(() => expect(requestedCategories).toContain("marketing"));
+ await waitFor(() =>
+ expect(screen.queryByRole("link", { name: /Max/ })).toBeNull(),
+ );
+ expect(screen.getByRole("link", { name: /Maria/ })).toBeDefined();
+ });
+
+ test("clearing the category restores the whole roster", async () => {
+ render(<MainMarkeplacePage />);
+ await screen.findByRole("link", { name: /Maria/ });
+
+ await userEvent.click(await findCategoryChip("Marketing"));
+ await waitFor(() =>
+ expect(screen.queryByRole("link", { name: /Max/ })).toBeNull(),
+ );
+
+ await userEvent.click(await findCategoryChip("Marketing"));
+
+ expect(await screen.findByRole("link", { name: /Max/ })).toBeDefined();
+ });
+
+ test("a category with no experts hides the shelf entirely", async () => {
+ server.use(
+ http.get("/api/proxy/api/experts/templates", ({ request }) => {
+ const category = new URL(request.url).searchParams.get("category");
+ return HttpResponse.json(category ? [] : ROSTER);
+ }),
+ );
+ render(<MainMarkeplacePage />);
+ await screen.findByRole("link", { name: /Maria/ });
+
+ await userEvent.click(await findCategoryChip("Sales"));
+
+ await waitFor(() =>
+ expect(screen.queryByText("Meet the AI Experts")).toBeNull(),
+ );
+ // Not the empty-roster fallback either: a filtered shelf offers no
+ // invitation to raise an expert.
+ expect(screen.queryByRole("link", { name: "Raise your own" })).toBeNull();
+ });
+
+ test("a failed roster request under a category still offers the raise link", async () => {
+ server.use(
+ http.get("/api/proxy/api/experts/templates", ({ request }) => {
+ const category = new URL(request.url).searchParams.get("category");
+ // Unfiltered succeeds so the page renders; the filtered fetch fails.
+ return category
+ ? new HttpResponse(null, { status: 500 })
+ : HttpResponse.json(ROSTER);
+ }),
+ );
+ render(<MainMarkeplacePage />);
+ await screen.findByRole("link", { name: /Maria/ });
+
+ await userEvent.click(await findCategoryChip("Sales"));
+
+ // The header carries its own "Raise your own" link, so wait for it to go:
+ // a failure is not an answer about the category, so the fallback stays.
+ await waitFor(() =>
+ expect(screen.queryByText("Meet the AI Experts")).toBeNull(),
+ );
+ expect(
+ screen.getByRole("link", { name: "Raise your own" }).getAttribute("href"),
+ ).toBe("/raise");
+ });
+});
+
+async function findCategoryChip(name: string) {
+ const group = await screen.findByRole("group", {
+ name: "Browse by category",
+ });
+ return within(group).findByRole("button", { name });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx
index 8a48f45fe3..2447be6023 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/skills-section.test.tsx
@@ -3,16 +3,19 @@ import { getListCopilotSkillsMockHandler200 } from "@/app/api/__generated__/endp
import {
getGetV2ListMarketplaceSkillsMockHandler200,
getGetV2ListStoreAgentsMockHandler,
+ getGetV2ListStoreCategoriesMockHandler,
getGetV2ListStoreCreatorsMockHandler,
} from "@/app/api/__generated__/endpoints/store/store.msw";
import type { MarketplaceSkill } from "@/app/api/__generated__/models/marketplaceSkill";
import { server } from "@/mocks/mock-server";
import { HttpResponse, http } from "msw";
+import userEvent from "@testing-library/user-event";
import {
configure,
render,
screen,
waitFor,
+ within,
} from "@/tests/integrations/test-utils";
import { beforeEach, describe, expect, test, vi } from "vitest";
@@ -84,6 +87,11 @@ const outreach: MarketplaceSkill = {
required_providers: ["google"],
};
+const CATEGORIES = [
+ { value: "sales", label: "Sales", description: "Leads and outreach" },
+ { value: "content", label: "Content", description: "Writing and editing" },
+];
+
function listing(skills: MarketplaceSkill[], totalItems = skills.length) {
return getGetV2ListMarketplaceSkillsMockHandler200({
skills,
@@ -217,6 +225,61 @@ describe("Marketplace SkillsSection", () => {
expect(await screen.findByRole("button", { name: "Retry" })).toBeDefined();
});
+ test("a category with no skills hides the shelf rather than showing it empty", async () => {
+ server.use(
+ getGetV2ListStoreCategoriesMockHandler(CATEGORIES),
+ http.get("/api/proxy/api/store/skills", ({ request }) => {
+ const filtered = new URL(request.url).searchParams.has("category");
+ const skills = filtered ? [] : [brandVoice];
+ return HttpResponse.json({
+ skills,
+ pagination: {
+ total_items: skills.length,
+ total_pages: 1,
+ current_page: 1,
+ page_size: 4,
+ },
+ });
+ }),
+ );
+ render(<MainMarkeplacePage />);
+ await screen.findByRole("link", { name: /Brand voice guide/ });
+
+ await userEvent.click(await findCategoryChip("Sales"));
+
+ // Without the category guard this falls through to the signed-in empty state.
+ await waitFor(() => expect(screen.queryByText("Otto Skills")).toBeNull());
+ expect(screen.queryByTestId("skills-shelf-empty")).toBeNull();
+ });
+
+ test("a failed filtered request keeps the shelf and offers a retry", async () => {
+ server.use(
+ getGetV2ListStoreCategoriesMockHandler(CATEGORIES),
+ http.get("/api/proxy/api/store/skills", ({ request }) => {
+ if (new URL(request.url).searchParams.has("category")) {
+ return HttpResponse.json({ detail: "Unavailable" }, { status: 500 });
+ }
+ return HttpResponse.json({
+ skills: [brandVoice],
+ pagination: {
+ total_items: 1,
+ total_pages: 1,
+ current_page: 1,
+ page_size: 4,
+ },
+ });
+ }),
+ );
+ render(<MainMarkeplacePage />);
+ await screen.findByRole("link", { name: /Brand voice guide/ });
+
+ await userEvent.click(await findCategoryChip("Sales"));
+
+ // A failure is not an answer about the category, so the shelf stays.
+ expect(await screen.findByRole("button", { name: "Retry" })).toBeDefined();
+ expect(screen.getByText("Otto Skills")).toBeDefined();
+ });
+
test("points a signed-in user at their own skills when none are published", async () => {
server.use(listing([]));
@@ -274,3 +337,10 @@ describe("Marketplace SkillsSection", () => {
await waitFor(() => expect(screen.queryByText("Otto Skills")).toBeNull());
});
});
+
+async function findCategoryChip(name: string) {
+ const group = await screen.findByRole("group", {
+ name: "Browse by category",
+ });
+ return within(group).findByRole("button", { name });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx
index 0635338ac7..9068698842 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx
@@ -10,11 +10,20 @@ import { useExpertsSection } from "./useExpertsSection";
const RAISE_LABEL = "Raise your own";
const RAISE_HREF = "/raise";
-export function ExpertsSection() {
+interface Props {
+ category?: string | null;
+}
+
+export function ExpertsSection({ category }: Props) {
const { isLoggedIn, templates, hiredTemplateIds, isLoading, isError } =
- useExpertsSection();
+ useExpertsSection({ category });
if (isError || (!isLoading && templates.length === 0)) {
+ // Under a category filter an empty shelf means "no experts in this
+ // category", so the whole section goes rather than inviting a raise.
+ // Only on a successful empty response: a failed request is not an answer
+ // about the category, and still deserves the fallback below.
+ if (!isError && category) return null;
// Raising an expert needs no roster templates, so the second door
// stays open even when the template list is empty or failed to load.
// It needs an account, though, so visitors get nothing here.
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts
index d134c963ce..a7615d3b03 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts
@@ -5,16 +5,45 @@ import {
import { Expert } from "@/app/api/__generated__/models/expert";
import { useAuth } from "@/lib/auth/hooks/useAuth";
+interface Args {
+ category?: string | null;
+ searchQuery?: string;
+ /** False keeps the roster unfetched where the surface is hidden. */
+ enabled?: boolean;
+}
+
/** Templates are public, so the section can show them to anyone; only the
* hired roster (for the "Hired" state) needs a session. */
-export function useExpertsSection() {
+export function useExpertsSection({
+ category,
+ searchQuery,
+ enabled = true,
+}: Args = {}) {
const { isLoggedIn } = useAuth();
- const templatesQuery = useListExpertTemplates({
- query: { select: (x) => x.data as Expert[] },
- });
+ const templatesQuery = useListExpertTemplates(
+ {
+ ...(category ? { category } : {}),
+ ...(searchQuery ? { search_query: searchQuery } : {}),
+ },
+ {
+ query: {
+ enabled,
+ select: (x) => x.data as Expert[],
+ // The shelf keeps its cards across a chip change; search must not show a
+ // previous term's cards, so it waits on the page's loading gate instead.
+ placeholderData:
+ searchQuery === undefined
+ ? (previousData) => previousData
+ : undefined,
+ },
+ },
+ );
const expertsQuery = useListExperts({
- query: { select: (x) => x.data as Expert[], enabled: isLoggedIn },
+ query: {
+ select: (x) => x.data as Expert[],
+ enabled: enabled && isLoggedIn,
+ },
});
const hiredTemplateIds = new Set<string>();
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/MainMarketplacePage.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/MainMarketplacePage.tsx
index dc1911fc8f..ad32526755 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/MainMarketplacePage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/MainMarketplacePage.tsx
@@ -67,8 +67,13 @@ export const MainMarkeplacePage = () => {
<div className="mx-auto w-full max-w-[1360px]">
<main className="px-6 pb-16 md:px-10 lg:px-14">
<HeroSection />
- {showExperts ? <ExpertsSection /> : null}
- {skillsHub.ready && skillsHub.enabled ? <SkillsSection /> : null}
+ {/* Above all three shelves because it narrows all three: a filter
+ below its content changes what the reader has scrolled past. */}
+ <CategoryFilter selected={category} onSelect={setCategory} />
+ {showExperts ? <ExpertsSection category={category} /> : null}
+ {skillsHub.ready && skillsHub.enabled ? (
+ <SkillsSection category={category} />
+ ) : null}
{topAgents && (
<div className="mb-20" id={AGENTS_SECTION_ID}>
<AgentsSection
@@ -81,7 +86,6 @@ export const MainMarkeplacePage = () => {
}
agents={topAgents.agents}
>
- <CategoryFilter selected={category} onSelect={setCategory} />
{/* Featured is a whole-marketplace shelf; under a category filter
it would show workflows the filter excludes. */}
{!category &&
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainSearchResultPageLoading.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainSearchResultPageLoading.tsx
index d4cd2d31eb..2383af82fe 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainSearchResultPageLoading.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainSearchResultPageLoading.tsx
@@ -2,7 +2,12 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
export function MainSearchResultPageLoading() {
return (
- <div className="w-full">
+ <div
+ className="w-full"
+ role="status"
+ aria-busy="true"
+ aria-label="Loading search results"
+ >
<div className="mx-auto min-h-screen w-full max-w-[1440px] px-6 md:px-10">
{/* Go back button */}
<div className="mb-4 mt-5">
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/SkillsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/SkillsSection.tsx
index 181bc75651..aeb2f9a233 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/SkillsSection.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/SkillsSection.tsx
@@ -12,7 +12,11 @@ import { useSkillsSection } from "./useSkillsSection";
const HEADING_ID = "skills-heading";
-export function SkillsSection() {
+interface Props {
+ category?: string | null;
+}
+
+export function SkillsSection({ category }: Props) {
const {
isLoggedIn,
skills,
@@ -21,8 +25,11 @@ export function SkillsSection() {
isLoading,
isError,
refetch,
- } = useSkillsSection();
+ } = useSkillsSection({ category });
+ // Under a category filter an empty shelf means "no skills in this
+ // category", so the whole section goes rather than offering an empty state.
+ if (!isLoading && !isError && skills.length === 0 && category) return null;
// Visitors get nothing when there is nothing to show, as Experts does.
if (!isLoading && !isError && skills.length === 0 && !isLoggedIn) return null;
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts
index cb675a95e5..aae74dcb1c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/SkillsSection/useSkillsSection.ts
@@ -4,12 +4,21 @@ import { okData } from "@/app/api/helpers";
import { useAuth } from "@/lib/auth/hooks/useAuth";
import { SHELF_SIZE } from "./helpers";
-export function useSkillsSection() {
+interface Args {
+ category?: string | null;
+}
+
+export function useSkillsSection({ category }: Args = {}) {
const { isLoggedIn } = useAuth();
const query = useGetV2ListMarketplaceSkills(
- { page_size: SHELF_SIZE },
- { query: { select: (response) => okData(response) } },
+ { page_size: SHELF_SIZE, ...(category ? { category } : {}) },
+ {
+ query: {
+ select: (response) => okData(response),
+ placeholderData: (previousData) => previousData,
+ },
+ },
);
// An install lands under the listing's slug, so the user's own skill names
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts
index 0ef4ed70be..68d30c7e96 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useExpertPage.ts
@@ -22,7 +22,7 @@ export function useExpertPage({ expertId }: Args) {
const isHiringOpen = Boolean(enabled);
const canHire = isLoggedIn && isHiringOpen;
- const templatesQuery = useListExpertTemplates({
+ const templatesQuery = useListExpertTemplates(undefined, {
query: { select: (x) => x.data as Expert[] },
});
const expertsQuery = useListExperts({
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/search/__tests__/experts-in-search.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/__tests__/experts-in-search.test.tsx
new file mode 100644
index 0000000000..535ff7ca32
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/__tests__/experts-in-search.test.tsx
@@ -0,0 +1,300 @@
+import { getListExpertsMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import {
+ getGetV2ListStoreAgentsMockHandler,
+ getGetV2ListStoreCreatorsMockHandler,
+} from "@/app/api/__generated__/endpoints/store/store.msw";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { server } from "@/mocks/mock-server";
+import {
+ configure,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { HttpResponse, delay, http } from "msw";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { MainSearchResultPage } from "../components/MainSearchResultPage/MainSearchResultPage";
+
+// These pages wait on several queries before anything renders, and CI is
+// slower than a dev machine; the testing-library default is one second.
+configure({ asyncUtilTimeout: 10000 });
+
+const mockUseAuth = vi.hoisted(() => vi.fn());
+const hireExpertsFlag = vi.hoisted(() => ({ enabled: true }));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ back: vi.fn(),
+ forward: vi.fn(),
+ prefetch: vi.fn(),
+ push: vi.fn(),
+ refresh: vi.fn(),
+ replace: vi.fn(),
+ }),
+ usePathname: () => "/marketplace/search",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+}));
+
+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: false, ready: true }),
+ useGetFlag: (flag: string) =>
+ flag === "hire-experts"
+ ? hireExpertsFlag.enabled
+ : actual.useGetFlag(flag as never),
+ };
+});
+
+const maria: Expert = {
+ id: "template-maria",
+ name: "Maria",
+ avatar_url: null,
+ role: "Marketing",
+ bio: null,
+ skills: [],
+ categories: ["marketing"],
+ tagline: "Writes your LinkedIn posts and SEO articles.",
+ identity: "You are Maria.",
+ voice_preferences: "Direct.",
+ boundaries: "Ask first.",
+ protected_soul_rules: [],
+ is_template: true,
+ source_template_id: null,
+ is_archived: false,
+ workflows: [],
+};
+
+/** Every ?search_query= the roster is asked for. */
+const searchedTerms: (string | null)[] = [];
+
+function rosterHandler(matches: Expert[]) {
+ return http.get("/api/proxy/api/experts/templates", ({ request }) => {
+ searchedTerms.push(new URL(request.url).searchParams.get("search_query"));
+ return HttpResponse.json(matches);
+ });
+}
+
+describe("Experts in marketplace search", () => {
+ beforeEach(() => {
+ searchedTerms.length = 0;
+ hireExpertsFlag.enabled = true;
+ mockUseAuth.mockReturnValue({ user: { id: "user-1" }, isLoggedIn: true });
+ server.use(
+ getGetV2ListStoreAgentsMockHandler(),
+ getGetV2ListStoreCreatorsMockHandler(),
+ getListExpertsMockHandler([]),
+ );
+ });
+
+ test("returns matching experts alongside agents and creators", async () => {
+ server.use(rosterHandler([maria]));
+
+ render(<MainSearchResultPage searchTerm="Maria" sort="runs" />);
+
+ expect(
+ await screen.findByRole("heading", { name: "Experts" }),
+ ).toBeDefined();
+ const card = await screen.findByRole("link", { name: /Maria/ });
+ expect(card.getAttribute("href")).toBe(
+ "/marketplace/experts/template-maria",
+ );
+ expect(screen.getByRole("button", { name: /Experts/ })).toBeDefined();
+ await waitFor(() => expect(searchedTerms).toContain("Maria"));
+ });
+
+ test("the experts group sits above the workflows", async () => {
+ server.use(
+ rosterHandler([maria]),
+ getGetV2ListStoreAgentsMockHandler({
+ agents: [
+ {
+ slug: "blog-writer",
+ agent_name: "Blog Writer",
+ agent_image: "",
+ creator: "creator",
+ creator_avatar: "",
+ sub_heading: "",
+ description: "",
+ runs: 1,
+ rating: 5,
+ agent_graph_id: "graph-blog-writer",
+ },
+ ],
+ pagination: {
+ current_page: 1,
+ total_items: 1,
+ total_pages: 1,
+ page_size: 20,
+ },
+ }),
+ );
+
+ render(<MainSearchResultPage searchTerm="Maria" sort="runs" />);
+
+ const experts = await screen.findByRole("heading", { name: "Experts" });
+ // The grid renders a mobile carousel and a desktop grid, so the first
+ // card in document order is the one to compare against.
+ const [workflow] = await screen.findAllByTestId("store-card");
+
+ // Node.DOCUMENT_POSITION_FOLLOWING: the workflow comes after the heading.
+ expect(experts.compareDocumentPosition(workflow) & 4).toBeTruthy();
+ });
+
+ test("a search that matches no expert shows no experts group", async () => {
+ server.use(rosterHandler([]));
+
+ render(<MainSearchResultPage searchTerm="nothing" sort="runs" />);
+
+ await screen.findByText(/Showing results for/);
+ await waitFor(() => expect(searchedTerms).toContain("nothing"));
+ expect(screen.queryByRole("heading", { name: "Experts" })).toBeNull();
+ });
+
+ test("a roster still in flight shows the skeleton, not 'No results found'", async () => {
+ server.use(
+ http.get("/api/proxy/api/experts/templates", async () => {
+ await delay(3000);
+ return HttpResponse.json([maria]);
+ }),
+ getGetV2ListStoreAgentsMockHandler({
+ agents: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ getGetV2ListStoreCreatorsMockHandler({
+ creators: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ );
+
+ render(<MainSearchResultPage searchTerm="Maria" sort="runs" />);
+
+ // Agents and creators resolve empty immediately while the roster is still
+ // in flight. `waitFor` cannot catch the resulting flash of the empty state
+ // — it retries until the roster lands and the flash is gone — so sample
+ // every tick until Maria appears and assert it was never painted.
+ let sawEmptyState = false;
+ let sawSkeleton = false;
+ for (let i = 0; i < 80; i++) {
+ if (screen.queryByText("No results found")) sawEmptyState = true;
+ if (screen.queryByRole("status", { name: "Loading search results" }))
+ sawSkeleton = true;
+ if (screen.queryByRole("heading", { name: "Experts" })) break;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ expect(sawEmptyState).toBe(false);
+ // A blank page would pass the line above; the wait has to be visible.
+ expect(sawSkeleton).toBe(true);
+ expect(screen.getByRole("heading", { name: "Experts" })).toBeDefined();
+ });
+
+ test("holds the skeleton while auth is still resolving", async () => {
+ // Until auth answers, we cannot know whether experts belong on this page,
+ // so an empty agent/creator result must not settle as "No results found".
+ mockUseAuth.mockReturnValue({
+ user: null,
+ isLoggedIn: false,
+ isUserLoading: true,
+ });
+ server.use(
+ rosterHandler([maria]),
+ getGetV2ListStoreAgentsMockHandler({
+ agents: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ getGetV2ListStoreCreatorsMockHandler({
+ creators: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ );
+
+ render(<MainSearchResultPage searchTerm="Maria" sort="runs" />);
+
+ for (let i = 0; i < 20; i++) {
+ expect(screen.queryByText("No results found")).toBeNull();
+ expect(
+ screen.getByRole("status", { name: "Loading search results" }),
+ ).toBeDefined();
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ });
+
+ test("a new search term never shows the previous term's experts", async () => {
+ const max: Expert = { ...maria, id: "template-max", name: "Max" };
+ server.use(
+ http.get("/api/proxy/api/experts/templates", async ({ request }) => {
+ const term = new URL(request.url).searchParams.get("search_query");
+ if (term === "Max") {
+ await delay(1500);
+ return HttpResponse.json([max]);
+ }
+ return HttpResponse.json([maria]);
+ }),
+ );
+ const { rerender } = render(
+ <MainSearchResultPage searchTerm="Maria" sort="runs" />,
+ );
+ await waitFor(() => expect(isExpertCardShown("template-maria")).toBe(true));
+
+ rerender(<MainSearchResultPage searchTerm="Max" sort="runs" />);
+
+ // Agents and creators answer the new term first; Maria must not come back
+ // while Max's request is still in flight.
+ let sawStaleCard = false;
+ for (let i = 0; i < 80; i++) {
+ if (isExpertCardShown("template-maria")) sawStaleCard = true;
+ if (isExpertCardShown("template-max")) break;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ expect(sawStaleCard).toBe(false);
+ expect(isExpertCardShown("template-max")).toBe(true);
+ });
+
+ test("asks for no experts and offers no chip outside the beta", async () => {
+ hireExpertsFlag.enabled = false;
+ server.use(rosterHandler([maria]));
+
+ render(<MainSearchResultPage searchTerm="Maria" sort="runs" />);
+
+ await screen.findByText(/Showing results for/);
+ await waitFor(() => expect(searchedTerms).toHaveLength(0));
+ expect(screen.queryByRole("heading", { name: "Experts" })).toBeNull();
+ expect(screen.queryByRole("button", { name: /Experts/ })).toBeNull();
+ });
+});
+
+function isExpertCardShown(id: string) {
+ return screen
+ .queryAllByRole("link")
+ .some((link) => link.getAttribute("href") === `/marketplace/experts/${id}`);
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/MainSearchResultPage.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/MainSearchResultPage.tsx
index d099664b64..e2a9c134a7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/MainSearchResultPage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/MainSearchResultPage.tsx
@@ -9,6 +9,8 @@ import { MainSearchResultPageLoading } from "../../../components/MainSearchResul
import { SearchBar } from "../../../components/SearchBar/SearchBar";
import { SectionHeader } from "../../../components/SectionHeader";
import { SkillCard } from "../../../components/SkillsSection/components/SkillCard";
+import { ExpertCard } from "../../../components/ExpertsSection/components/ExpertCard";
+import { AITeamIcon } from "@/components/atoms/AITeamIcon/AITeamIcon";
import { BookOpen01Icon } from "@hugeicons/core-free-icons";
import { useMainSearchResultPage } from "./useMainSearchResultPage";
import { ArrowLeft02Icon } from "@hugeicons/core-free-icons";
@@ -27,23 +29,32 @@ export const MainSearchResultPage = ({
agents,
creators,
skills,
+ experts,
+ hiredTemplateIds,
totalCount,
agentsCount,
creatorsCount,
skillsCount,
+ expertsCount,
handleFilterChange,
handleSortChange,
showAgents,
showCreators,
showSkills,
+ showExperts,
+ isExpertsVisible,
isSkillsHubEnabled,
isAgentsLoading,
isCreatorsLoading,
+ isExpertsLoading,
isAgentsError,
isCreatorsError,
} = useMainSearchResultPage({ searchTerm, sort });
- const isLoading = isAgentsLoading || isCreatorsLoading;
+ // Experts gate the skeleton too: without it a roster still in flight reads
+ // as zero results, and a search matching only an expert says "No results
+ // found" before the card arrives.
+ const isLoading = isAgentsLoading || isCreatorsLoading || isExpertsLoading;
const hasError = isAgentsError || isCreatorsError;
if (isLoading) {
@@ -98,6 +109,7 @@ export const MainSearchResultPage = ({
agentsCount={agentsCount}
creatorsCount={creatorsCount}
skillsCount={isSkillsHubEnabled ? skillsCount : undefined}
+ expertsCount={isExpertsVisible ? expertsCount : undefined}
onFilterChange={handleFilterChange}
/>
<div className="mt-4 md:!mt-0">
@@ -106,6 +118,24 @@ export const MainSearchResultPage = ({
</div>
{/* Content section */}
<div className="min-h-[500px] max-w-[1440px] space-y-8 py-8">
+ {showExperts && expertsCount > 0 ? (
+ <section aria-labelledby="search-experts-heading">
+ <SectionHeader
+ titleIcon={<AITeamIcon size={30} />}
+ title="Experts"
+ titleId="search-experts-heading"
+ />
+ <div className="grid grid-cols-1 gap-5 md:grid-cols-2 lg:grid-cols-3">
+ {experts.map((expert) => (
+ <ExpertCard
+ key={expert.id}
+ expert={expert}
+ isHired={hiredTemplateIds.has(expert.id)}
+ />
+ ))}
+ </div>
+ </section>
+ ) : null}
{showAgents && agentsCount > 0 && agents && (
<AgentsSection agents={agents} />
)}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/useMainSearchResultPage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/useMainSearchResultPage.ts
index e19bff4b43..3f87a4d78b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/useMainSearchResultPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/search/components/MainSearchResultPage/useMainSearchResultPage.ts
@@ -8,7 +8,13 @@ import { CreatorsResponse } from "@/app/api/__generated__/models/creatorsRespons
import { GetV2ListStoreAgentsParams } from "@/app/api/__generated__/models/getV2ListStoreAgentsParams";
import { GetV2ListStoreCreatorsParams } from "@/app/api/__generated__/models/getV2ListStoreCreatorsParams";
import { StoreAgentsResponse } from "@/app/api/__generated__/models/storeAgentsResponse";
-import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";
+import {
+ Flag,
+ useFlagStatus,
+ useGetFlag,
+} from "@/services/feature-flags/use-get-flag";
+import { useAuth } from "@/lib/auth/hooks/useAuth";
+import { useExpertsSection } from "../../../components/ExpertsSection/useExpertsSection";
import { useState, useMemo } from "react";
type MarketplaceSearchSort = GetV2ListStoreAgentsParams["sorted_by"];
@@ -26,7 +32,14 @@ export const useMainSearchResultPage = ({
const [showAgents, setShowAgents] = useState(true);
const [showCreators, setShowCreators] = useState(true);
const [showSkills, setShowSkills] = useState(true);
+ const [showExperts, setShowExperts] = useState(true);
const skillsHub = useFlagStatus(Flag.SKILLS_HUB);
+ const { isLoggedIn, isUserLoading } = useAuth();
+ const isHireExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);
+ // Same gate as the marketplace shelf: expert pages are public, hiring is
+ // not, so a signed-in user outside the beta sees neither surface.
+ const isExpertsVisible =
+ !isUserLoading && (!isLoggedIn || isHireExpertsEnabled);
const [clientSortBy, setClientSortBy] = useState<string>(
sort ?? "updated_at",
);
@@ -88,6 +101,15 @@ export const useMainSearchResultPage = ({
},
);
+ const {
+ templates: experts,
+ hiredTemplateIds,
+ isLoading: isExpertsLoading,
+ } = useExpertsSection({
+ searchQuery: searchTerm,
+ enabled: isExpertsVisible,
+ });
+
// This is the strategy, we are using for sorting the agents and creators.
// currently we are doing it client side but maybe we will shift it to the server side.
// we will store the sortBy state in the url params, and then refetch the data with the new sortBy.
@@ -124,12 +146,14 @@ export const useMainSearchResultPage = ({
const agentsCount = agents?.length ?? 0;
const creatorsCount = creators?.length ?? 0;
const skillsCount = skills.length;
- const totalCount = agentsCount + creatorsCount + skillsCount;
+ const expertsCount = isExpertsVisible ? experts.length : 0;
+ const totalCount = agentsCount + creatorsCount + skillsCount + expertsCount;
const handleFilterChange = (value: string) => {
setShowAgents(value === "all" || value === "agents");
setShowCreators(value === "all" || value === "creators");
setShowSkills(value === "all" || value === "skills");
+ setShowExperts(value === "all" || value === "experts");
};
const handleSortChange = (sortValue: string) => {
@@ -140,19 +164,28 @@ export const useMainSearchResultPage = ({
agents,
creators,
skills,
+ experts,
+ hiredTemplateIds,
handleFilterChange,
handleSortChange,
agentsCount,
creatorsCount,
skillsCount,
+ expertsCount,
totalCount,
showAgents,
showCreators,
showSkills,
+ showExperts,
+ isExpertsVisible,
isSkillsHubEnabled: skillsHub.ready && skillsHub.enabled,
isAgentsLoading,
isCreatorsLoading,
isSkillsLoading,
+ // `isUserLoading` counts as pending: until auth answers, isExpertsVisible
+ // is false, so without it the gate reports "not loading" and the empty
+ // state can still paint before we know whether experts belong here.
+ isExpertsLoading: isUserLoading || (isExpertsVisible && isExpertsLoading),
isAgentsError,
isCreatorsError,
};
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 1f0addbae6..432414f927 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -6537,19 +6537,48 @@
"get": {
"tags": ["v2", "experts", "experts"],
"summary": "List Expert Templates",
+ "description": "Roster templates, narrowed by a search term and/or a marketplace category.\n\nUnpaginated: the roster is small, and every caller reads the whole list.",
"operationId": "list_expert_templates",
+ "parameters": [
+ {
+ "name": "search_query",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Search Query"
+ }
+ },
+ {
+ "name": "category",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Category"
+ }
+ }
+ ],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
- "items": { "$ref": "#/components/schemas/Expert" },
"type": "array",
+ "items": { "$ref": "#/components/schemas/Expert" },
"title": "Response List Expert Templates"
}
}
}
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
}
}
}
@@ -20580,6 +20609,12 @@
"type": "array",
"title": "Skills"
},
+ "categories": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Categories",
+ "default": []
+ },
"identity": { "type": "string", "title": "Identity" },
"voice_preferences": {
"type": "string",
diff --git a/autogpt_platform/frontend/src/components/__legacy__/SearchFilterChips.tsx b/autogpt_platform/frontend/src/components/__legacy__/SearchFilterChips.tsx
index 84fcd977b9..99de0f7d5b 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/SearchFilterChips.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/SearchFilterChips.tsx
@@ -14,6 +14,8 @@ interface SearchFilterChipsProps {
creatorsCount?: number;
/** Omitted where skills are not searchable, which drops the chip. */
skillsCount?: number;
+ /** Omitted where experts are not searchable, which drops the chip. */
+ expertsCount?: number;
onFilterChange?: (value: string) => void;
}
@@ -22,12 +24,16 @@ export const SearchFilterChips: React.FC<SearchFilterChipsProps> = ({
agentsCount = 8,
creatorsCount = 2,
skillsCount,
+ expertsCount,
onFilterChange,
}) => {
const [selected, setSelected] = React.useState("all");
const filters: FilterOption[] = [
{ label: "All", count: totalCount, value: "all" },
+ ...(expertsCount === undefined
+ ? []
+ : [{ label: "Experts", count: expertsCount, value: "experts" }]),
{ label: "Agents", count: agentsCount, value: "agents" },
...(skillsCount === undefined
? []