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): canonical categories and a category filter (#14428)

Reinier van der Leer79f23c9bd21d
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 02630dd033..acb3504d1b 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
@@ -143,7 +143,7 @@ async def _seed_store_listing(server: SpinTestServer, approved: bool = True) ->
video_url=None,
image_urls=[],
description="Seed description",
- categories=[],
+ categories=["operations"],
),
owner.id,
)
diff --git a/autogpt_platform/backend/backend/api/features/store/categories.py b/autogpt_platform/backend/backend/api/features/store/categories.py
new file mode 100644
index 0000000000..c70ad9ad51
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/categories.py
@@ -0,0 +1,129 @@
+"""The canonical marketplace category set, and how legacy free-text values fold into it."""
+
+from enum import Enum
+
+from backend.util.settings import Settings
+
+settings = Settings()
+
+
+class StoreCategory(str, Enum):
+ MARKETING = "marketing"
+ SALES = "sales"
+ FINANCE = "finance"
+ SUPPORT = "support"
+ OPERATIONS = "operations"
+ RESEARCH = "research"
+ CONTENT = "content"
+ DEVELOPMENT = "development"
+
+
+CATEGORY_LABELS: dict[StoreCategory, str] = {
+ StoreCategory.MARKETING: "Marketing",
+ StoreCategory.SALES: "Sales",
+ StoreCategory.FINANCE: "Finance",
+ StoreCategory.SUPPORT: "Support",
+ StoreCategory.OPERATIONS: "Operations",
+ StoreCategory.RESEARCH: "Research",
+ StoreCategory.CONTENT: "Content",
+ StoreCategory.DEVELOPMENT: "Development",
+}
+
+CATEGORY_DESCRIPTIONS: dict[StoreCategory, str] = {
+ StoreCategory.MARKETING: "Campaigns, SEO, social media, brand and audience growth",
+ StoreCategory.SALES: "Lead generation, prospecting, outreach and CRM work",
+ StoreCategory.FINANCE: "Accounting, invoicing, budgeting, reporting and analysis",
+ StoreCategory.SUPPORT: "Customer service, ticket handling and personal assistance",
+ StoreCategory.OPERATIONS: "Internal process automation, scheduling, HR and admin",
+ StoreCategory.RESEARCH: "Gathering, extracting and analysing information or data",
+ StoreCategory.CONTENT: "Writing, editing, design and media production",
+ StoreCategory.DEVELOPMENT: "Software engineering, DevOps, testing and integrations",
+}
+
+# Only mappings with one defensible target belong here; ambiguous ones go to the
+# classifier. "business" spanned Finance, Sales and Support in the real data.
+CATEGORY_ALIASES: dict[str, StoreCategory] = {
+ "writing": StoreCategory.CONTENT,
+ "creative": StoreCategory.CONTENT,
+ "content & writing": StoreCategory.CONTENT,
+ "writing & content": StoreCategory.CONTENT,
+ "creative & design": StoreCategory.CONTENT,
+ "design": StoreCategory.CONTENT,
+ "marketing & seo": StoreCategory.MARKETING,
+ "seo": StoreCategory.MARKETING,
+ "research & learning": StoreCategory.RESEARCH,
+ "development": StoreCategory.DEVELOPMENT,
+ "engineering": StoreCategory.DEVELOPMENT,
+ "devops": StoreCategory.DEVELOPMENT,
+ "productivity": StoreCategory.OPERATIONS,
+ "automation": StoreCategory.OPERATIONS,
+ "customer support": StoreCategory.SUPPORT,
+ "customer service": StoreCategory.SUPPORT,
+ "sales & crm": StoreCategory.SALES,
+ "business & finance": StoreCategory.FINANCE,
+ "accounting": StoreCategory.FINANCE,
+}
+
+
+def normalize_category(value: str) -> StoreCategory | None:
+ """Fold one free-text category onto the canonical set, or None if it doesn't fit."""
+ key = value.strip().lower()
+ if not key:
+ return None
+ try:
+ return StoreCategory(key)
+ except ValueError:
+ return CATEGORY_ALIASES.get(key)
+
+
+def normalize_categories(values: list[str]) -> list[StoreCategory]:
+ """Fold a listing's categories, dropping unmappable ones and preserving order."""
+ seen: list[StoreCategory] = []
+ for value in values:
+ category = normalize_category(value)
+ if category and category not in seen:
+ seen.append(category)
+ return seen
+
+
+def category_filter_values(category: str | None) -> list[str] | None:
+ """Stored category strings a listing query should match, or None for no filter.
+
+ With no category asked for, the default view still narrows to the canonical
+ set once the backfill has run and the setting is turned on.
+ """
+ if category:
+ return category_match_values(category)
+ if settings.config.marketplace_require_canonical_category:
+ return all_category_match_values()
+ return None
+
+
+def category_match_values(category: str) -> list[str]:
+ """The stored category strings a filter for ``category`` should match.
+
+ Includes the legacy aliases so a filter works both before and after the
+ backfill has folded a listing onto the canonical set.
+ """
+ canonical = normalize_category(category)
+ if canonical is None:
+ return [category]
+ return [canonical.value] + [
+ alias for alias, target in CATEGORY_ALIASES.items() if target is canonical
+ ]
+
+
+def all_category_match_values() -> list[str]:
+ """Every stored string that counts as "has a canonical category"."""
+ return [category.value for category in StoreCategory] + list(CATEGORY_ALIASES)
+
+
+def validate_canonical_categories(values: list[str]) -> list[str]:
+ """Reusable field validator: a listing must carry at least one canonical category."""
+ normalized = normalize_categories(values)
+ if not normalized:
+ raise ValueError(
+ "at least one category is required, from: "
+ + ", ".join(category.value for category in StoreCategory)
+ )
+ return [category.value for category in normalized]
diff --git a/autogpt_platform/backend/backend/api/features/store/categories_test.py b/autogpt_platform/backend/backend/api/features/store/categories_test.py
new file mode 100644
index 0000000000..45bb5161aa
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/categories_test.py
@@ -0,0 +1,93 @@
+import pytest
+
+from .categories import (
+ CATEGORY_DESCRIPTIONS,
+ CATEGORY_LABELS,
+ StoreCategory,
+ all_category_match_values,
+ category_match_values,
+ normalize_categories,
+ normalize_category,
+ validate_canonical_categories,
+)
+
+
+def test_every_category_has_a_label_and_description():
+ for category in StoreCategory:
+ assert CATEGORY_LABELS[category]
+ assert CATEGORY_DESCRIPTIONS[category]
+
+
+def test_the_canonical_set_is_the_eight_the_product_promises():
+ assert {category.value for category in StoreCategory} == {
+ "marketing",
+ "sales",
+ "finance",
+ "support",
+ "operations",
+ "research",
+ "content",
+ "development",
+ }
+
+
+ "raw,expected",
+ [
+ ("marketing", StoreCategory.MARKETING),
+ (" Marketing ", StoreCategory.MARKETING),
+ ("MARKETING", StoreCategory.MARKETING),
+ ("writing", StoreCategory.CONTENT),
+ ("Creative & Design", StoreCategory.CONTENT),
+ ("productivity", StoreCategory.OPERATIONS),
+ ("", None),
+ (" ", None),
+ ("business", None),
+ ("personal", None),
+ ("other", None),
+ ("testing", None),
+ ],
+)
+def test_normalize_category(raw, expected):
+ assert normalize_category(raw) is expected
+
+
+def test_normalize_categories_drops_unmappable_and_deduplicates():
+ assert normalize_categories(["writing", "creative", "testing", "sales"]) == [
+ StoreCategory.CONTENT,
+ StoreCategory.SALES,
+ ]
+
+
+def test_category_match_values_covers_the_alias_that_folds_onto_it():
+ matches = category_match_values("content")
+ assert "content" in matches
+ assert "writing" in matches
+ assert "marketing" not in matches
+
+
+def test_an_alias_and_its_canonical_form_select_the_same_listings():
+ assert set(category_match_values("writing")) == set(
+ category_match_values("content")
+ )
+
+
+def test_category_match_values_passes_an_unknown_value_through():
+ assert category_match_values("testing") == ["testing"]
+
+
+def test_all_category_match_values_holds_every_canonical_value():
+ matches = set(all_category_match_values())
+ assert {category.value for category in StoreCategory} <= matches
+ assert "writing" in matches
+ assert "testing" not in matches
+
+
+def test_validate_canonical_categories_normalizes():
+ assert validate_canonical_categories(["Writing", "sales"]) == ["content", "sales"]
+
+
[email protected]("values", [[], [""], ["testing"], ["other"]])
+def test_validate_canonical_categories_rejects(values):
+ with pytest.raises(ValueError):
+ validate_canonical_categories(values)
diff --git a/autogpt_platform/backend/backend/api/features/store/category_classifier.py b/autogpt_platform/backend/backend/api/features/store/category_classifier.py
new file mode 100644
index 0000000000..14eb2a23be
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/category_classifier.py
@@ -0,0 +1,80 @@
+"""Assigns a canonical category to listings whose own categories map to none.
+
+Used by the backfill command, so it answers per listing and never raises: an
+unclassifiable listing is left uncategorised rather than mislabelled.
+"""
+
+import asyncio
+import logging
+import os
+
+from backend.util.clients import get_openai_client
+
+from .categories import CATEGORY_DESCRIPTIONS, StoreCategory
+
+logger = logging.getLogger(__name__)
+
+# Picking one label off a fixed list of eight is a matching task, not a writing
+# one, so it runs on the fast model — same choice as the brain-dump recommender.
+_MODEL = os.environ.get("STORE_CATEGORY_MODEL", "anthropic/claude-haiku-4-5")
+_TIMEOUT_SECONDS = 30
+_MAX_DESCRIPTION_CHARS = 2000
+
+_PROMPT = """Assign the single best category to this marketplace listing for an \
+AI agent. Answer with ONLY the category id, lowercase, nothing else.
+
+Categories:
+{categories}
+
+If none of them fits, answer exactly: none
+
+Listing name: {name}
+Tagline: {sub_heading}
+Description: {description}
+"""
+
+
+async def classify_category(
+ name: str, sub_heading: str, description: str
+) -> StoreCategory | None:
+ """The model's category for one listing, or None if it declines or fails."""
+ client = get_openai_client(prefer_openrouter=True)
+ if client is None:
+ logger.warning("Store category classifier: no LLM client configured")
+ return None
+
+ prompt = _PROMPT.format(
+ categories="\n".join(
+ f"- {category.value}: {description}"
+ for category, description in CATEGORY_DESCRIPTIONS.items()
+ ),
+ name=name.strip() or "(none)",
+ sub_heading=sub_heading.strip() or "(none)",
+ description=description.strip()[:_MAX_DESCRIPTION_CHARS] or "(none)",
+ )
+ try:
+ response = await asyncio.wait_for(
+ client.chat.completions.create(
+ model=_MODEL,
+ messages=[{"role": "user", "content": prompt}],
+ temperature=0,
+ max_tokens=16,
+ ),
+ timeout=_TIMEOUT_SECONDS,
+ )
+ except Exception as e:
+ logger.warning("Store category classification failed for %r: %s", name, e)
+ return None
+
+ if not response.choices:
+ logger.warning("Store category classification returned no choices for %r", name)
+ return None
+ return _parse_category(response.choices[0].message.content or "")
+
+
+def _parse_category(content: str) -> StoreCategory | None:
+ answer = content.strip().strip(".\"'` ").lower()
+ try:
+ return StoreCategory(answer)
+ except ValueError:
+ return None
diff --git a/autogpt_platform/backend/backend/api/features/store/category_classifier_test.py b/autogpt_platform/backend/backend/api/features/store/category_classifier_test.py
new file mode 100644
index 0000000000..623c36bba8
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/category_classifier_test.py
@@ -0,0 +1,85 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from . import category_classifier
+from .categories import StoreCategory
+from .category_classifier import _parse_category, classify_category
+
+
+ "answer,expected",
+ [
+ ("sales", StoreCategory.SALES),
+ (" Sales\n", StoreCategory.SALES),
+ ("`content`", StoreCategory.CONTENT),
+ ("Development.", StoreCategory.DEVELOPMENT),
+ ("none", None),
+ ("", None),
+ ("writing", None),
+ ("sales and marketing", None),
+ ],
+)
+def test_parse_category(answer, expected):
+ assert _parse_category(answer) is expected
+
+
+def _client(content: str):
+ client = MagicMock()
+ client.chat.completions.create = AsyncMock(
+ return_value=SimpleNamespace(
+ choices=[SimpleNamespace(message=SimpleNamespace(content=content))]
+ )
+ )
+ return client
+
+
+async def test_classifies_a_listing(monkeypatch):
+ client = _client("finance")
+ monkeypatch.setattr(category_classifier, "get_openai_client", lambda **_: client)
+
+ assert (
+ await classify_category("Invoice Chaser", "Chases invoices", "Emails debtors.")
+ is StoreCategory.FINANCE
+ )
+
+ prompt = client.chat.completions.create.await_args.kwargs["messages"][0]["content"]
+ for category in StoreCategory:
+ assert category.value in prompt
+ assert "Invoice Chaser" in prompt
+
+
+async def test_returns_none_when_the_model_answers_with_no_choices(monkeypatch):
+ client = MagicMock()
+ client.chat.completions.create = AsyncMock(return_value=SimpleNamespace(choices=[]))
+ monkeypatch.setattr(category_classifier, "get_openai_client", lambda **_: client)
+
+ assert (
+ await classify_category("Invoice Chaser", "Chases invoices", "Emails.") is None
+ )
+
+
+async def test_returns_none_without_a_configured_client(monkeypatch):
+ monkeypatch.setattr(category_classifier, "get_openai_client", lambda **_: None)
+
+ assert await classify_category("n", "s", "d") is None
+
+
+async def test_a_failed_call_never_propagates(monkeypatch):
+ client = MagicMock()
+ client.chat.completions.create = AsyncMock(side_effect=RuntimeError("boom"))
+ monkeypatch.setattr(category_classifier, "get_openai_client", lambda **_: client)
+
+ assert await classify_category("n", "s", "d") is None
+
+
+async def test_a_long_description_is_truncated_before_it_is_sent(monkeypatch):
+ client = _client("research")
+ monkeypatch.setattr(category_classifier, "get_openai_client", lambda **_: client)
+
+ await classify_category("n", "s", "x" * 5000)
+
+ prompt = client.chat.completions.create.await_args.kwargs["messages"][0]["content"]
+ assert "x" * 2000 in prompt
+ assert "x" * 2001 not in prompt
diff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.py
index c22b608b81..f8fbe5fd74 100644
--- a/autogpt_platform/backend/backend/api/features/store/db.py
+++ b/autogpt_platform/backend/backend/api/features/store/db.py
@@ -25,6 +25,7 @@ from backend.util.settings import Settings
from . import exceptions as store_exceptions
from . import model as store_model
+from .categories import category_filter_values
from .embeddings import ensure_embedding
from .hybrid_search import hybrid_search
from .store_listing_versions import installable_store_version_where
@@ -184,8 +185,8 @@ async def _fallback_store_agent_search(
where_clause["featured"] = featured
if creators:
where_clause["creator_username"] = {"in": creators}
- if category:
- where_clause["categories"] = {"has": category}
+ if category_values := category_filter_values(category):
+ where_clause["categories"] = {"has_some": category_values}
order_by = []
if sorted_by == StoreAgentsSortOptions.RATING:
@@ -217,9 +218,9 @@ async def _fallback_store_agent_search(
params.append(creators)
filters.append(f"sa.creator_username = ANY(${param_idx})")
param_idx += 1
- if category:
- params.append(category)
- filters.append(f"${param_idx} = ANY(sa.categories)")
+ if category_values := category_filter_values(category):
+ params.append(category_values)
+ filters.append(f"sa.categories && ${param_idx}")
param_idx += 1
where_sql = " AND ".join(filters)
diff --git a/autogpt_platform/backend/backend/api/features/store/db_test.py b/autogpt_platform/backend/backend/api/features/store/db_test.py
index 9829f8d373..717b4432d2 100644
--- a/autogpt_platform/backend/backend/api/features/store/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py
@@ -9,6 +9,7 @@ from prisma import Prisma
from backend.util.exceptions import NotFoundError
+from . import categories as store_categories
from . import db
from .model import MyAgentsSortBy, Profile, SubmissionStats
@@ -485,7 +486,7 @@ async def test_get_store_agents_with_search_and_filters_parameterized():
assert isinstance(result.agents, list)
fallback_sql, *fallback_params = fallback_query_raw.call_args.args
- assert malicious_category in fallback_params
+ assert [malicious_category] in fallback_params
assert malicious_category not in fallback_sql
assert [malicious_creator, "creator2"] in fallback_params
@@ -508,7 +509,7 @@ async def test_get_store_agents_search_category_array_injection():
assert isinstance(result.agents, list)
fallback_sql, *fallback_params = fallback_query_raw.call_args.args
- assert malicious_category in fallback_params
+ assert [malicious_category] in fallback_params
assert malicious_category not in fallback_sql
@@ -1193,3 +1194,52 @@ async def test_get_agent_skips_graph_access_check(mocker):
for_export=True,
skip_access_check=True,
)
+
+
+def store_agent_query(mocker):
+ """Capture the where/order Prisma is asked for, without a database."""
+ mock = mocker.patch("prisma.models.StoreAgent.prisma")
+ mock.return_value.find_many = AsyncMock(return_value=[])
+ mock.return_value.count = AsyncMock(return_value=0)
+ return mock.return_value.find_many
+
+
[email protected](loop_scope="session")
+async def test_category_filter_matches_the_canonical_value_and_its_aliases(
+ store_agent_query,
+):
+ await db.get_store_agents(category="content")
+
+ matches = store_agent_query.call_args.kwargs["where"]["categories"]["has_some"]
+ assert "content" in matches
+ assert "writing" in matches
+
+
[email protected](loop_scope="session")
+async def test_uncategorised_listings_are_shown_while_the_setting_is_off(
+ store_agent_query,
+):
+ assert (
+ store_categories.settings.config.marketplace_require_canonical_category is False
+ )
+
+ await db.get_store_agents()
+
+ assert "categories" not in store_agent_query.call_args.kwargs["where"]
+
+
[email protected](loop_scope="session")
+async def test_uncategorised_listings_are_hidden_when_the_setting_is_on(
+ store_agent_query, monkeypatch
+):
+ monkeypatch.setattr(
+ store_categories.settings.config,
+ "marketplace_require_canonical_category",
+ True,
+ )
+
+ await db.get_store_agents()
+
+ matches = store_agent_query.call_args.kwargs["where"]["categories"]["has_some"]
+ assert set(store_categories.all_category_match_values()) == set(matches)
diff --git a/autogpt_platform/backend/backend/api/features/store/hybrid_search.py b/autogpt_platform/backend/backend/api/features/store/hybrid_search.py
index a8a1c26259..691d8bff37 100644
--- a/autogpt_platform/backend/backend/api/features/store/hybrid_search.py
+++ b/autogpt_platform/backend/backend/api/features/store/hybrid_search.py
@@ -26,6 +26,8 @@ from backend.api.features.search.hybrid_search import (
)
from backend.data.db import query_raw_with_schema
+from .categories import category_filter_values
+
logger = logging.getLogger(__name__)
@@ -156,9 +158,9 @@ async def hybrid_search(
where_parts.append(f"sa.creator_username = ANY(${param_idx})")
param_idx += 1
- if category:
- params.append(category)
- where_parts.append(f"${param_idx} = ANY(sa.categories)")
+ if category_values := category_filter_values(category):
+ params.append(category_values)
+ where_parts.append(f"sa.categories && ${param_idx}")
param_idx += 1
where_clause = " AND ".join(where_parts)
diff --git a/autogpt_platform/backend/backend/api/features/store/model.py b/autogpt_platform/backend/backend/api/features/store/model.py
index eb11ffe6dc..6dd41bcc9a 100644
--- a/autogpt_platform/backend/backend/api/features/store/model.py
+++ b/autogpt_platform/backend/backend/api/features/store/model.py
@@ -7,6 +7,8 @@ import pydantic
from backend.util.models import Pagination
+from .categories import validate_canonical_categories
+
if TYPE_CHECKING:
import prisma.models
@@ -301,6 +303,12 @@ class StoreSubmissionsResponse(pydantic.BaseModel):
stats: SubmissionStats
+class StoreCategoryInfo(pydantic.BaseModel):
+ value: str
+ label: str
+ description: str
+
+
class StoreSubmissionRequest(pydantic.BaseModel):
graph_id: str = pydantic.Field(
..., min_length=1, description="Graph ID cannot be empty"
@@ -316,10 +324,14 @@ class StoreSubmissionRequest(pydantic.BaseModel):
image_urls: list[str] = []
description: str = ""
instructions: str | None = None
- categories: list[str] = []
+ categories: list[str]
changes_summary: str | None = None
recommended_schedule_cron: str | None = None
+ _canonical_categories = pydantic.field_validator("categories")(
+ validate_canonical_categories
+ )
+
class StoreSubmissionEditRequest(pydantic.BaseModel):
name: str
@@ -329,10 +341,14 @@ class StoreSubmissionEditRequest(pydantic.BaseModel):
image_urls: list[str] = []
description: str = ""
instructions: str | None = None
- categories: list[str] = []
+ categories: list[str]
changes_summary: str | None = None
recommended_schedule_cron: str | None = None
+ _canonical_categories = pydantic.field_validator("categories")(
+ validate_canonical_categories
+ )
+
class StoreSubmissionAdminView(StoreSubmission):
internal_comments: str | None # Private admin notes
diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.py
index 1177b7f231..b55ce42479 100644
--- a/autogpt_platform/backend/backend/api/features/store/routes.py
+++ b/autogpt_platform/backend/backend/api/features/store/routes.py
@@ -16,6 +16,7 @@ from backend.util.exceptions import NotFoundError
from backend.util.models import Pagination
from . import cache as store_cache
+from . import categories as store_categories
from . import db as store_db
from . import image_gen as store_image_gen
from . import media as store_media
@@ -183,6 +184,23 @@ async def get_agents(
return agents
+ "/categories",
+ summary="List store categories",
+ tags=["store", "public"],
+)
+async def get_categories() -> list[store_model.StoreCategoryInfo]:
+ """The canonical categories a listing can be filed under."""
+ return [
+ store_model.StoreCategoryInfo(
+ value=category.value,
+ label=store_categories.CATEGORY_LABELS[category],
+ description=store_categories.CATEGORY_DESCRIPTIONS[category],
+ )
+ for category in store_categories.StoreCategory
+ ]
+
+
@router.get(
"/agents/{username}/{agent_name}",
summary="Get specific agent",
diff --git a/autogpt_platform/backend/backend/cli/main.py b/autogpt_platform/backend/backend/cli/main.py
index 772ba87d92..b049393c0c 100644
--- a/autogpt_platform/backend/backend/cli/main.py
+++ b/autogpt_platform/backend/backend/cli/main.py
@@ -9,6 +9,7 @@ import psutil
from backend.util.process import AppProcess
from .chat import chat
+from .store import store
from .test import test
@@ -19,6 +20,7 @@ def main():
main.add_command(chat)
+main.add_command(store)
main.add_command(test)
diff --git a/autogpt_platform/backend/backend/cli/store.py b/autogpt_platform/backend/backend/cli/store.py
new file mode 100644
index 0000000000..c26ded43e4
--- /dev/null
+++ b/autogpt_platform/backend/backend/cli/store.py
@@ -0,0 +1,106 @@
+import logging
+
+import click
+
+
+def store():
+ """
+ Group for marketplace maintenance commands
+ """
+ logging.disable(logging.INFO)
+
+
[email protected](name="backfill-categories")
[email protected]("--apply", is_flag=True, help="Write the results. Without it, dry run.")
+ "--limit",
+ type=click.IntRange(min=0),
+ default=None,
+ help="Classify at most N listings.",
+)
+ "--concurrency", type=int, default=5, help="Classifier calls in flight at once."
+)
+def backfill_categories(apply: bool, limit: int | None, concurrency: int):
+ """Give every store listing a canonical category.
+
+ Folds legacy free-text values onto the canonical set by alias where the
+ mapping is unambiguous, and asks the classifier for the rest. Idempotent:
+ a listing already on a canonical category is never touched, so a re-run
+ only picks up what the previous one could not classify.
+ """
+ import asyncio
+
+ asyncio.run(_run_backfill(apply=apply, limit=limit, concurrency=concurrency))
+
+
+async def _run_backfill(*, apply: bool, limit: int | None, concurrency: int) -> None:
+ import asyncio
+
+ import prisma.models
+
+ from backend.api.features.store.categories import normalize_categories
+ from backend.api.features.store.category_classifier import classify_category
+ from backend.data.db import connect, disconnect
+
+ await connect()
+ try:
+ versions = await prisma.models.StoreListingVersion.prisma().find_many(
+ where={"isDeleted": False}, order={"createdAt": "asc"}
+ )
+ folds = {
+ v.id: [c.value for c in normalize_categories(v.categories)]
+ for v in versions
+ }
+ pending = [v for v in versions if not folds[v.id]]
+ if limit is not None:
+ pending = pending[:limit]
+
+ mode = "" if apply else " (dry run — nothing will be written)"
+ print(
+ f"{len(versions)} listing versions; {len(pending)} need the classifier, "
+ f"{sum(1 for v in versions if folds[v.id] and folds[v.id] != v.categories)}"
+ f" fold from legacy values{mode}"
+ )
+
+ semaphore = asyncio.Semaphore(max(1, concurrency))
+
+ async def classify(version: prisma.models.StoreListingVersion):
+ async with semaphore:
+ return version, await classify_category(
+ version.name, version.subHeading, version.description
+ )
+
+ classified = 0
+ for version, category in await asyncio.gather(*map(classify, pending)):
+ if category is None:
+ print(f" skip {version.name!r}: no category")
+ continue
+ classified += 1
+ print(f" {category.value:<12} {version.name!r}")
+ if apply:
+ await prisma.models.StoreListingVersion.prisma().update(
+ where={"id": version.id}, data={"categories": [category.value]}
+ )
+
+ folded = 0
+ for version in versions:
+ canonical = folds[version.id]
+ if not canonical or canonical == version.categories:
+ continue
+ folded += 1
+ print(f" fold {version.name!r}: {version.categories} -> {canonical}")
+ if apply:
+ await prisma.models.StoreListingVersion.prisma().update(
+ where={"id": version.id}, data={"categories": canonical}
+ )
+
+ print(
+ f"\n{classified} classified, {folded} folded, "
+ f"{len(pending) - classified} still uncategorised"
+ )
+ if not apply:
+ print("Dry run — re-run with --apply to write.")
+ finally:
+ await disconnect()
diff --git a/autogpt_platform/backend/backend/cli/store_test.py b/autogpt_platform/backend/backend/cli/store_test.py
new file mode 100644
index 0000000000..14b580a1ce
--- /dev/null
+++ b/autogpt_platform/backend/backend/cli/store_test.py
@@ -0,0 +1,119 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from click.testing import CliRunner
+
+from backend.api.features.store import category_classifier
+from backend.api.features.store.categories import StoreCategory
+from backend.cli.store import _run_backfill, backfill_categories
+
+
+def _version(id: str, name: str, categories: list[str]):
+ return SimpleNamespace(
+ id=id,
+ name=name,
+ subHeading="sub heading",
+ description="description",
+ categories=categories,
+ )
+
+
+def backfill(monkeypatch):
+ """Drive _run_backfill against in-memory listings, recording every write."""
+ import prisma.models
+
+ from backend.data import db as data_db
+
+ monkeypatch.setattr(data_db, "connect", AsyncMock())
+ monkeypatch.setattr(data_db, "disconnect", AsyncMock())
+
+ state = SimpleNamespace(versions=[], classified={}, writes=[], classify_calls=[])
+
+ async def classify(name, sub_heading, description):
+ state.classify_calls.append(name)
+ return state.classified.get(name)
+
+ monkeypatch.setattr(category_classifier, "classify_category", classify)
+
+ client = MagicMock()
+ client.find_many = AsyncMock(side_effect=lambda **_: state.versions)
+ client.update = AsyncMock(
+ side_effect=lambda where, data: state.writes.append(
+ (where["id"], data["categories"])
+ )
+ )
+ monkeypatch.setattr(
+ prisma.models.StoreListingVersion, "prisma", MagicMock(return_value=client)
+ )
+ return state
+
+
+async def test_a_dry_run_classifies_but_writes_nothing(backfill):
+ backfill.versions = [_version("v1", "Lead Finder", [])]
+ backfill.classified = {"Lead Finder": StoreCategory.SALES}
+
+ await _run_backfill(apply=False, limit=None, concurrency=5)
+
+ assert backfill.classify_calls == ["Lead Finder"]
+ assert backfill.writes == []
+
+
+async def test_apply_writes_the_classified_category(backfill):
+ backfill.versions = [_version("v1", "Lead Finder", [])]
+ backfill.classified = {"Lead Finder": StoreCategory.SALES}
+
+ await _run_backfill(apply=True, limit=None, concurrency=5)
+
+ assert backfill.writes == [("v1", ["sales"])]
+
+
+async def test_a_canonical_listing_is_neither_classified_nor_written(backfill):
+ backfill.versions = [_version("v1", "Already Filed", ["sales"])]
+
+ await _run_backfill(apply=True, limit=None, concurrency=5)
+
+ assert backfill.classify_calls == []
+ assert backfill.writes == []
+
+
+async def test_a_legacy_alias_is_folded_without_the_classifier(backfill):
+ backfill.versions = [_version("v1", "Blog Writer", ["writing"])]
+
+ await _run_backfill(apply=True, limit=None, concurrency=5)
+
+ assert backfill.classify_calls == []
+ assert backfill.writes == [("v1", ["content"])]
+
+
+async def test_a_listing_the_classifier_declines_is_left_alone(backfill):
+ backfill.versions = [_version("v1", "Mystery", [])]
+
+ await _run_backfill(apply=True, limit=None, concurrency=5)
+
+ assert backfill.classify_calls == ["Mystery"]
+ assert backfill.writes == []
+
+
+async def test_limit_caps_the_classifier_but_not_the_folds(backfill):
+ backfill.versions = [
+ _version("v1", "One", []),
+ _version("v2", "Two", []),
+ _version("v3", "Folds", ["creative"]),
+ ]
+ backfill.classified = {"One": StoreCategory.SALES, "Two": StoreCategory.SALES}
+
+ await _run_backfill(apply=True, limit=1, concurrency=5)
+
+ assert backfill.classify_calls == ["One"]
+ assert backfill.writes == [("v1", ["sales"]), ("v3", ["content"])]
+
+
+def test_a_negative_limit_is_rejected():
+ result = CliRunner().invoke(backfill_categories, ["--limit", "-1"])
+
+ # Click's usage-error code: rejected before the command body runs, so the
+ # backfill never reaches the database.
+ assert result.exit_code == 2
+ assert "is not in the range" in result.output
diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.py
index d55787b1e4..9dcac4f79c 100644
--- a/autogpt_platform/backend/backend/data/graph_test.py
+++ b/autogpt_platform/backend/backend/data/graph_test.py
@@ -409,7 +409,7 @@ async def test_access_store_listing_graph(server: SpinTestServer):
video_url=None,
image_urls=[],
description="Test description",
- categories=[],
+ categories=["operations"],
)
# First we check the graph can not be accessed by a different user
diff --git a/autogpt_platform/backend/backend/executor/manager_test.py b/autogpt_platform/backend/backend/executor/manager_test.py
index e30650f4fb..a0be02d7d1 100644
--- a/autogpt_platform/backend/backend/executor/manager_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_test.py
@@ -522,7 +522,7 @@ async def test_store_listing_graph(server: SpinTestServer):
video_url=None,
image_urls=[],
description="Test description",
- categories=[],
+ categories=["operations"],
)
store_listing = await server.agent_server.test_create_store_listing(
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index ae6601ddc3..6525172850 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -557,6 +557,10 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
default=True,
description="Whether to use the new agent image generation service",
)
+ marketplace_require_canonical_category: bool = Field(
+ default=False,
+ description="Hide listings without a canonical category from the marketplace's default view. Turn on only once the category backfill has run, or real listings disappear.",
+ )
enable_agent_input_subtype_blocks: bool = Field(
default=True,
description="Whether to enable the agent input subtype blocks",
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/category-filter.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/category-filter.test.tsx
new file mode 100644
index 0000000000..87ca2ea627
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/category-filter.test.tsx
@@ -0,0 +1,160 @@
+import { getListExpertTemplatesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import {
+ getGetV2ListStoreCategoriesMockHandler,
+ getGetV2ListStoreCreatorsMockHandler,
+} from "@/app/api/__generated__/endpoints/store/store.msw";
+import { server } from "@/mocks/mock-server";
+import {
+ 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";
+
+const mockUseAuth = vi.hoisted(() => vi.fn());
+
+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 }));
+
+const CATEGORIES = [
+ { value: "marketing", label: "Marketing", description: "Campaigns and SEO" },
+ { value: "sales", label: "Sales", description: "Leads and outreach" },
+];
+
+function agent(name: string) {
+ return {
+ slug: name.toLowerCase(),
+ agent_name: name,
+ agent_image: "",
+ creator: "creator",
+ creator_avatar: "",
+ sub_heading: "",
+ description: "",
+ runs: 1,
+ rating: 5,
+ agent_graph_id: `graph-${name}`,
+ };
+}
+
+/** Records every ?category= the page asks for, and answers from BY_CATEGORY. */
+const requestedCategories: (string | null)[] = [];
+const BY_CATEGORY: Record<string, string[]> = {
+ all: ["Blog Writer", "Lead Finder"],
+ marketing: ["Blog Writer"],
+};
+
+describe("Marketplace category filter", () => {
+ beforeEach(() => {
+ requestedCategories.length = 0;
+ mockUseAuth.mockReturnValue({ user: { id: "user-1" }, isLoggedIn: true });
+ server.use(
+ getListExpertTemplatesMockHandler([]),
+ getGetV2ListStoreCreatorsMockHandler({
+ creators: [],
+ pagination: {
+ current_page: 1,
+ total_items: 0,
+ total_pages: 0,
+ page_size: 20,
+ },
+ }),
+ getGetV2ListStoreCategoriesMockHandler(CATEGORIES),
+ http.get("/api/proxy/api/store/agents", ({ request }) => {
+ const params = new URL(request.url).searchParams;
+ // The featured shelf is a separate query; keep it empty so the grid
+ // is the only thing rendering agent names.
+ const names = params.get("featured")
+ ? []
+ : (BY_CATEGORY[params.get("category") ?? "all"] ?? []);
+ if (!params.get("featured")) {
+ requestedCategories.push(params.get("category"));
+ }
+ return HttpResponse.json({
+ agents: names.map(agent),
+ pagination: {
+ current_page: 1,
+ total_items: names.length,
+ total_pages: 1,
+ page_size: 20,
+ },
+ });
+ }),
+ );
+ });
+
+ test("filtering by a category asks the API for it and narrows the grid", async () => {
+ render(<MainMarkeplacePage />);
+
+ expect((await screen.findAllByText("Lead Finder")).length).toBeGreaterThan(
+ 0,
+ );
+ expect(requestedCategories).toEqual([null]);
+
+ await userEvent.click(await findCategoryChip("Marketing"));
+
+ await waitFor(() =>
+ expect(screen.queryAllByText("Lead Finder")).toHaveLength(0),
+ );
+ expect(screen.queryAllByText("Blog Writer").length).toBeGreaterThan(0);
+ expect(requestedCategories).toContain("marketing");
+ });
+
+ test("clicking the active category again clears the filter", async () => {
+ render(<MainMarkeplacePage />);
+ expect((await screen.findAllByText("Lead Finder")).length).toBeGreaterThan(
+ 0,
+ );
+
+ const marketing = await findCategoryChip("Marketing");
+ await userEvent.click(marketing);
+ await waitFor(() =>
+ expect(screen.queryAllByText("Lead Finder")).toHaveLength(0),
+ );
+ expect(marketing.getAttribute("aria-pressed")).toBe("true");
+
+ await userEvent.click(marketing);
+
+ await waitFor(() =>
+ expect(screen.queryAllByText("Lead Finder").length).toBeGreaterThan(0),
+ );
+ expect(marketing.getAttribute("aria-pressed")).toBe("false");
+ });
+
+ test("only the eight canonical categories the API serves are offered", async () => {
+ render(<MainMarkeplacePage />);
+
+ expect(await findCategoryChip("Marketing")).toBeDefined();
+ expect(await findCategoryChip("Sales")).toBeDefined();
+ // The legacy free-text options are gone.
+ const chips = within(
+ await screen.findByRole("group", { name: "Browse by category" }),
+ );
+ expect(chips.queryByRole("button", { name: "Productivity" })).toBeNull();
+ expect(chips.queryByRole("button", { name: /Writing/ })).toBeNull();
+ });
+});
+
+/** The hero has its own chip row with overlapping labels, so scope to ours. */
+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/CategoryFilter/CategoryFilter.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CategoryFilter/CategoryFilter.tsx
new file mode 100644
index 0000000000..4b7655cf07
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CategoryFilter/CategoryFilter.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { useStoreCategories } from "@/hooks/useStoreCategories";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ selected: string | null;
+ onSelect: (category: string | null) => void;
+}
+
+export function CategoryFilter({ selected, onSelect }: Props) {
+ const { categories } = useStoreCategories();
+
+ if (categories.length === 0) return null;
+
+ function handleClick(value: string | null) {
+ onSelect(value === selected ? null : value);
+ }
+
+ return (
+ // Labelled because the hero above carries its own chip row of search
+ // terms, and the two overlap on names like "Marketing".
+ <div
+ className="mb-8 flex flex-wrap items-center gap-x-4 gap-y-2.5"
+ role="group"
+ aria-label="Browse by category"
+ >
+ <span className="text-sm font-medium text-zinc-500">
+ Browse by category
+ </span>
+ {/* One flex item, so the whole list drops below the label before it
+ breaks within itself. */}
+ <div className="flex flex-wrap gap-2.5">
+ <CategoryChip
+ label="All"
+ isSelected={selected === null}
+ onClick={() => onSelect(null)}
+ />
+ {categories.map((category) => (
+ <CategoryChip
+ key={category.value}
+ label={category.label}
+ title={category.description}
+ isSelected={selected === category.value}
+ onClick={() => handleClick(category.value)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+interface ChipProps {
+ label: string;
+ title?: string;
+ isSelected: boolean;
+ onClick: () => void;
+}
+
+function CategoryChip({ label, title, isSelected, onClick }: ChipProps) {
+ return (
+ <button
+ type="button"
+ title={title}
+ aria-pressed={isSelected}
+ onClick={onClick}
+ className={cn(
+ "inline-flex h-9 items-center rounded-full border px-4 text-sm font-medium transition-all duration-200",
+ isSelected
+ ? "border-zinc-900 bg-zinc-900 text-white shadow-[0_1px_2px_rgba(16,24,40,0.1)]"
+ : "border-zinc-200 bg-white text-zinc-600 shadow-[0_1px_2px_rgba(16,24,40,0.04)] hover:-translate-y-px hover:border-zinc-300 hover:text-zinc-900",
+ )}
+ >
+ {label}
+ </button>
+ );
+}
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 d5d5dd36cf..b47252a50a 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
@@ -4,6 +4,7 @@ import { useAuth } from "@/lib/auth/hooks/useAuth";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { AICatalogIcon } from "../AICatalogIcon";
import { AgentsSection } from "../AgentsSection/AgentsSection";
+import { CategoryFilter } from "../CategoryFilter/CategoryFilter";
import { BecomeACreator } from "../BecomeACreator/BecomeACreator";
import { FeaturedCreators } from "../FeaturedCreators/FeaturedCreators";
import { FeaturedSection } from "../FeaturedSection/FeaturedSection";
@@ -15,8 +16,15 @@ import { AGENTS_SECTION_ID } from "../MarketplaceTabIntro/helpers";
import { useMainMarketplacePage } from "./useMainMarketplacePage";
export const MainMarkeplacePage = () => {
- const { featuredAgents, topAgents, featuredCreators, isLoading, hasError } =
- useMainMarketplacePage();
+ const {
+ featuredAgents,
+ topAgents,
+ featuredCreators,
+ category,
+ setCategory,
+ isLoading,
+ hasError,
+ } = useMainMarketplacePage();
const { isLoggedIn, isUserLoading } = useAuth();
const isHireExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);
// Hiring is still behind the flag, but the expert pages are public: a
@@ -64,9 +72,14 @@ export const MainMarkeplacePage = () => {
}
agents={topAgents.agents}
>
- {featuredAgents && featuredAgents.agents.length > 0 && (
- <FeaturedSection featuredAgents={featuredAgents.agents} />
- )}
+ <CategoryFilter selected={category} onSelect={setCategory} />
+ {/* Featured is a whole-marketplace shelf; under a category filter
+ it would show workflows the filter excludes. */}
+ {!category &&
+ featuredAgents &&
+ featuredAgents.agents.length > 0 && (
+ <FeaturedSection featuredAgents={featuredAgents.agents} />
+ )}
</AgentsSection>
</div>
)}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/useMainMarketplacePage.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/useMainMarketplacePage.ts
index 1123ab2eee..aa24cffb49 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/useMainMarketplacePage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/MainMarketplacePage/useMainMarketplacePage.ts
@@ -4,6 +4,7 @@ import {
} from "@/app/api/__generated__/endpoints/store/store";
import { StoreAgentsResponse } from "@/app/api/__generated__/models/storeAgentsResponse";
import { CreatorsResponse } from "@/app/api/__generated__/models/creatorsResponse";
+import { useState } from "react";
const queryConfig = {
staleTime: 60 * 1000, // 60 seconds - match server cache
@@ -13,6 +14,8 @@ const queryConfig = {
};
export const useMainMarketplacePage = () => {
+ const [category, setCategory] = useState<string | null>(null);
+
// Data is prefetched on server and hydrated, these queries will use cached data
const {
data: featuredAgents,
@@ -38,10 +41,14 @@ export const useMainMarketplacePage = () => {
{
sorted_by: "runs",
page_size: 1000,
+ ...(category ? { category } : {}),
},
{
query: {
...queryConfig,
+ // Keep the current grid on screen while a category change loads, so
+ // picking a filter doesn't collapse the whole page to skeletons.
+ placeholderData: (previousData) => previousData,
select: (x) => {
return x.data as StoreAgentsResponse;
},
@@ -74,6 +81,8 @@ export const useMainMarketplacePage = () => {
featuredAgents,
topAgents,
featuredCreators,
+ category,
+ setCategory,
isLoading,
hasError,
};
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 76f43f4acf..e747c25dd0 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -14009,6 +14009,28 @@
}
}
},
+ "/api/store/categories": {
+ "get": {
+ "tags": ["v2", "store", "public"],
+ "summary": "List store categories",
+ "description": "The canonical categories a listing can be filed under.",
+ "operationId": "getV2List store categories",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": { "$ref": "#/components/schemas/StoreCategoryInfo" },
+ "type": "array",
+ "title": "Response Getv2List Store Categories"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/store/creators": {
"get": {
"tags": ["v2", "store", "public"],
@@ -27097,6 +27119,16 @@
"enum": ["rating", "runs", "name", "updated_at"],
"title": "StoreAgentsSortOptions"
},
+ "StoreCategoryInfo": {
+ "properties": {
+ "value": { "type": "string", "title": "Value" },
+ "label": { "type": "string", "title": "Label" },
+ "description": { "type": "string", "title": "Description" }
+ },
+ "type": "object",
+ "required": ["value", "label", "description"],
+ "title": "StoreCategoryInfo"
+ },
"StoreCreatorsSortOptions": {
"type": "string",
"enum": ["agent_rating", "agent_runs", "num_agents"],
@@ -27425,8 +27457,7 @@
"categories": {
"items": { "type": "string" },
"type": "array",
- "title": "Categories",
- "default": []
+ "title": "Categories"
},
"changes_summary": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
@@ -27438,7 +27469,7 @@
}
},
"type": "object",
- "required": ["name", "sub_heading"],
+ "required": ["name", "sub_heading", "categories"],
"title": "StoreSubmissionEditRequest"
},
"StoreSubmissionRequest": {
@@ -27484,8 +27515,7 @@
"categories": {
"items": { "type": "string" },
"type": "array",
- "title": "Categories",
- "default": []
+ "title": "Categories"
},
"changes_summary": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
@@ -27502,7 +27532,8 @@
"graph_version",
"slug",
"name",
- "sub_heading"
+ "sub_heading",
+ "categories"
],
"title": "StoreSubmissionRequest"
},
diff --git a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/__tests__/EditAgentModal.test.tsx b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/__tests__/EditAgentModal.test.tsx
index 9a64bf110d..1f3089c05f 100644
--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/__tests__/EditAgentModal.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/__tests__/EditAgentModal.test.tsx
@@ -1,7 +1,9 @@
import { describe, expect, it, vi } from "vitest";
import { StoreSubmissionEditRequest } from "@/app/api/__generated__/models/storeSubmissionEditRequest";
+import { server } from "@/mocks/mock-server";
import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { http, HttpResponse } from "msw";
import { EditAgentModal } from "../EditAgentModal";
@@ -56,6 +58,30 @@ describe("EditAgentModal", () => {
).toBeDefined();
});
+ it("disables the category field when the category list cannot be loaded", async () => {
+ server.use(
+ http.get("http://localhost:3000/api/proxy/api/store/categories", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ );
+ render(
+ <EditAgentModal
+ isOpen={true}
+ onClose={() => {}}
+ // No stored category, so the field shows the placeholder rather than a
+ // value: the error copy is the only thing that separates the failed
+ // state from the loading one, which disables the field too.
+ submission={{ ...makeSubmission(), categories: [] }}
+ onSuccess={() => {}}
+ />,
+ );
+
+ expect(await screen.findByText("Categories unavailable")).toBeDefined();
+
+ const category = screen.getByRole("combobox", { name: /category/i });
+ expect(category.hasAttribute("disabled")).toBe(true);
+ });
+
it("invokes onClose when the Cancel button is clicked", () => {
const onClose = vi.fn();
render(
diff --git a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/EditAgentForm.tsx b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/EditAgentForm.tsx
index 2c18046077..02dcacfec1 100644
--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/EditAgentForm.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/EditAgentForm.tsx
@@ -50,6 +50,8 @@ export function EditAgentForm({
form,
images,
categoryOptions,
+ categoriesUnavailable,
+ categoryPlaceholder,
isSubmitting,
handleFormSubmit,
handleImagesChange,
@@ -208,7 +210,8 @@ export function EditAgentForm({
labelVariant="body"
label="Category"
labelTooltip="Primary category that helps users discover the agent."
- placeholder="Select a category"
+ placeholder={categoryPlaceholder}
+ disabled={categoriesUnavailable}
value={field.value}
onValueChange={field.onChange}
error={form.formState.errors.category?.message}
diff --git a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts
index 48ed622c80..2e5a4ef1b3 100644
--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts
+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts
@@ -6,6 +6,7 @@ import {
import { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
import { StoreSubmissionEditRequest } from "@/app/api/__generated__/models/storeSubmissionEditRequest";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useStoreCategories } from "@/hooks/useStoreCategories";
import { validateYouTubeUrl } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQueryClient } from "@tanstack/react-query";
@@ -65,6 +66,12 @@ export const useEditAgentForm = ({
const queryClient = useQueryClient();
const { toast } = useToast();
+ const {
+ categories,
+ isUnavailable: categoriesUnavailable,
+ placeholder: categoryPlaceholder,
+ } = useStoreCategories();
+
const form = useForm<EditAgentFormData>({
resolver: zodResolver(editAgentSchema),
defaultValues: {
@@ -78,18 +85,10 @@ export const useEditAgentForm = ({
},
});
- const categoryOptions = [
- { value: "productivity", label: "Productivity" },
- { value: "writing", label: "Writing & Content" },
- { value: "development", label: "Development" },
- { value: "data", label: "Data & Analytics" },
- { value: "marketing", label: "Marketing & SEO" },
- { value: "research", label: "Research & Learning" },
- { value: "creative", label: "Creative & Design" },
- { value: "business", label: "Business & Finance" },
- { value: "personal", label: "Personal Assistant" },
- { value: "other", label: "Other" },
- ];
+ const categoryOptions = categories.map((category) => ({
+ value: category.value,
+ label: category.label,
+ }));
const handleImagesChange = React.useCallback((newImages: string[]) => {
setImages(newImages);
@@ -105,8 +104,7 @@ export const useEditAgentForm = ({
return;
}
- const categories = data.category ? [data.category] : [];
- const filteredCategories = categories.filter(Boolean);
+ const filteredCategories = [data.category].filter(Boolean);
setIsSubmitting(true);
try {
@@ -164,5 +162,7 @@ export const useEditAgentForm = ({
handleFormSubmit,
handleImagesChange,
categoryOptions,
+ categoriesUnavailable,
+ categoryPlaceholder,
};
};
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/AgentInfoStep.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/AgentInfoStep.tsx
index e4428e2037..9488faeb4f 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/AgentInfoStep.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/AgentInfoStep.tsx
@@ -12,6 +12,7 @@ import { Button } from "@/components/atoms/Button/Button";
import { Input } from "@/components/atoms/Input/Input";
import { Select } from "@/components/atoms/Select/Select";
import { Text } from "@/components/atoms/Text/Text";
+import { useStoreCategories } from "@/hooks/useStoreCategories";
import { humanizeCronExpression } from "@/lib/cron-expression-utils";
import { cn } from "@/lib/utils";
import { InformationTooltip } from "@/components/molecules/InformationTooltip/InformationTooltip";
@@ -61,6 +62,8 @@ export function AgentInfoStep({
isMarketplaceUpdate,
});
+ const { categories, isUnavailable, placeholder } = useStoreCategories();
+
const [cronScheduleDialogOpen, setCronScheduleDialogOpen] =
React.useState(false);
const [openAccordion, setOpenAccordion] = React.useState("");
@@ -75,18 +78,10 @@ export function AgentInfoStep({
form.setValue("recommendedScheduleCron", cronExpression);
};
- const categoryOptions = [
- { value: "productivity", label: "Productivity" },
- { value: "writing", label: "Writing & Content" },
- { value: "development", label: "Development" },
- { value: "data", label: "Data & Analytics" },
- { value: "marketing", label: "Marketing & SEO" },
- { value: "research", label: "Research & Learning" },
- { value: "creative", label: "Creative & Design" },
- { value: "business", label: "Business & Finance" },
- { value: "personal", label: "Personal Assistant" },
- { value: "other", label: "Other" },
- ];
+ const categoryOptions = categories.map((category) => ({
+ value: category.value,
+ label: category.label,
+ }));
const isSubmitDisabled =
Object.keys(form.formState.errors).length > 0 || isSubmitting;
@@ -268,7 +263,8 @@ export function AgentInfoStep({
labelVariant="body"
label="Category"
labelTooltip="Primary category that helps users discover the agent."
- placeholder="Select a category"
+ placeholder={placeholder}
+ disabled={isUnavailable}
value={field.value}
onValueChange={field.onChange}
error={form.formState.errors.category?.message}
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/AgentInfoStep.test.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/AgentInfoStep.test.tsx
index 3c00c34ea9..412be2d6e9 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/AgentInfoStep.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/AgentInfoStep.test.tsx
@@ -53,6 +53,23 @@ describe("AgentInfoStep", () => {
expect(await screen.findByText("Describe the update")).toBeDefined();
});
+ it("disables the category field when the category list cannot be loaded", async () => {
+ server.use(
+ http.get("http://localhost:3000/api/proxy/api/store/categories", () =>
+ HttpResponse.json({ detail: "boom" }, { status: 500 }),
+ ),
+ );
+ render(<AgentInfoStep {...baseProps} />);
+
+ // The field is disabled while loading too, so wait for the copy that only
+ // the error state renders before asserting on it. The accordion holding it
+ // opens on a timer after mount.
+ expect(await screen.findByText("Categories unavailable")).toBeDefined();
+
+ const category = screen.getByRole("combobox", { name: /category/i });
+ expect(category.hasAttribute("disabled")).toBe(true);
+ });
+
it("mounts cleanly when the submissions API would error (handler installed)", async () => {
server.use(
http.post("http://localhost:3000/api/proxy/api/store/submissions", () =>
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/helpers.test.ts
index 775f7ff74d..dc68db5b4e 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/__tests__/helpers.test.ts
@@ -76,14 +76,22 @@ describe("publishAgentSchemaFactory", () => {
expect(result.success).toBe(true);
});
- it("treats title / subheader / category as optional on updates", () => {
+ it("treats title and subheader as optional on updates", () => {
const result = publishAgentSchemaFactory(true).safeParse({
...validBase,
title: "",
subheader: "",
- category: "",
changesSummary: "Refreshed copy",
});
expect(result.success).toBe(true);
});
+
+ it("still requires a category on updates, which overwrite the stored ones", () => {
+ const result = publishAgentSchemaFactory(true).safeParse({
+ ...validBase,
+ category: "",
+ changesSummary: "Refreshed copy",
+ });
+ expect(result.success).toBe(false);
+ });
});
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/helpers.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/helpers.ts
index 86e6c0ce30..8ba9d32b4b 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/helpers.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/helpers.ts
@@ -63,9 +63,7 @@ export const publishAgentSchemaFactory = (
: z
.string()
.refine(validateYouTubeUrl, "Please enter a valid YouTube URL"),
- category: isMarketplaceUpdate
- ? z.string().optional()
- : z.string().min(1, "Category is required"),
+ category: z.string().min(1, "Category is required"),
description: isMarketplaceUpdate
? z
.string()
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts
index 1ee6e45ea5..bd57bbb6b1 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/useAgentInfoStep.ts
@@ -115,8 +115,7 @@ export function useAgentInfoStep({
return;
}
- const categories = data.category ? [data.category] : [];
- const filteredCategories = categories.filter(Boolean);
+ const filteredCategories = [data.category].filter(Boolean);
setIsSubmitting(true);
diff --git a/autogpt_platform/frontend/src/hooks/useStoreCategories.ts b/autogpt_platform/frontend/src/hooks/useStoreCategories.ts
new file mode 100644
index 0000000000..580884e42f
--- /dev/null
+++ b/autogpt_platform/frontend/src/hooks/useStoreCategories.ts
@@ -0,0 +1,25 @@
+import { useGetV2ListStoreCategories } from "@/app/api/__generated__/endpoints/store/store";
+import { StoreCategoryInfo } from "@/app/api/__generated__/models/storeCategoryInfo";
+
+export function useStoreCategories() {
+ const { data, isLoading, isError } = useGetV2ListStoreCategories({
+ query: {
+ // The canonical set only changes with a deploy.
+ staleTime: Infinity,
+ select: (x) => x.data as StoreCategoryInfo[],
+ },
+ });
+
+ return {
+ categories: data ?? [],
+ isLoading,
+ isUnavailable: isLoading || isError,
+ // The two publish forms render the same required select; keeping the copy
+ // here is what stops them drifting apart.
+ placeholder: isLoading
+ ? "Loading categories…"
+ : isError
+ ? "Categories unavailable"
+ : "Select a category",
+ };
+}
diff --git a/autogpt_platform/frontend/src/playwright/pages/marketplace.page.ts b/autogpt_platform/frontend/src/playwright/pages/marketplace.page.ts
index 3d1293c608..84691acbcb 100644
--- a/autogpt_platform/frontend/src/playwright/pages/marketplace.page.ts
+++ b/autogpt_platform/frontend/src/playwright/pages/marketplace.page.ts
@@ -260,7 +260,7 @@ export class MarketplacePage extends BasePage {
await publishAgentModal.getByLabel("Slug").fill(agentSlug);
await publishAgentModal.getByRole("combobox", { name: "Category" }).click();
- await this.page.getByRole("option", { name: "Other" }).click();
+ await this.page.getByRole("option", { name: "Operations" }).click();
// Stub the GCS-backed media upload so the flow is hermetic in CI, then
// select a file to trigger it. This satisfies the "at least one image is