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.

refactor(backend/db): Improve & clean up Marketplace DB layer & API (#12284)

Reinier van der Leeraa08063939af
diff --git a/autogpt_platform/backend/backend/api/external/v1/routes.py b/autogpt_platform/backend/backend/api/external/v1/routes.py
index dcfce5c7ae..b803db417a 100644
--- a/autogpt_platform/backend/backend/api/external/v1/routes.py
+++ b/autogpt_platform/backend/backend/api/external/v1/routes.py
@@ -1,7 +1,7 @@
import logging
import urllib.parse
from collections import defaultdict
-from typing import Annotated, Any, Literal, Optional, Sequence
+from typing import Annotated, Any, Optional, Sequence
from fastapi import APIRouter, Body, HTTPException, Security
from prisma.enums import AgentExecutionStatus, APIKeyPermission
@@ -9,9 +9,10 @@ from pydantic import BaseModel, Field
from typing_extensions import TypedDict
import backend.api.features.store.cache as store_cache
+import backend.api.features.store.db as store_db
import backend.api.features.store.model as store_model
import backend.blocks
-from backend.api.external.middleware import require_permission
+from backend.api.external.middleware import require_auth, require_permission
from backend.data import execution as execution_db
from backend.data import graph as graph_db
from backend.data import user as user_db
@@ -230,13 +231,13 @@ async def get_graph_execution_results(
@v1_router.get(
path="/store/agents",
tags=["store"],
- dependencies=[Security(require_permission(APIKeyPermission.READ_STORE))],
+ dependencies=[Security(require_auth)], # data is public; auth required as anti-DDoS
response_model=store_model.StoreAgentsResponse,
)
async def get_store_agents(
featured: bool = False,
creator: str | None = None,
- sorted_by: Literal["rating", "runs", "name", "updated_at"] | None = None,
+ sorted_by: store_db.StoreAgentsSortOptions | None = None,
search_query: str | None = None,
category: str | None = None,
page: int = 1,
@@ -278,7 +279,7 @@ async def get_store_agents(
@v1_router.get(
path="/store/agents/{username}/{agent_name}",
tags=["store"],
- dependencies=[Security(require_permission(APIKeyPermission.READ_STORE))],
+ dependencies=[Security(require_auth)], # data is public; auth required as anti-DDoS
response_model=store_model.StoreAgentDetails,
)
async def get_store_agent(
@@ -306,13 +307,13 @@ async def get_store_agent(
@v1_router.get(
path="/store/creators",
tags=["store"],
- dependencies=[Security(require_permission(APIKeyPermission.READ_STORE))],
+ dependencies=[Security(require_auth)], # data is public; auth required as anti-DDoS
response_model=store_model.CreatorsResponse,
)
async def get_store_creators(
featured: bool = False,
search_query: str | None = None,
- sorted_by: Literal["agent_rating", "agent_runs", "num_agents"] | None = None,
+ sorted_by: store_db.StoreCreatorsSortOptions | None = None,
page: int = 1,
page_size: int = 20,
) -> store_model.CreatorsResponse:
@@ -348,7 +349,7 @@ async def get_store_creators(
@v1_router.get(
path="/store/creators/{username}",
tags=["store"],
- dependencies=[Security(require_permission(APIKeyPermission.READ_STORE))],
+ dependencies=[Security(require_auth)], # data is public; auth required as anti-DDoS
response_model=store_model.CreatorDetails,
)
async def get_store_creator(
diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py
index 9c4b89fee6..6327c266e8 100644
--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py
+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py
@@ -24,14 +24,13 @@ router = fastapi.APIRouter(
@router.get(
"/listings",
summary="Get Admin Listings History",
- response_model=store_model.StoreListingsWithVersionsResponse,
)
async def get_admin_listings_with_versions(
status: typing.Optional[prisma.enums.SubmissionStatus] = None,
search: typing.Optional[str] = None,
page: int = 1,
page_size: int = 20,
-):
+) -> store_model.StoreListingsWithVersionsAdminViewResponse:
"""
Get store listings with their version history for admins.
@@ -45,36 +44,26 @@ async def get_admin_listings_with_versions(
page_size: Number of items per page
Returns:
- StoreListingsWithVersionsResponse with listings and their versions
+ Paginated listings with their versions
"""
- try:
- listings = await store_db.get_admin_listings_with_versions(
- status=status,
- search_query=search,
- page=page,
- page_size=page_size,
- )
- return listings
- except Exception as e:
- logger.exception("Error getting admin listings with versions: %s", e)
- return fastapi.responses.JSONResponse(
- status_code=500,
- content={
- "detail": "An error occurred while retrieving listings with versions"
- },
- )
+ listings = await store_db.get_admin_listings_with_versions(
+ status=status,
+ search_query=search,
+ page=page,
+ page_size=page_size,
+ )
+ return listings
@router.post(
"/submissions/{store_listing_version_id}/review",
summary="Review Store Submission",
- response_model=store_model.StoreSubmission,
)
async def review_submission(
store_listing_version_id: str,
request: store_model.ReviewSubmissionRequest,
user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
+) -> store_model.StoreSubmissionAdminView:
"""
Review a store listing submission.
@@ -84,31 +73,24 @@ async def review_submission(
user_id: Authenticated admin user performing the review
Returns:
- StoreSubmission with updated review information
+ StoreSubmissionAdminView with updated review information
"""
- try:
- already_approved = await store_db.check_submission_already_approved(
- store_listing_version_id=store_listing_version_id,
- )
- submission = await store_db.review_store_submission(
- store_listing_version_id=store_listing_version_id,
- is_approved=request.is_approved,
- external_comments=request.comments,
- internal_comments=request.internal_comments or "",
- reviewer_id=user_id,
- )
+ already_approved = await store_db.check_submission_already_approved(
+ store_listing_version_id=store_listing_version_id,
+ )
+ submission = await store_db.review_store_submission(
+ store_listing_version_id=store_listing_version_id,
+ is_approved=request.is_approved,
+ external_comments=request.comments,
+ internal_comments=request.internal_comments or "",
+ reviewer_id=user_id,
+ )
- state_changed = already_approved != request.is_approved
- # Clear caches when the request is approved as it updates what is shown on the store
- if state_changed:
- store_cache.clear_all_caches()
- return submission
- except Exception as e:
- logger.exception("Error reviewing submission: %s", e)
- return fastapi.responses.JSONResponse(
- status_code=500,
- content={"detail": "An error occurred while reviewing the submission"},
- )
+ state_changed = already_approved != request.is_approved
+ # Clear caches whenever approval state changes, since store visibility can change
+ if state_changed:
+ store_cache.clear_all_caches()
+ return submission
@router.get(
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index db52ca89b0..dced6075d5 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -8,7 +8,6 @@ import prisma.errors
import prisma.models
import prisma.types
-import backend.api.features.store.exceptions as store_exceptions
import backend.api.features.store.image_gen as store_image_gen
import backend.api.features.store.media as store_media
import backend.data.graph as graph_db
@@ -251,7 +250,7 @@ async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent
The requested LibraryAgent.
Raises:
- AgentNotFoundError: If the specified agent does not exist.
+ NotFoundError: If the specified agent does not exist.
DatabaseError: If there's an error during retrieval.
"""
library_agent = await prisma.models.LibraryAgent.prisma().find_first(
@@ -414,7 +413,7 @@ async def create_library_agent(
If the graph has sub-graphs, the parent graph will always be the first entry in the list.
Raises:
- AgentNotFoundError: If the specified agent does not exist.
+ NotFoundError: If the specified agent does not exist.
DatabaseError: If there's an error during creation or if image generation fails.
"""
logger.info(
@@ -817,7 +816,7 @@ async def add_store_agent_to_library(
The newly created LibraryAgent if successfully added, the existing corresponding one if any.
Raises:
- AgentNotFoundError: If the store listing or associated agent is not found.
+ NotFoundError: If the store listing or associated agent is not found.
DatabaseError: If there's an issue creating the LibraryAgent record.
"""
logger.debug(
@@ -832,7 +831,7 @@ async def add_store_agent_to_library(
)
if not store_listing_version or not store_listing_version.AgentGraph:
logger.warning(f"Store listing version not found: {store_listing_version_id}")
- raise store_exceptions.AgentNotFoundError(
+ raise NotFoundError(
f"Store listing version {store_listing_version_id} not found or invalid"
)
@@ -846,7 +845,7 @@ async def add_store_agent_to_library(
include_subgraphs=False,
)
if not graph_model:
- raise store_exceptions.AgentNotFoundError(
+ raise NotFoundError(
f"Graph #{graph.id} v{graph.version} not found or accessible"
)
diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.py
index 46db1672a9..1c5106e150 100644
--- a/autogpt_platform/backend/backend/api/features/library/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py
@@ -4,7 +4,6 @@ import prisma.enums
import prisma.models
import pytest
-import backend.api.features.store.exceptions
from backend.data.db import connect
from backend.data.includes import library_agent_include
@@ -218,7 +217,7 @@ async def test_add_agent_to_library_not_found(mocker):
)
# Call function and verify exception
- with pytest.raises(backend.api.features.store.exceptions.AgentNotFoundError):
+ with pytest.raises(db.NotFoundError):
await db.add_store_agent_to_library("version123", "test-user")
# Verify mock called correctly
diff --git a/autogpt_platform/backend/backend/api/features/store/cache.py b/autogpt_platform/backend/backend/api/features/store/cache.py
index 5d9bc24e5d..e81a9cd84a 100644
--- a/autogpt_platform/backend/backend/api/features/store/cache.py
+++ b/autogpt_platform/backend/backend/api/features/store/cache.py
@@ -1,5 +1,3 @@
-from typing import Literal
-
from backend.util.cache import cached
from . import db as store_db
@@ -23,7 +21,7 @@ def clear_all_caches():
async def _get_cached_store_agents(
featured: bool,
creator: str | None,
- sorted_by: Literal["rating", "runs", "name", "updated_at"] | None,
+ sorted_by: store_db.StoreAgentsSortOptions | None,
search_query: str | None,
category: str | None,
page: int,
@@ -57,7 +55,7 @@ async def _get_cached_agent_details(
async def _get_cached_store_creators(
featured: bool,
search_query: str | None,
- sorted_by: Literal["agent_rating", "agent_runs", "num_agents"] | None,
+ sorted_by: store_db.StoreCreatorsSortOptions | None,
page: int,
page_size: int,
):
@@ -75,4 +73,4 @@ async def _get_cached_store_creators(
@cached(maxsize=100, ttl_seconds=300, shared_cache=True)
async def _get_cached_creator_details(username: str):
"""Cached helper to get creator details."""
- return await store_db.get_store_creator_details(username=username.lower())
+ return await store_db.get_store_creator(username=username.lower())
diff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.py
index 87b72d6a9c..2b4d8b12ec 100644
--- a/autogpt_platform/backend/backend/api/features/store/db.py
+++ b/autogpt_platform/backend/backend/api/features/store/db.py
@@ -1,9 +1,9 @@
import asyncio
import logging
from datetime import datetime, timezone
+from enum import Enum
from typing import Any, Literal, overload
-import fastapi
import prisma.enums
import prisma.errors
import prisma.models
@@ -24,7 +24,7 @@ from backend.data.notifications import (
NotificationEventModel,
)
from backend.notifications.notifications import queue_notification_async
-from backend.util.exceptions import DatabaseError
+from backend.util.exceptions import DatabaseError, NotFoundError, PreconditionFailed
from backend.util.settings import Settings
from . import exceptions as store_exceptions
@@ -41,10 +41,17 @@ DEFAULT_ADMIN_NAME = "AutoGPT Admin"
DEFAULT_ADMIN_EMAIL = "[email protected]"
+class StoreAgentsSortOptions(Enum):
+ RATING = "rating"
+ RUNS = "runs"
+ NAME = "name"
+ UPDATED_AT = "updated_at"
+
+
async def get_store_agents(
featured: bool = False,
creators: list[str] | None = None,
- sorted_by: Literal["rating", "runs", "name", "updated_at"] | None = None,
+ sorted_by: StoreAgentsSortOptions | None = None,
search_query: str | None = None,
category: str | None = None,
page: int = 1,
@@ -61,7 +68,9 @@ async def get_store_agents(
Note: Admin operations (approval) use fail-fast to prevent inconsistent state.
"""
logger.debug(
- f"Getting store agents. featured={featured}, creators={creators}, sorted_by={sorted_by}, search={search_query}, category={category}, page={page}"
+ "Getting store agents: "
+ f"featured={featured}, creators={creators}, sorted_by={sorted_by}, "
+ f"query={search_query}, category={category}, page={page}"
)
search_used_hybrid = False
@@ -112,7 +121,7 @@ async def get_store_agents(
description=agent["description"],
runs=agent["runs"],
rating=agent["rating"],
- agent_graph_id=agent.get("agentGraphId", ""),
+ agent_graph_id=agent.get("graph_id", ""),
)
store_agents.append(store_agent)
except Exception as e:
@@ -140,12 +149,14 @@ async def get_store_agents(
]
order_by = []
- if sorted_by == "rating":
+ if sorted_by == StoreAgentsSortOptions.RATING:
order_by.append({"rating": "desc"})
- elif sorted_by == "runs":
+ elif sorted_by == StoreAgentsSortOptions.RUNS:
order_by.append({"runs": "desc"})
- elif sorted_by == "name":
+ elif sorted_by == StoreAgentsSortOptions.NAME:
order_by.append({"agent_name": "asc"})
+ elif sorted_by == StoreAgentsSortOptions.UPDATED_AT:
+ order_by.append({"updated_at": "desc"})
db_agents = await prisma.models.StoreAgent.prisma().find_many(
where=where_clause,
@@ -160,27 +171,9 @@ async def get_store_agents(
store_agents: list[store_model.StoreAgent] = []
for agent in db_agents:
try:
- # Create the StoreAgent object safely
- store_agent = store_model.StoreAgent(
- slug=agent.slug,
- agent_name=agent.agent_name,
- agent_image=agent.agent_image[0] if agent.agent_image else "",
- creator=agent.creator_username or "Needs Profile",
- creator_avatar=agent.creator_avatar or "",
- sub_heading=agent.sub_heading,
- description=agent.description,
- runs=agent.runs,
- rating=agent.rating,
- agent_graph_id=agent.agentGraphId,
- )
- # Add to the list only if creation was successful
- store_agents.append(store_agent)
+ store_agents.append(store_model.StoreAgent.from_db(agent))
except Exception as e:
- # Skip this agent if there was an error
- # You could log the error here if needed
- logger.error(
- f"Error parsing Store agent when getting store agents from db: {e}"
- )
+ logger.error(f"Error parsing StoreAgent from db: {e}")
continue
logger.debug(f"Found {len(store_agents)} agents")
@@ -229,66 +222,15 @@ async def get_store_agent_details(
if not agent:
logger.warning(f"Agent not found: {username}/{agent_name}")
- raise store_exceptions.AgentNotFoundError(
- f"Agent {username}/{agent_name} not found"
- )
-
- profile = await prisma.models.Profile.prisma().find_first(
- where={"username": username}
- )
- user_id = profile.userId if profile else None
-
- # Retrieve StoreListing to get active_version_id and has_approved_version
- store_listing = await prisma.models.StoreListing.prisma().find_first(
- where=prisma.types.StoreListingWhereInput(
- slug=agent_name,
- owningUserId=user_id or "",
- ),
- include={"ActiveVersion": True},
- )
-
- active_version_id = store_listing.activeVersionId if store_listing else None
- has_approved_version = (
- store_listing.hasApprovedVersion if store_listing else False
- )
-
- if active_version_id:
- agent_by_active = await prisma.models.StoreAgent.prisma().find_first(
- where={"storeListingVersionId": active_version_id}
- )
- if agent_by_active:
- agent = agent_by_active
- elif store_listing:
- latest_approved = (
- await prisma.models.StoreListingVersion.prisma().find_first(
- where={
- "storeListingId": store_listing.id,
- "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
- },
- order=[{"version": "desc"}],
- )
- )
- if latest_approved:
- agent_latest = await prisma.models.StoreAgent.prisma().find_first(
- where={"storeListingVersionId": latest_approved.id}
- )
- if agent_latest:
- agent = agent_latest
-
- if store_listing and store_listing.ActiveVersion:
- recommended_schedule_cron = (
- store_listing.ActiveVersion.recommendedScheduleCron
- )
- else:
- recommended_schedule_cron = None
+ raise NotFoundError(f"Agent {username}/{agent_name} not found")
# Fetch changelog data if requested
changelog_data = None
- if include_changelog and store_listing:
+ if include_changelog:
changelog_versions = (
await prisma.models.StoreListingVersion.prisma().find_many(
where={
- "storeListingId": store_listing.id,
+ "storeListingId": agent.listing_id,
"submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
},
order=[{"version": "desc"}],
@@ -304,30 +246,10 @@ async def get_store_agent_details(
]
logger.debug(f"Found agent details for {username}/{agent_name}")
- return store_model.StoreAgentDetails(
- store_listing_version_id=agent.storeListingVersionId,
- slug=agent.slug,
- agent_name=agent.agent_name,
- agent_video=agent.agent_video or "",
- agent_output_demo=agent.agent_output_demo or "",
- agent_image=agent.agent_image,
- creator=agent.creator_username or "",
- creator_avatar=agent.creator_avatar or "",
- sub_heading=agent.sub_heading,
- description=agent.description,
- categories=agent.categories,
- runs=agent.runs,
- rating=agent.rating,
- versions=agent.versions,
- agentGraphVersions=agent.agentGraphVersions,
- agentGraphId=agent.agentGraphId,
- last_updated=agent.updated_at,
- active_version_id=active_version_id,
- has_approved_version=has_approved_version,
- recommended_schedule_cron=recommended_schedule_cron,
- changelog=changelog_data,
- )
- except store_exceptions.AgentNotFoundError:
+ details = store_model.StoreAgentDetails.from_db(agent)
+ details.changelog = changelog_data
+ return details
+ except NotFoundError:
raise
except Exception as e:
logger.error(f"Error getting store agent details: {e}")
@@ -364,9 +286,8 @@ async def get_available_graph(
)
if not store_listing_version or not store_listing_version.AgentGraph:
- raise fastapi.HTTPException(
- status_code=404,
- detail=f"Store listing version {store_listing_version_id} not found",
+ raise NotFoundError(
+ f"Store listing version {store_listing_version_id} not found",
)
return (GraphModelWithoutNodes if hide_nodes else GraphModel).from_db(
@@ -385,52 +306,40 @@ async def get_store_agent_by_version_id(
try:
agent = await prisma.models.StoreAgent.prisma().find_first(
- where={"storeListingVersionId": store_listing_version_id}
+ where={"listing_version_id": store_listing_version_id}
)
if not agent:
logger.warning(f"Agent not found: {store_listing_version_id}")
- raise store_exceptions.AgentNotFoundError(
- f"Agent {store_listing_version_id} not found"
- )
+ raise NotFoundError(f"Agent {store_listing_version_id} not found")
logger.debug(f"Found agent details for {store_listing_version_id}")
- return store_model.StoreAgentDetails(
- store_listing_version_id=agent.storeListingVersionId,
- slug=agent.slug,
- agent_name=agent.agent_name,
- agent_video=agent.agent_video or "",
- agent_output_demo=agent.agent_output_demo or "",
- agent_image=agent.agent_image,
- creator=agent.creator_username or "",
- creator_avatar=agent.creator_avatar or "",
- sub_heading=agent.sub_heading,
- description=agent.description,
- categories=agent.categories,
- runs=agent.runs,
- rating=agent.rating,
- versions=agent.versions,
- agentGraphVersions=agent.agentGraphVersions,
- agentGraphId=agent.agentGraphId,
- last_updated=agent.updated_at,
- )
- except store_exceptions.AgentNotFoundError:
+ return store_model.StoreAgentDetails.from_db(agent)
+ except NotFoundError:
raise
except Exception as e:
logger.error(f"Error getting store agent details: {e}")
raise DatabaseError("Failed to fetch agent details") from e
+class StoreCreatorsSortOptions(Enum):
+ # NOTE: values correspond 1:1 to columns of the Creator view
+ AGENT_RATING = "agent_rating"
+ AGENT_RUNS = "agent_runs"
+ NUM_AGENTS = "num_agents"
+
+
async def get_store_creators(
featured: bool = False,
search_query: str | None = None,
- sorted_by: Literal["agent_rating", "agent_runs", "num_agents"] | None = None,
+ sorted_by: StoreCreatorsSortOptions | None = None,
page: int = 1,
page_size: int = 20,
) -> store_model.CreatorsResponse:
"""Get PUBLIC store creators from the Creator view"""
logger.debug(
- f"Getting store creators. featured={featured}, search={search_query}, sorted_by={sorted_by}, page={page}"
+ "Getting store creators: "
+ f"featured={featured}, query={search_query}, sorted_by={sorted_by}, page={page}"
)
# Build where clause with sanitized inputs
@@ -484,13 +393,19 @@ async def get_store_creators(
skip = (page - 1) * page_size
take = page_size
- # Add sorting with validated sort parameter
- order = []
- valid_sort_fields = {"agent_rating", "agent_runs", "num_agents"}
- if sorted_by in valid_sort_fields:
- order.append({sorted_by: "desc"})
- else:
- order.append({"username": "asc"})
+ order: prisma.types.CreatorOrderByInput = (
+ {"agent_rating": "desc"}
+ if sorted_by == StoreCreatorsSortOptions.AGENT_RATING
+ else (
+ {"agent_runs": "desc"}
+ if sorted_by == StoreCreatorsSortOptions.AGENT_RUNS
+ else (
+ {"num_agents": "desc"}
+ if sorted_by == StoreCreatorsSortOptions.NUM_AGENTS
+ else {"username": "asc"}
+ )
+ )
+ )
# Execute query with sanitized parameters
creators = await prisma.models.Creator.prisma().find_many(
@@ -502,17 +417,7 @@ async def get_store_creators(
# Convert to response model
creator_models = [
- store_model.Creator(
- username=creator.username,
- name=creator.name,
- description=creator.description,
- avatar_url=creator.avatar_url,
- num_agents=creator.num_agents,
- agent_rating=creator.agent_rating,
- agent_runs=creator.agent_runs,
- is_featured=creator.is_featured,
- )
- for creator in creators
+ store_model.CreatorDetails.from_db(creator) for creator in creators
]
logger.debug(f"Found {len(creator_models)} creators")
@@ -530,7 +435,7 @@ async def get_store_creators(
raise DatabaseError("Failed to fetch store creators") from e
-async def get_store_creator_details(
+async def get_store_creator(
username: str,
) -> store_model.CreatorDetails:
logger.debug(f"Getting store creator details for {username}")
@@ -546,16 +451,7 @@ async def get_store_creator_details(
raise store_exceptions.CreatorNotFoundError(f"Creator {username} not found")
logger.debug(f"Found creator details for {username}")
- return store_model.CreatorDetails(
- name=creator.name,
- username=creator.username,
- description=creator.description,
- links=creator.links,
- avatar_url=creator.avatar_url,
- agent_rating=creator.agent_rating,
- agent_runs=creator.agent_runs,
- top_categories=creator.top_categories,
- )
+ return store_model.CreatorDetails.from_db(creator)
except store_exceptions.CreatorNotFoundError:
raise
except Exception as e:
@@ -573,13 +469,16 @@ async def get_store_submissions(
# Calculate pagination values
skip = (page - 1) * page_size
- where = prisma.types.StoreSubmissionWhereInput(user_id=user_id)
+ where: prisma.types.StoreSubmissionWhereInput = {
+ "user_id": user_id,
+ "is_deleted": False,
+ }
# Query submissions from database
submissions = await prisma.models.StoreSubmission.prisma().find_many(
where=where,
skip=skip,
take=page_size,
- order=[{"date_submitted": "desc"}],
+ order=[{"submitted_at": "desc"}],
)
# Get total count for pagination
@@ -587,33 +486,10 @@ async def get_store_submissions(
total_pages = (total + page_size - 1) // page_size
- # Convert to response models
- submission_models = []
- for sub in submissions:
- submission_model = store_model.StoreSubmission(
- listing_id=sub.listing_id,
- agent_id=sub.agent_id,
- agent_version=sub.agent_version,
- name=sub.name,
- sub_heading=sub.sub_heading,
- slug=sub.slug,
- description=sub.description,
- instructions=getattr(sub, "instructions", None),
- image_urls=sub.image_urls or [],
- date_submitted=sub.date_submitted or datetime.now(tz=timezone.utc),
- status=sub.status,
- runs=sub.runs or 0,
- rating=sub.rating or 0.0,
- store_listing_version_id=sub.store_listing_version_id,
- reviewer_id=sub.reviewer_id,
- review_comments=sub.review_comments,
- # internal_comments omitted for regular users
- reviewed_at=sub.reviewed_at,
- changes_summary=sub.changes_summary,
- video_url=sub.video_url,
- categories=sub.categories,
- )
- submission_models.append(submission_model)
+ # Convert to response models (internal_comments omitted for regular users)
+ submission_models = [
+ store_model.StoreSubmission.from_db(sub) for sub in submissions
+ ]
logger.debug(f"Found {len(submission_models)} submissions")
return store_model.StoreSubmissionsResponse(
@@ -696,8 +572,8 @@ async def delete_store_submission(
async def create_store_submission(
user_id: str,
- agent_id: str,
- agent_version: int,
+ graph_id: str,
+ graph_version: int,
slug: str,
name: str,
video_url: str | None = None,
@@ -715,8 +591,8 @@ async def create_store_submission(
Args:
user_id: ID of the authenticated user submitting the listing
- agent_id: ID of the agent being submitted
- agent_version: Version of the agent being submitted
+ graph_id: ID of the agent graph being submitted
+ graph_version: Version of the agent graph being submitted
slug: URL slug for the listing
name: Name of the agent
video_url: Optional URL to video demo
@@ -730,7 +606,8 @@ async def create_store_submission(
StoreSubmission: The created store submission
"""
logger.debug(
- f"Creating store submission for user {user_id}, agent {agent_id} v{agent_version}"
+ f"Creating store submission for user #{user_id}, "
+ f"graph #{graph_id} v{graph_version}"
)
try:
@@ -739,122 +616,123 @@ async def create_store_submission(
c if c.isalpha() or c == "-" or c.isnumeric() else "" for c in slug
).lower()
- # First verify the agent belongs to this user
- agent = await prisma.models.AgentGraph.prisma().find_first(
- where=prisma.types.AgentGraphWhereInput(
- id=agent_id, version=agent_version, userId=user_id
- )
+ # First verify the agent graph belongs to this user
+ graph = await prisma.models.AgentGraph.prisma().find_first(
+ where={"id": graph_id, "version": graph_version, "userId": user_id},
+ include={"User": {"include": {"Profile": True}}},
)
- if not agent:
+ if not graph:
logger.warning(
- f"Agent not found for user {user_id}: {agent_id} v{agent_version}"
+ f"Agent graph {graph_id} v{graph_version} not found for user {user_id}"
)
- # Provide more user-friendly error message when agent_id is empty
- if not agent_id or agent_id.strip() == "":
- raise store_exceptions.AgentNotFoundError(
- "No agent selected. Please select an agent before submitting to the store."
+ # Provide more user-friendly error message when graph_id is empty
+ if not graph_id or graph_id.strip() == "":
+ raise ValueError(
+ "No agent selected. "
+ "Please select an agent before submitting to the store."
)
else:
- raise store_exceptions.AgentNotFoundError(
- f"Agent not found for this user. User ID: {user_id}, Agent ID: {agent_id}, Version: {agent_version}"
+ raise NotFoundError(
+ f"Agent #{graph_id} v{graph_version} not found "
+ f"for this user (#{user_id})"
)
- # Check if listing already exists for this agent
- existing_listing = await prisma.models.StoreListing.prisma().find_first(
- where=prisma.types.StoreListingWhereInput(
- agentGraphId=agent_id, owningUserId=user_id
+ if not graph.User or not graph.User.Profile:
+ logger.warning(f"User #{user_id} does not have a Profile")
+ raise PreconditionFailed(
+ "User must create a Marketplace Profile before submitting an agent"
)
- )
- if existing_listing is not None:
- logger.info(
- f"Listing already exists for agent {agent_id}, creating new version instead"
+ async with transaction() as tx:
+ # Determine next version number for this listing
+ existing_listing = await prisma.models.StoreListing.prisma(tx).find_unique(
+ where={"agentGraphId": graph_id},
+ include={
+ "Versions": {
+ # We just need the latest version and one of each status:
+ "order_by": {"version": "desc"},
+ "distinct": ["submissionStatus"],
+ "where": {"isDeleted": False},
+ }
+ },
)
+ next_version = 1
+ graph_has_pending_submissions = False
+ if existing_listing and existing_listing.Versions:
+ current_latest_version = max(
+ (slv.version for slv in existing_listing.Versions), default=0
+ )
+ next_version = current_latest_version + 1
- # Delegate to create_store_version which already handles this case correctly
- return await create_store_version(
- user_id=user_id,
- agent_id=agent_id,
- agent_version=agent_version,
- store_listing_id=existing_listing.id,
- name=name,
- video_url=video_url,
- image_urls=image_urls,
- description=description,
- instructions=instructions,
- sub_heading=sub_heading,
- categories=categories,
- changes_summary=changes_summary,
- )
+ graph_has_pending_submissions = any(
+ slv.submissionStatus == prisma.enums.SubmissionStatus.PENDING
+ for slv in existing_listing.Versions
+ )
- # If no existing listing, create a new one
- data = prisma.types.StoreListingCreateInput(
- slug=slug,
- agentGraphId=agent_id,
- agentGraphVersion=agent_version,
- owningUserId=user_id,
- createdAt=datetime.now(tz=timezone.utc),
- Versions={
- "create": [
- prisma.types.StoreListingVersionCreateInput(
- agentGraphId=agent_id,
- agentGraphVersion=agent_version,
- name=name,
- videoUrl=video_url,
- agentOutputDemoUrl=agent_output_demo_url,
- imageUrls=image_urls,
- description=description,
- instructions=instructions,
- categories=categories,
- subHeading=sub_heading,
- submissionStatus=prisma.enums.SubmissionStatus.PENDING,
- submittedAt=datetime.now(tz=timezone.utc),
- changesSummary=changes_summary,
- recommendedScheduleCron=recommended_schedule_cron,
- )
- ]
- },
- )
- listing = await prisma.models.StoreListing.prisma().create(
- data=data,
- include=prisma.types.StoreListingInclude(Versions=True),
- )
+ # Delete any currently PENDING submissions for the same graph
+ # in favor of the new submission
+ if graph_has_pending_submissions:
+ await prisma.models.StoreListingVersion.prisma(tx).update_many(
+ where={
+ "agentGraphId": graph.id,
+ "submissionStatus": prisma.enums.SubmissionStatus.PENDING,
+ "isDeleted": False,
+ },
+ data={"isDeleted": True},
+ )
- store_listing_version_id = (
- listing.Versions[0].id
- if listing.Versions is not None and len(listing.Versions) > 0
- else None
- )
+ new_submission = await prisma.models.StoreListingVersion.prisma(tx).create(
+ data={
+ "AgentGraph": {
+ "connect": {
+ "graphVersionId": {
+ "id": graph_id,
+ "version": graph_version,
+ }
+ }
+ },
+ "name": name,
+ "version": next_version,
+ "videoUrl": video_url,
+ "agentOutputDemoUrl": agent_output_demo_url,
+ "imageUrls": image_urls,
+ "description": description,
+ "instructions": instructions,
+ "categories": categories,
+ "subHeading": sub_heading,
+ "submissionStatus": prisma.enums.SubmissionStatus.PENDING,
+ "submittedAt": datetime.now(tz=timezone.utc),
+ "changesSummary": changes_summary,
+ "recommendedScheduleCron": recommended_schedule_cron,
+ "StoreListing": {
+ "connect_or_create": {
+ "where": {"agentGraphId": graph_id},
+ "create": {
+ "slug": slug,
+ "agentGraphId": graph_id,
+ "OwningUser": {"connect": {"id": user_id}},
+ "CreatorProfile": {"connect": {"userId": user_id}},
+ },
+ }
+ },
+ },
+ include={"StoreListing": True},
+ )
- logger.debug(f"Created store listing for agent {agent_id}")
- # Return submission details
- return store_model.StoreSubmission(
- listing_id=listing.id,
- agent_id=agent_id,
- agent_version=agent_version,
- name=name,
- slug=slug,
- sub_heading=sub_heading,
- description=description,
- instructions=instructions,
- image_urls=image_urls,
- date_submitted=listing.createdAt,
- status=prisma.enums.SubmissionStatus.PENDING,
- runs=0,
- rating=0.0,
- store_listing_version_id=store_listing_version_id,
- changes_summary=changes_summary,
- )
+ if not new_submission:
+ raise DatabaseError("Failed to create store listing version")
+
+ logger.debug(f"Created store listing for agent {graph_id}")
+ return store_model.StoreSubmission.from_listing_version(new_submission)
except prisma.errors.UniqueViolationError as exc:
# Attempt to check if the error was due to the slug field being unique
error_str = str(exc)
if "slug" in error_str.lower():
- logger.debug(
- f"Slug '{slug}' is already in use by another agent (agent_id: {agent_id}) for user {user_id}"
- )
+ logger.debug(f"Slug '{slug}' is already in use by graph #{graph_id}")
raise store_exceptions.SlugAlreadyInUseError(
- f"The URL slug '{slug}' is already in use by another one of your agents. Please choose a different slug."
+ f"The slug '{slug}' is already in use by another one of your agents. "
+ "Please choose a different slug."
) from exc
else:
# Reraise as a generic database error for other unique violations
@@ -862,7 +740,7 @@ async def create_store_submission(
f"Unique constraint violated (not slug): {error_str}"
) from exc
except (
- store_exceptions.AgentNotFoundError,
+ NotFoundError,
store_exceptions.ListingExistsError,
):
raise
@@ -891,9 +769,6 @@ async def edit_store_submission(
Args:
user_id: ID of the authenticated user editing the submission
store_listing_version_id: ID of the store listing version to edit
- agent_id: ID of the agent being submitted
- agent_version: Version of the agent being submitted
- slug: URL slug for the listing (only changeable for PENDING submissions)
name: Name of the agent
video_url: Optional URL to video demo
image_urls: List of image URLs for the listing
@@ -916,13 +791,7 @@ async def edit_store_submission(
where=prisma.types.StoreListingVersionWhereInput(
id=store_listing_version_id
),
- include={
- "StoreListing": {
- "include": {
- "Versions": {"order_by": {"version": "desc"}, "take": 1}
- }
- }
- },
+ include={"StoreListing": True},
)
if not current_version:
@@ -930,7 +799,7 @@ async def edit_store_submission(
f"Store listing version not found: {store_listing_version_id}"
)
- # Verify the user owns this submission
+ # Verify the user owns this listing (submission)
if (
not current_version.StoreListing
or current_version.StoreListing.owningUserId != user_id
@@ -939,13 +808,12 @@ async def edit_store_submission(
f"User {user_id} does not own submission {store_listing_version_id}"
)
- # Currently we are not allowing user to update the agent associated with a submission
- # If we allow it in future, then we need a check here to verify the agent belongs to this user.
-
# Only allow editing of PENDING submissions
if current_version.submissionStatus != prisma.enums.SubmissionStatus.PENDING:
+ display_status = current_version.submissionStatus.value.lower()
raise store_exceptions.InvalidOperationError(
- f"Cannot edit a {current_version.submissionStatus.value.lower()} submission. Only pending submissions can be edited."
+ f"Cannot edit a {display_status} submission. "
+ "Only pending submissions can be edited."
)
# For PENDING submissions, we can update the existing version
@@ -964,39 +832,22 @@ async def edit_store_submission(
recommendedScheduleCron=recommended_schedule_cron,
instructions=instructions,
),
+ include={"StoreListing": True},
)
+ if not updated_version:
+ raise DatabaseError("Failed to update store listing version")
logger.debug(
- f"Updated existing version {store_listing_version_id} for agent {current_version.agentGraphId}"
+ f"Updated existing listing version {store_listing_version_id} "
+ f"for graph {current_version.agentGraphId}"
)
- if not updated_version:
- raise DatabaseError("Failed to update store listing version")
- return store_model.StoreSubmission(
- listing_id=current_version.StoreListing.id,
- agent_id=current_version.agentGraphId,
- agent_version=current_version.agentGraphVersion,
- name=name,
- sub_heading=sub_heading,
- slug=current_version.StoreListing.slug,
- description=description,
- instructions=instructions,
- image_urls=image_urls,
- date_submitted=updated_version.submittedAt or updated_version.createdAt,
- status=updated_version.submissionStatus,
- runs=0,
- rating=0.0,
- store_listing_version_id=updated_version.id,
- changes_summary=changes_summary,
- video_url=video_url,
- categories=categories,
- version=updated_version.version,
- )
+ return store_model.StoreSubmission.from_listing_version(updated_version)
except (
store_exceptions.SubmissionNotFoundError,
store_exceptions.UnauthorizedError,
- store_exceptions.AgentNotFoundError,
+ NotFoundError,
store_exceptions.ListingExistsError,
store_exceptions.InvalidOperationError,
):
@@ -1006,163 +857,6 @@ async def edit_store_submission(
raise DatabaseError("Failed to edit store submission") from e
-async def create_store_version(
- user_id: str,
- agent_id: str,
- agent_version: int,
- store_listing_id: str,
- name: str,
- video_url: str | None = None,
- agent_output_demo_url: str | None = None,
- image_urls: list[str] = [],
- description: str = "",
- instructions: str | None = None,
- sub_heading: str = "",
- categories: list[str] = [],
- changes_summary: str | None = "Initial submission",
- recommended_schedule_cron: str | None = None,
-) -> store_model.StoreSubmission:
- """
- Create a new version for an existing store listing
-
- Args:
- user_id: ID of the authenticated user submitting the version
- agent_id: ID of the agent being submitted
- agent_version: Version of the agent being submitted
- store_listing_id: ID of the existing store listing
- name: Name of the agent
- video_url: Optional URL to video demo
- image_urls: List of image URLs for the listing
- description: Description of the agent
- categories: List of categories for the agent
- changes_summary: Summary of changes from the previous version
-
- Returns:
- StoreSubmission: The created store submission
- """
- logger.debug(
- f"Creating new version for store listing {store_listing_id} for user {user_id}, agent {agent_id} v{agent_version}"
- )
-
- try:
- # First verify the listing belongs to this user
- listing = await prisma.models.StoreListing.prisma().find_first(
- where=prisma.types.StoreListingWhereInput(
- id=store_listing_id, owningUserId=user_id
- ),
- include={"Versions": {"order_by": {"version": "desc"}, "take": 1}},
- )
-
- if not listing:
- raise store_exceptions.ListingNotFoundError(
- f"Store listing not found. User ID: {user_id}, Listing ID: {store_listing_id}"
- )
-
- # Verify the agent belongs to this user
- agent = await prisma.models.AgentGraph.prisma().find_first(
- where=prisma.types.AgentGraphWhereInput(
- id=agent_id, version=agent_version, userId=user_id
- )
- )
-
- if not agent:
- raise store_exceptions.AgentNotFoundError(
- f"Agent not found for this user. User ID: {user_id}, Agent ID: {agent_id}, Version: {agent_version}"
- )
-
- # Check if there's already a PENDING submission for this agent (any version)
- existing_pending_submission = (
- await prisma.models.StoreListingVersion.prisma().find_first(
- where=prisma.types.StoreListingVersionWhereInput(
- storeListingId=store_listing_id,
- agentGraphId=agent_id,
- submissionStatus=prisma.enums.SubmissionStatus.PENDING,
- isDeleted=False,
- )
- )
- )
-
- # Handle existing pending submission and create new one atomically
- async with transaction() as tx:
- # Get the latest version number first
- latest_listing = await prisma.models.StoreListing.prisma(tx).find_first(
- where=prisma.types.StoreListingWhereInput(
- id=store_listing_id, owningUserId=user_id
- ),
- include={"Versions": {"order_by": {"version": "desc"}, "take": 1}},
- )
-
- if not latest_listing:
- raise store_exceptions.ListingNotFoundError(
- f"Store listing not found. User ID: {user_id}, Listing ID: {store_listing_id}"
- )
-
- latest_version = (
- latest_listing.Versions[0] if latest_listing.Versions else None
- )
- next_version = (latest_version.version + 1) if latest_version else 1
-
- # If there's an existing pending submission, delete it atomically before creating new one
- if existing_pending_submission:
- logger.info(
- f"Found existing PENDING submission for agent {agent_id} (was v{existing_pending_submission.agentGraphVersion}, now v{agent_version}), replacing existing submission instead of creating duplicate"
- )
- await prisma.models.StoreListingVersion.prisma(tx).delete(
- where={"id": existing_pending_submission.id}
- )
- logger.debug(
- f"Deleted existing pending submission {existing_pending_submission.id}"
- )
-
- # Create a new version for the existing listing
- new_version = await prisma.models.StoreListingVersion.prisma(tx).create(
- data=prisma.types.StoreListingVersionCreateInput(
- version=next_version,
- agentGraphId=agent_id,
- agentGraphVersion=agent_version,
- name=name,
- videoUrl=video_url,
- agentOutputDemoUrl=agent_output_demo_url,
- imageUrls=image_urls,
- description=description,
- instructions=instructions,
- categories=categories,
- subHeading=sub_heading,
- submissionStatus=prisma.enums.SubmissionStatus.PENDING,
- submittedAt=datetime.now(),
- changesSummary=changes_summary,
- recommendedScheduleCron=recommended_schedule_cron,
- storeListingId=store_listing_id,
- )
- )
-
- logger.debug(
- f"Created new version for listing {store_listing_id} of agent {agent_id}"
- )
- # Return submission details
- return store_model.StoreSubmission(
- listing_id=listing.id,
- agent_id=agent_id,
- agent_version=agent_version,
- name=name,
- slug=listing.slug,
- sub_heading=sub_heading,
- description=description,
- instructions=instructions,
- image_urls=image_urls,
- date_submitted=datetime.now(),
- status=prisma.enums.SubmissionStatus.PENDING,
- runs=0,
- rating=0.0,
- store_listing_version_id=new_version.id,
- changes_summary=changes_summary,
- version=next_version,
- )
-
- except prisma.errors.PrismaError as e:
- raise DatabaseError("Failed to create new store version") from e
-
-
async def create_store_review(
user_id: str,
store_listing_version_id: str,
@@ -1215,13 +909,7 @@ async def get_user_profile(
if not profile:
return None
- return store_model.ProfileDetails(
- name=profile.name,
- username=profile.username,
- description=profile.description,
- links=profile.links,
- avatar_url=profile.avatarUrl,
- )
+ return store_model.ProfileDetails.from_db(profile)
except Exception as e:
logger.error(f"Error getting user profile: {e}")
raise DatabaseError("Failed to get user profile") from e
@@ -1229,14 +917,14 @@ async def get_user_profile(
async def update_profile(
user_id: str, profile: store_model.Profile
-) -> store_model.CreatorDetails:
+) -> store_model.ProfileDetails:
"""
Update the store profile for a user or create a new one if it doesn't exist.
Args:
user_id: ID of the authenticated user
profile: Updated profile details
Returns:
- CreatorDetails: The updated or created profile details
+ ProfileDetails: The updated or created profile details
Raises:
DatabaseError: If there's an issue updating or creating the profile
"""
@@ -1259,10 +947,12 @@ async def update_profile(
# Verify that the user is authorized to update this profile
if existing_profile.userId != user_id:
logger.error(
- f"Unauthorized update attempt for profile {existing_profile.id} by user {user_id}"
+ f"Unauthorized update attempt for profile {existing_profile.id} "
+ f"by user {user_id}"
)
raise DatabaseError(
- f"Unauthorized update attempt for profile {existing_profile.id} by user {user_id}"
+ f"Unauthorized update attempt for profile {existing_profile.id} "
+ f"by user {user_id}"
)
logger.debug(f"Updating existing profile for user {user_id}")
@@ -1288,16 +978,7 @@ async def update_profile(
logger.error(f"Failed to update profile for user {user_id}")
raise DatabaseError("Failed to update profile")
- return store_model.CreatorDetails(
- name=updated_profile.name,
- username=updated_profile.username,
- description=updated_profile.description,
- links=updated_profile.links,
- avatar_url=updated_profile.avatarUrl or "",
- agent_rating=0.0,
- agent_runs=0,
- top_categories=[],
- )
+ return store_model.ProfileDetails.from_db(updated_profile)
except prisma.errors.PrismaError as e:
logger.error(f"Database error updating profile: {e}")
@@ -1308,23 +989,20 @@ async def get_my_agents(
user_id: str,
page: int = 1,
page_size: int = 20,
-) -> store_model.MyAgentsResponse:
+) -> store_model.MyUnpublishedAgentsResponse:
"""Get the agents for the authenticated user"""
logger.debug(f"Getting my agents for user {user_id}, page={page}")
try:
search_filter: prisma.types.LibraryAgentWhereInput = {
"userId": user_id,
+ # Filter for unpublished agents only:
"AgentGraph": {
"is": {
- "StoreListings": {
+ "StoreListingVersions": {
"none": {
- "isDeleted": False,
- "Versions": {
- "some": {
- "isAvailable": True,
- }
- },
+ "isAvailable": True,
+ "StoreListing": {"is": {"isDeleted": False}},
}
}
}
@@ -1345,9 +1023,9 @@ async def get_my_agents(
total_pages = (total + page_size - 1) // page_size
my_agents = [
- store_model.MyAgent(
- agent_id=graph.id,
- agent_version=graph.version,
+ store_model.MyUnpublishedAgent(
+ graph_id=graph.id,
+ graph_version=graph.version,
agent_name=graph.name or "",
last_edited=graph.updatedAt or graph.createdAt,
description=graph.description or "",
@@ -1358,7 +1036,7 @@ async def get_my_agents(
if (graph := library_agent.AgentGraph)
]
- return store_model.MyAgentsResponse(
+ return store_model.MyUnpublishedAgentsResponse(
agents=my_agents,
pagination=store_model.Pagination(
current_page=page,
@@ -1374,26 +1052,25 @@ async def get_my_agents(
async def get_agent(store_listing_version_id: str) -> GraphModel:
"""Get agent using the version ID and store listing version ID."""
- store_listing_version = (
- await prisma.models.StoreListingVersion.prisma().find_unique(
- where={"id": store_listing_version_id}
- )
+ slv = await prisma.models.StoreListingVersion.prisma().find_unique(
+ where={"id": store_listing_version_id}
)
- if not store_listing_version:
- raise ValueError(f"Store listing version {store_listing_version_id} not found")
+ if not slv:
+ raise NotFoundError(
+ f"Store listing version {store_listing_version_id} not found"
+ )
graph = await get_graph(
- graph_id=store_listing_version.agentGraphId,
- version=store_listing_version.agentGraphVersion,
+ graph_id=slv.agentGraphId,
+ version=slv.agentGraphVersion,
user_id=None,
for_export=True,
)
if not graph:
- raise ValueError(
- f"Agent {store_listing_version.agentGraphId} v{store_listing_version.agentGraphVersion} not found"
+ raise NotFoundError(
+ f"Graph {slv.agentGraphId} v{slv.agentGraphVersion} not found"
)
-
return graph
@@ -1402,140 +1079,35 @@ async def get_agent(store_listing_version_id: str) -> GraphModel:
#####################################################
-async def _approve_sub_agent(
- tx,
- sub_graph: prisma.models.AgentGraph,
- main_agent_name: str,
- main_agent_version: int,
- main_agent_user_id: str,
-) -> None:
- """Approve a single sub-agent by creating/updating store listings as needed"""
- heading = f"Sub-agent of {main_agent_name} v{main_agent_version}"
-
- # Find existing listing for this sub-agent
- listing = await prisma.models.StoreListing.prisma(tx).find_first(
- where={"agentGraphId": sub_graph.id, "isDeleted": False},
- include={"Versions": True},
- )
-
- # Early return: Create new listing if none exists
- if not listing:
- await prisma.models.StoreListing.prisma(tx).create(
- data=prisma.types.StoreListingCreateInput(
- slug=f"sub-agent-{sub_graph.id[:8]}",
- agentGraphId=sub_graph.id,
- agentGraphVersion=sub_graph.version,
- owningUserId=main_agent_user_id,
- hasApprovedVersion=True,
- Versions={
- "create": [
- _create_sub_agent_version_data(
- sub_graph, heading, main_agent_name
- )
- ]
- },
- )
- )
- return
-
- # Find version matching this sub-graph
- matching_version = next(
- (
- v
- for v in listing.Versions or []
- if v.agentGraphId == sub_graph.id
- and v.agentGraphVersion == sub_graph.version
- ),
- None,
- )
-
- # Early return: Approve existing version if found and not already approved
- if matching_version:
- if matching_version.submissionStatus == prisma.enums.SubmissionStatus.APPROVED:
- return # Already approved, nothing to do
-
- await prisma.models.StoreListingVersion.prisma(tx).update(
- where={"id": matching_version.id},
- data={
- "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
- "reviewedAt": datetime.now(tz=timezone.utc),
- },
- )
- await prisma.models.StoreListing.prisma(tx).update(
- where={"id": listing.id}, data={"hasApprovedVersion": True}
- )
- return
-
- # Create new version if no matching version found
- next_version = max((v.version for v in listing.Versions or []), default=0) + 1
- await prisma.models.StoreListingVersion.prisma(tx).create(
- data={
- **_create_sub_agent_version_data(sub_graph, heading, main_agent_name),
- "version": next_version,
- "storeListingId": listing.id,
- }
- )
- await prisma.models.StoreListing.prisma(tx).update(
- where={"id": listing.id}, data={"hasApprovedVersion": True}
- )
-
-
-def _create_sub_agent_version_data(
- sub_graph: prisma.models.AgentGraph, heading: str, main_agent_name: str
-) -> prisma.types.StoreListingVersionCreateInput:
- """Create store listing version data for a sub-agent"""
- return prisma.types.StoreListingVersionCreateInput(
- agentGraphId=sub_graph.id,
- agentGraphVersion=sub_graph.version,
- name=sub_graph.name or heading,
- submissionStatus=prisma.enums.SubmissionStatus.APPROVED,
- subHeading=heading,
- description=(
- f"{heading}: {sub_graph.description}" if sub_graph.description else heading
- ),
- changesSummary=f"Auto-approved as sub-agent of {main_agent_name}",
- isAvailable=False,
- submittedAt=datetime.now(tz=timezone.utc),
- imageUrls=[], # Sub-agents don't need images
- categories=[], # Sub-agents don't need categories
- )
-
-
async def review_store_submission(
store_listing_version_id: str,
is_approved: bool,
external_comments: str,
internal_comments: str,
reviewer_id: str,
-) -> store_model.StoreSubmission:
+) -> store_model.StoreSubmissionAdminView:
"""Review a store listing submission as an admin."""
try:
- store_listing_version = (
- await prisma.models.StoreListingVersion.prisma().find_unique(
- where={"id": store_listing_version_id},
- include={
- "StoreListing": True,
- "AgentGraph": {"include": {**AGENT_GRAPH_INCLUDE, "User": True}},
- "Reviewer": True,
- },
- )
+ submission = await prisma.models.StoreListingVersion.prisma().find_unique(
+ where={"id": store_listing_version_id},
+ include={"AgentGraph": {"include": AGENT_GRAPH_INCLUDE}},
)
- if not store_listing_version or not store_listing_version.StoreListing:
- raise fastapi.HTTPException(
- status_code=404,
- detail=f"Store listing version {store_listing_version_id} not found",
+ if not submission:
+ raise NotFoundError(
+ f"Store listing version {store_listing_version_id} not found"
)
+ assert submission.AgentGraph is not None
+ creator_user_id = submission.AgentGraph.userId
# Check if we're rejecting an already approved agent
is_rejecting_approved = (
not is_approved
- and store_listing_version.submissionStatus
- == prisma.enums.SubmissionStatus.APPROVED
+ and submission.submissionStatus == prisma.enums.SubmissionStatus.APPROVED
)
# If approving, update the listing to indicate it has an approved version
- if is_approved and store_listing_version.AgentGraph:
+ if is_approved:
async with transaction() as tx:
# Handle sub-agent approvals in transaction
await asyncio.gather(
@@ -1543,13 +1115,11 @@ async def review_store_submission(
_approve_sub_agent(
tx,
sub_graph,
- store_listing_version.name,
- store_listing_version.agentGraphVersion,
- store_listing_version.StoreListing.owningUserId,
- )
- for sub_graph in await get_sub_graphs(
- store_listing_version.AgentGraph
+ submission.name,
+ submission.agentGraphVersion,
+ creator_user_id,
)
+ for sub_graph in await get_sub_graphs(submission.AgentGraph)
]
)
@@ -1557,15 +1127,15 @@ async def review_store_submission(
await prisma.models.AgentGraph.prisma(tx).update(
where={
"graphVersionId": {
- "id": store_listing_version.agentGraphId,
- "version": store_listing_version.agentGraphVersion,
+ "id": submission.agentGraphId,
+ "version": submission.agentGraphVersion,
}
},
data={
- "name": store_listing_version.name,
- "description": store_listing_version.description,
- "recommendedScheduleCron": store_listing_version.recommendedScheduleCron,
- "instructions": store_listing_version.instructions,
+ "name": submission.name,
+ "description": submission.description,
+ "recommendedScheduleCron": submission.recommendedScheduleCron,
+ "instructions": submission.instructions,
},
)
@@ -1573,15 +1143,15 @@ async def review_store_submission(
# Inside transaction: if embedding fails, entire transaction rolls back
await ensure_embedding(
version_id=store_listing_version_id,
- name=store_listing_version.name,
- description=store_listing_version.description,
- sub_heading=store_listing_version.subHeading,
- categories=store_listing_version.categories or [],
+ name=submission.name,
+ description=submission.description,
+ sub_heading=submission.subHeading,
+ categories=submission.categories,
tx=tx,
)
await prisma.models.StoreListing.prisma(tx).update(
- where={"id": store_listing_version.StoreListing.id},
+ where={"id": submission.storeListingId},
data={
"hasApprovedVersion": True,
"ActiveVersion": {"connect": {"id": store_listing_version_id}},
@@ -1594,7 +1164,7 @@ async def review_store_submission(
other_approved = (
await prisma.models.StoreListingVersion.prisma().find_first(
where={
- "storeListingId": store_listing_version.StoreListing.id,
+ "storeListingId": submission.storeListingId,
"id": {"not": store_listing_version_id},
"submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
}
@@ -1604,7 +1174,7 @@ async def review_store_submission(
if not other_approved:
# No other approved versions, update hasApprovedVersion to False
await prisma.models.StoreListing.prisma().update(
- where={"id": store_listing_version.StoreListing.id},
+ where={"id": submission.storeListingId},
data={
"hasApprovedVersion": False,
"ActiveVersion": {"disconnect": True},
@@ -1613,7 +1183,7 @@ async def review_store_submission(
else:
# Set the most recent other approved version as active
await prisma.models.StoreListing.prisma().update(
- where={"id": store_listing_version.StoreListing.id},
+ where={"id": submission.storeListingId},
data={
"ActiveVersion": {"connect": {"id": other_approved.id}},
},
@@ -1628,142 +1198,226 @@ async def review_store_submission(
# Update the version with review information
update_data: prisma.types.StoreListingVersionUpdateInput = {
"submissionStatus": submission_status,
+ "reviewedAt": datetime.now(tz=timezone.utc),
+ "Reviewer": {"connect": {"id": reviewer_id}},
"reviewComments": external_comments,
"internalComments": internal_comments,
- "Reviewer": {"connect": {"id": reviewer_id}},
- "StoreListing": {"connect": {"id": store_listing_version.StoreListing.id}},
- "reviewedAt": datetime.now(tz=timezone.utc),
}
# Update the version
- submission = await prisma.models.StoreListingVersion.prisma().update(
+ reviewed_submission = await prisma.models.StoreListingVersion.prisma().update(
where={"id": store_listing_version_id},
data=update_data,
- include={"StoreListing": True},
+ include={
+ "StoreListing": True, # required for StoreSubmissionAdminView
+ "Reviewer": True, # used in _send_submission_review_notification
+ },
)
- if not submission:
+ if not reviewed_submission:
raise DatabaseError(
f"Failed to update store listing version {store_listing_version_id}"
)
- # Send email notification to the agent creator
- if store_listing_version.AgentGraph and store_listing_version.AgentGraph.User:
- agent_creator = store_listing_version.AgentGraph.User
- reviewer = (
- store_listing_version.Reviewer
- if store_listing_version.Reviewer
- else None
+ try:
+ await _send_submission_review_notification(
+ creator_user_id,
+ is_approved,
+ external_comments,
+ reviewed_submission,
)
+ except Exception as e:
+ logger.error(f"Failed to send email notification for agent review: {e}")
+ # Don't fail the review process if email sending fails
- try:
- base_url = (
- settings.config.frontend_base_url
- or settings.config.platform_base_url
- )
-
- if is_approved:
- store_agent = (
- await prisma.models.StoreAgent.prisma().find_first_or_raise(
- where={"storeListingVersionId": submission.id}
- )
- )
-
- # Send approval notification
- notification_data = AgentApprovalData(
- agent_name=submission.name,
- agent_id=submission.agentGraphId,
- agent_version=submission.agentGraphVersion,
- reviewer_name=(
- reviewer.name
- if reviewer and reviewer.name
- else DEFAULT_ADMIN_NAME
- ),
- reviewer_email=(
- reviewer.email if reviewer else DEFAULT_ADMIN_EMAIL
- ),
- comments=external_comments,
- reviewed_at=submission.reviewedAt
- or datetime.now(tz=timezone.utc),
- store_url=f"{base_url}/marketplace/agent/{store_agent.creator_username}/{store_agent.slug}",
- )
-
- notification_event = NotificationEventModel[AgentApprovalData](
- user_id=agent_creator.id,
- type=prisma.enums.NotificationType.AGENT_APPROVED,
- data=notification_data,
- )
- else:
- # Send rejection notification
- notification_data = AgentRejectionData(
- agent_name=submission.name,
- agent_id=submission.agentGraphId,
- agent_version=submission.agentGraphVersion,
- reviewer_name=(
- reviewer.name
- if reviewer and reviewer.name
- else DEFAULT_ADMIN_NAME
- ),
- reviewer_email=(
- reviewer.email if reviewer else DEFAULT_ADMIN_EMAIL
- ),
- comments=external_comments,
- reviewed_at=submission.reviewedAt
- or datetime.now(tz=timezone.utc),
- resubmit_url=f"{base_url}/build?flowID={submission.agentGraphId}",
- )
-
- notification_event = NotificationEventModel[AgentRejectionData](
- user_id=agent_creator.id,
- type=prisma.enums.NotificationType.AGENT_REJECTED,
- data=notification_data,
- )
-
- # Queue the notification for immediate sending
- await queue_notification_async(notification_event)
- logger.info(
- f"Queued {'approval' if is_approved else 'rejection'} notification for user {agent_creator.id} and agent {submission.name}"
- )
-
- except Exception as e:
- logger.error(f"Failed to send email notification for agent review: {e}")
- # Don't fail the review process if email sending fails
- pass
-
- # Convert to Pydantic model for consistency
- return store_model.StoreSubmission(
- listing_id=(submission.StoreListing.id if submission.StoreListing else ""),
- agent_id=submission.agentGraphId,
- agent_version=submission.agentGraphVersion,
- name=submission.name,
- sub_heading=submission.subHeading,
- slug=(submission.StoreListing.slug if submission.StoreListing else ""),
- description=submission.description,
- instructions=submission.instructions,
- image_urls=submission.imageUrls or [],
- date_submitted=submission.submittedAt or submission.createdAt,
- status=submission.submissionStatus,
- runs=0, # Default values since we don't have this data here
- rating=0.0,
- store_listing_version_id=submission.id,
- reviewer_id=submission.reviewerId,
- review_comments=submission.reviewComments,
- internal_comments=submission.internalComments,
- reviewed_at=submission.reviewedAt,
- changes_summary=submission.changesSummary,
+ return store_model.StoreSubmissionAdminView.from_listing_version(
+ reviewed_submission
)
+ except NotFoundError:
+ raise
except Exception as e:
logger.error(f"Could not create store submission review: {e}")
raise DatabaseError("Failed to create store submission review") from e
+async def _approve_sub_agent(
+ tx,
+ sub_graph: prisma.models.AgentGraph,
+ main_agent_name: str,
+ main_agent_graph_version: int,
+ main_agent_user_id: str,
+) -> None:
+ """Approve a single sub-agent by creating/updating store listings as needed"""
+ heading = f"Sub-agent of {main_agent_name} v{main_agent_graph_version}"
+
+ # Find existing listing for this sub-agent
+ listing = await prisma.models.StoreListing.prisma(tx).find_first(
+ where={"agentGraphId": sub_graph.id, "isDeleted": False},
+ include={"Versions": True},
+ )
+
+ # Early return: Create new listing if none exists
+ if not listing:
+ await prisma.models.StoreListing.prisma(tx).create(
+ data=prisma.types.StoreListingCreateInput(
+ slug=f"sub-agent-{sub_graph.id[:8]}",
+ agentGraphId=sub_graph.id,
+ owningUserId=main_agent_user_id,
+ hasApprovedVersion=True,
+ Versions={
+ "create": [
+ _create_sub_agent_version_data(
+ sub_graph, heading, main_agent_name
+ )
+ ]
+ },
+ )
+ )
+ return
+
+ # Find version matching this sub-graph
+ matching_version = next(
+ (
+ v
+ for v in listing.Versions or []
+ if v.agentGraphId == sub_graph.id
+ and v.agentGraphVersion == sub_graph.version
+ ),
+ None,
+ )
+
+ # Early return: Approve existing version if found and not already approved
+ if matching_version:
+ if matching_version.submissionStatus == prisma.enums.SubmissionStatus.APPROVED:
+ return # Already approved, nothing to do
+
+ await prisma.models.StoreListingVersion.prisma(tx).update(
+ where={"id": matching_version.id},
+ data={
+ "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
+ "reviewedAt": datetime.now(tz=timezone.utc),
+ },
+ )
+ await prisma.models.StoreListing.prisma(tx).update(
+ where={"id": listing.id}, data={"hasApprovedVersion": True}
+ )
+ return
+
+ # Create new version if no matching version found
+ next_version = max((v.version for v in listing.Versions or []), default=0) + 1
+ await prisma.models.StoreListingVersion.prisma(tx).create(
+ data={
+ **_create_sub_agent_version_data(sub_graph, heading, main_agent_name),
+ "version": next_version,
+ "storeListingId": listing.id,
+ }
+ )
+ await prisma.models.StoreListing.prisma(tx).update(
+ where={"id": listing.id}, data={"hasApprovedVersion": True}
+ )
+
+
+def _create_sub_agent_version_data(
+ sub_graph: prisma.models.AgentGraph, heading: str, main_agent_name: str
+) -> prisma.types.StoreListingVersionCreateInput:
+ """Create store listing version data for a sub-agent"""
+ return prisma.types.StoreListingVersionCreateInput(
+ agentGraphId=sub_graph.id,
+ agentGraphVersion=sub_graph.version,
+ name=sub_graph.name or heading,
+ submissionStatus=prisma.enums.SubmissionStatus.APPROVED,
+ subHeading=heading,
+ description=(
+ f"{heading}: {sub_graph.description}" if sub_graph.description else heading
+ ),
+ changesSummary=f"Auto-approved as sub-agent of {main_agent_name}",
+ isAvailable=False,
+ submittedAt=datetime.now(tz=timezone.utc),
+ imageUrls=[], # Sub-agents don't need images
+ categories=[], # Sub-agents don't need categories
+ )
+
+
+async def _send_submission_review_notification(
+ creator_user_id: str,
+ is_approved: bool,
+ external_comments: str,
+ reviewed_listing_version: prisma.models.StoreListingVersion,
+):
+ """Send email notification to the agent creator"""
+ reviewer = (
+ reviewed_listing_version.Reviewer if reviewed_listing_version.Reviewer else None
+ )
+
+ base_url = settings.config.frontend_base_url or settings.config.platform_base_url
+
+ if is_approved:
+ store_agent = await prisma.models.StoreAgent.prisma().find_first_or_raise(
+ where={"listing_version_id": reviewed_listing_version.id}
+ )
+
+ # Send approval notification
+ creator_username = store_agent.creator_username
+ notification_data = AgentApprovalData(
+ agent_name=reviewed_listing_version.name,
+ graph_id=reviewed_listing_version.agentGraphId,
+ graph_version=reviewed_listing_version.agentGraphVersion,
+ reviewer_name=(
+ reviewer.name if reviewer and reviewer.name else DEFAULT_ADMIN_NAME
+ ),
+ reviewer_email=(reviewer.email if reviewer else DEFAULT_ADMIN_EMAIL),
+ comments=external_comments,
+ reviewed_at=(
+ reviewed_listing_version.reviewedAt or datetime.now(tz=timezone.utc)
+ ),
+ store_url=(
+ f"{base_url}/marketplace/agent/{creator_username}/{store_agent.slug}"
+ ),
+ )
+
+ notification_event = NotificationEventModel[AgentApprovalData](
+ user_id=creator_user_id,
+ type=prisma.enums.NotificationType.AGENT_APPROVED,
+ data=notification_data,
+ )
+ else:
+ # Send rejection notification
+ graph_id = reviewed_listing_version.agentGraphId
+ notification_data = AgentRejectionData(
+ agent_name=reviewed_listing_version.name,
+ graph_id=reviewed_listing_version.agentGraphId,
+ graph_version=reviewed_listing_version.agentGraphVersion,
+ reviewer_name=(
+ reviewer.name if reviewer and reviewer.name else DEFAULT_ADMIN_NAME
+ ),
+ reviewer_email=(reviewer.email if reviewer else DEFAULT_ADMIN_EMAIL),
+ comments=external_comments,
+ reviewed_at=reviewed_listing_version.reviewedAt
+ or datetime.now(tz=timezone.utc),
+ resubmit_url=f"{base_url}/build?flowID={graph_id}",
+ )
+
+ notification_event = NotificationEventModel[AgentRejectionData](
+ user_id=creator_user_id,
+ type=prisma.enums.NotificationType.AGENT_REJECTED,
+ data=notification_data,
+ )
+
+ # Queue the notification for immediate sending
+ await queue_notification_async(notification_event)
+ logger.info(
+ f"Queued {'approval' if is_approved else 'rejection'} notification "
+ f"for agent '{reviewed_listing_version.name}' of user #{creator_user_id}"
+ )
+
+
async def get_admin_listings_with_versions(
status: prisma.enums.SubmissionStatus | None = None,
search_query: str | None = None,
page: int = 1,
page_size: int = 20,
-) -> store_model.StoreListingsWithVersionsResponse:
+) -> store_model.StoreListingsWithVersionsAdminViewResponse:
"""
Get store listings for admins with all their versions.
@@ -1774,160 +1428,128 @@ async def get_admin_listings_with_versions(
page_size: Number of items per page
Returns:
- StoreListingsWithVersionsResponse with listings and their versions
+ Paginated listings with their versions
"""
logger.debug(
- f"Getting admin store listings with status={status}, search={search_query}, page={page}"
+ "Getting admin store listings: "
+ f"status={status}, search={search_query}, page={page}"
)
- try:
- # Build the where clause for StoreListing
- where_dict: prisma.types.StoreListingWhereInput = {
- "isDeleted": False,
- }
- if status:
- where_dict["Versions"] = {"some": {"submissionStatus": status}}
+ # Build the where clause for StoreListing
+ store_listing_filter: prisma.types.StoreListingWhereInput = {
+ "isDeleted": False,
+ }
+ if status:
+ store_listing_filter["Versions"] = {"some": {"submissionStatus": status}}
- if search_query:
- # Find users with matching email
- matching_users = await prisma.models.User.prisma().find_many(
- where={"email": {"contains": search_query, "mode": "insensitive"}},
- )
+ if search_query:
+ # Find users with matching email
+ matching_users = await prisma.models.User.prisma().find_many(
+ where={"email": {"contains": search_query, "mode": "insensitive"}},
+ )
- user_ids = [user.id for user in matching_users]
+ user_ids = [user.id for user in matching_users]
- # Set up OR conditions
- where_dict["OR"] = [
- {"slug": {"contains": search_query, "mode": "insensitive"}},
- {
- "Versions": {
- "some": {
- "name": {"contains": search_query, "mode": "insensitive"}
- }
- }
- },
- {
- "Versions": {
- "some": {
- "description": {
- "contains": search_query,
- "mode": "insensitive",
- }
+ # Set up OR conditions
+ store_listing_filter["OR"] = [
+ {"slug": {"contains": search_query, "mode": "insensitive"}},
+ {
+ "Versions": {
+ "some": {"name": {"contains": search_query, "mode": "insensitive"}}
+ }
+ },
+ {
+ "Versions": {
+ "some": {
+ "description": {
+ "contains": search_query,
+ "mode": "insensitive",
}
}
- },
- {
- "Versions": {
- "some": {
- "subHeading": {
- "contains": search_query,
- "mode": "insensitive",
- }
+ }
+ },
+ {
+ "Versions": {
+ "some": {
+ "subHeading": {
+ "contains": search_query,
+ "mode": "insensitive",
}
}
- },
- ]
-
- # Add user_id condition if any users matched
- if user_ids:
- where_dict["OR"].append({"owningUserId": {"in": user_ids}})
-
- # Calculate pagination
- skip = (page - 1) * page_size
-
- # Create proper Prisma types for the query
- where = prisma.types.StoreListingWhereInput(**where_dict)
- include = prisma.types.StoreListingInclude(
- Versions=prisma.types.FindManyStoreListingVersionArgsFromStoreListing(
- order_by={"version": "desc"}
- ),
- OwningUser=True,
- )
-
- # Query listings with their versions
- listings = await prisma.models.StoreListing.prisma().find_many(
- where=where,
- skip=skip,
- take=page_size,
- include=include,
- order=[{"createdAt": "desc"}],
- )
+ }
+ },
+ ]
- # Get total count for pagination
- total = await prisma.models.StoreListing.prisma().count(where=where)
- total_pages = (total + page_size - 1) // page_size
+ # Add user_id condition if any users matched
+ if user_ids:
+ store_listing_filter["OR"].append({"owningUserId": {"in": user_ids}})
+
+ # Calculate pagination
+ skip = (page - 1) * page_size
+
+ # Create proper Prisma types for the query
+ include: prisma.types.StoreListingInclude = {
+ "Versions": {
+ "order_by": {"version": "desc"},
+ "where": {"isDeleted": False},
+ },
+ "OwningUser": True,
+ }
+
+ # Query listings with their versions
+ listings = await prisma.models.StoreListing.prisma().find_many(
+ where=store_listing_filter,
+ skip=skip,
+ take=page_size,
+ include=include,
+ order=[{"createdAt": "desc"}],
+ )
- # Convert to response models
- listings_with_versions = []
- for listing in listings:
- versions: list[store_model.StoreSubmission] = []
- # If we have versions, turn them into StoreSubmission models
- for version in listing.Versions or []:
- version_model = store_model.StoreSubmission(
- listing_id=listing.id,
- agent_id=version.agentGraphId,
- agent_version=version.agentGraphVersion,
- name=version.name,
- sub_heading=version.subHeading,
- slug=listing.slug,
- description=version.description,
- instructions=version.instructions,
- image_urls=version.imageUrls or [],
- date_submitted=version.submittedAt or version.createdAt,
- status=version.submissionStatus,
- runs=0, # Default values since we don't have this data here
- rating=0.0, # Default values since we don't have this data here
- store_listing_version_id=version.id,
- reviewer_id=version.reviewerId,
- review_comments=version.reviewComments,
- internal_comments=version.internalComments,
- reviewed_at=version.reviewedAt,
- changes_summary=version.changesSummary,
- version=version.version,
- )
- versions.append(version_model)
-
- # Get the latest version (first in the sorted list)
- latest_version = versions[0] if versions else None
-
- creator_email = listing.OwningUser.email if listing.OwningUser else None
-
- listing_with_versions = store_model.StoreListingWithVersions(
- listing_id=listing.id,
- slug=listing.slug,
- agent_id=listing.agentGraphId,
- agent_version=listing.agentGraphVersion,
- active_version_id=listing.activeVersionId,
- has_approved_version=listing.hasApprovedVersion,
- creator_email=creator_email,
- latest_version=latest_version,
- versions=versions,
+ # Get total count for pagination
+ total = await prisma.models.StoreListing.prisma().count(where=store_listing_filter)
+ total_pages = (total + page_size - 1) // page_size
+
+ # Convert to response models
+ listings_with_versions = []
+ for listing in listings:
+ versions: list[store_model.StoreSubmissionAdminView] = []
+ # If we have versions, turn them into StoreSubmissionAdminView models
+ for version in listing.Versions or []:
+ # .StoreListing is required for StoreSubmission.from_listing_version(v)
+ version.StoreListing = listing.model_copy(update={"Versions": None})
+
+ versions.append(
+ store_model.StoreSubmissionAdminView.from_listing_version(version)
)
- listings_with_versions.append(listing_with_versions)
+ # Get the latest version (first in the sorted list)
+ latest_version = versions[0] if versions else None
- logger.debug(f"Found {len(listings_with_versions)} listings for admin")
- return store_model.StoreListingsWithVersionsResponse(
- listings=listings_with_versions,
- pagination=store_model.Pagination(
- current_page=page,
- total_items=total,
- total_pages=total_pages,
- page_size=page_size,
- ),
- )
- except Exception as e:
- logger.error(f"Error fetching admin store listings: {e}")
- # Return empty response rather than exposing internal errors
- return store_model.StoreListingsWithVersionsResponse(
- listings=[],
- pagination=store_model.Pagination(
- current_page=page,
- total_items=0,
- total_pages=0,
- page_size=page_size,
- ),
- )
+ creator_email = listing.OwningUser.email if listing.OwningUser else None
+
+ listing_with_versions = store_model.StoreListingWithVersionsAdminView(
+ listing_id=listing.id,
+ slug=listing.slug,
+ graph_id=listing.agentGraphId,
+ active_listing_version_id=listing.activeVersionId,
+ has_approved_version=listing.hasApprovedVersion,
+ creator_email=creator_email,
+ latest_version=latest_version,
+ versions=versions,
+ )
+
+ listings_with_versions.append(listing_with_versions)
+
+ logger.debug(f"Found {len(listings_with_versions)} listings for admin")
+ return store_model.StoreListingsWithVersionsAdminViewResponse(
+ listings=listings_with_versions,
+ pagination=store_model.Pagination(
+ current_page=page,
+ total_items=total,
+ total_pages=total_pages,
+ page_size=page_size,
+ ),
+ )
async def check_submission_already_approved(
@@ -1956,24 +1578,24 @@ async def get_agent_as_admin(
store_listing_version_id: str,
) -> GraphModel:
"""Get agent using the version ID and store listing version ID."""
- store_listing_version = (
- await prisma.models.StoreListingVersion.prisma().find_unique(
- where={"id": store_listing_version_id}
- )
+ slv = await prisma.models.StoreListingVersion.prisma().find_unique(
+ where={"id": store_listing_version_id}
)
- if not store_listing_version:
- raise ValueError(f"Store listing version {store_listing_version_id} not found")
+ if not slv:
+ raise NotFoundError(
+ f"Store listing version {store_listing_version_id} not found"
+ )
graph = await get_graph_as_admin(
user_id=user_id,
- graph_id=store_listing_version.agentGraphId,
- version=store_listing_version.agentGraphVersion,
+ graph_id=slv.agentGraphId,
+ version=slv.agentGraphVersion,
for_export=True,
)
if not graph:
- raise ValueError(
- f"Agent {store_listing_version.agentGraphId} v{store_listing_version.agentGraphVersion} not found"
+ raise NotFoundError(
+ f"Graph {slv.agentGraphId} v{slv.agentGraphVersion} not found"
)
return graph
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 b48ce5db95..35946b8980 100644
--- a/autogpt_platform/backend/backend/api/features/store/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py
@@ -26,7 +26,7 @@ async def test_get_store_agents(mocker):
mock_agents = [
prisma.models.StoreAgent(
listing_id="test-id",
- storeListingVersionId="version123",
+ listing_version_id="version123",
slug="test-agent",
agent_name="Test Agent",
agent_video=None,
@@ -40,11 +40,11 @@ async def test_get_store_agents(mocker):
runs=10,
rating=4.5,
versions=["1.0"],
- agentGraphVersions=["1"],
- agentGraphId="test-graph-id",
+ graph_id="test-graph-id",
+ graph_versions=["1"],
updated_at=datetime.now(),
is_available=False,
- useForOnboarding=False,
+ use_for_onboarding=False,
)
]
@@ -68,10 +68,10 @@ async def test_get_store_agents(mocker):
@pytest.mark.asyncio(loop_scope="session")
async def test_get_store_agent_details(mocker):
- # Mock data
+ # Mock data - StoreAgent view already contains the active version data
mock_agent = prisma.models.StoreAgent(
listing_id="test-id",
- storeListingVersionId="version123",
+ listing_version_id="version123",
slug="test-agent",
agent_name="Test Agent",
agent_video="video.mp4",
@@ -85,102 +85,38 @@ async def test_get_store_agent_details(mocker):
runs=10,
rating=4.5,
versions=["1.0"],
- agentGraphVersions=["1"],
- agentGraphId="test-graph-id",
- updated_at=datetime.now(),
- is_available=False,
- useForOnboarding=False,
- )
-
- # Mock active version agent (what we want to return for active version)
- mock_active_agent = prisma.models.StoreAgent(
- listing_id="test-id",
- storeListingVersionId="active-version-id",
- slug="test-agent",
- agent_name="Test Agent Active",
- agent_video="active_video.mp4",
- agent_image=["active_image.jpg"],
- featured=False,
- creator_username="creator",
- creator_avatar="avatar.jpg",
- sub_heading="Test heading active",
- description="Test description active",
- categories=["test"],
- runs=15,
- rating=4.8,
- versions=["1.0", "2.0"],
- agentGraphVersions=["1", "2"],
- agentGraphId="test-graph-id-active",
+ graph_id="test-graph-id",
+ graph_versions=["1"],
updated_at=datetime.now(),
is_available=True,
- useForOnboarding=False,
+ use_for_onboarding=False,
)
- # Create a mock StoreListing result
- mock_store_listing = mocker.MagicMock()
- mock_store_listing.activeVersionId = "active-version-id"
- mock_store_listing.hasApprovedVersion = True
- mock_store_listing.ActiveVersion = mocker.MagicMock()
- mock_store_listing.ActiveVersion.recommendedScheduleCron = None
-
- # Mock StoreAgent prisma call - need to handle multiple calls
+ # Mock StoreAgent prisma call
mock_store_agent = mocker.patch("prisma.models.StoreAgent.prisma")
-
- # Set up side_effect to return different results for different calls
- def mock_find_first_side_effect(*args, **kwargs):
- where_clause = kwargs.get("where", {})
- if "storeListingVersionId" in where_clause:
- # Second call for active version
- return mock_active_agent
- else:
- # First call for initial lookup
- return mock_agent
-
- mock_store_agent.return_value.find_first = mocker.AsyncMock(
- side_effect=mock_find_first_side_effect
- )
-
- # Mock Profile prisma call
- mock_profile = mocker.MagicMock()
- mock_profile.userId = "user-id-123"
- mock_profile_db = mocker.patch("prisma.models.Profile.prisma")
- mock_profile_db.return_value.find_first = mocker.AsyncMock(
- return_value=mock_profile
- )
-
- # Mock StoreListing prisma call
- mock_store_listing_db = mocker.patch("prisma.models.StoreListing.prisma")
- mock_store_listing_db.return_value.find_first = mocker.AsyncMock(
- return_value=mock_store_listing
- )
+ mock_store_agent.return_value.find_first = mocker.AsyncMock(return_value=mock_agent)
# Call function
result = await db.get_store_agent_details("creator", "test-agent")
- # Verify results - should use active version data
+ # Verify results - constructed from the StoreAgent view
assert result.slug == "test-agent"
- assert result.agent_name == "Test Agent Active" # From active version
- assert result.active_version_id == "active-version-id"
+ assert result.agent_name == "Test Agent"
+ assert result.active_version_id == "version123"
assert result.has_approved_version is True
- assert (
- result.store_listing_version_id == "active-version-id"
- ) # Should be active version ID
+ assert result.store_listing_version_id == "version123"
+ assert result.graph_id == "test-graph-id"
+ assert result.runs == 10
+ assert result.rating == 4.5
- # Verify mocks called correctly - now expecting 2 calls
- assert mock_store_agent.return_value.find_first.call_count == 2
-
- # Check the specific calls
- calls = mock_store_agent.return_value.find_first.call_args_list
- assert calls[0] == mocker.call(
+ # Verify single StoreAgent lookup
+ mock_store_agent.return_value.find_first.assert_called_once_with(
where={"creator_username": "creator", "slug": "test-agent"}
)
- assert calls[1] == mocker.call(where={"storeListingVersionId": "active-version-id"})
-
- mock_store_listing_db.return_value.find_first.assert_called_once()
@pytest.mark.asyncio(loop_scope="session")
-async def test_get_store_creator_details(mocker):
+async def test_get_store_creator(mocker):
# Mock data
mock_creator_data = prisma.models.Creator(
name="Test Creator",
@@ -202,7 +138,7 @@ async def test_get_store_creator_details(mocker):
mock_creator.return_value.find_unique.return_value = mock_creator_data
# Call function
- result = await db.get_store_creator_details("creator")
+ result = await db.get_store_creator("creator")
# Verify results
assert result.username == "creator"
@@ -218,61 +154,110 @@ async def test_get_store_creator_details(mocker):
@pytest.mark.asyncio(loop_scope="session")
async def test_create_store_submission(mocker):
- # Mock data
+ now = datetime.now()
+
+ # Mock agent graph (with no pending submissions) and user with profile
+ mock_profile = prisma.models.Profile(
+ id="profile-id",
+ userId="user-id",
+ name="Test User",
+ username="testuser",
+ description="Test",
+ isFeatured=False,
+ links=[],
+ createdAt=now,
+ updatedAt=now,
+ )
+ mock_user = prisma.models.User(
+ id="user-id",
+ createdAt=now,
+ updatedAt=now,
+ Profile=[mock_profile],
+ emailVerified=True,
+ metadata="{}", # type: ignore[reportArgumentType]
+ integrations="",
+ maxEmailsPerDay=1,
+ notifyOnAgentRun=True,
+ notifyOnZeroBalance=True,
+ notifyOnLowBalance=True,
+ notifyOnBlockExecutionFailed=True,
+ notifyOnContinuousAgentError=True,
+ notifyOnDailySummary=True,
+ notifyOnWeeklySummary=True,
+ notifyOnMonthlySummary=True,
+ notifyOnAgentApproved=True,
+ notifyOnAgentRejected=True,
+ timezone="Europe/Delft",
+ )
mock_agent = prisma.models.AgentGraph(
id="agent-id",
version=1,
userId="user-id",
- createdAt=datetime.now(),
+ createdAt=now,
isActive=True,
+ StoreListingVersions=[],
+ User=mock_user,
)
- mock_listing = prisma.models.StoreListing(
+ # Mock the created StoreListingVersion (returned by create)
+ mock_store_listing_obj = prisma.models.StoreListing(
id="listing-id",
- createdAt=datetime.now(),
- updatedAt=datetime.now(),
+ createdAt=now,
+ updatedAt=now,
isDeleted=False,
hasApprovedVersion=False,
slug="test-agent",
agentGraphId="agent-id",
- agentGraphVersion=1,
owningUserId="user-id",
- Versions=[
- prisma.models.StoreListingVersion(
- id="version-id",
- agentGraphId="agent-id",
- agentGraphVersion=1,
- name="Test Agent",
- description="Test description",
- createdAt=datetime.now(),
- updatedAt=datetime.now(),
- subHeading="Test heading",
- imageUrls=["image.jpg"],
- categories=["test"],
- isFeatured=False,
- isDeleted=False,
- version=1,
- storeListingId="listing-id",
- submissionStatus=prisma.enums.SubmissionStatus.PENDING,
- isAvailable=True,
- )
- ],
useForOnboarding=False,
)
+ mock_version = prisma.models.StoreListingVersion(
+ id="version-id",
+ agentGraphId="agent-id",
+ agentGraphVersion=1,
+ name="Test Agent",
+ description="Test description",
+ createdAt=now,
+ updatedAt=now,
+ subHeading="",
+ imageUrls=[],
+ categories=[],
+ isFeatured=False,
+ isDeleted=False,
+ version=1,
+ storeListingId="listing-id",
+ submissionStatus=prisma.enums.SubmissionStatus.PENDING,
+ isAvailable=True,
+ submittedAt=now,
+ StoreListing=mock_store_listing_obj,
+ )
# Mock prisma calls
mock_agent_graph = mocker.patch("prisma.models.AgentGraph.prisma")
mock_agent_graph.return_value.find_first = mocker.AsyncMock(return_value=mock_agent)
- mock_store_listing = mocker.patch("prisma.models.StoreListing.prisma")
- mock_store_listing.return_value.find_first = mocker.AsyncMock(return_value=None)
- mock_store_listing.return_value.create = mocker.AsyncMock(return_value=mock_listing)
+ # Mock transaction context manager
+ mock_tx = mocker.MagicMock()
+ mocker.patch(
+ "backend.api.features.store.db.transaction",
+ return_value=mocker.AsyncMock(
+ __aenter__=mocker.AsyncMock(return_value=mock_tx),
+ __aexit__=mocker.AsyncMock(return_value=False),
+ ),
+ )
+
+ mock_sl = mocker.patch("prisma.models.StoreListing.prisma")
+ mock_sl.return_value.find_unique = mocker.AsyncMock(return_value=None)
+
+ mock_slv = mocker.patch("prisma.models.StoreListingVersion.prisma")
+ mock_slv.return_value.create = mocker.AsyncMock(return_value=mock_version)
# Call function
result = await db.create_store_submission(
user_id="user-id",
- agent_id="agent-id",
- agent_version=1,
+ graph_id="agent-id",
+ graph_version=1,
slug="test-agent",
name="Test Agent",
description="Test description",
@@ -281,11 +266,11 @@ async def test_create_store_submission(mocker):
# Verify results
assert result.name == "Test Agent"
assert result.description == "Test description"
- assert result.store_listing_version_id == "version-id"
+ assert result.listing_version_id == "version-id"
# Verify mocks called correctly
mock_agent_graph.return_value.find_first.assert_called_once()
- mock_store_listing.return_value.create.assert_called_once()
+ mock_slv.return_value.create.assert_called_once()
@pytest.mark.asyncio(loop_scope="session")
@@ -318,7 +303,6 @@ async def test_update_profile(mocker):
description="Test description",
links=["link1"],
avatar_url="avatar.jpg",
- is_featured=False,
)
# Call function
@@ -389,7 +373,7 @@ async def test_get_store_agents_with_search_and_filters_parameterized():
creators=["creator1'; DROP TABLE Users; --", "creator2"],
category="AI'; DELETE FROM StoreAgent; --",
featured=True,
- sorted_by="rating",
+ sorted_by=db.StoreAgentsSortOptions.RATING,
page=1,
page_size=20,
)
diff --git a/autogpt_platform/backend/backend/api/features/store/exceptions.py b/autogpt_platform/backend/backend/api/features/store/exceptions.py
index 1e9b4ac051..92b65d3511 100644
--- a/autogpt_platform/backend/backend/api/features/store/exceptions.py
+++ b/autogpt_platform/backend/backend/api/features/store/exceptions.py
@@ -57,12 +57,6 @@ class StoreError(ValueError):
pass
-class AgentNotFoundError(NotFoundError):
- """Raised when an agent is not found"""
-
- pass
-
-
class CreatorNotFoundError(NotFoundError):
"""Raised when a creator is not found"""
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 b10bfbcc06..ff05be5613 100644
--- a/autogpt_platform/backend/backend/api/features/store/hybrid_search.py
+++ b/autogpt_platform/backend/backend/api/features/store/hybrid_search.py
@@ -568,7 +568,7 @@ async def hybrid_search(
SELECT uce."contentId" as "storeListingVersionId"
FROM {{schema_prefix}}"UnifiedContentEmbedding" uce
INNER JOIN {{schema_prefix}}"StoreAgent" sa
- ON uce."contentId" = sa."storeListingVersionId"
+ ON uce."contentId" = sa.listing_version_id
WHERE uce."contentType" = 'STORE_AGENT'::{{schema_prefix}}"ContentType"
AND uce."userId" IS NULL
AND uce.search @@ plainto_tsquery('english', {query_param})
@@ -582,7 +582,7 @@ async def hybrid_search(
SELECT uce."contentId", uce.embedding
FROM {{schema_prefix}}"UnifiedContentEmbedding" uce
INNER JOIN {{schema_prefix}}"StoreAgent" sa
- ON uce."contentId" = sa."storeListingVersionId"
+ ON uce."contentId" = sa.listing_version_id
WHERE uce."contentType" = 'STORE_AGENT'::{{schema_prefix}}"ContentType"
AND uce."userId" IS NULL
AND {where_clause}
@@ -605,7 +605,7 @@ async def hybrid_search(
sa.featured,
sa.is_available,
sa.updated_at,
- sa."agentGraphId",
+ sa.graph_id,
-- Searchable text for BM25 reranking
COALESCE(sa.agent_name, '') || ' ' || COALESCE(sa.sub_heading, '') || ' ' || COALESCE(sa.description, '') as searchable_text,
-- Semantic score
@@ -627,9 +627,9 @@ async def hybrid_search(
sa.runs as popularity_raw
FROM candidates c
INNER JOIN {{schema_prefix}}"StoreAgent" sa
- ON c."storeListingVersionId" = sa."storeListingVersionId"
+ ON c."storeListingVersionId" = sa.listing_version_id
INNER JOIN {{schema_prefix}}"UnifiedContentEmbedding" uce
- ON sa."storeListingVersionId" = uce."contentId"
+ ON sa.listing_version_id = uce."contentId"
AND uce."contentType" = 'STORE_AGENT'::{{schema_prefix}}"ContentType"
),
max_vals AS (
@@ -665,7 +665,7 @@ async def hybrid_search(
featured,
is_available,
updated_at,
- "agentGraphId",
+ graph_id,
searchable_text,
semantic_score,
lexical_score,
diff --git a/autogpt_platform/backend/backend/api/features/store/model.py b/autogpt_platform/backend/backend/api/features/store/model.py
index d66b91807d..d7de01a2b4 100644
--- a/autogpt_platform/backend/backend/api/features/store/model.py
+++ b/autogpt_platform/backend/backend/api/features/store/model.py
@@ -1,11 +1,14 @@
import datetime
-from typing import List
+from typing import TYPE_CHECKING, List, Self
import prisma.enums
import pydantic
from backend.util.models import Pagination
+if TYPE_CHECKING:
+ import prisma.models
+
class ChangelogEntry(pydantic.BaseModel):
version: str
@@ -13,9 +16,9 @@ class ChangelogEntry(pydantic.BaseModel):
date: datetime.datetime
-class MyAgent(pydantic.BaseModel):
- agent_id: str
- agent_version: int
+class MyUnpublishedAgent(pydantic.BaseModel):
+ graph_id: str
+ graph_version: int
agent_name: str
agent_image: str | None = None
description: str
@@ -23,8 +26,8 @@ class MyAgent(pydantic.BaseModel):
recommended_schedule_cron: str | None = None
-class MyAgentsResponse(pydantic.BaseModel):
- agents: list[MyAgent]
+class MyUnpublishedAgentsResponse(pydantic.BaseModel):
+ agents: list[MyUnpublishedAgent]
pagination: Pagination
@@ -40,6 +43,21 @@ class StoreAgent(pydantic.BaseModel):
rating: float
agent_graph_id: str
+ @classmethod
+ def from_db(cls, agent: "prisma.models.StoreAgent") -> "StoreAgent":
+ return cls(
+ slug=agent.slug,
+ agent_name=agent.agent_name,
+ agent_image=agent.agent_image[0] if agent.agent_image else "",
+ creator=agent.creator_username or "Needs Profile",
+ creator_avatar=agent.creator_avatar or "",
+ sub_heading=agent.sub_heading,
+ description=agent.description,
+ runs=agent.runs,
+ rating=agent.rating,
+ agent_graph_id=agent.graph_id,
+ )
+
class StoreAgentsResponse(pydantic.BaseModel):
agents: list[StoreAgent]
@@ -62,81 +80,192 @@ class StoreAgentDetails(pydantic.BaseModel):
runs: int
rating: float
versions: list[str]
- agentGraphVersions: list[str]
- agentGraphId: str
+ graph_id: str
+ graph_versions: list[str]
last_updated: datetime.datetime
recommended_schedule_cron: str | None = None
- active_version_id: str | None = None
- has_approved_version: bool = False
+ active_version_id: str
+ has_approved_version: bool
# Optional changelog data when include_changelog=True
changelog: list[ChangelogEntry] | None = None
+ @classmethod
+ def from_db(cls, agent: "prisma.models.StoreAgent") -> "StoreAgentDetails":
+ return cls(
+ store_listing_version_id=agent.listing_version_id,
+ slug=agent.slug,
+ agent_name=agent.agent_name,
+ agent_video=agent.agent_video or "",
+ agent_output_demo=agent.agent_output_demo or "",
+ agent_image=agent.agent_image,
+ creator=agent.creator_username or "",
+ creator_avatar=agent.creator_avatar or "",
+ sub_heading=agent.sub_heading,
+ description=agent.description,
+ categories=agent.categories,
+ runs=agent.runs,
+ rating=agent.rating,
+ versions=agent.versions,
+ graph_id=agent.graph_id,
+ graph_versions=agent.graph_versions,
+ last_updated=agent.updated_at,
+ recommended_schedule_cron=agent.recommended_schedule_cron,
+ active_version_id=agent.listing_version_id,
+ has_approved_version=True, # StoreAgent view only has approved agents
+ )
+
+
+class Profile(pydantic.BaseModel):
+ """Marketplace user profile (only attributes that the user can update)"""
-class Creator(pydantic.BaseModel):
- name: str
username: str
+ name: str
description: str
- avatar_url: str
- num_agents: int
- agent_rating: float
- agent_runs: int
+ avatar_url: str | None
+ links: list[str]
+
+
+class ProfileDetails(Profile):
+ """Marketplace user profile (including read-only fields)"""
+
is_featured: bool
+ @classmethod
+ def from_db(cls, profile: "prisma.models.Profile") -> "ProfileDetails":
+ return cls(
+ name=profile.name,
+ username=profile.username,
+ avatar_url=profile.avatarUrl,
+ description=profile.description,
+ links=profile.links,
+ is_featured=profile.isFeatured,
+ )
-class CreatorsResponse(pydantic.BaseModel):
- creators: List[Creator]
- pagination: Pagination
+class CreatorDetails(ProfileDetails):
+ """Marketplace creator profile details, including aggregated stats"""
-class CreatorDetails(pydantic.BaseModel):
- name: str
- username: str
- description: str
- links: list[str]
- avatar_url: str
- agent_rating: float
+ num_agents: int
agent_runs: int
+ agent_rating: float
top_categories: list[str]
+ @classmethod
+ def from_db(cls, creator: "prisma.models.Creator") -> "CreatorDetails": # type: ignore[override]
+ return cls(
+ name=creator.name,
+ username=creator.username,
+ avatar_url=creator.avatar_url,
+ description=creator.description,
+ links=creator.links,
+ is_featured=creator.is_featured,
+ num_agents=creator.num_agents,
+ agent_runs=creator.agent_runs,
+ agent_rating=creator.agent_rating,
+ top_categories=creator.top_categories,
+ )
-class Profile(pydantic.BaseModel):
- name: str
- username: str
- description: str
- links: list[str]
- avatar_url: str
- is_featured: bool = False
+
+class CreatorsResponse(pydantic.BaseModel):
+ creators: List[CreatorDetails]
+ pagination: Pagination
class StoreSubmission(pydantic.BaseModel):
+ # From StoreListing:
listing_id: str
- agent_id: str
- agent_version: int
+ user_id: str
+ slug: str
+
+ # From StoreListingVersion:
+ listing_version_id: str
+ listing_version: int
+ graph_id: str
+ graph_version: int
name: str
sub_heading: str
- slug: str
description: str
- instructions: str | None = None
+ instructions: str | None
+ categories: list[str]
image_urls: list[str]
- date_submitted: datetime.datetime
- status: prisma.enums.SubmissionStatus
- runs: int
- rating: float
- store_listing_version_id: str | None = None
- version: int | None = None # Actual version number from the database
+ video_url: str | None
+ agent_output_demo_url: str | None
+ submitted_at: datetime.datetime | None
+ changes_summary: str | None
+ status: prisma.enums.SubmissionStatus
+ reviewed_at: datetime.datetime | None = None
reviewer_id: str | None = None
review_comments: str | None = None # External comments visible to creator
- internal_comments: str | None = None # Private notes for admin use only
- reviewed_at: datetime.datetime | None = None
- changes_summary: str | None = None
- # Additional fields for editing
- video_url: str | None = None
- agent_output_demo_url: str | None = None
- categories: list[str] = []
+ # Aggregated from AgentGraphExecutions and StoreListingReviews:
+ run_count: int = 0
+ review_count: int = 0
+ review_avg_rating: float = 0.0
+
+ @classmethod
+ def from_db(cls, _sub: "prisma.models.StoreSubmission") -> Self:
+ """Construct from the StoreSubmission Prisma view."""
+ return cls(
+ listing_id=_sub.listing_id,
+ user_id=_sub.user_id,
+ slug=_sub.slug,
+ listing_version_id=_sub.listing_version_id,
+ listing_version=_sub.listing_version,
+ graph_id=_sub.graph_id,
+ graph_version=_sub.graph_version,
+ name=_sub.name,
+ sub_heading=_sub.sub_heading,
+ description=_sub.description,
+ instructions=_sub.instructions,
+ categories=_sub.categories,
+ image_urls=_sub.image_urls,
+ video_url=_sub.video_url,
+ agent_output_demo_url=_sub.agent_output_demo_url,
+ submitted_at=_sub.submitted_at,
+ changes_summary=_sub.changes_summary,
+ status=_sub.status,
+ reviewed_at=_sub.reviewed_at,
+ reviewer_id=_sub.reviewer_id,
+ review_comments=_sub.review_comments,
+ run_count=_sub.run_count,
+ review_count=_sub.review_count,
+ review_avg_rating=_sub.review_avg_rating,
+ )
+
+ @classmethod
+ def from_listing_version(cls, _lv: "prisma.models.StoreListingVersion") -> Self:
+ """
+ Construct from the StoreListingVersion Prisma model (with StoreListing included)
+ """
+ if not (_l := _lv.StoreListing):
+ raise ValueError("StoreListingVersion must have included StoreListing")
+
+ return cls(
+ listing_id=_l.id,
+ user_id=_l.owningUserId,
+ slug=_l.slug,
+ listing_version_id=_lv.id,
+ listing_version=_lv.version,
+ graph_id=_lv.agentGraphId,
+ graph_version=_lv.agentGraphVersion,
+ name=_lv.name,
+ sub_heading=_lv.subHeading,
+ description=_lv.description,
+ instructions=_lv.instructions,
+ categories=_lv.categories,
+ image_urls=_lv.imageUrls,
+ video_url=_lv.videoUrl,
+ agent_output_demo_url=_lv.agentOutputDemoUrl,
+ submitted_at=_lv.submittedAt,
+ changes_summary=_lv.changesSummary,
+ status=_lv.submissionStatus,
+ reviewed_at=_lv.reviewedAt,
+ reviewer_id=_lv.reviewerId,
+ review_comments=_lv.reviewComments,
+ )
class StoreSubmissionsResponse(pydantic.BaseModel):
@@ -144,33 +273,12 @@ class StoreSubmissionsResponse(pydantic.BaseModel):
pagination: Pagination
-class StoreListingWithVersions(pydantic.BaseModel):
- """A store listing with its version history"""
-
- listing_id: str
- slug: str
- agent_id: str
- agent_version: int
- active_version_id: str | None = None
- has_approved_version: bool = False
- creator_email: str | None = None
- latest_version: StoreSubmission | None = None
- versions: list[StoreSubmission] = []
-
-
-class StoreListingsWithVersionsResponse(pydantic.BaseModel):
- """Response model for listings with version history"""
-
- listings: list[StoreListingWithVersions]
- pagination: Pagination
-
-
class StoreSubmissionRequest(pydantic.BaseModel):
- agent_id: str = pydantic.Field(
- ..., min_length=1, description="Agent ID cannot be empty"
+ graph_id: str = pydantic.Field(
+ ..., min_length=1, description="Graph ID cannot be empty"
)
- agent_version: int = pydantic.Field(
- ..., gt=0, description="Agent version must be greater than 0"
+ graph_version: int = pydantic.Field(
+ ..., gt=0, description="Graph version must be greater than 0"
)
slug: str
name: str
@@ -198,12 +306,42 @@ class StoreSubmissionEditRequest(pydantic.BaseModel):
recommended_schedule_cron: str | None = None
-class ProfileDetails(pydantic.BaseModel):
- name: str
- username: str
- description: str
- links: list[str]
- avatar_url: str | None = None
+class StoreSubmissionAdminView(StoreSubmission):
+ internal_comments: str | None # Private admin notes
+
+ @classmethod
+ def from_db(cls, _sub: "prisma.models.StoreSubmission") -> Self:
+ return cls(
+ **StoreSubmission.from_db(_sub).model_dump(),
+ internal_comments=_sub.internal_comments,
+ )
+
+ @classmethod
+ def from_listing_version(cls, _lv: "prisma.models.StoreListingVersion") -> Self:
+ return cls(
+ **StoreSubmission.from_listing_version(_lv).model_dump(),
+ internal_comments=_lv.internalComments,
+ )
+
+
+class StoreListingWithVersionsAdminView(pydantic.BaseModel):
+ """A store listing with its version history"""
+
+ listing_id: str
+ graph_id: str
+ slug: str
+ active_listing_version_id: str | None = None
+ has_approved_version: bool = False
+ creator_email: str | None = None
+ latest_version: StoreSubmissionAdminView | None = None
+ versions: list[StoreSubmissionAdminView] = []
+
+
+class StoreListingsWithVersionsAdminViewResponse(pydantic.BaseModel):
+ """Response model for listings with version history"""
+
+ listings: list[StoreListingWithVersionsAdminView]
+ pagination: Pagination
class StoreReview(pydantic.BaseModel):
diff --git a/autogpt_platform/backend/backend/api/features/store/model_test.py b/autogpt_platform/backend/backend/api/features/store/model_test.py
deleted file mode 100644
index c4109f4603..0000000000
--- a/autogpt_platform/backend/backend/api/features/store/model_test.py
+++ /dev/null
@@ -1,203 +0,0 @@
-import datetime
-
-import prisma.enums
-
-from . import model as store_model
-
-
-def test_pagination():
- pagination = store_model.Pagination(
- total_items=100, total_pages=5, current_page=2, page_size=20
- )
- assert pagination.total_items == 100
- assert pagination.total_pages == 5
- assert pagination.current_page == 2
- assert pagination.page_size == 20
-
-
-def test_store_agent():
- agent = store_model.StoreAgent(
- slug="test-agent",
- agent_name="Test Agent",
- agent_image="test.jpg",
- creator="creator1",
- creator_avatar="avatar.jpg",
- sub_heading="Test subheading",
- description="Test description",
- runs=50,
- rating=4.5,
- agent_graph_id="test-graph-id",
- )
- assert agent.slug == "test-agent"
- assert agent.agent_name == "Test Agent"
- assert agent.runs == 50
- assert agent.rating == 4.5
- assert agent.agent_graph_id == "test-graph-id"
-
-
-def test_store_agents_response():
- response = store_model.StoreAgentsResponse(
- agents=[
- store_model.StoreAgent(
- slug="test-agent",
- agent_name="Test Agent",
- agent_image="test.jpg",
- creator="creator1",
- creator_avatar="avatar.jpg",
- sub_heading="Test subheading",
- description="Test description",
- runs=50,
- rating=4.5,
- agent_graph_id="test-graph-id",
- )
- ],
- pagination=store_model.Pagination(
- total_items=1, total_pages=1, current_page=1, page_size=20
- ),
- )
- assert len(response.agents) == 1
- assert response.pagination.total_items == 1
-
-
-def test_store_agent_details():
- details = store_model.StoreAgentDetails(
- store_listing_version_id="version123",
- slug="test-agent",
- agent_name="Test Agent",
- agent_video="video.mp4",
- agent_output_demo="demo.mp4",
- agent_image=["image1.jpg", "image2.jpg"],
- creator="creator1",
- creator_avatar="avatar.jpg",
- sub_heading="Test subheading",
- description="Test description",
- categories=["cat1", "cat2"],
- runs=50,
- rating=4.5,
- versions=["1.0", "2.0"],
- agentGraphVersions=["1", "2"],
- agentGraphId="test-graph-id",
- last_updated=datetime.datetime.now(),
- )
- assert details.slug == "test-agent"
- assert len(details.agent_image) == 2
- assert len(details.categories) == 2
- assert len(details.versions) == 2
-
-
-def test_creator():
- creator = store_model.Creator(
- agent_rating=4.8,
- agent_runs=1000,
- name="Test Creator",
- username="creator1",
- description="Test description",
- avatar_url="avatar.jpg",
- num_agents=5,
- is_featured=False,
- )
- assert creator.name == "Test Creator"
- assert creator.num_agents == 5
-
-
-def test_creators_response():
- response = store_model.CreatorsResponse(
- creators=[
- store_model.Creator(
- agent_rating=4.8,
- agent_runs=1000,
- name="Test Creator",
- username="creator1",
- description="Test description",
- avatar_url="avatar.jpg",
- num_agents=5,
- is_featured=False,
- )
- ],
- pagination=store_model.Pagination(
- total_items=1, total_pages=1, current_page=1, page_size=20
- ),
- )
- assert len(response.creators) == 1
- assert response.pagination.total_items == 1
-
-
-def test_creator_details():
- details = store_model.CreatorDetails(
- name="Test Creator",
- username="creator1",
- description="Test description",
- links=["link1.com", "link2.com"],
- avatar_url="avatar.jpg",
- agent_rating=4.8,
- agent_runs=1000,
- top_categories=["cat1", "cat2"],
- )
- assert details.name == "Test Creator"
- assert len(details.links) == 2
- assert details.agent_rating == 4.8
- assert len(details.top_categories) == 2
-
-
-def test_store_submission():
- submission = store_model.StoreSubmission(
- listing_id="listing123",
- agent_id="agent123",
- agent_version=1,
- sub_heading="Test subheading",
- name="Test Agent",
- slug="test-agent",
- description="Test description",
- image_urls=["image1.jpg", "image2.jpg"],
- date_submitted=datetime.datetime(2023, 1, 1),
- status=prisma.enums.SubmissionStatus.PENDING,
- runs=50,
- rating=4.5,
- )
- assert submission.name == "Test Agent"
- assert len(submission.image_urls) == 2
- assert submission.status == prisma.enums.SubmissionStatus.PENDING
-
-
-def test_store_submissions_response():
- response = store_model.StoreSubmissionsResponse(
- submissions=[
- store_model.StoreSubmission(
- listing_id="listing123",
- agent_id="agent123",
- agent_version=1,
- sub_heading="Test subheading",
- name="Test Agent",
- slug="test-agent",
- description="Test description",
- image_urls=["image1.jpg"],
- date_submitted=datetime.datetime(2023, 1, 1),
- status=prisma.enums.SubmissionStatus.PENDING,
- runs=50,
- rating=4.5,
- )
- ],
- pagination=store_model.Pagination(
- total_items=1, total_pages=1, current_page=1, page_size=20
- ),
- )
- assert len(response.submissions) == 1
- assert response.pagination.total_items == 1
-
-
-def test_store_submission_request():
- request = store_model.StoreSubmissionRequest(
- agent_id="agent123",
- agent_version=1,
- slug="test-agent",
- name="Test Agent",
- sub_heading="Test subheading",
- video_url="video.mp4",
- image_urls=["image1.jpg", "image2.jpg"],
- description="Test description",
- categories=["cat1", "cat2"],
- )
- assert request.agent_id == "agent123"
- assert request.agent_version == 1
- assert len(request.image_urls) == 2
- assert len(request.categories) == 2
diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.py
index d93fe60f15..9ebdf63e2d 100644
--- a/autogpt_platform/backend/backend/api/features/store/routes.py
+++ b/autogpt_platform/backend/backend/api/features/store/routes.py
@@ -1,16 +1,17 @@
import logging
import tempfile
-import typing
import urllib.parse
-from typing import Literal
import autogpt_libs.auth
import fastapi
import fastapi.responses
import prisma.enums
+from fastapi import Query, Security
+from pydantic import BaseModel
import backend.data.graph
import backend.util.json
+from backend.util.exceptions import NotFoundError
from backend.util.models import Pagination
from . import cache as store_cache
@@ -34,22 +35,15 @@ router = fastapi.APIRouter()
"/profile",
summary="Get user profile",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.ProfileDetails,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def get_profile(
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Get the profile details for the authenticated user.
- Cached for 1 hour per user.
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> store_model.ProfileDetails:
+ """Get the profile details for the authenticated user."""
profile = await store_db.get_user_profile(user_id)
if profile is None:
- return fastapi.responses.JSONResponse(
- status_code=404,
- content={"detail": "Profile not found"},
- )
+ raise NotFoundError("User does not have a profile yet")
return profile
@@ -57,98 +51,17 @@ async def get_profile(
"/profile",
summary="Update user profile",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.CreatorDetails,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def update_or_create_profile(
profile: store_model.Profile,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Update the store profile for the authenticated user.
-
- Args:
- profile (Profile): The updated profile details
- user_id (str): ID of the authenticated user
-
- Returns:
- CreatorDetails: The updated profile
-
- Raises:
- HTTPException: If there is an error updating the profile
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> store_model.ProfileDetails:
+ """Update the store profile for the authenticated user."""
updated_profile = await store_db.update_profile(user_id=user_id, profile=profile)
return updated_profile
-##############################################
-############### Agent Endpoints ##############
-##############################################
-
-
- "/agents",
- summary="List store agents",
- tags=["store", "public"],
- response_model=store_model.StoreAgentsResponse,
-)
-async def get_agents(
- featured: bool = False,
- creator: str | None = None,
- sorted_by: Literal["rating", "runs", "name", "updated_at"] | None = None,
- search_query: str | None = None,
- category: str | None = None,
- page: int = 1,
- page_size: int = 20,
-):
- """
- Get a paginated list of agents from the store with optional filtering and sorting.
-
- Args:
- featured (bool, optional): Filter to only show featured agents. Defaults to False.
- creator (str | None, optional): Filter agents by creator username. Defaults to None.
- sorted_by (str | None, optional): Sort agents by "runs" or "rating". Defaults to None.
- search_query (str | None, optional): Search agents by name, subheading and description. Defaults to None.
- category (str | None, optional): Filter agents by category. Defaults to None.
- page (int, optional): Page number for pagination. Defaults to 1.
- page_size (int, optional): Number of agents per page. Defaults to 20.
-
- Returns:
- StoreAgentsResponse: Paginated list of agents matching the filters
-
- Raises:
- HTTPException: If page or page_size are less than 1
-
- Used for:
- - Home Page Featured Agents
- - Home Page Top Agents
- - Search Results
- - Agent Details - Other Agents By Creator
- - Agent Details - Similar Agents
- - Creator Details - Agents By Creator
- """
- if page < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page must be greater than 0"
- )
-
- if page_size < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page size must be greater than 0"
- )
-
- agents = await store_cache._get_cached_store_agents(
- featured=featured,
- creator=creator,
- sorted_by=sorted_by,
- search_query=search_query,
- category=category,
- page=page,
- page_size=page_size,
- )
- return agents
-
-
##############################################
############### Search Endpoints #############
##############################################
@@ -158,60 +71,30 @@ async def get_agents(
"/search",
summary="Unified search across all content types",
tags=["store", "public"],
- response_model=store_model.UnifiedSearchResponse,
)
async def unified_search(
query: str,
- content_types: list[str] | None = fastapi.Query(
+ content_types: list[prisma.enums.ContentType] | None = Query(
default=None,
- description="Content types to search: STORE_AGENT, BLOCK, DOCUMENTATION. If not specified, searches all.",
+ description="Content types to search. If not specified, searches all.",
),
- page: int = 1,
- page_size: int = 20,
- user_id: str | None = fastapi.Security(
+ page: int = Query(ge=1, default=1),
+ page_size: int = Query(ge=1, default=20),
+ user_id: str | None = Security(
autogpt_libs.auth.get_optional_user_id, use_cache=False
),
-):
+) -> store_model.UnifiedSearchResponse:
"""
- Search across all content types (store agents, blocks, documentation) using hybrid search.
+ Search across all content types (marketplace agents, blocks, documentation)
+ using hybrid search.
Combines semantic (embedding-based) and lexical (text-based) search for best results.
-
- Args:
- query: The search query string
- content_types: Optional list of content types to filter by (STORE_AGENT, BLOCK, DOCUMENTATION)
- page: Page number for pagination (default 1)
- page_size: Number of results per page (default 20)
- user_id: Optional authenticated user ID (for user-scoped content in future)
-
- Returns:
- UnifiedSearchResponse: Paginated list of search results with relevance scores
"""
- if page < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page must be greater than 0"
- )
-
- if page_size < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page size must be greater than 0"
- )
-
- # Convert string content types to enum
- content_type_enums: list[prisma.enums.ContentType] | None = None
- if content_types:
- try:
- content_type_enums = [prisma.enums.ContentType(ct) for ct in content_types]
- except ValueError as e:
- raise fastapi.HTTPException(
- status_code=422,
- detail=f"Invalid content type. Valid values: STORE_AGENT, BLOCK, DOCUMENTATION. Error: {e}",
- )
# Perform unified hybrid search
results, total = await store_hybrid_search.unified_hybrid_search(
query=query,
- content_types=content_type_enums,
+ content_types=content_types,
user_id=user_id,
page=page,
page_size=page_size,
@@ -245,22 +128,69 @@ async def unified_search(
)
+##############################################
+############### Agent Endpoints ##############
+##############################################
+
+
+ "/agents",
+ summary="List store agents",
+ tags=["store", "public"],
+)
+async def get_agents(
+ featured: bool = Query(
+ default=False, description="Filter to only show featured agents"
+ ),
+ creator: str | None = Query(
+ default=None, description="Filter agents by creator username"
+ ),
+ category: str | None = Query(default=None, description="Filter agents by category"),
+ search_query: str | None = Query(
+ default=None, description="Literal + semantic search on names and descriptions"
+ ),
+ sorted_by: store_db.StoreAgentsSortOptions | None = Query(
+ default=None,
+ description="Property to sort results by. Ignored if search_query is provided.",
+ ),
+ page: int = Query(ge=1, default=1),
+ page_size: int = Query(ge=1, default=20),
+) -> store_model.StoreAgentsResponse:
+ """
+ Get a paginated list of agents from the marketplace,
+ with optional filtering and sorting.
+
+ Used for:
+ - Home Page Featured Agents
+ - Home Page Top Agents
+ - Search Results
+ - Agent Details - Other Agents By Creator
+ - Agent Details - Similar Agents
+ - Creator Details - Agents By Creator
+ """
+ agents = await store_cache._get_cached_store_agents(
+ featured=featured,
+ creator=creator,
+ sorted_by=sorted_by,
+ search_query=search_query,
+ category=category,
+ page=page,
+ page_size=page_size,
+ )
+ return agents
+
+
@router.get(
"/agents/{username}/{agent_name}",
summary="Get specific agent",
tags=["store", "public"],
- response_model=store_model.StoreAgentDetails,
)
-async def get_agent(
+async def get_agent_by_name(
username: str,
agent_name: str,
- include_changelog: bool = fastapi.Query(default=False),
-):
- """
- This is only used on the AgentDetails Page.
-
- It returns the store listing agents details.
- """
+ include_changelog: bool = Query(default=False),
+) -> store_model.StoreAgentDetails:
+ """Get details of a marketplace agent"""
username = urllib.parse.unquote(username).lower()
# URL decode the agent name since it comes from the URL path
agent_name = urllib.parse.unquote(agent_name).lower()
@@ -270,76 +200,82 @@ async def get_agent(
return agent
- "/graph/{store_listing_version_id}",
- summary="Get agent graph",
- tags=["store"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
-)
-async def get_graph_meta_by_store_listing_version_id(
- store_listing_version_id: str,
-) -> backend.data.graph.GraphModelWithoutNodes:
- """
- Get Agent Graph from Store Listing Version ID.
- """
- graph = await store_db.get_available_graph(store_listing_version_id)
- return graph
-
-
- "/agents/{store_listing_version_id}",
- summary="Get agent by version",
- tags=["store"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.StoreAgentDetails,
-)
-async def get_store_agent(store_listing_version_id: str):
- """
- Get Store Agent Details from Store Listing Version ID.
- """
- agent = await store_db.get_store_agent_by_version_id(store_listing_version_id)
-
- return agent
-
-
@router.post(
"/agents/{username}/{agent_name}/review",
summary="Create agent review",
tags=["store"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.StoreReview,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
-async def create_review(
+async def post_user_review_for_agent(
username: str,
agent_name: str,
review: store_model.StoreReviewCreate,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Create a review for a store agent.
-
- Args:
- username: Creator's username
- agent_name: Name/slug of the agent
- review: Review details including score and optional comments
- user_id: ID of authenticated user creating the review
-
- Returns:
- The created review
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> store_model.StoreReview:
+ """Post a user review on a marketplace agent listing"""
username = urllib.parse.unquote(username).lower()
agent_name = urllib.parse.unquote(agent_name).lower()
- # Create the review
+
created_review = await store_db.create_store_review(
user_id=user_id,
store_listing_version_id=review.store_listing_version_id,
score=review.score,
comments=review.comments,
)
-
return created_review
+ "/listings/versions/{store_listing_version_id}",
+ summary="Get agent by version",
+ tags=["store"],
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
+)
+async def get_agent_by_listing_version(
+ store_listing_version_id: str,
+) -> store_model.StoreAgentDetails:
+ agent = await store_db.get_store_agent_by_version_id(store_listing_version_id)
+ return agent
+
+
+ "/listings/versions/{store_listing_version_id}/graph",
+ summary="Get agent graph",
+ tags=["store"],
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
+)
+async def get_graph_meta_by_store_listing_version_id(
+ store_listing_version_id: str,
+) -> backend.data.graph.GraphModelWithoutNodes:
+ """Get outline of graph belonging to a specific marketplace listing version"""
+ graph = await store_db.get_available_graph(store_listing_version_id)
+ return graph
+
+
+ "/listings/versions/{store_listing_version_id}/graph/download",
+ summary="Download agent file",
+ tags=["store", "public"],
+)
+async def download_agent_file(
+ store_listing_version_id: str,
+) -> fastapi.responses.FileResponse:
+ """Download agent graph file for a specific marketplace listing version"""
+ graph_data = await store_db.get_agent(store_listing_version_id)
+ file_name = f"agent_{graph_data.id}_v{graph_data.version or 'latest'}.json"
+
+ # Sending graph as a stream (similar to marketplace v1)
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".json", delete=False
+ ) as tmp_file:
+ tmp_file.write(backend.util.json.dumps(graph_data))
+ tmp_file.flush()
+
+ return fastapi.responses.FileResponse(
+ tmp_file.name, filename=file_name, media_type="application/json"
+ )
+
+
##############################################
############# Creator Endpoints #############
##############################################
@@ -349,37 +285,19 @@ async def create_review(
"/creators",
summary="List store creators",
tags=["store", "public"],
- response_model=store_model.CreatorsResponse,
)
async def get_creators(
- featured: bool = False,
- search_query: str | None = None,
- sorted_by: Literal["agent_rating", "agent_runs", "num_agents"] | None = None,
- page: int = 1,
- page_size: int = 20,
-):
- """
- This is needed for:
- - Home Page Featured Creators
- - Search Results Page
-
- ---
-
- To support this functionality we need:
- - featured: bool - to limit the list to just featured agents
- - search_query: str - vector search based on the creators profile description.
- - sorted_by: [agent_rating, agent_runs] -
- """
- if page < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page must be greater than 0"
- )
-
- if page_size < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page size must be greater than 0"
- )
-
+ featured: bool = Query(
+ default=False, description="Filter to only show featured creators"
+ ),
+ search_query: str | None = Query(
+ default=None, description="Literal + semantic search on names and descriptions"
+ ),
+ sorted_by: store_db.StoreCreatorsSortOptions | None = None,
+ page: int = Query(ge=1, default=1),
+ page_size: int = Query(ge=1, default=20),
+) -> store_model.CreatorsResponse:
+ """List or search marketplace creators"""
creators = await store_cache._get_cached_store_creators(
featured=featured,
search_query=search_query,
@@ -391,18 +309,12 @@ async def get_creators(
@router.get(
- "/creator/{username}",
+ "/creators/{username}",
summary="Get creator details",
tags=["store", "public"],
- response_model=store_model.CreatorDetails,
)
-async def get_creator(
- username: str,
-):
- """
- Get the details of a creator.
- - Creator Details Page
- """
+async def get_creator(username: str) -> store_model.CreatorDetails:
+ """Get details on a marketplace creator"""
username = urllib.parse.unquote(username).lower()
creator = await store_cache._get_cached_creator_details(username=username)
return creator
@@ -414,20 +326,17 @@ async def get_creator(
@router.get(
- "/myagents",
+ "/my-unpublished-agents",
summary="Get my agents",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.MyAgentsResponse,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
-async def get_my_agents(
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
- page: typing.Annotated[int, fastapi.Query(ge=1)] = 1,
- page_size: typing.Annotated[int, fastapi.Query(ge=1)] = 20,
-):
- """
- Get user's own agents.
- """
+async def get_my_unpublished_agents(
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+ page: int = Query(ge=1, default=1),
+ page_size: int = Query(ge=1, default=20),
+) -> store_model.MyUnpublishedAgentsResponse:
+ """List the authenticated user's unpublished agents"""
agents = await store_db.get_my_agents(user_id, page=page, page_size=page_size)
return agents
@@ -436,28 +345,17 @@ async def get_my_agents(
"/submissions/{submission_id}",
summary="Delete store submission",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=bool,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def delete_submission(
submission_id: str,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Delete a store listing submission.
-
- Args:
- user_id (str): ID of the authenticated user
- submission_id (str): ID of the submission to be deleted
-
- Returns:
- bool: True if the submission was successfully deleted, False otherwise
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> bool:
+ """Delete a marketplace listing submission"""
result = await store_db.delete_store_submission(
user_id=user_id,
submission_id=submission_id,
)
-
return result
@@ -465,37 +363,14 @@ async def delete_submission(
"/submissions",
summary="List my submissions",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.StoreSubmissionsResponse,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def get_submissions(
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
- page: int = 1,
- page_size: int = 20,
-):
- """
- Get a paginated list of store submissions for the authenticated user.
-
- Args:
- user_id (str): ID of the authenticated user
- page (int, optional): Page number for pagination. Defaults to 1.
- page_size (int, optional): Number of submissions per page. Defaults to 20.
-
- Returns:
- StoreListingsResponse: Paginated list of store submissions
-
- Raises:
- HTTPException: If page or page_size are less than 1
- """
- if page < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page must be greater than 0"
- )
-
- if page_size < 1:
- raise fastapi.HTTPException(
- status_code=422, detail="Page size must be greater than 0"
- )
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+ page: int = Query(ge=1, default=1),
+ page_size: int = Query(ge=1, default=20),
+) -> store_model.StoreSubmissionsResponse:
+ """List the authenticated user's marketplace listing submissions"""
listings = await store_db.get_store_submissions(
user_id=user_id,
page=page,
@@ -508,30 +383,17 @@ async def get_submissions(
"/submissions",
summary="Create store submission",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.StoreSubmission,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def create_submission(
submission_request: store_model.StoreSubmissionRequest,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Create a new store listing submission.
-
- Args:
- submission_request (StoreSubmissionRequest): The submission details
- user_id (str): ID of the authenticated user submitting the listing
-
- Returns:
- StoreSubmission: The created store submission
-
- Raises:
- HTTPException: If there is an error creating the submission
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> store_model.StoreSubmission:
+ """Submit a new marketplace listing for review"""
result = await store_db.create_store_submission(
user_id=user_id,
- agent_id=submission_request.agent_id,
- agent_version=submission_request.agent_version,
+ graph_id=submission_request.graph_id,
+ graph_version=submission_request.graph_version,
slug=submission_request.slug,
name=submission_request.name,
video_url=submission_request.video_url,
@@ -544,7 +406,6 @@ async def create_submission(
changes_summary=submission_request.changes_summary or "Initial Submission",
recommended_schedule_cron=submission_request.recommended_schedule_cron,
)
-
return result
@@ -552,28 +413,14 @@ async def create_submission(
"/submissions/{store_listing_version_id}",
summary="Edit store submission",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
- response_model=store_model.StoreSubmission,
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def edit_submission(
store_listing_version_id: str,
submission_request: store_model.StoreSubmissionEditRequest,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Edit an existing store listing submission.
-
- Args:
- store_listing_version_id (str): ID of the store listing version to edit
- submission_request (StoreSubmissionRequest): The updated submission details
- user_id (str): ID of the authenticated user editing the listing
-
- Returns:
- StoreSubmission: The updated store submission
-
- Raises:
- HTTPException: If there is an error editing the submission
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> store_model.StoreSubmission:
+ """Update a pending marketplace listing submission"""
result = await store_db.edit_store_submission(
user_id=user_id,
store_listing_version_id=store_listing_version_id,
@@ -588,7 +435,6 @@ async def edit_submission(
changes_summary=submission_request.changes_summary,
recommended_schedule_cron=submission_request.recommended_schedule_cron,
)
-
return result
@@ -596,115 +442,61 @@ async def edit_submission(
"/submissions/media",
summary="Upload submission media",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def upload_submission_media(
file: fastapi.UploadFile,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-):
- """
- Upload media (images/videos) for a store listing submission.
-
- Args:
- file (UploadFile): The media file to upload
- user_id (str): ID of the authenticated user uploading the media
-
- Returns:
- str: URL of the uploaded media file
-
- Raises:
- HTTPException: If there is an error uploading the media
- """
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> str:
+ """Upload media for a marketplace listing submission"""
media_url = await store_media.upload_media(user_id=user_id, file=file)
return media_url
+class ImageURLResponse(BaseModel):
+ image_url: str
+
+
@router.post(
"/submissions/generate_image",
summary="Generate submission image",
tags=["store", "private"],
- dependencies=[fastapi.Security(autogpt_libs.auth.requires_user)],
+ dependencies=[Security(autogpt_libs.auth.requires_user)],
)
async def generate_image(
- agent_id: str,
- user_id: str = fastapi.Security(autogpt_libs.auth.get_user_id),
-) -> fastapi.responses.Response:
+ graph_id: str,
+ user_id: str = Security(autogpt_libs.auth.get_user_id),
+) -> ImageURLResponse:
"""
- Generate an image for a store listing submission.
-
- Args:
- agent_id (str): ID of the agent to generate an image for
- user_id (str): ID of the authenticated user
-
- Returns:
- JSONResponse: JSON containing the URL of the generated image
+ Generate an image for a marketplace listing submission based on the properties
+ of a given graph.
"""
- agent = await backend.data.graph.get_graph(
- graph_id=agent_id, version=None, user_id=user_id
+ graph = await backend.data.graph.get_graph(
+ graph_id=graph_id, version=None, user_id=user_id
)
- if not agent:
- raise fastapi.HTTPException(
- status_code=404, detail=f"Agent with ID {agent_id} not found"
- )
+ if not graph:
+ raise NotFoundError(f"Agent graph #{graph_id} not found")
# Use .jpeg here since we are generating JPEG images
- filename = f"agent_{agent_id}.jpeg"
+ filename = f"agent_{graph_id}.jpeg"
existing_url = await store_media.check_media_exists(user_id, filename)
if existing_url:
- logger.info(f"Using existing image for agent {agent_id}")
- return fastapi.responses.JSONResponse(content={"image_url": existing_url})
+ logger.info(f"Using existing image for agent graph {graph_id}")
+ return ImageURLResponse(image_url=existing_url)
# Generate agent image as JPEG
- image = await store_image_gen.generate_agent_image(agent=agent)
+ image = await store_image_gen.generate_agent_image(agent=graph)
# Create UploadFile with the correct filename and content_type
image_file = fastapi.UploadFile(
file=image,
filename=filename,
)
-
image_url = await store_media.upload_media(
user_id=user_id, file=image_file, use_file_name=True
)
- return fastapi.responses.JSONResponse(content={"image_url": image_url})
-
-
- "/download/agents/{store_listing_version_id}",
- summary="Download agent file",
- tags=["store", "public"],
-)
-async def download_agent_file(
- store_listing_version_id: str = fastapi.Path(
- ..., description="The ID of the agent to download"
- ),
-) -> fastapi.responses.FileResponse:
- """
- Download the agent file by streaming its content.
-
- Args:
- store_listing_version_id (str): The ID of the agent to download
-
- Returns:
- StreamingResponse: A streaming response containing the agent's graph data.
-
- Raises:
- HTTPException: If the agent is not found or an unexpected error occurs.
- """
- graph_data = await store_db.get_agent(store_listing_version_id)
- file_name = f"agent_{graph_data.id}_v{graph_data.version or 'latest'}.json"
-
- # Sending graph as a stream (similar to marketplace v1)
- with tempfile.NamedTemporaryFile(
- mode="w", suffix=".json", delete=False
- ) as tmp_file:
- tmp_file.write(backend.util.json.dumps(graph_data))
- tmp_file.flush()
-
- return fastapi.responses.FileResponse(
- tmp_file.name, filename=file_name, media_type="application/json"
- )
+ return ImageURLResponse(image_url=image_url)
##############################################
diff --git a/autogpt_platform/backend/backend/api/features/store/routes_test.py b/autogpt_platform/backend/backend/api/features/store/routes_test.py
index fcef3f845a..862db04a67 100644
--- a/autogpt_platform/backend/backend/api/features/store/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/routes_test.py
@@ -8,6 +8,8 @@ import pytest
import pytest_mock
from pytest_snapshot.plugin import Snapshot
+from backend.api.features.store.db import StoreAgentsSortOptions
+
from . import model as store_model
from . import routes as store_routes
@@ -196,7 +198,7 @@ def test_get_agents_sorted(
mock_db_call.assert_called_once_with(
featured=False,
creators=None,
- sorted_by="runs",
+ sorted_by=StoreAgentsSortOptions.RUNS,
search_query=None,
category=None,
page=1,
@@ -380,9 +382,11 @@ def test_get_agent_details(
runs=100,
rating=4.5,
versions=["1.0.0", "1.1.0"],
- agentGraphVersions=["1", "2"],
- agentGraphId="test-graph-id",
+ graph_versions=["1", "2"],
+ graph_id="test-graph-id",
last_updated=FIXED_NOW,
+ active_version_id="test-version-id",
+ has_approved_version=True,
)
mock_db_call = mocker.patch("backend.api.features.store.db.get_store_agent_details")
mock_db_call.return_value = mocked_value
@@ -435,15 +439,17 @@ def test_get_creators_pagination(
) -> None:
mocked_value = store_model.CreatorsResponse(
creators=[
- store_model.Creator(
+ store_model.CreatorDetails(
name=f"Creator {i}",
username=f"creator{i}",
- description=f"Creator {i} description",
avatar_url=f"avatar{i}.jpg",
+ description=f"Creator {i} description",
+ links=[f"user{i}.link.com"],
+ is_featured=False,
num_agents=1,
- agent_rating=4.5,
agent_runs=100,
- is_featured=False,
+ agent_rating=4.5,
+ top_categories=["cat1", "cat2", "cat3"],
)
for i in range(5)
],
@@ -496,19 +502,19 @@ def test_get_creator_details(
mocked_value = store_model.CreatorDetails(
name="Test User",
username="creator1",
+ avatar_url="avatar.jpg",
description="Test creator description",
links=["link1.com", "link2.com"],
- avatar_url="avatar.jpg",
- agent_rating=4.8,
+ is_featured=True,
+ num_agents=5,
agent_runs=1000,
+ agent_rating=4.8,
top_categories=["category1", "category2"],
)
- mock_db_call = mocker.patch(
- "backend.api.features.store.db.get_store_creator_details"
- )
+ mock_db_call = mocker.patch("backend.api.features.store.db.get_store_creator")
mock_db_call.return_value = mocked_value
- response = client.get("/creator/creator1")
+ response = client.get("/creators/creator1")
assert response.status_code == 200
data = store_model.CreatorDetails.model_validate(response.json())
@@ -528,19 +534,26 @@ def test_get_submissions_success(
submissions=[
store_model.StoreSubmission(
listing_id="test-listing-id",
+ user_id="test-user-id",
+ slug="test-agent",
+ listing_version_id="test-version-id",
+ listing_version=1,
+ graph_id="test-agent-id",
+ graph_version=1,
name="Test Agent",
+ sub_heading="Test agent subheading",
description="Test agent description",
+ instructions="Click the button!",
+ categories=["test-category"],
image_urls=["test.jpg"],
- date_submitted=FIXED_NOW,
- status=prisma.enums.SubmissionStatus.APPROVED,
- runs=50,
- rating=4.2,
- agent_id="test-agent-id",
- agent_version=1,
- sub_heading="Test agent subheading",
- slug="test-agent",
video_url="test.mp4",
- categories=["test-category"],
+ agent_output_demo_url="demo_video.mp4",
+ submitted_at=FIXED_NOW,
+ changes_summary="Initial Submission",
+ status=prisma.enums.SubmissionStatus.APPROVED,
+ run_count=50,
+ review_count=5,
+ review_avg_rating=4.2,
)
],
pagination=store_model.Pagination(
diff --git a/autogpt_platform/backend/backend/api/features/store/test_cache_delete.py b/autogpt_platform/backend/backend/api/features/store/test_cache_delete.py
index 298c51d47c..00609efff2 100644
--- a/autogpt_platform/backend/backend/api/features/store/test_cache_delete.py
+++ b/autogpt_platform/backend/backend/api/features/store/test_cache_delete.py
@@ -11,6 +11,7 @@ import pytest
from backend.util.models import Pagination
from . import cache as store_cache
+from .db import StoreAgentsSortOptions
from .model import StoreAgent, StoreAgentsResponse
@@ -215,7 +216,7 @@ class TestCacheDeletion:
await store_cache._get_cached_store_agents(
featured=True,
creator="testuser",
- sorted_by="rating",
+ sorted_by=StoreAgentsSortOptions.RATING,
search_query="AI assistant",
category="productivity",
page=2,
@@ -227,7 +228,7 @@ class TestCacheDeletion:
deleted = store_cache._get_cached_store_agents.cache_delete(
featured=True,
creator="testuser",
- sorted_by="rating",
+ sorted_by=StoreAgentsSortOptions.RATING,
search_query="AI assistant",
category="productivity",
page=2,
@@ -239,7 +240,7 @@ class TestCacheDeletion:
deleted = store_cache._get_cached_store_agents.cache_delete(
featured=True,
creator="testuser",
- sorted_by="rating",
+ sorted_by=StoreAgentsSortOptions.RATING,
search_query="AI assistant",
category="productivity",
page=2,
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 62f2a769e4..a7fc2fa69c 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -449,7 +449,6 @@ async def execute_graph_block(
async def upload_file(
user_id: Annotated[str, Security(get_user_id)],
file: UploadFile = File(...),
- provider: str = "gcs",
expiration_hours: int = 24,
) -> UploadFileResponse:
"""
@@ -512,7 +511,6 @@ async def upload_file(
storage_path = await cloud_storage.store_file(
content=content,
filename=file_name,
- provider=provider,
expiration_hours=expiration_hours,
user_id=user_id,
)
diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.py
index f0ee22deb6..25f68d0a85 100644
--- a/autogpt_platform/backend/backend/api/features/v1_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_test.py
@@ -515,7 +515,6 @@ async def test_upload_file_success(test_user_id: str):
result = await upload_file(
file=upload_file_mock,
user_id=test_user_id,
- provider="gcs",
expiration_hours=24,
)
@@ -533,7 +532,6 @@ async def test_upload_file_success(test_user_id: str):
mock_handler.store_file.assert_called_once_with(
content=file_content,
filename="test.txt",
- provider="gcs",
expiration_hours=24,
user_id=test_user_id,
)
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 7b8786dbc1..d48620ee62 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -55,6 +55,7 @@ from backend.util.exceptions import (
MissingConfigError,
NotAuthorizedError,
NotFoundError,
+ PreconditionFailed,
)
from backend.util.feature_flag import initialize_launchdarkly, shutdown_launchdarkly
from backend.util.service import UnhealthyServiceError
@@ -275,6 +276,7 @@ app.add_exception_handler(RequestValidationError, validation_error_handler)
app.add_exception_handler(pydantic.ValidationError, validation_error_handler)
app.add_exception_handler(MissingConfigError, handle_internal_http_error(503))
app.add_exception_handler(ValueError, handle_internal_http_error(400))
+app.add_exception_handler(PreconditionFailed, handle_internal_http_error(428))
app.add_exception_handler(Exception, handle_internal_http_error(500))
app.include_router(backend.api.features.v1.v1_router, tags=["v1"], prefix="/api")
diff --git a/autogpt_platform/backend/backend/blocks/system/store_operations.py b/autogpt_platform/backend/backend/blocks/system/store_operations.py
index 88958a5707..25cd0788bc 100644
--- a/autogpt_platform/backend/backend/blocks/system/store_operations.py
+++ b/autogpt_platform/backend/backend/blocks/system/store_operations.py
@@ -1,8 +1,8 @@
import logging
-from typing import Literal
from pydantic import BaseModel
+from backend.api.features.store.db import StoreAgentsSortOptions
from backend.blocks._base import (
Block,
BlockCategory,
@@ -176,8 +176,8 @@ class SearchStoreAgentsBlock(Block):
category: str | None = SchemaField(
description="Filter by category", default=None
)
- sort_by: Literal["rating", "runs", "name", "updated_at"] = SchemaField(
- description="How to sort the results", default="rating"
+ sort_by: StoreAgentsSortOptions = SchemaField(
+ description="How to sort the results", default=StoreAgentsSortOptions.RATING
)
limit: int = SchemaField(
description="Maximum number of results to return", default=10, ge=1, le=100
@@ -278,7 +278,7 @@ class SearchStoreAgentsBlock(Block):
self,
query: str | None = None,
category: str | None = None,
- sort_by: Literal["rating", "runs", "name", "updated_at"] = "rating",
+ sort_by: StoreAgentsSortOptions = StoreAgentsSortOptions.RATING,
limit: int = 10,
) -> SearchAgentsResponse:
"""
diff --git a/autogpt_platform/backend/backend/blocks/test/test_store_operations.py b/autogpt_platform/backend/backend/blocks/test/test_store_operations.py
index 088d0d60e5..ac0619c4f9 100644
--- a/autogpt_platform/backend/backend/blocks/test/test_store_operations.py
+++ b/autogpt_platform/backend/backend/blocks/test/test_store_operations.py
@@ -2,6 +2,7 @@ from unittest.mock import MagicMock
import pytest
+from backend.api.features.store.db import StoreAgentsSortOptions
from backend.blocks.system.library_operations import (
AddToLibraryFromStoreBlock,
LibraryAgent,
@@ -121,7 +122,10 @@ async def test_search_store_agents_block(mocker):
)
input_data = block.Input(
- query="test", category="productivity", sort_by="rating", limit=10
+ query="test",
+ category="productivity",
+ sort_by=StoreAgentsSortOptions.RATING, # type: ignore[reportArgumentType]
+ limit=10,
)
outputs = {}
diff --git a/autogpt_platform/backend/backend/copilot/tools/_test_data.py b/autogpt_platform/backend/backend/copilot/tools/_test_data.py
index e46545ba31..1bb8e973ca 100644
--- a/autogpt_platform/backend/backend/copilot/tools/_test_data.py
+++ b/autogpt_platform/backend/backend/copilot/tools/_test_data.py
@@ -151,8 +151,8 @@ async def setup_test_data(server):
unique_slug = f"test-agent-{str(uuid.uuid4())[:8]}"
store_submission = await store_db.create_store_submission(
user_id=user.id,
- agent_id=created_graph.id,
- agent_version=created_graph.version,
+ graph_id=created_graph.id,
+ graph_version=created_graph.version,
slug=unique_slug,
name="Test Agent",
description="A simple test agent",
@@ -161,10 +161,10 @@ async def setup_test_data(server):
image_urls=["https://example.com/image.jpg"],
)
- assert store_submission.store_listing_version_id is not None
+ assert store_submission.listing_version_id is not None
# 4. Approve the store listing version
await store_db.review_store_submission(
- store_listing_version_id=store_submission.store_listing_version_id,
+ store_listing_version_id=store_submission.listing_version_id,
is_approved=True,
external_comments="Approved for testing",
internal_comments="Test approval",
@@ -321,8 +321,8 @@ async def setup_llm_test_data(server):
unique_slug = f"llm-test-agent-{str(uuid.uuid4())[:8]}"
store_submission = await store_db.create_store_submission(
user_id=user.id,
- agent_id=created_graph.id,
- agent_version=created_graph.version,
+ graph_id=created_graph.id,
+ graph_version=created_graph.version,
slug=unique_slug,
name="LLM Test Agent",
description="An agent with LLM capabilities",
@@ -330,9 +330,9 @@ async def setup_llm_test_data(server):
categories=["testing", "ai"],
image_urls=["https://example.com/image.jpg"],
)
- assert store_submission.store_listing_version_id is not None
+ assert store_submission.listing_version_id is not None
await store_db.review_store_submission(
- store_listing_version_id=store_submission.store_listing_version_id,
+ store_listing_version_id=store_submission.listing_version_id,
is_approved=True,
external_comments="Approved for testing",
internal_comments="Test approval for LLM agent",
@@ -476,8 +476,8 @@ async def setup_firecrawl_test_data(server):
unique_slug = f"firecrawl-test-agent-{str(uuid.uuid4())[:8]}"
store_submission = await store_db.create_store_submission(
user_id=user.id,
- agent_id=created_graph.id,
- agent_version=created_graph.version,
+ graph_id=created_graph.id,
+ graph_version=created_graph.version,
slug=unique_slug,
name="Firecrawl Test Agent",
description="An agent with Firecrawl integration (no credentials)",
@@ -485,9 +485,9 @@ async def setup_firecrawl_test_data(server):
categories=["testing", "scraping"],
image_urls=["https://example.com/image.jpg"],
)
- assert store_submission.store_listing_version_id is not None
+ assert store_submission.listing_version_id is not None
await store_db.review_store_submission(
- store_listing_version_id=store_submission.store_listing_version_id,
+ store_listing_version_id=store_submission.listing_version_id,
is_approved=True,
external_comments="Approved for testing",
internal_comments="Test approval for Firecrawl agent",
diff --git a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
index d2368f2656..52c1eafb21 100644
--- a/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/customize_agent.py
@@ -3,9 +3,9 @@
import logging
from typing import Any
-from backend.api.features.store.exceptions import AgentNotFoundError
from backend.copilot.model import ChatSession
from backend.data.db_accessors import store_db as get_store_db
+from backend.util.exceptions import NotFoundError
from .agent_generator import (
AgentGeneratorNotConfiguredError,
@@ -140,7 +140,7 @@ class CustomizeAgentTool(BaseTool):
agent_details = await store_db.get_store_agent_details(
username=creator_username, agent_name=agent_slug
)
- except AgentNotFoundError:
+ except NotFoundError:
return ErrorResponse(
message=(
f"Could not find marketplace agent '{agent_id}'. "
diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.py
index 3cb6f24b87..f07317b879 100644
--- a/autogpt_platform/backend/backend/data/graph_test.py
+++ b/autogpt_platform/backend/backend/data/graph_test.py
@@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, patch
from uuid import UUID
import fastapi.exceptions
+import prisma
import pytest
from pytest_snapshot.plugin import Snapshot
@@ -250,8 +251,8 @@ async def test_clean_graph(server: SpinTestServer):
"_test_id": "node_with_secrets",
"input": "normal_value",
"control_test_input": "should be preserved",
- "api_key": "secret_api_key_123", # Should be filtered
- "password": "secret_password_456", # Should be filtered
+ "api_key": "secret_api_key_123", # Should be filtered # pragma: allowlist secret # noqa
+ "password": "secret_password_456", # Should be filtered # pragma: allowlist secret # noqa
"token": "secret_token_789", # Should be filtered
"credentials": { # Should be filtered
"id": "fake-github-credentials-id",
@@ -354,9 +355,24 @@ async def test_access_store_listing_graph(server: SpinTestServer):
create_graph, DEFAULT_USER_ID
)
+ # Ensure the default user has a Profile (required for store submissions)
+ existing_profile = await prisma.models.Profile.prisma().find_first(
+ where={"userId": DEFAULT_USER_ID}
+ )
+ if not existing_profile:
+ await prisma.models.Profile.prisma().create(
+ data=prisma.types.ProfileCreateInput(
+ userId=DEFAULT_USER_ID,
+ name="Default User",
+ username=f"default-user-{DEFAULT_USER_ID[:8]}",
+ description="Default test user profile",
+ links=[],
+ )
+ )
+
store_submission_request = store.StoreSubmissionRequest(
- agent_id=created_graph.id,
- agent_version=created_graph.version,
+ graph_id=created_graph.id,
+ graph_version=created_graph.version,
slug=created_graph.id,
name="Test name",
sub_heading="Test sub heading",
@@ -385,8 +401,8 @@ async def test_access_store_listing_graph(server: SpinTestServer):
assert False, "Failed to create store listing"
slv_id = (
- store_listing.store_listing_version_id
- if store_listing.store_listing_version_id is not None
+ store_listing.listing_version_id
+ if store_listing.listing_version_id is not None
else None
)
diff --git a/autogpt_platform/backend/backend/data/notifications.py b/autogpt_platform/backend/backend/data/notifications.py
index 0b80acba62..88c8b2f361 100644
--- a/autogpt_platform/backend/backend/data/notifications.py
+++ b/autogpt_platform/backend/backend/data/notifications.py
@@ -13,7 +13,14 @@ from prisma.types import (
)
# from backend.notifications.models import NotificationEvent
-from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ EmailStr,
+ Field,
+ field_validator,
+ model_validator,
+)
from backend.util.exceptions import DatabaseError
from backend.util.json import SafeJson
@@ -175,10 +182,26 @@ class RefundRequestData(BaseNotificationData):
balance: int
-class AgentApprovalData(BaseNotificationData):
+class _LegacyAgentFieldsMixin:
+ """Temporary patch to handle existing queued payloads"""
+
+ # FIXME: remove in next release
+
+ @model_validator(mode="before")
+ @classmethod
+ def _map_legacy_agent_fields(cls, values: Any):
+ if isinstance(values, dict):
+ if "graph_id" not in values and "agent_id" in values:
+ values["graph_id"] = values.pop("agent_id")
+ if "graph_version" not in values and "agent_version" in values:
+ values["graph_version"] = values.pop("agent_version")
+ return values
+
+
+class AgentApprovalData(_LegacyAgentFieldsMixin, BaseNotificationData):
agent_name: str
- agent_id: str
- agent_version: int
+ graph_id: str
+ graph_version: int
reviewer_name: str
reviewer_email: str
comments: str
@@ -193,10 +216,10 @@ class AgentApprovalData(BaseNotificationData):
return value
-class AgentRejectionData(BaseNotificationData):
+class AgentRejectionData(_LegacyAgentFieldsMixin, BaseNotificationData):
agent_name: str
- agent_id: str
- agent_version: int
+ graph_id: str
+ graph_version: int
reviewer_name: str
reviewer_email: str
comments: str
diff --git a/autogpt_platform/backend/backend/data/notifications_test.py b/autogpt_platform/backend/backend/data/notifications_test.py
index bdbf64401e..7469183a12 100644
--- a/autogpt_platform/backend/backend/data/notifications_test.py
+++ b/autogpt_platform/backend/backend/data/notifications_test.py
@@ -15,8 +15,8 @@ class TestAgentApprovalData:
"""Test creating valid AgentApprovalData."""
data = AgentApprovalData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="John Doe",
reviewer_email="[email protected]",
comments="Great agent, approved!",
@@ -25,8 +25,8 @@ class TestAgentApprovalData:
)
assert data.agent_name == "Test Agent"
- assert data.agent_id == "test-agent-123"
- assert data.agent_version == 1
+ assert data.graph_id == "test-agent-123"
+ assert data.graph_version == 1
assert data.reviewer_name == "John Doe"
assert data.reviewer_email == "[email protected]"
assert data.comments == "Great agent, approved!"
@@ -40,8 +40,8 @@ class TestAgentApprovalData:
):
AgentApprovalData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="John Doe",
reviewer_email="[email protected]",
comments="Great agent, approved!",
@@ -53,8 +53,8 @@ class TestAgentApprovalData:
"""Test AgentApprovalData with empty comments."""
data = AgentApprovalData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="John Doe",
reviewer_email="[email protected]",
comments="", # Empty comments
@@ -72,8 +72,8 @@ class TestAgentRejectionData:
"""Test creating valid AgentRejectionData."""
data = AgentRejectionData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="Jane Doe",
reviewer_email="[email protected]",
comments="Please fix the security issues before resubmitting.",
@@ -82,8 +82,8 @@ class TestAgentRejectionData:
)
assert data.agent_name == "Test Agent"
- assert data.agent_id == "test-agent-123"
- assert data.agent_version == 1
+ assert data.graph_id == "test-agent-123"
+ assert data.graph_version == 1
assert data.reviewer_name == "Jane Doe"
assert data.reviewer_email == "[email protected]"
assert data.comments == "Please fix the security issues before resubmitting."
@@ -97,8 +97,8 @@ class TestAgentRejectionData:
):
AgentRejectionData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="Jane Doe",
reviewer_email="[email protected]",
comments="Please fix the security issues.",
@@ -111,8 +111,8 @@ class TestAgentRejectionData:
long_comment = "A" * 1000 # Very long comment
data = AgentRejectionData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="Jane Doe",
reviewer_email="[email protected]",
comments=long_comment,
@@ -126,8 +126,8 @@ class TestAgentRejectionData:
"""Test that models can be serialized and deserialized."""
original_data = AgentRejectionData(
agent_name="Test Agent",
- agent_id="test-agent-123",
- agent_version=1,
+ graph_id="test-agent-123",
+ graph_version=1,
reviewer_name="Jane Doe",
reviewer_email="[email protected]",
comments="Please fix the issues.",
@@ -142,8 +142,8 @@ class TestAgentRejectionData:
restored_data = AgentRejectionData.model_validate(data_dict)
assert restored_data.agent_name == original_data.agent_name
- assert restored_data.agent_id == original_data.agent_id
- assert restored_data.agent_version == original_data.agent_version
+ assert restored_data.graph_id == original_data.graph_id
+ assert restored_data.graph_version == original_data.graph_version
assert restored_data.reviewer_name == original_data.reviewer_name
assert restored_data.reviewer_email == original_data.reviewer_email
assert restored_data.comments == original_data.comments
diff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.py
index 4af8e8dffd..72f46fa172 100644
--- a/autogpt_platform/backend/backend/data/onboarding.py
+++ b/autogpt_platform/backend/backend/data/onboarding.py
@@ -244,7 +244,10 @@ def _clean_and_split(text: str) -> list[str]:
def _calculate_points(
- agent, categories: list[str], custom: list[str], integrations: list[str]
+ agent: prisma.models.StoreAgent,
+ categories: list[str],
+ custom: list[str],
+ integrations: list[str],
) -> int:
"""
Calculates the total points for an agent based on the specified criteria.
@@ -397,7 +400,7 @@ async def get_recommended_agents(user_id: str) -> list[StoreAgentDetails]:
storeAgents = await prisma.models.StoreAgent.prisma().find_many(
where={
"is_available": True,
- "useForOnboarding": True,
+ "use_for_onboarding": True,
},
order=[
{"featured": "desc"},
@@ -407,7 +410,7 @@ async def get_recommended_agents(user_id: str) -> list[StoreAgentDetails]:
take=100,
)
- # If not enough agents found, relax the useForOnboarding filter
+ # If not enough agents found, relax the use_for_onboarding filter
if len(storeAgents) < 2:
storeAgents = await prisma.models.StoreAgent.prisma().find_many(
where=prisma.types.StoreAgentWhereInput(**where_clause),
@@ -420,7 +423,7 @@ async def get_recommended_agents(user_id: str) -> list[StoreAgentDetails]:
)
# Calculate points for the first X agents and choose the top 2
- agent_points = []
+ agent_points: list[tuple[prisma.models.StoreAgent, int]] = []
for agent in storeAgents[:POINTS_AGENT_COUNT]:
points = _calculate_points(
agent, categories, custom, user_onboarding.integrations
@@ -430,28 +433,7 @@ async def get_recommended_agents(user_id: str) -> list[StoreAgentDetails]:
agent_points.sort(key=lambda x: x[1], reverse=True)
recommended_agents = [agent for agent, _ in agent_points[:2]]
- return [
- StoreAgentDetails(
- store_listing_version_id=agent.storeListingVersionId,
- slug=agent.slug,
- agent_name=agent.agent_name,
- agent_video=agent.agent_video or "",
- agent_output_demo=agent.agent_output_demo or "",
- agent_image=agent.agent_image,
- creator=agent.creator_username,
- creator_avatar=agent.creator_avatar,
- sub_heading=agent.sub_heading,
- description=agent.description,
- categories=agent.categories,
- runs=agent.runs,
- rating=agent.rating,
- versions=agent.versions,
- agentGraphVersions=agent.agentGraphVersions,
- agentGraphId=agent.agentGraphId,
- last_updated=agent.updated_at,
- )
- for agent in recommended_agents
- ]
+ return [StoreAgentDetails.from_db(agent) for agent in recommended_agents]
@cached(maxsize=1, ttl_seconds=300) # Cache for 5 minutes since this rarely changes
diff --git a/autogpt_platform/backend/backend/executor/manager_test.py b/autogpt_platform/backend/backend/executor/manager_test.py
index 69deba4b00..76093e5174 100644
--- a/autogpt_platform/backend/backend/executor/manager_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_test.py
@@ -2,6 +2,7 @@ import logging
from unittest.mock import AsyncMock, patch
import fastapi.responses
+import prisma
import pytest
import backend.api.features.library.model
@@ -497,9 +498,24 @@ async def test_store_listing_graph(server: SpinTestServer):
test_user = await create_test_user()
test_graph = await create_graph(server, create_test_graph(), test_user)
+ # Ensure the test user has a Profile (required for store submissions)
+ existing_profile = await prisma.models.Profile.prisma().find_first(
+ where={"userId": test_user.id}
+ )
+ if not existing_profile:
+ await prisma.models.Profile.prisma().create(
+ data=prisma.types.ProfileCreateInput(
+ userId=test_user.id,
+ name=test_user.name or "Test User",
+ username=f"test-user-{test_user.id[:8]}",
+ description="Test user profile",
+ links=[],
+ )
+ )
+
store_submission_request = backend.api.features.store.model.StoreSubmissionRequest(
- agent_id=test_graph.id,
- agent_version=test_graph.version,
+ graph_id=test_graph.id,
+ graph_version=test_graph.version,
slug=test_graph.id,
name="Test name",
sub_heading="Test sub heading",
@@ -517,8 +533,8 @@ async def test_store_listing_graph(server: SpinTestServer):
assert False, "Failed to create store listing"
slv_id = (
- store_listing.store_listing_version_id
- if store_listing.store_listing_version_id is not None
+ store_listing.listing_version_id
+ if store_listing.listing_version_id is not None
else None
)
diff --git a/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2
index 14ca591580..fceb350c7a 100644
--- a/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2
+++ b/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2
@@ -2,8 +2,8 @@
{#
Template variables:
data.agent_name: the name of the approved agent
- data.agent_id: the ID of the agent
- data.agent_version: the version of the agent
+ data.graph_id: the ID of the agent
+ data.graph_version: the version of the agent
data.reviewer_name: the name of the reviewer who approved it
data.reviewer_email: the email of the reviewer
data.comments: comments from the reviewer
@@ -70,4 +70,4 @@
Thank you for contributing to the AutoGPT ecosystem! 🚀
</p>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2
index 69a8081900..7c4ddd41c3 100644
--- a/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2
+++ b/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2
@@ -2,8 +2,8 @@
{#
Template variables:
data.agent_name: the name of the rejected agent
- data.agent_id: the ID of the agent
- data.agent_version: the version of the agent
+ data.graph_id: the ID of the agent
+ data.graph_version: the version of the agent
data.reviewer_name: the name of the reviewer who rejected it
data.reviewer_email: the email of the reviewer
data.comments: comments from the reviewer explaining the rejection
@@ -74,4 +74,4 @@
We're excited to see your improved agent submission! 🚀
</p>
-{% endblock %}
\ No newline at end of file
+{% endblock %}
diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.py
index ffda783873..04172465b9 100644
--- a/autogpt_platform/backend/backend/util/exceptions.py
+++ b/autogpt_platform/backend/backend/util/exceptions.py
@@ -64,6 +64,10 @@ class GraphNotInLibraryError(GraphNotAccessibleError):
"""Raised when attempting to execute a graph that is not / no longer in the user's library."""
+class PreconditionFailed(Exception):
+ """The user must do something else first before trying the current operation"""
+
+
class InsufficientBalanceError(ValueError):
user_id: str
message: str
diff --git a/autogpt_platform/backend/migrations/20260228114302_improve_store_entity_relations/migration.sql b/autogpt_platform/backend/migrations/20260228114302_improve_store_entity_relations/migration.sql
new file mode 100644
index 0000000000..809ed64185
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260228114302_improve_store_entity_relations/migration.sql
@@ -0,0 +1,32 @@
+BEGIN;
+
+-- Drop illogical column StoreListing.agentGraphVersion;
+ALTER TABLE "StoreListing" DROP CONSTRAINT "StoreListing_agentGraphId_agentGraphVersion_fkey";
+DROP INDEX "StoreListing_agentGraphId_agentGraphVersion_idx";
+ALTER TABLE "StoreListing" DROP COLUMN "agentGraphVersion";
+
+-- Add uniqueness constraint to Profile.userId and remove invalid data
+--
+-- Delete any profiles with null userId (which is invalid and doesn't occur in theory)
+DELETE FROM "Profile" WHERE "userId" IS NULL;
+--
+-- Delete duplicate profiles per userId, keeping the most recently updated one
+DELETE FROM "Profile"
+WHERE "id" IN (
+ SELECT "id" FROM (
+ SELECT "id", ROW_NUMBER() OVER (
+ PARTITION BY "userId" ORDER BY "updatedAt" DESC, "id" DESC
+ ) AS rn
+ FROM "Profile"
+ ) ranked
+ WHERE rn > 1
+);
+--
+-- Add userId uniqueness constraint
+ALTER TABLE "Profile" ALTER COLUMN "userId" SET NOT NULL;
+CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId");
+
+-- Add formal relation StoreListing.owningUserId -> Profile.userId
+ALTER TABLE "StoreListing" ADD CONSTRAINT "StoreListing_owner_Profile_fkey" FOREIGN KEY ("owningUserId") REFERENCES "Profile"("userId") ON DELETE CASCADE ON UPDATE CASCADE;
+
+COMMIT;
diff --git a/autogpt_platform/backend/migrations/20260304123456_update_store_views/migration.sql b/autogpt_platform/backend/migrations/20260304123456_update_store_views/migration.sql
new file mode 100644
index 0000000000..3cd7a16670
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260304123456_update_store_views/migration.sql
@@ -0,0 +1,219 @@
+-- Update the StoreSubmission and StoreAgent views with additional fields, clearer field names, and faster joins.
+-- Steps:
+-- 1. Update `mv_agent_run_counts` to exclude runs by the agent's creator
+-- a. Drop dependent views `StoreAgent` and `Creator`
+-- b. Update `mv_agent_run_counts` and its index
+-- c. Recreate `StoreAgent` view (with updates)
+-- d. Restore `Creator` view
+-- 2. Update `StoreSubmission` view
+-- 3. Update `StoreListingReview` indices to make `StoreSubmission` query more efficient
+
+BEGIN;
+
+-- Drop views that are dependent on mv_agent_run_counts
+DROP VIEW IF EXISTS "StoreAgent";
+DROP VIEW IF EXISTS "Creator";
+
+-- Update materialized view for agent run counts to exclude runs by the agent's creator
+DROP INDEX IF EXISTS "idx_mv_agent_run_counts";
+DROP MATERIALIZED VIEW IF EXISTS "mv_agent_run_counts";
+CREATE MATERIALIZED VIEW "mv_agent_run_counts" AS
+SELECT
+ run."agentGraphId" AS graph_id,
+ COUNT(*) AS run_count
+FROM "AgentGraphExecution" run
+JOIN "AgentGraph" graph ON graph.id = run."agentGraphId"
+-- Exclude runs by the agent's creator to avoid inflating run counts
+WHERE graph."userId" != run."userId"
+GROUP BY run."agentGraphId";
+
+-- Recreate index
+CREATE UNIQUE INDEX IF NOT EXISTS "idx_mv_agent_run_counts" ON "mv_agent_run_counts"("graph_id");
+
+-- Re-populate the materialized view
+REFRESH MATERIALIZED VIEW "mv_agent_run_counts";
+
+
+-- Recreate the StoreAgent view with the following changes
+-- (compared to 20260115210000_remove_storelistingversion_search):
+-- - Narrow to *explicitly active* version (sl.activeVersionId) instead of MAX(version)
+-- - Add `recommended_schedule_cron` column
+-- - Rename `"storeListingVersionId"` -> `listing_version_id`
+-- - Rename `"agentGraphVersions"` -> `graph_versions`
+-- - Rename `"agentGraphId"` -> `graph_id`
+-- - Rename `"useForOnboarding"` -> `use_for_onboarding`
+CREATE OR REPLACE VIEW "StoreAgent" AS
+WITH store_agent_versions AS (
+ SELECT
+ "storeListingId",
+ array_agg(DISTINCT version::text ORDER BY version::text) AS versions
+ FROM "StoreListingVersion"
+ WHERE "submissionStatus" = 'APPROVED'
+ GROUP BY "storeListingId"
+),
+agent_graph_versions AS (
+ SELECT
+ "storeListingId",
+ array_agg(DISTINCT "agentGraphVersion"::text ORDER BY "agentGraphVersion"::text) AS graph_versions
+ FROM "StoreListingVersion"
+ WHERE "submissionStatus" = 'APPROVED'
+ GROUP BY "storeListingId"
+)
+SELECT
+ sl.id AS listing_id,
+ slv.id AS listing_version_id,
+ slv."createdAt" AS updated_at,
+ sl.slug,
+ COALESCE(slv.name, '') AS agent_name,
+ slv."videoUrl" AS agent_video,
+ slv."agentOutputDemoUrl" AS agent_output_demo,
+ COALESCE(slv."imageUrls", ARRAY[]::text[]) AS agent_image,
+ slv."isFeatured" AS featured,
+ cp.username AS creator_username,
+ cp."avatarUrl" AS creator_avatar,
+ slv."subHeading" AS sub_heading,
+ slv.description,
+ slv.categories,
+ COALESCE(arc.run_count, 0::bigint) AS runs,
+ COALESCE(reviews.avg_rating, 0.0)::double precision AS rating,
+ COALESCE(sav.versions, ARRAY[slv.version::text]) AS versions,
+ slv."agentGraphId" AS graph_id,
+ COALESCE(
+ agv.graph_versions,
+ ARRAY[slv."agentGraphVersion"::text]
+ ) AS graph_versions,
+ slv."isAvailable" AS is_available,
+ COALESCE(sl."useForOnboarding", false) AS use_for_onboarding,
+ slv."recommendedScheduleCron" AS recommended_schedule_cron
+FROM "StoreListing" AS sl
+JOIN "StoreListingVersion" AS slv
+ ON slv."storeListingId" = sl.id
+ AND slv.id = sl."activeVersionId"
+ AND slv."submissionStatus" = 'APPROVED'
+JOIN "AgentGraph" AS ag
+ ON slv."agentGraphId" = ag.id
+ AND slv."agentGraphVersion" = ag.version
+LEFT JOIN "Profile" AS cp
+ ON sl."owningUserId" = cp."userId"
+LEFT JOIN "mv_review_stats" AS reviews
+ ON sl.id = reviews."storeListingId"
+LEFT JOIN "mv_agent_run_counts" AS arc
+ ON ag.id = arc.graph_id
+LEFT JOIN store_agent_versions AS sav
+ ON sl.id = sav."storeListingId"
+LEFT JOIN agent_graph_versions AS agv
+ ON sl.id = agv."storeListingId"
+WHERE sl."isDeleted" = false
+ AND sl."hasApprovedVersion" = true;
+
+
+-- Restore Creator view as last updated in 20250604130249_optimise_store_agent_and_creator_views,
+-- with minor changes:
+-- - Ensure top_categories always TEXT[]
+-- - Filter out empty ('') categories
+CREATE OR REPLACE VIEW "Creator" AS
+WITH creator_listings AS (
+ SELECT
+ sl."owningUserId",
+ sl.id AS listing_id,
+ slv."agentGraphId",
+ slv.categories,
+ sr.score,
+ ar.run_count
+ FROM "StoreListing" sl
+ JOIN "StoreListingVersion" slv
+ ON slv."storeListingId" = sl.id
+ AND slv."submissionStatus" = 'APPROVED'
+ LEFT JOIN "StoreListingReview" sr
+ ON sr."storeListingVersionId" = slv.id
+ LEFT JOIN "mv_agent_run_counts" ar
+ ON ar.graph_id = slv."agentGraphId"
+ WHERE sl."isDeleted" = false
+ AND sl."hasApprovedVersion" = true
+),
+creator_stats AS (
+ SELECT
+ cl."owningUserId",
+ COUNT(DISTINCT cl.listing_id) AS num_agents,
+ AVG(COALESCE(cl.score, 0)::numeric) AS agent_rating,
+ SUM(COALESCE(cl.run_count, 0)) AS agent_runs,
+ array_agg(DISTINCT cat ORDER BY cat)
+ FILTER (WHERE cat IS NOT NULL AND cat != '') AS all_categories
+ FROM creator_listings cl
+ LEFT JOIN LATERAL unnest(COALESCE(cl.categories, ARRAY[]::text[])) AS cat ON true
+ GROUP BY cl."owningUserId"
+)
+SELECT
+ p.username,
+ p.name,
+ p."avatarUrl" AS avatar_url,
+ p.description,
+ COALESCE(cs.all_categories, ARRAY[]::text[]) AS top_categories,
+ p.links,
+ p."isFeatured" AS is_featured,
+ COALESCE(cs.num_agents, 0::bigint) AS num_agents,
+ COALESCE(cs.agent_rating, 0.0) AS agent_rating,
+ COALESCE(cs.agent_runs, 0::numeric) AS agent_runs
+FROM "Profile" p
+LEFT JOIN creator_stats cs ON cs."owningUserId" = p."userId";
+
+
+-- Recreate the StoreSubmission view with updated fields & query strategy:
+-- - Uses mv_agent_run_counts instead of full AgentGraphExecution table scan + aggregation
+-- - Renamed agent_id, agent_version -> graph_id, graph_version
+-- - Renamed store_listing_version_id -> listing_version_id
+-- - Renamed date_submitted -> submitted_at
+-- - Renamed runs, rating -> run_count, review_avg_rating
+-- - Added fields: instructions, agent_output_demo_url, review_count, is_deleted
+DROP VIEW IF EXISTS "StoreSubmission";
+CREATE OR REPLACE VIEW "StoreSubmission" AS
+WITH review_stats AS (
+ SELECT
+ "storeListingVersionId" AS version_id, -- more specific than mv_review_stats
+ avg(score) AS avg_rating,
+ count(*) AS review_count
+ FROM "StoreListingReview"
+ GROUP BY "storeListingVersionId"
+)
+SELECT
+ sl.id AS listing_id,
+ sl."owningUserId" AS user_id,
+ sl.slug AS slug,
+
+ slv.id AS listing_version_id,
+ slv.version AS listing_version,
+ slv."agentGraphId" AS graph_id,
+ slv."agentGraphVersion" AS graph_version,
+ slv.name AS name,
+ slv."subHeading" AS sub_heading,
+ slv.description AS description,
+ slv.instructions AS instructions,
+ slv.categories AS categories,
+ slv."imageUrls" AS image_urls,
+ slv."videoUrl" AS video_url,
+ slv."agentOutputDemoUrl" AS agent_output_demo_url,
+ slv."submittedAt" AS submitted_at,
+ slv."changesSummary" AS changes_summary,
+ slv."submissionStatus" AS status,
+ slv."reviewedAt" AS reviewed_at,
+ slv."reviewerId" AS reviewer_id,
+ slv."reviewComments" AS review_comments,
+ slv."internalComments" AS internal_comments,
+ slv."isDeleted" AS is_deleted,
+
+ COALESCE(run_stats.run_count, 0::bigint) AS run_count,
+ COALESCE(review_stats.review_count, 0::bigint) AS review_count,
+ COALESCE(review_stats.avg_rating, 0.0)::double precision AS review_avg_rating
+FROM "StoreListing" sl
+JOIN "StoreListingVersion" slv ON slv."storeListingId" = sl.id
+LEFT JOIN review_stats ON review_stats.version_id = slv.id
+LEFT JOIN mv_agent_run_counts run_stats ON run_stats.graph_id = slv."agentGraphId"
+WHERE sl."isDeleted" = false;
+
+
+-- Drop unused index on StoreListingReview.reviewByUserId
+DROP INDEX IF EXISTS "StoreListingReview_reviewByUserId_idx";
+-- Add index on storeListingVersionId to make StoreSubmission query faster
+CREATE INDEX "StoreListingReview_storeListingVersionId_idx" ON "StoreListingReview"("storeListingVersionId");
+
+COMMIT;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 8a48a7a764..ed992ec20f 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -281,7 +281,6 @@ model AgentGraph {
Presets AgentPreset[]
LibraryAgents LibraryAgent[]
- StoreListings StoreListing[]
StoreListingVersions StoreListingVersion[]
@@id(name: "graphVersionId", [id, version])
@@ -814,10 +813,8 @@ model Profile {
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
- // Only 1 of user or group can be set.
- // The user this profile belongs to, if any.
- userId String?
- User User? @relation(fields: [userId], references: [id], onDelete: Cascade)
+ userId String @unique
+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)
name String
username String @unique
@@ -830,6 +827,7 @@ model Profile {
isFeatured Boolean @default(false)
LibraryAgents LibraryAgent[]
+ StoreListings StoreListing[]
@@index([userId])
}
@@ -860,9 +858,9 @@ view Creator {
}
view StoreAgent {
- listing_id String @id
- storeListingVersionId String
- updated_at DateTime
+ listing_id String @id
+ listing_version_id String
+ updated_at DateTime
slug String
agent_name String
@@ -879,10 +877,12 @@ view StoreAgent {
runs Int
rating Float
versions String[]
- agentGraphVersions String[]
- agentGraphId String
+ graph_id String
+ graph_versions String[]
is_available Boolean @default(true)
- useForOnboarding Boolean @default(false)
+ use_for_onboarding Boolean @default(false)
+
+ recommended_schedule_cron String?
// Materialized views used (refreshed every 15 minutes via pg_cron):
// - mv_agent_run_counts - Pre-aggregated agent execution counts by agentGraphId
@@ -896,41 +896,52 @@ view StoreAgent {
}
view StoreSubmission {
- listing_id String @id
- user_id String
- slug String
- name String
- sub_heading String
- description String
- image_urls String[]
- date_submitted DateTime
- status SubmissionStatus
- runs Int
- rating Float
- agent_id String
- agent_version Int
- store_listing_version_id String
- reviewer_id String?
- review_comments String?
- internal_comments String?
- reviewed_at DateTime?
- changes_summary String?
- video_url String?
- categories String[]
-
- // Index or unique are not applied to views
+ // From StoreListing:
+ listing_id String
+ user_id String
+ slug String
+
+ // From StoreListingVersion:
+ listing_version_id String @id
+ listing_version Int
+ graph_id String
+ graph_version Int
+
+ name String
+ sub_heading String
+ description String
+ instructions String?
+ categories String[]
+ image_urls String[]
+ video_url String?
+ agent_output_demo_url String?
+
+ submitted_at DateTime?
+ changes_summary String?
+ status SubmissionStatus
+ reviewed_at DateTime?
+ reviewer_id String?
+ review_comments String?
+ internal_comments String?
+
+ is_deleted Boolean
+
+ // Aggregated from AgentGraphExecutions and StoreListingReviews:
+ run_count Int
+ review_count Int
+ review_avg_rating Float
}
// Note: This is actually a MATERIALIZED VIEW in the database
// Refreshed automatically every 15 minutes via pg_cron (with fallback to manual refresh)
view mv_agent_run_counts {
- agentGraphId String @unique
- run_count Int
+ graph_id String @unique
+ run_count Int // excluding runs by the graph's creator
- // Pre-aggregated count of AgentGraphExecution records by agentGraphId
- // Used by StoreAgent and Creator views for performance optimization
- // Unique index created automatically on agentGraphId for fast lookups
- // Refresh uses CONCURRENTLY to avoid blocking reads
+ // Pre-aggregated count of AgentGraphExecution records by agentGraphId.
+ // Used by StoreAgent, Creator, and StoreSubmission views for performance optimization.
+ // - Should have a unique index on graph_id for fast lookups
+ // - Refresh should use CONCURRENTLY to avoid blocking reads
}
// Note: This is actually a MATERIALIZED VIEW in the database
@@ -979,22 +990,18 @@ model StoreListing {
ActiveVersion StoreListingVersion? @relation("ActiveVersion", fields: [activeVersionId], references: [id])
// The agent link here is only so we can do lookup on agentId
- agentGraphId String
- agentGraphVersion Int
- AgentGraph AgentGraph @relation(fields: [agentGraphId, agentGraphVersion], references: [id, version], onDelete: Cascade)
+ agentGraphId String @unique
- owningUserId String
- OwningUser User @relation(fields: [owningUserId], references: [id])
+ owningUserId String
+ OwningUser User @relation(fields: [owningUserId], references: [id])
+ CreatorProfile Profile @relation(fields: [owningUserId], references: [userId], map: "StoreListing_owner_Profile_fkey", onDelete: Cascade)
// Relations
Versions StoreListingVersion[] @relation("ListingVersions")
- // Unique index on agentId to ensure only one listing per agent, regardless of number of versions the agent has.
- @@unique([agentGraphId])
@@unique([owningUserId, slug])
// Used in the view query
@@index([isDeleted, hasApprovedVersion])
- @@index([agentGraphId, agentGraphVersion])
}
model StoreListingVersion {
@@ -1089,16 +1096,16 @@ model UnifiedContentEmbedding {
// Search data
embedding Unsupported("vector(1536)") // pgvector embedding (extension in platform schema)
searchableText String // Combined text for search and fallback
- search Unsupported("tsvector")? @default(dbgenerated("''::tsvector")) // Full-text search (auto-populated by trigger)
+ search Unsupported("tsvector")? @default(dbgenerated("''::tsvector")) // Full-text search (auto-populated by trigger)
metadata Json @default("{}") // Content-specific metadata
+ // NO @@index for search - GIN index "UnifiedContentEmbedding_search_idx" created via SQL migration
+ // Prisma may generate DROP INDEX on migrate dev - that's okay, migration recreates it
@@unique([contentType, contentId, userId], map: "UnifiedContentEmbedding_contentType_contentId_userId_key")
@@index([contentType])
@@index([userId])
@@index([contentType, userId])
@@index([embedding], map: "UnifiedContentEmbedding_embedding_idx")
- // NO @@index for search - GIN index "UnifiedContentEmbedding_search_idx" created via SQL migration
- // Prisma may generate DROP INDEX on migrate dev - that's okay, migration recreates it
}
model StoreListingReview {
@@ -1115,8 +1122,9 @@ model StoreListingReview {
score Int
comments String?
+ // Enforce one review per user per listing version
@@unique([storeListingVersionId, reviewByUserId])
- @@index([reviewByUserId])
+ @@index([storeListingVersionId])
}
enum SubmissionStatus {
diff --git a/autogpt_platform/backend/snapshots/agt_details b/autogpt_platform/backend/snapshots/agt_details
index 0d69f1c23a..28fb570635 100644
--- a/autogpt_platform/backend/snapshots/agt_details
+++ b/autogpt_platform/backend/snapshots/agt_details
@@ -23,14 +23,14 @@
"1.0.0",
"1.1.0"
],
- "agentGraphVersions": [
+ "graph_id": "test-graph-id",
+ "graph_versions": [
"1",
"2"
],
- "agentGraphId": "test-graph-id",
"last_updated": "2023-01-01T00:00:00",
"recommended_schedule_cron": null,
- "active_version_id": null,
- "has_approved_version": false,
+ "active_version_id": "test-version-id",
+ "has_approved_version": true,
"changelog": null
}
\ No newline at end of file
diff --git a/autogpt_platform/backend/snapshots/creator_details b/autogpt_platform/backend/snapshots/creator_details
index 0b4e4812c2..c4de360700 100644
--- a/autogpt_platform/backend/snapshots/creator_details
+++ b/autogpt_platform/backend/snapshots/creator_details
@@ -1,14 +1,16 @@
{
- "name": "Test User",
"username": "creator1",
+ "name": "Test User",
"description": "Test creator description",
+ "avatar_url": "avatar.jpg",
"links": [
"link1.com",
"link2.com"
],
- "avatar_url": "avatar.jpg",
- "agent_rating": 4.8,
+ "is_featured": true,
+ "num_agents": 5,
"agent_runs": 1000,
+ "agent_rating": 4.8,
"top_categories": [
"category1",
"category2"
diff --git a/autogpt_platform/backend/snapshots/creators_pagination b/autogpt_platform/backend/snapshots/creators_pagination
index 5076160d5d..71d8f53380 100644
--- a/autogpt_platform/backend/snapshots/creators_pagination
+++ b/autogpt_platform/backend/snapshots/creators_pagination
@@ -1,54 +1,94 @@
{
"creators": [
{
- "name": "Creator 0",
"username": "creator0",
+ "name": "Creator 0",
"description": "Creator 0 description",
"avatar_url": "avatar0.jpg",
+ "links": [
+ "user0.link.com"
+ ],
+ "is_featured": false,
"num_agents": 1,
- "agent_rating": 4.5,
"agent_runs": 100,
- "is_featured": false
+ "agent_rating": 4.5,
+ "top_categories": [
+ "cat1",
+ "cat2",
+ "cat3"
+ ]
},
{
- "name": "Creator 1",
"username": "creator1",
+ "name": "Creator 1",
"description": "Creator 1 description",
"avatar_url": "avatar1.jpg",
+ "links": [
+ "user1.link.com"
+ ],
+ "is_featured": false,
"num_agents": 1,
- "agent_rating": 4.5,
"agent_runs": 100,
- "is_featured": false
+ "agent_rating": 4.5,
+ "top_categories": [
+ "cat1",
+ "cat2",
+ "cat3"
+ ]
},
{
- "name": "Creator 2",
"username": "creator2",
+ "name": "Creator 2",
"description": "Creator 2 description",
"avatar_url": "avatar2.jpg",
+ "links": [
+ "user2.link.com"
+ ],
+ "is_featured": false,
"num_agents": 1,
- "agent_rating": 4.5,
"agent_runs": 100,
- "is_featured": false
+ "agent_rating": 4.5,
+ "top_categories": [
+ "cat1",
+ "cat2",
+ "cat3"
+ ]
},
{
- "name": "Creator 3",
"username": "creator3",
+ "name": "Creator 3",
"description": "Creator 3 description",
"avatar_url": "avatar3.jpg",
+ "links": [
+ "user3.link.com"
+ ],
+ "is_featured": false,
"num_agents": 1,
- "agent_rating": 4.5,
"agent_runs": 100,
- "is_featured": false
+ "agent_rating": 4.5,
+ "top_categories": [
+ "cat1",
+ "cat2",
+ "cat3"
+ ]
},
{
- "name": "Creator 4",
"username": "creator4",
+ "name": "Creator 4",
"description": "Creator 4 description",
"avatar_url": "avatar4.jpg",
+ "links": [
+ "user4.link.com"
+ ],
+ "is_featured": false,
"num_agents": 1,
- "agent_rating": 4.5,
"agent_runs": 100,
- "is_featured": false
+ "agent_rating": 4.5,
+ "top_categories": [
+ "cat1",
+ "cat2",
+ "cat3"
+ ]
}
],
"pagination": {
diff --git a/autogpt_platform/backend/snapshots/sub_success b/autogpt_platform/backend/snapshots/sub_success
index 268d577745..abd56f99d9 100644
--- a/autogpt_platform/backend/snapshots/sub_success
+++ b/autogpt_platform/backend/snapshots/sub_success
@@ -2,32 +2,33 @@
"submissions": [
{
"listing_id": "test-listing-id",
- "agent_id": "test-agent-id",
- "agent_version": 1,
+ "user_id": "test-user-id",
+ "slug": "test-agent",
+ "listing_version_id": "test-version-id",
+ "listing_version": 1,
+ "graph_id": "test-agent-id",
+ "graph_version": 1,
"name": "Test Agent",
"sub_heading": "Test agent subheading",
- "slug": "test-agent",
"description": "Test agent description",
- "instructions": null,
+ "instructions": "Click the button!",
+ "categories": [
+ "test-category"
+ ],
"image_urls": [
"test.jpg"
],
- "date_submitted": "2023-01-01T00:00:00",
+ "video_url": "test.mp4",
+ "agent_output_demo_url": "demo_video.mp4",
+ "submitted_at": "2023-01-01T00:00:00",
+ "changes_summary": "Initial Submission",
"status": "APPROVED",
- "runs": 50,
- "rating": 4.2,
- "store_listing_version_id": null,
- "version": null,
+ "reviewed_at": null,
"reviewer_id": null,
"review_comments": null,
- "internal_comments": null,
- "reviewed_at": null,
- "changes_summary": null,
- "video_url": "test.mp4",
- "agent_output_demo_url": null,
- "categories": [
- "test-category"
- ]
+ "run_count": 50,
+ "review_count": 5,
+ "review_avg_rating": 4.2
}
],
"pagination": {
diff --git a/autogpt_platform/backend/test/e2e_test_data.py b/autogpt_platform/backend/test/e2e_test_data.py
index 7288197a90..500075da21 100644
--- a/autogpt_platform/backend/test/e2e_test_data.py
+++ b/autogpt_platform/backend/test/e2e_test_data.py
@@ -128,7 +128,7 @@ class TestDataCreator:
else:
email = faker.unique.email()
- password = "testpassword123" # Standard test password
+ password = "testpassword123" # Standard test password # pragma: allowlist secret # noqa
user_id = f"test-user-{i}-{faker.uuid4()}"
# Create user in Supabase Auth (if needed)
@@ -571,8 +571,8 @@ class TestDataCreator:
if test_user and self.agent_graphs:
test_submission_data = {
"user_id": test_user["id"],
- "agent_id": self.agent_graphs[0]["id"],
- "agent_version": 1,
+ "graph_id": self.agent_graphs[0]["id"],
+ "graph_version": 1,
"slug": "test-agent-submission",
"name": "Test Agent Submission",
"sub_heading": "A test agent for frontend testing",
@@ -593,9 +593,9 @@ class TestDataCreator:
print("✅ Created special test store submission for [email protected]")
# ALWAYS approve and feature the test submission
- if test_submission.store_listing_version_id:
+ if test_submission.listing_version_id:
approved_submission = await review_store_submission(
- store_listing_version_id=test_submission.store_listing_version_id,
+ store_listing_version_id=test_submission.listing_version_id,
is_approved=True,
external_comments="Test submission approved",
internal_comments="Auto-approved test submission",
@@ -605,7 +605,7 @@ class TestDataCreator:
print("✅ Approved test store submission")
await prisma.storelistingversion.update(
- where={"id": test_submission.store_listing_version_id},
+ where={"id": test_submission.listing_version_id},
data={"isFeatured": True},
)
featured_count += 1
@@ -640,8 +640,8 @@ class TestDataCreator:
submission = await create_store_submission(
user_id=user["id"],
- agent_id=graph["id"],
- agent_version=graph.get("version", 1),
+ graph_id=graph["id"],
+ graph_version=graph.get("version", 1),
slug=faker.slug(),
name=graph.get("name", faker.sentence(nb_words=3)),
sub_heading=faker.sentence(),
@@ -654,7 +654,7 @@ class TestDataCreator:
submissions.append(submission.model_dump())
print(f"✅ Created store submission: {submission.name}")
- if submission.store_listing_version_id:
+ if submission.listing_version_id:
# DETERMINISTIC: First N submissions are always approved
# First GUARANTEED_FEATURED_AGENTS of those are always featured
should_approve = (
@@ -667,7 +667,7 @@ class TestDataCreator:
try:
reviewer_id = random.choice(self.users)["id"]
approved_submission = await review_store_submission(
- store_listing_version_id=submission.store_listing_version_id,
+ store_listing_version_id=submission.listing_version_id,
is_approved=True,
external_comments="Auto-approved for E2E testing",
internal_comments="Automatically approved by E2E test data script",
@@ -683,9 +683,7 @@ class TestDataCreator:
if should_feature:
try:
await prisma.storelistingversion.update(
- where={
- "id": submission.store_listing_version_id
- },
+ where={"id": submission.listing_version_id},
data={"isFeatured": True},
)
featured_count += 1
@@ -699,9 +697,7 @@ class TestDataCreator:
elif random.random() < 0.2:
try:
await prisma.storelistingversion.update(
- where={
- "id": submission.store_listing_version_id
- },
+ where={"id": submission.listing_version_id},
data={"isFeatured": True},
)
featured_count += 1
@@ -721,7 +717,7 @@ class TestDataCreator:
try:
reviewer_id = random.choice(self.users)["id"]
await review_store_submission(
- store_listing_version_id=submission.store_listing_version_id,
+ store_listing_version_id=submission.listing_version_id,
is_approved=False,
external_comments="Submission rejected - needs improvements",
internal_comments="Automatically rejected by E2E test data script",
diff --git a/autogpt_platform/backend/test/test_data_creator.py b/autogpt_platform/backend/test/test_data_creator.py
index befb1dcacd..75ffb63154 100644
--- a/autogpt_platform/backend/test/test_data_creator.py
+++ b/autogpt_platform/backend/test/test_data_creator.py
@@ -394,7 +394,6 @@ async def main():
listing = await db.storelisting.create(
data={
"agentGraphId": graph.id,
- "agentGraphVersion": graph.version,
"owningUserId": user.id,
"hasApprovedVersion": random.choice([True, False]),
"slug": slug,
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts
index 480e79e669..948cdd4bb7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts
@@ -1,33 +1,39 @@
"use server";
import { revalidatePath } from "next/cache";
-import BackendApi from "@/lib/autogpt-server-api";
import {
- StoreListingsWithVersionsResponse,
- SubmissionStatus,
-} from "@/lib/autogpt-server-api/types";
+ getV2GetAdminListingsHistory,
+ postV2ReviewStoreSubmission,
+ getV2AdminDownloadAgentFile,
+} from "@/app/api/__generated__/endpoints/admin/admin";
+import { okData } from "@/app/api/helpers";
+import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
export async function approveAgent(formData: FormData) {
- const data = {
- store_listing_version_id: formData.get("id") as string,
+ const storeListingVersionId = formData.get("id") as string;
+ const comments = formData.get("comments") as string;
+
+ await postV2ReviewStoreSubmission(storeListingVersionId, {
+ store_listing_version_id: storeListingVersionId,
is_approved: true,
- comments: formData.get("comments") as string,
- };
- const api = new BackendApi();
- await api.reviewSubmissionAdmin(data.store_listing_version_id, data);
+ comments,
+ });
revalidatePath("/admin/marketplace");
}
export async function rejectAgent(formData: FormData) {
- const data = {
- store_listing_version_id: formData.get("id") as string,
+ const storeListingVersionId = formData.get("id") as string;
+ const comments = formData.get("comments") as string;
+ const internal_comments =
+ (formData.get("internal_comments") as string) || undefined;
+
+ await postV2ReviewStoreSubmission(storeListingVersionId, {
+ store_listing_version_id: storeListingVersionId,
is_approved: false,
- comments: formData.get("comments") as string,
- internal_comments: formData.get("internal_comments") as string,
- };
- const api = new BackendApi();
- await api.reviewSubmissionAdmin(data.store_listing_version_id, data);
+ comments,
+ internal_comments,
+ });
revalidatePath("/admin/marketplace");
}
@@ -37,26 +43,18 @@ export async function getAdminListingsWithVersions(
search?: string,
page: number = 1,
pageSize: number = 20,
-): Promise<StoreListingsWithVersionsResponse> {
- const data: Record<string, any> = {
+) {
+ const response = await getV2GetAdminListingsHistory({
+ status,
+ search,
page,
page_size: pageSize,
- };
-
- if (status) {
- data.status = status;
- }
-
- if (search) {
- data.search = search;
- }
- const api = new BackendApi();
- const response = await api.getAdminListingsWithVersions(data);
- return response;
+ });
+
+ return okData(response);
}
export async function downloadAsAdmin(storeListingVersion: string) {
- const api = new BackendApi();
- const file = await api.downloadStoreAgentAdmin(storeListingVersion);
- return file;
+ const response = await getV2AdminDownloadAgentFile(storeListingVersion);
+ return okData(response);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminAgentsDataTable.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminAgentsDataTable.tsx
index 727cf42813..dd3030ea2e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminAgentsDataTable.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/AdminAgentsDataTable.tsx
@@ -6,10 +6,8 @@ import {
TableHeader,
TableRow,
} from "@/components/__legacy__/ui/table";
-import {
- StoreSubmission,
- SubmissionStatus,
-} from "@/lib/autogpt-server-api/types";
+import type { StoreSubmissionAdminView } from "@/app/api/__generated__/models/storeSubmissionAdminView";
+import type { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
import { PaginationControls } from "../../../../../components/__legacy__/ui/pagination-controls";
import { getAdminListingsWithVersions } from "@/app/(platform)/admin/marketplace/actions";
import { ExpandableRow } from "./ExpandleRow";
@@ -17,12 +15,14 @@ import { SearchAndFilterAdminMarketplace } from "./SearchFilterForm";
// Helper function to get the latest version by version number
const getLatestVersionByNumber = (
- versions: StoreSubmission[],
-): StoreSubmission | null => {
+ versions: StoreSubmissionAdminView[] | undefined,
+): StoreSubmissionAdminView | null => {
if (!versions || versions.length === 0) return null;
return versions.reduce(
(latest, current) =>
- (current.version ?? 0) > (latest.version ?? 1) ? current : latest,
+ (current.listing_version ?? 0) > (latest.listing_version ?? 1)
+ ? current
+ : latest,
versions[0],
);
};
@@ -37,12 +37,14 @@ export async function AdminAgentsDataTable({
initialSearch?: string;
}) {
// Server-side data fetching
- const { listings, pagination } = await getAdminListingsWithVersions(
+ const data = await getAdminListingsWithVersions(
initialStatus,
initialSearch,
initialPage,
10,
);
+ const listings = data?.listings ?? [];
+ const pagination = data?.pagination;
return (
<div className="space-y-4">
@@ -92,7 +94,7 @@ export async function AdminAgentsDataTable({
<PaginationControls
currentPage={initialPage}
- totalPages={pagination.total_pages}
+ totalPages={pagination?.total_pages ?? 1}
/>
</div>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ApproveRejectButton.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ApproveRejectButton.tsx
index a2f954d572..ab7752c290 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ApproveRejectButton.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ApproveRejectButton.tsx
@@ -13,7 +13,7 @@ import {
} from "@/components/__legacy__/ui/dialog";
import { Label } from "@/components/__legacy__/ui/label";
import { Textarea } from "@/components/__legacy__/ui/textarea";
-import type { StoreSubmission } from "@/lib/autogpt-server-api/types";
+import type { StoreSubmissionAdminView } from "@/app/api/__generated__/models/storeSubmissionAdminView";
import { useRouter } from "next/navigation";
import {
approveAgent,
@@ -23,7 +23,7 @@ import {
export function ApproveRejectButtons({
version,
}: {
- version: StoreSubmission;
+ version: StoreSubmissionAdminView;
}) {
const router = useRouter();
const [isApproveDialogOpen, setIsApproveDialogOpen] = useState(false);
@@ -95,7 +95,7 @@ export function ApproveRejectButtons({
<input
type="hidden"
name="id"
- value={version.store_listing_version_id || ""}
+ value={version.listing_version_id || ""}
/>
<div className="grid gap-4 py-4">
@@ -142,7 +142,7 @@ export function ApproveRejectButtons({
<input
type="hidden"
name="id"
- value={version.store_listing_version_id || ""}
+ value={version.listing_version_id || ""}
/>
<div className="grid gap-4 py-4">
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ExpandleRow.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ExpandleRow.tsx
index e13a5eeed3..78a5eb5504 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ExpandleRow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/ExpandleRow.tsx
@@ -12,11 +12,9 @@ import {
import { Badge } from "@/components/__legacy__/ui/badge";
import { ChevronDown, ChevronRight } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
-import {
- type StoreListingWithVersions,
- type StoreSubmission,
- SubmissionStatus,
-} from "@/lib/autogpt-server-api/types";
+import type { StoreListingWithVersionsAdminView } from "@/app/api/__generated__/models/storeListingWithVersionsAdminView";
+import type { StoreSubmissionAdminView } from "@/app/api/__generated__/models/storeSubmissionAdminView";
+import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
import { ApproveRejectButtons } from "./ApproveRejectButton";
import { DownloadAgentAdminButton } from "./DownloadAgentButton";
@@ -38,8 +36,8 @@ export function ExpandableRow({
listing,
latestVersion,
}: {
- listing: StoreListingWithVersions;
- latestVersion: StoreSubmission | null;
+ listing: StoreListingWithVersionsAdminView;
+ latestVersion: StoreSubmissionAdminView | null;
}) {
const [expanded, setExpanded] = useState(false);
@@ -69,17 +67,17 @@ export function ExpandableRow({
{latestVersion?.status && getStatusBadge(latestVersion.status)}
</TableCell>
<TableCell onClick={() => setExpanded(!expanded)}>
- {latestVersion?.date_submitted
- ? formatDistanceToNow(new Date(latestVersion.date_submitted), {
+ {latestVersion?.submitted_at
+ ? formatDistanceToNow(new Date(latestVersion.submitted_at), {
addSuffix: true,
})
: "Unknown"}
</TableCell>
<TableCell className="text-right">
<div className="flex justify-end gap-2">
- {latestVersion?.store_listing_version_id && (
+ {latestVersion?.listing_version_id && (
<DownloadAgentAdminButton
- storeListingVersionId={latestVersion.store_listing_version_id}
+ storeListingVersionId={latestVersion.listing_version_id}
/>
)}
@@ -115,14 +113,17 @@ export function ExpandableRow({
</TableRow>
</TableHeader>
<TableBody>
- {listing.versions
- .sort((a, b) => (b.version ?? 1) - (a.version ?? 0))
+ {(listing.versions ?? [])
+ .sort(
+ (a, b) =>
+ (b.listing_version ?? 1) - (a.listing_version ?? 0),
+ )
.map((version) => (
- <TableRow key={version.store_listing_version_id}>
+ <TableRow key={version.listing_version_id}>
<TableCell>
- v{version.version || "?"}
- {version.store_listing_version_id ===
- listing.active_version_id && (
+ v{version.listing_version || "?"}
+ {version.listing_version_id ===
+ listing.active_listing_version_id && (
<Badge className="ml-2 bg-blue-500">Active</Badge>
)}
</TableCell>
@@ -131,9 +132,9 @@ export function ExpandableRow({
{version.changes_summary || "No summary"}
</TableCell>
<TableCell>
- {version.date_submitted
+ {version.submitted_at
? formatDistanceToNow(
- new Date(version.date_submitted),
+ new Date(version.submitted_at),
{ addSuffix: true },
)
: "Unknown"}
@@ -182,10 +183,10 @@ export function ExpandableRow({
{/* <TableCell>{version.categories.join(", ")}</TableCell> */}
<TableCell className="text-right">
<div className="flex justify-end gap-2">
- {version.store_listing_version_id && (
+ {version.listing_version_id && (
<DownloadAgentAdminButton
storeListingVersionId={
- version.store_listing_version_id
+ version.listing_version_id
}
/>
)}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx
index ac67867eaf..6c32b3b5a0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/components/SearchFilterForm.tsx
@@ -12,7 +12,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/__legacy__/ui/select";
-import { SubmissionStatus } from "@/lib/autogpt-server-api/types";
+import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
export function SearchAndFilterAdminMarketplace({
initialSearch,
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/page.tsx
index 7fcfb6b5d4..fb9b1ff52b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/page.tsx
@@ -1,11 +1,11 @@
import { withRoleAccess } from "@/lib/withRoleAccess";
import { Suspense } from "react";
-import type { SubmissionStatus } from "@/lib/autogpt-server-api/types";
+import type { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
import { AdminAgentsDataTable } from "./components/AdminAgentsDataTable";
type MarketplaceAdminPageSearchParams = {
page?: string;
- status?: string;
+ status?: SubmissionStatus;
search?: string;
};
@@ -15,7 +15,7 @@ async function AdminMarketplaceDashboard({
searchParams: MarketplaceAdminPageSearchParams;
}) {
const page = searchParams.page ? Number.parseInt(searchParams.page) : 1;
- const status = searchParams.status as SubmissionStatus | undefined;
+ const status = searchParams.status;
const search = searchParams.search;
return (
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/AgentVersionChangelog.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/AgentVersionChangelog.tsx
index 8781376b17..a760a03f7e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/AgentVersionChangelog.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/AgentVersionChangelog.tsx
@@ -42,8 +42,8 @@ export function AgentVersionChangelog({
// Create version info from available graph versions
const storeData = okData(storeAgentData) as StoreAgentDetails | undefined;
- const agentVersions: VersionInfo[] = storeData?.agentGraphVersions
- ? storeData.agentGraphVersions
+ const agentVersions: VersionInfo[] = storeData?.graph_versions
+ ? storeData.graph_versions
.map((versionStr: string) => parseInt(versionStr, 10))
.sort((a: number, b: number) => b - a) // Sort descending (newest first)
.map((version: number) => ({
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/useRunAgentInputs.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/useRunAgentInputs.ts
index 38fe30b9ea..3d03c4aa70 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/useRunAgentInputs.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/useRunAgentInputs.ts
@@ -1,14 +1,16 @@
-import BackendAPI from "@/lib/autogpt-server-api";
+import { postV1UploadFileToCloudStorage } from "@/app/api/__generated__/endpoints/files/files";
+import { resolveResponse } from "@/app/api/helpers";
import { useState } from "react";
export function useRunAgentInputs() {
- const api = new BackendAPI();
const [uploadProgress, setUploadProgress] = useState(0);
async function handleUploadFile(file: File) {
- const result = await api.uploadFile(file, "gcs", 24, (progress) =>
- setUploadProgress(progress),
+ setUploadProgress(0);
+ const result = await resolveResponse(
+ postV1UploadFileToCloudStorage({ file }, { expiration_hours: 24 }),
);
+ setUploadProgress(100);
return result;
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useMarketplaceUpdate.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useMarketplaceUpdate.ts
index 158fd3f134..b9c6cb5811 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useMarketplaceUpdate.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/hooks/useMarketplaceUpdate.ts
@@ -95,14 +95,14 @@ export function useMarketplaceUpdate({ agent }: UseMarketplaceUpdateProps) {
const submissionsResponse = okData(submissionsData) as any;
const agentSubmissions =
submissionsResponse?.submissions?.filter(
- (submission: StoreSubmission) => submission.agent_id === agent.graph_id,
+ (submission: StoreSubmission) => submission.graph_id === agent.graph_id,
) || [];
const highestSubmittedVersion =
agentSubmissions.length > 0
? Math.max(
...agentSubmissions.map(
- (submission: StoreSubmission) => submission.agent_version,
+ (submission: StoreSubmission) => submission.graph_version,
),
)
: 0;
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorCard/CreatorCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorCard/CreatorCard.tsx
index aa21125597..5e1bb78798 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorCard/CreatorCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorCard/CreatorCard.tsx
@@ -3,7 +3,7 @@ import { backgroundColor } from "./helper";
interface CreatorCardProps {
creatorName: string;
- creatorImage: string;
+ creatorImage: string | null;
bio: string;
agentsUploaded: number;
onClick: () => void;
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorInfoCard/CreatorInfoCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorInfoCard/CreatorInfoCard.tsx
index 86868186d1..addefc7ca7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorInfoCard/CreatorInfoCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/CreatorInfoCard/CreatorInfoCard.tsx
@@ -7,7 +7,7 @@ import { StarRatingIcons } from "@/components/__legacy__/ui/icons";
interface CreatorInfoCardProps {
username: string;
handle: string;
- avatarSrc: string;
+ avatarSrc: string | null;
categories: string[];
averageRating: number;
totalRuns: number;
@@ -29,12 +29,14 @@ export const CreatorInfoCard = ({
>
<div className="flex w-full flex-col items-start justify-start gap-3.5 sm:h-[218px]">
<Avatar className="h-[100px] w-[100px] sm:h-[130px] sm:w-[130px]">
- <AvatarImage
- width={130}
- height={130}
- src={avatarSrc}
- alt={`${username}'s avatar`}
- />
+ {avatarSrc && (
+ <AvatarImage
+ width={130}
+ height={130}
+ src={avatarSrc}
+ alt={`${username}'s avatar`}
+ />
+ )}
<AvatarFallback
size={130}
className="h-[100px] w-[100px] sm:h-[130px] sm:w-[130px]"
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/FeaturedCreators.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/FeaturedCreators.tsx
index ddb3e1a50d..095e25f1d7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/FeaturedCreators.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/FeaturedCreators.tsx
@@ -2,11 +2,11 @@
import { CreatorCard } from "../CreatorCard/CreatorCard";
import { useFeaturedCreators } from "./useFeaturedCreators";
-import { Creator } from "@/app/api/__generated__/models/creator";
+import { CreatorDetails } from "@/app/api/__generated__/models/creatorDetails";
interface FeaturedCreatorsProps {
title?: string;
- featuredCreators: Creator[];
+ featuredCreators: CreatorDetails[];
}
export const FeaturedCreators = ({
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/useFeaturedCreators.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/useFeaturedCreators.ts
index 80e2aa9832..e4d4040db4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/useFeaturedCreators.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedCreators/useFeaturedCreators.ts
@@ -1,8 +1,8 @@
-import { Creator } from "@/app/api/__generated__/models/creator";
+import { CreatorDetails } from "@/app/api/__generated__/models/creatorDetails";
import { useRouter } from "next/navigation";
interface useFeaturedCreatorsProps {
- featuredCreators: Creator[];
+ featuredCreators: CreatorDetails[];
}
export const useFeaturedCreators = ({
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTable/AgentTable.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTable/AgentTable.tsx
index f5a25fc6bc..50511206fd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTable/AgentTable.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTable/AgentTable.tsx
@@ -3,33 +3,23 @@
import * as React from "react";
import { AgentTableCard } from "../AgentTableCard/AgentTableCard";
import { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
-import {
- AgentTableRow,
- AgentTableRowProps,
-} from "../AgentTableRow/AgentTableRow";
+import { AgentTableRow } from "../AgentTableRow/AgentTableRow";
import { StoreSubmissionEditRequest } from "@/app/api/__generated__/models/storeSubmissionEditRequest";
export interface AgentTableProps {
- agents: Omit<
- AgentTableRowProps,
- | "setSelectedAgents"
- | "selectedAgents"
- | "onViewSubmission"
- | "onDeleteSubmission"
- | "onEditSubmission"
- >[];
+ storeAgentSubmissions: StoreSubmission[];
onViewSubmission: (submission: StoreSubmission) => void;
onDeleteSubmission: (submission_id: string) => void;
onEditSubmission: (
submission: StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
},
) => void;
}
export const AgentTable: React.FC<AgentTableProps> = ({
- agents,
+ storeAgentSubmissions,
onViewSubmission,
onDeleteSubmission,
onEditSubmission,
@@ -63,19 +53,19 @@ export const AgentTable: React.FC<AgentTableProps> = ({
</div>
{/* Table body */}
- {agents.length > 0 ? (
+ {storeAgentSubmissions.length > 0 ? (
<div className="flex flex-col">
- {agents.map((agent) => (
- <div key={agent.id} className="md:block">
+ {storeAgentSubmissions.map((agentSubmission) => (
+ <div key={agentSubmission.listing_version_id} className="md:block">
<AgentTableRow
- {...agent}
+ storeAgentSubmission={agentSubmission}
onViewSubmission={onViewSubmission}
onDeleteSubmission={onDeleteSubmission}
onEditSubmission={onEditSubmission}
/>
<div className="block md:hidden">
<AgentTableCard
- {...agent}
+ storeAgentSubmission={agentSubmission}
onViewSubmission={onViewSubmission}
/>
</div>
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx
index 0e1a6ac095..4595405a80 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx
@@ -3,62 +3,38 @@
import Image from "next/image";
import { IconStarFilled, IconMore } from "@/components/__legacy__/ui/icons";
import { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
-import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
import { Status } from "@/components/__legacy__/Status";
export interface AgentTableCardProps {
- agent_id: string;
- agent_version: number;
- agentName: string;
- sub_heading: string;
- description: string;
- imageSrc: string[];
- dateSubmitted: Date;
- status: SubmissionStatus;
- runs: number;
- rating: number;
- id: number;
- listing_id?: string;
+ storeAgentSubmission: StoreSubmission;
onViewSubmission: (submission: StoreSubmission) => void;
}
export const AgentTableCard = ({
- agent_id,
- agent_version,
- agentName,
- sub_heading,
- description,
- imageSrc,
- dateSubmitted,
- status,
- runs,
- rating,
- listing_id,
+ storeAgentSubmission,
onViewSubmission,
}: AgentTableCardProps) => {
const onView = () => {
- onViewSubmission({
- listing_id: listing_id || "",
- agent_id,
- agent_version,
- slug: "",
- name: agentName,
- sub_heading,
- description,
- image_urls: imageSrc,
- date_submitted: dateSubmitted,
- status: status,
- runs,
- rating,
- });
+ onViewSubmission(storeAgentSubmission);
};
+ const {
+ graph_version,
+ name: agentName,
+ description,
+ image_urls,
+ submitted_at,
+ status,
+ run_count,
+ review_avg_rating: rating,
+ } = storeAgentSubmission;
+
return (
<div className="border-b border-neutral-300 p-4 dark:border-neutral-700">
<div className="flex gap-4">
<div className="relative aspect-video w-24 shrink-0 overflow-hidden rounded-lg bg-[#d9d9d9] dark:bg-neutral-800">
<Image
- src={imageSrc?.[0] ?? "/nada.png"}
+ src={image_urls?.[0] ?? "/nada.png"}
alt={agentName}
fill
style={{ objectFit: "cover" }}
@@ -70,7 +46,7 @@ export const AgentTableCard = ({
{agentName}
</h3>
<span className="text-[13px] text-neutral-500 dark:text-neutral-400">
- v{agent_version}
+ v{graph_version}
</span>
</div>
<p className="line-clamp-2 text-sm text-neutral-600 dark:text-neutral-400">
@@ -88,14 +64,14 @@ export const AgentTableCard = ({
<div className="mt-4 flex flex-wrap gap-4">
<Status status={status} />
<div className="text-sm text-neutral-600 dark:text-neutral-400">
- {dateSubmitted.toLocaleDateString()}
+ {submitted_at && submitted_at.toLocaleDateString()}
</div>
<div className="text-sm text-neutral-600 dark:text-neutral-400">
- {runs.toLocaleString()} runs
+ {(run_count ?? 0).toLocaleString()} runs
</div>
<div className="flex items-center gap-1">
<span className="text-sm font-medium text-neutral-800 dark:text-neutral-200">
- {rating.toFixed(1)}
+ {(rating ?? 0).toFixed(1)}
</span>
<IconStarFilled className="h-4 w-4 text-neutral-800 dark:text-neutral-200" />
</div>
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx
index 917b872df1..414da27bda 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx
@@ -18,92 +18,60 @@ import {
import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
import { StoreSubmissionEditRequest } from "@/app/api/__generated__/models/storeSubmissionEditRequest";
-export interface AgentTableRowProps {
- agent_id: string;
- agent_version: number;
- agentName: string;
- sub_heading: string;
- description: string;
- imageSrc: string[];
- dateSubmitted: Date;
- status: SubmissionStatus;
- runs: number;
- rating: number;
- id: number;
- video_url?: string;
- categories?: string[];
- store_listing_version_id?: string;
- changes_summary?: string;
- listing_id?: string;
+export type AgentTableRowProps = {
+ storeAgentSubmission: StoreSubmission;
onViewSubmission: (submission: StoreSubmission) => void;
onDeleteSubmission: (submission_id: string) => void;
onEditSubmission: (
submission: StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
},
) => void;
-}
+};
export const AgentTableRow = ({
- agent_id,
- agent_version,
- agentName,
- sub_heading,
- description,
- imageSrc,
- dateSubmitted,
- status,
- runs,
- rating,
- id,
- video_url,
- categories,
- store_listing_version_id,
- changes_summary,
- listing_id,
+ storeAgentSubmission,
onViewSubmission,
onDeleteSubmission,
onEditSubmission,
}: AgentTableRowProps) => {
const { handleView, handleDelete, handleEdit } = useAgentTableRow({
- id,
+ storeAgentSubmission,
onViewSubmission,
onDeleteSubmission,
onEditSubmission,
- agent_id,
- agent_version,
- agentName,
- sub_heading,
+ });
+
+ const {
+ listing_version_id,
+ graph_id,
+ graph_version,
+ name: agentName,
description,
- imageSrc,
- dateSubmitted,
+ image_urls,
+ submitted_at,
status,
- runs,
- rating,
- video_url,
- categories,
- store_listing_version_id,
- changes_summary,
- listing_id,
- });
+ run_count,
+ review_avg_rating,
+ } = storeAgentSubmission;
const canModify = status === SubmissionStatus.PENDING;
return (
<div
data-testid="agent-table-row"
- data-agent-id={agent_id}
- data-submission-id={store_listing_version_id}
+ data-agent-id={graph_id}
+ data-submission-id={listing_version_id}
className="hidden items-center border-b border-neutral-300 px-4 py-4 hover:bg-neutral-50 dark:border-neutral-700 dark:hover:bg-neutral-800 md:flex"
>
<div className="grid w-full grid-cols-[minmax(400px,1fr),180px,140px,100px,100px,40px] items-center gap-4">
{/* Agent info column */}
<div className="flex items-center gap-4">
- {imageSrc?.[0] ? (
+ {image_urls?.[0] ? (
<div className="relative aspect-video w-32 shrink-0 overflow-hidden rounded-[10px] bg-zinc-100">
<Image
- src={imageSrc?.[0] ?? ""}
+ src={image_urls?.[0] ?? ""}
alt={agentName}
fill
style={{ objectFit: "cover" }}
@@ -128,7 +96,7 @@ export const AgentTableRow = ({
size="small"
className="text-neutral-500 dark:text-neutral-400"
>
- v{agent_version}
+ v{graph_version}
</Text>
</div>
<Text
@@ -142,7 +110,7 @@ export const AgentTableRow = ({
{/* Date column */}
<div className="text-sm text-neutral-600 dark:text-neutral-400">
- {dateSubmitted.toLocaleDateString()}
+ {submitted_at && submitted_at.toLocaleDateString()}
</div>
{/* Status column */}
@@ -152,14 +120,16 @@ export const AgentTableRow = ({
{/* Runs column */}
<div className="text-right text-sm text-neutral-600 dark:text-neutral-400">
- {runs?.toLocaleString() ?? "0"}
+ {run_count?.toLocaleString() ?? "0"}
</div>
{/* Reviews column */}
<div className="text-right">
- {rating ? (
+ {review_avg_rating ? (
<div className="flex items-center justify-end gap-1">
- <span className="text-sm font-medium">{rating.toFixed(1)}</span>
+ <span className="text-sm font-medium">
+ {review_avg_rating.toFixed(1)}
+ </span>
<StarIcon weight="fill" className="h-2 w-2" />
</div>
) : (
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/useAgentTableRow.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/useAgentTableRow.ts
index 7879446d27..16fcad0489 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/useAgentTableRow.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/useAgentTableRow.ts
@@ -1,97 +1,45 @@
import { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
import { StoreSubmissionEditRequest } from "@/app/api/__generated__/models/storeSubmissionEditRequest";
-import { SubmissionStatus } from "@/app/api/__generated__/models/submissionStatus";
interface useAgentTableRowProps {
- id: number;
+ storeAgentSubmission: StoreSubmission;
onViewSubmission: (submission: StoreSubmission) => void;
onDeleteSubmission: (submission_id: string) => void;
onEditSubmission: (
submission: StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
},
) => void;
- agent_id: string;
- agent_version: number;
- agentName: string;
- sub_heading: string;
- description: string;
- imageSrc: string[];
- dateSubmitted: Date;
- status: SubmissionStatus;
- runs: number;
- rating: number;
- video_url?: string;
- categories?: string[];
- store_listing_version_id?: string;
- changes_summary?: string;
- listing_id?: string;
}
export const useAgentTableRow = ({
+ storeAgentSubmission,
onViewSubmission,
onDeleteSubmission,
onEditSubmission,
- agent_id,
- agent_version,
- agentName,
- sub_heading,
- description,
- imageSrc,
- dateSubmitted,
- status,
- runs,
- rating,
- video_url,
- categories,
- store_listing_version_id,
- changes_summary,
- listing_id,
}: useAgentTableRowProps) => {
const handleView = () => {
- onViewSubmission({
- listing_id: listing_id || "",
- agent_id,
- agent_version,
- slug: "",
- name: agentName,
- sub_heading,
- description,
- image_urls: imageSrc,
- date_submitted: dateSubmitted,
- status: status,
- runs,
- rating,
- video_url,
- categories,
- store_listing_version_id,
- } satisfies StoreSubmission);
+ onViewSubmission(storeAgentSubmission);
};
const handleEdit = () => {
onEditSubmission({
- name: agentName,
- sub_heading,
- description,
- image_urls: imageSrc,
- video_url,
- categories,
- changes_summary: changes_summary || "Update Submission",
- store_listing_version_id,
- agent_id,
+ name: storeAgentSubmission.name,
+ sub_heading: storeAgentSubmission.sub_heading,
+ description: storeAgentSubmission.description,
+ image_urls: storeAgentSubmission.image_urls,
+ video_url: storeAgentSubmission.video_url,
+ categories: storeAgentSubmission.categories,
+ changes_summary:
+ storeAgentSubmission.changes_summary || "Update Submission",
+ store_listing_version_id: storeAgentSubmission.listing_version_id,
+ graph_id: storeAgentSubmission.graph_id,
});
};
const handleDelete = () => {
- // Backend only accepts StoreListingVersion IDs for deletion
- if (!store_listing_version_id) {
- console.error(
- "Cannot delete submission: store_listing_version_id is required",
- );
- return;
- }
- onDeleteSubmission(store_listing_version_id);
+ onDeleteSubmission(storeAgentSubmission.listing_version_id);
};
return { handleView, handleDelete, handleEdit };
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/MainDashboardPage.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/MainDashboardPage.tsx
index 9bfc536d8b..304121be67 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/MainDashboardPage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/MainDashboardPage.tsx
@@ -81,26 +81,7 @@ export const MainDashboardPage = () => {
<SubmissionsLoading />
) : submissions && submissions.submissions.length > 0 ? (
<AgentTable
- agents={submissions.submissions.map((submission, index) => ({
- id: index,
- agent_id: submission.agent_id,
- agent_version: submission.agent_version,
- sub_heading: submission.sub_heading,
- agentName: submission.name,
- description: submission.description,
- imageSrc: submission.image_urls || [""],
- dateSubmitted: submission.date_submitted,
- status: submission.status,
- runs: submission.runs,
- rating: submission.rating,
- video_url: submission.video_url || undefined,
- categories: submission.categories,
- slug: submission.slug,
- store_listing_version_id:
- submission.store_listing_version_id || undefined,
- changes_summary: submission.changes_summary || undefined,
- listing_id: submission.listing_id,
- }))}
+ storeAgentSubmissions={submissions.submissions}
onViewSubmission={onViewSubmission}
onDeleteSubmission={onDeleteSubmission}
onEditSubmission={onEditSubmission}
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/useMainDashboardPage.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/useMainDashboardPage.ts
index 02eef96a51..6125063678 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/useMainDashboardPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/MainDashboardPage/useMainDashboardPage.ts
@@ -24,7 +24,7 @@ type EditState = {
submission:
| (StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
})
| null;
};
@@ -79,7 +79,7 @@ export const useMainDashboardPage = () => {
const onEditSubmission = (
submission: StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
},
) => {
setEditState({
@@ -90,7 +90,7 @@ export const useMainDashboardPage = () => {
const onEditSuccess = async (submission: StoreSubmission) => {
try {
- if (!submission.store_listing_version_id) {
+ if (!submission.listing_version_id) {
Sentry.captureException(
new Error("No store listing version ID found for submission"),
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx
index 979b113f55..4320e0719c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx
@@ -4,7 +4,7 @@ import { useGetV2GetUserProfile } from "@/app/api/__generated__/endpoints/store/
import { ProfileInfoForm } from "@/components/__legacy__/ProfileInfoForm";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
import { isLogoutInProgress } from "@/lib/autogpt-server-api/helpers";
-import { ProfileDetails } from "@/lib/autogpt-server-api/types";
+import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { ProfileLoading } from "./ProfileLoading";
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 18f660b829..d807573c34 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -2060,16 +2060,6 @@
"operationId": "postV1Upload file to cloud storage",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
- {
- "name": "provider",
- "in": "query",
- "required": false,
- "schema": {
- "type": "string",
- "default": "gcs",
- "title": "Provider"
- }
- },
{
"name": "expiration_hours",
"in": "query",
@@ -5599,7 +5589,7 @@
"get": {
"tags": ["v2", "admin", "store", "admin"],
"summary": "Get Admin Listings History",
- "description": "Get store listings with their version history for admins.\n\nThis provides a consolidated view of listings with their versions,\nallowing for an expandable UI in the admin dashboard.\n\nArgs:\n status: Filter by submission status (PENDING, APPROVED, REJECTED)\n search: Search by name, description, or user email\n page: Page number for pagination\n page_size: Number of items per page\n\nReturns:\n StoreListingsWithVersionsResponse with listings and their versions",
+ "description": "Get store listings with their version history for admins.\n\nThis provides a consolidated view of listings with their versions,\nallowing for an expandable UI in the admin dashboard.\n\nArgs:\n status: Filter by submission status (PENDING, APPROVED, REJECTED)\n search: Search by name, description, or user email\n page: Page number for pagination\n page_size: Number of items per page\n\nReturns:\n Paginated listings with their versions",
"operationId": "getV2Get admin listings history",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -5643,7 +5633,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/StoreListingsWithVersionsResponse"
+ "$ref": "#/components/schemas/StoreListingsWithVersionsAdminViewResponse"
}
}
}
@@ -5705,7 +5695,7 @@
"post": {
"tags": ["v2", "admin", "store", "admin"],
"summary": "Review Store Submission",
- "description": "Review a store listing submission.\n\nArgs:\n store_listing_version_id: ID of the submission to review\n request: Review details including approval status and comments\n user_id: Authenticated admin user performing the review\n\nReturns:\n StoreSubmission with updated review information",
+ "description": "Review a store listing submission.\n\nArgs:\n store_listing_version_id: ID of the submission to review\n request: Review details including approval status and comments\n user_id: Authenticated admin user performing the review\n\nReturns:\n StoreSubmissionAdminView with updated review information",
"operationId": "postV2Review store submission",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -5731,7 +5721,9 @@
"description": "Successful Response",
"content": {
"application/json": {
- "schema": { "$ref": "#/components/schemas/StoreSubmission" }
+ "schema": {
+ "$ref": "#/components/schemas/StoreSubmissionAdminView"
+ }
}
}
},
@@ -5753,7 +5745,7 @@
"get": {
"tags": ["v2", "store", "public"],
"summary": "List store agents",
- "description": "Get a paginated list of agents from the store with optional filtering and sorting.\n\nArgs:\n featured (bool, optional): Filter to only show featured agents. Defaults to False.\n creator (str | None, optional): Filter agents by creator username. Defaults to None.\n sorted_by (str | None, optional): Sort agents by \"runs\" or \"rating\". Defaults to None.\n search_query (str | None, optional): Search agents by name, subheading and description. Defaults to None.\n category (str | None, optional): Filter agents by category. Defaults to None.\n page (int, optional): Page number for pagination. Defaults to 1.\n page_size (int, optional): Number of agents per page. Defaults to 20.\n\nReturns:\n StoreAgentsResponse: Paginated list of agents matching the filters\n\nRaises:\n HTTPException: If page or page_size are less than 1\n\nUsed for:\n- Home Page Featured Agents\n- Home Page Top Agents\n- Search Results\n- Agent Details - Other Agents By Creator\n- Agent Details - Similar Agents\n- Creator Details - Agents By Creator",
+ "description": "Get a paginated list of agents from the marketplace,\nwith optional filtering and sorting.\n\nUsed for:\n- Home Page Featured Agents\n- Home Page Top Agents\n- Search Results\n- Agent Details - Other Agents By Creator\n- Agent Details - Similar Agents\n- Creator Details - Agents By Creator",
"operationId": "getV2List store agents",
"parameters": [
{
@@ -5762,9 +5754,11 @@
"required": false,
"schema": {
"type": "boolean",
+ "description": "Filter to only show featured agents",
"default": false,
"title": "Featured"
- }
+ },
+ "description": "Filter to only show featured agents"
},
{
"name": "creator",
@@ -5772,23 +5766,21 @@
"required": false,
"schema": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Filter agents by creator username",
"title": "Creator"
- }
+ },
+ "description": "Filter agents by creator username"
},
{
- "name": "sorted_by",
+ "name": "category",
"in": "query",
"required": false,
"schema": {
- "anyOf": [
- {
- "enum": ["rating", "runs", "name", "updated_at"],
- "type": "string"
- },
- { "type": "null" }
- ],
- "title": "Sorted By"
- }
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Filter agents by category",
+ "title": "Category"
+ },
+ "description": "Filter agents by category"
},
{
"name": "search_query",
@@ -5796,78 +5788,57 @@
"required": false,
"schema": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Literal + semantic search on names and descriptions",
"title": "Search Query"
- }
+ },
+ "description": "Literal + semantic search on names and descriptions"
},
{
- "name": "category",
+ "name": "sorted_by",
"in": "query",
"required": false,
"schema": {
- "anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Category"
- }
+ "anyOf": [
+ { "$ref": "#/components/schemas/StoreAgentsSortOptions" },
+ { "type": "null" }
+ ],
+ "description": "Property to sort results by. Ignored if search_query is provided.",
+ "title": "Sorted By"
+ },
+ "description": "Property to sort results by. Ignored if search_query is provided."
},
{
"name": "page",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 1, "title": "Page" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 1,
+ "title": "Page"
+ }
},
{
"name": "page_size",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 20, "title": "Page Size" }
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/StoreAgentsResponse" }
- }
- }
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
- }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 20,
+ "title": "Page Size"
}
}
- }
- }
- },
- "/api/store/agents/{store_listing_version_id}": {
- "get": {
- "tags": ["v2", "store"],
- "summary": "Get agent by version",
- "description": "Get Store Agent Details from Store Listing Version ID.",
- "operationId": "getV2Get agent by version",
- "security": [{ "HTTPBearerJWT": [] }],
- "parameters": [
- {
- "name": "store_listing_version_id",
- "in": "path",
- "required": true,
- "schema": { "type": "string", "title": "Store Listing Version Id" }
- }
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
- "schema": { "$ref": "#/components/schemas/StoreAgentDetails" }
+ "schema": { "$ref": "#/components/schemas/StoreAgentsResponse" }
}
}
},
- "401": {
- "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
- },
"422": {
"description": "Validation Error",
"content": {
@@ -5883,7 +5854,7 @@
"get": {
"tags": ["v2", "store", "public"],
"summary": "Get specific agent",
- "description": "This is only used on the AgentDetails Page.\n\nIt returns the store listing agents details.",
+ "description": "Get details of a marketplace agent",
"operationId": "getV2Get specific agent",
"parameters": [
{
@@ -5933,7 +5904,7 @@
"post": {
"tags": ["v2", "store"],
"summary": "Create agent review",
- "description": "Create a review for a store agent.\n\nArgs:\n username: Creator's username\n agent_name: Name/slug of the agent\n review: Review details including score and optional comments\n user_id: ID of authenticated user creating the review\n\nReturns:\n The created review",
+ "description": "Post a user review on a marketplace agent listing",
"operationId": "postV2Create agent review",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -5981,45 +5952,11 @@
}
}
},
- "/api/store/creator/{username}": {
- "get": {
- "tags": ["v2", "store", "public"],
- "summary": "Get creator details",
- "description": "Get the details of a creator.\n- Creator Details Page",
- "operationId": "getV2Get creator details",
- "parameters": [
- {
- "name": "username",
- "in": "path",
- "required": true,
- "schema": { "type": "string", "title": "Username" }
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/CreatorDetails" }
- }
- }
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
- }
- }
- }
- }
- }
- },
"/api/store/creators": {
"get": {
"tags": ["v2", "store", "public"],
"summary": "List store creators",
- "description": "This is needed for:\n- Home Page Featured Creators\n- Search Results Page\n\n---\n\nTo support this functionality we need:\n- featured: bool - to limit the list to just featured agents\n- search_query: str - vector search based on the creators profile description.\n- sorted_by: [agent_rating, agent_runs] -",
+ "description": "List or search marketplace creators",
"operationId": "getV2List store creators",
"parameters": [
{
@@ -6028,9 +5965,11 @@
"required": false,
"schema": {
"type": "boolean",
+ "description": "Filter to only show featured creators",
"default": false,
"title": "Featured"
- }
+ },
+ "description": "Filter to only show featured creators"
},
{
"name": "search_query",
@@ -6038,8 +5977,10 @@
"required": false,
"schema": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Literal + semantic search on names and descriptions",
"title": "Search Query"
- }
+ },
+ "description": "Literal + semantic search on names and descriptions"
},
{
"name": "sorted_by",
@@ -6047,10 +5988,7 @@
"required": false,
"schema": {
"anyOf": [
- {
- "enum": ["agent_rating", "agent_runs", "num_agents"],
- "type": "string"
- },
+ { "$ref": "#/components/schemas/StoreCreatorsSortOptions" },
{ "type": "null" }
],
"title": "Sorted By"
@@ -6060,13 +5998,23 @@
"name": "page",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 1, "title": "Page" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 1,
+ "title": "Page"
+ }
},
{
"name": "page_size",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 20, "title": "Page Size" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 20,
+ "title": "Page Size"
+ }
}
],
"responses": {
@@ -6089,29 +6037,65 @@
}
}
},
- "/api/store/download/agents/{store_listing_version_id}": {
+ "/api/store/creators/{username}": {
"get": {
"tags": ["v2", "store", "public"],
- "summary": "Download agent file",
- "description": "Download the agent file by streaming its content.\n\nArgs:\n store_listing_version_id (str): The ID of the agent to download\n\nReturns:\n StreamingResponse: A streaming response containing the agent's graph data.\n\nRaises:\n HTTPException: If the agent is not found or an unexpected error occurs.",
- "operationId": "getV2Download agent file",
+ "summary": "Get creator details",
+ "description": "Get details on a marketplace creator",
+ "operationId": "getV2Get creator details",
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Username" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/CreatorDetails" }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/api/store/listings/versions/{store_listing_version_id}": {
+ "get": {
+ "tags": ["v2", "store"],
+ "summary": "Get agent by version",
+ "operationId": "getV2Get agent by version",
+ "security": [{ "HTTPBearerJWT": [] }],
"parameters": [
{
"name": "store_listing_version_id",
"in": "path",
"required": true,
- "schema": {
- "type": "string",
- "description": "The ID of the agent to download",
- "title": "Store Listing Version Id"
- },
- "description": "The ID of the agent to download"
+ "schema": { "type": "string", "title": "Store Listing Version Id" }
}
],
"responses": {
"200": {
"description": "Successful Response",
- "content": { "application/json": { "schema": {} } }
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/StoreAgentDetails" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
},
"422": {
"description": "Validation Error",
@@ -6124,11 +6108,11 @@
}
}
},
- "/api/store/graph/{store_listing_version_id}": {
+ "/api/store/listings/versions/{store_listing_version_id}/graph": {
"get": {
"tags": ["v2", "store"],
"summary": "Get agent graph",
- "description": "Get Agent Graph from Store Listing Version ID.",
+ "description": "Get outline of graph belonging to a specific marketplace listing version",
"operationId": "getV2Get agent graph",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -6164,6 +6148,36 @@
}
}
},
+ "/api/store/listings/versions/{store_listing_version_id}/graph/download": {
+ "get": {
+ "tags": ["v2", "store", "public"],
+ "summary": "Download agent file",
+ "description": "Download agent graph file for a specific marketplace listing version",
+ "operationId": "getV2Download agent file",
+ "parameters": [
+ {
+ "name": "store_listing_version_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Store Listing Version Id" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": { "application/json": { "schema": {} } }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/store/metrics/cache": {
"get": {
"tags": ["v2", "store", "metrics"],
@@ -6178,11 +6192,11 @@
}
}
},
- "/api/store/myagents": {
+ "/api/store/my-unpublished-agents": {
"get": {
"tags": ["v2", "store", "private"],
"summary": "Get my agents",
- "description": "Get user's own agents.",
+ "description": "List the authenticated user's unpublished agents",
"operationId": "getV2Get my agents",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -6214,7 +6228,9 @@
"description": "Successful Response",
"content": {
"application/json": {
- "schema": { "$ref": "#/components/schemas/MyAgentsResponse" }
+ "schema": {
+ "$ref": "#/components/schemas/MyUnpublishedAgentsResponse"
+ }
}
}
},
@@ -6236,7 +6252,7 @@
"get": {
"tags": ["v2", "store", "private"],
"summary": "Get user profile",
- "description": "Get the profile details for the authenticated user.\nCached for 1 hour per user.",
+ "description": "Get the profile details for the authenticated user.",
"operationId": "getV2Get user profile",
"responses": {
"200": {
@@ -6256,7 +6272,7 @@
"post": {
"tags": ["v2", "store", "private"],
"summary": "Update user profile",
- "description": "Update the store profile for the authenticated user.\n\nArgs:\n profile (Profile): The updated profile details\n user_id (str): ID of the authenticated user\n\nReturns:\n CreatorDetails: The updated profile\n\nRaises:\n HTTPException: If there is an error updating the profile",
+ "description": "Update the store profile for the authenticated user.",
"operationId": "postV2Update user profile",
"requestBody": {
"content": {
@@ -6271,7 +6287,7 @@
"description": "Successful Response",
"content": {
"application/json": {
- "schema": { "$ref": "#/components/schemas/CreatorDetails" }
+ "schema": { "$ref": "#/components/schemas/ProfileDetails" }
}
}
},
@@ -6294,7 +6310,7 @@
"get": {
"tags": ["v2", "store", "public"],
"summary": "Unified search across all content types",
- "description": "Search across all content types (store agents, blocks, documentation) using hybrid search.\n\nCombines semantic (embedding-based) and lexical (text-based) search for best results.\n\nArgs:\n query: The search query string\n content_types: Optional list of content types to filter by (STORE_AGENT, BLOCK, DOCUMENTATION)\n page: Page number for pagination (default 1)\n page_size: Number of results per page (default 20)\n user_id: Optional authenticated user ID (for user-scoped content in future)\n\nReturns:\n UnifiedSearchResponse: Paginated list of search results with relevance scores",
+ "description": "Search across all content types (marketplace agents, blocks, documentation)\nusing hybrid search.\n\nCombines semantic (embedding-based) and lexical (text-based) search for best results.",
"operationId": "getV2Unified search across all content types",
"security": [{ "HTTPBearer": [] }],
"parameters": [
@@ -6310,25 +6326,38 @@
"required": false,
"schema": {
"anyOf": [
- { "type": "array", "items": { "type": "string" } },
+ {
+ "type": "array",
+ "items": { "$ref": "#/components/schemas/ContentType" }
+ },
{ "type": "null" }
],
- "description": "Content types to search: STORE_AGENT, BLOCK, DOCUMENTATION. If not specified, searches all.",
+ "description": "Content types to search. If not specified, searches all.",
"title": "Content Types"
},
- "description": "Content types to search: STORE_AGENT, BLOCK, DOCUMENTATION. If not specified, searches all."
+ "description": "Content types to search. If not specified, searches all."
},
{
"name": "page",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 1, "title": "Page" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 1,
+ "title": "Page"
+ }
},
{
"name": "page_size",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 20, "title": "Page Size" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 20,
+ "title": "Page Size"
+ }
}
],
"responses": {
@@ -6357,7 +6386,7 @@
"get": {
"tags": ["v2", "store", "private"],
"summary": "List my submissions",
- "description": "Get a paginated list of store submissions for the authenticated user.\n\nArgs:\n user_id (str): ID of the authenticated user\n page (int, optional): Page number for pagination. Defaults to 1.\n page_size (int, optional): Number of submissions per page. Defaults to 20.\n\nReturns:\n StoreListingsResponse: Paginated list of store submissions\n\nRaises:\n HTTPException: If page or page_size are less than 1",
+ "description": "List the authenticated user's marketplace listing submissions",
"operationId": "getV2List my submissions",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -6365,13 +6394,23 @@
"name": "page",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 1, "title": "Page" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 1,
+ "title": "Page"
+ }
},
{
"name": "page_size",
"in": "query",
"required": false,
- "schema": { "type": "integer", "default": 20, "title": "Page Size" }
+ "schema": {
+ "type": "integer",
+ "minimum": 1,
+ "default": 20,
+ "title": "Page Size"
+ }
}
],
"responses": {
@@ -6401,7 +6440,7 @@
"post": {
"tags": ["v2", "store", "private"],
"summary": "Create store submission",
- "description": "Create a new store listing submission.\n\nArgs:\n submission_request (StoreSubmissionRequest): The submission details\n user_id (str): ID of the authenticated user submitting the listing\n\nReturns:\n StoreSubmission: The created store submission\n\nRaises:\n HTTPException: If there is an error creating the submission",
+ "description": "Submit a new marketplace listing for review",
"operationId": "postV2Create store submission",
"security": [{ "HTTPBearerJWT": [] }],
"requestBody": {
@@ -6441,21 +6480,25 @@
"post": {
"tags": ["v2", "store", "private"],
"summary": "Generate submission image",
- "description": "Generate an image for a store listing submission.\n\nArgs:\n agent_id (str): ID of the agent to generate an image for\n user_id (str): ID of the authenticated user\n\nReturns:\n JSONResponse: JSON containing the URL of the generated image",
+ "description": "Generate an image for a marketplace listing submission based on the properties\nof a given graph.",
"operationId": "postV2Generate submission image",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
{
- "name": "agent_id",
+ "name": "graph_id",
"in": "query",
"required": true,
- "schema": { "type": "string", "title": "Agent Id" }
+ "schema": { "type": "string", "title": "Graph Id" }
}
],
"responses": {
"200": {
"description": "Successful Response",
- "content": { "application/json": { "schema": {} } }
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ImageURLResponse" }
+ }
+ }
},
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
@@ -6475,7 +6518,7 @@
"post": {
"tags": ["v2", "store", "private"],
"summary": "Upload submission media",
- "description": "Upload media (images/videos) for a store listing submission.\n\nArgs:\n file (UploadFile): The media file to upload\n user_id (str): ID of the authenticated user uploading the media\n\nReturns:\n str: URL of the uploaded media file\n\nRaises:\n HTTPException: If there is an error uploading the media",
+ "description": "Upload media for a marketplace listing submission",
"operationId": "postV2Upload submission media",
"requestBody": {
"content": {
@@ -6490,7 +6533,14 @@
"responses": {
"200": {
"description": "Successful Response",
- "content": { "application/json": { "schema": {} } }
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "string",
+ "title": "Response Postv2Upload Submission Media"
+ }
+ }
+ }
},
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
@@ -6511,7 +6561,7 @@
"put": {
"tags": ["v2", "store", "private"],
"summary": "Edit store submission",
- "description": "Edit an existing store listing submission.\n\nArgs:\n store_listing_version_id (str): ID of the store listing version to edit\n submission_request (StoreSubmissionRequest): The updated submission details\n user_id (str): ID of the authenticated user editing the listing\n\nReturns:\n StoreSubmission: The updated store submission\n\nRaises:\n HTTPException: If there is an error editing the submission",
+ "description": "Update a pending marketplace listing submission",
"operationId": "putV2Edit store submission",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -6559,7 +6609,7 @@
"delete": {
"tags": ["v2", "store", "private"],
"summary": "Delete store submission",
- "description": "Delete a store listing submission.\n\nArgs:\n user_id (str): ID of the authenticated user\n submission_id (str): ID of the submission to be deleted\n\nReturns:\n bool: True if the submission was successfully deleted, False otherwise",
+ "description": "Delete a marketplace listing submission",
"operationId": "deleteV2Delete store submission",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -8089,6 +8139,17 @@
"title": "ClarifyingQuestion",
"description": "A question that needs user clarification."
},
+ "ContentType": {
+ "type": "string",
+ "enum": [
+ "STORE_AGENT",
+ "BLOCK",
+ "INTEGRATION",
+ "DOCUMENTATION",
+ "LIBRARY_AGENT"
+ ],
+ "title": "ContentType"
+ },
"CountResponse": {
"properties": {
"all_blocks": { "type": "integer", "title": "All Blocks" },
@@ -8169,43 +8230,24 @@
"title": "CreateSessionResponse",
"description": "Response model containing information on a newly created chat session."
},
- "Creator": {
- "properties": {
- "name": { "type": "string", "title": "Name" },
- "username": { "type": "string", "title": "Username" },
- "description": { "type": "string", "title": "Description" },
- "avatar_url": { "type": "string", "title": "Avatar Url" },
- "num_agents": { "type": "integer", "title": "Num Agents" },
- "agent_rating": { "type": "number", "title": "Agent Rating" },
- "agent_runs": { "type": "integer", "title": "Agent Runs" },
- "is_featured": { "type": "boolean", "title": "Is Featured" }
- },
- "type": "object",
- "required": [
- "name",
- "username",
- "description",
- "avatar_url",
- "num_agents",
- "agent_rating",
- "agent_runs",
- "is_featured"
- ],
- "title": "Creator"
- },
"CreatorDetails": {
"properties": {
- "name": { "type": "string", "title": "Name" },
"username": { "type": "string", "title": "Username" },
+ "name": { "type": "string", "title": "Name" },
"description": { "type": "string", "title": "Description" },
+ "avatar_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Avatar Url"
+ },
"links": {
"items": { "type": "string" },
"type": "array",
"title": "Links"
},
- "avatar_url": { "type": "string", "title": "Avatar Url" },
- "agent_rating": { "type": "number", "title": "Agent Rating" },
+ "is_featured": { "type": "boolean", "title": "Is Featured" },
+ "num_agents": { "type": "integer", "title": "Num Agents" },
"agent_runs": { "type": "integer", "title": "Agent Runs" },
+ "agent_rating": { "type": "number", "title": "Agent Rating" },
"top_categories": {
"items": { "type": "string" },
"type": "array",
@@ -8214,21 +8256,24 @@
},
"type": "object",
"required": [
- "name",
"username",
+ "name",
"description",
- "links",
"avatar_url",
- "agent_rating",
+ "links",
+ "is_featured",
+ "num_agents",
"agent_runs",
+ "agent_rating",
"top_categories"
],
- "title": "CreatorDetails"
+ "title": "CreatorDetails",
+ "description": "Marketplace creator profile details, including aggregated stats"
},
"CreatorsResponse": {
"properties": {
"creators": {
- "items": { "$ref": "#/components/schemas/Creator" },
+ "items": { "$ref": "#/components/schemas/CreatorDetails" },
"type": "array",
"title": "Creators"
},
@@ -9590,6 +9635,14 @@
"required": ["provider", "host"],
"title": "HostScopedCredentials"
},
+ "ImageURLResponse": {
+ "properties": {
+ "image_url": { "type": "string", "title": "Image Url" }
+ },
+ "type": "object",
+ "required": ["image_url"],
+ "title": "ImageURLResponse"
+ },
"InputValidationErrorResponse": {
"properties": {
"type": {
@@ -10343,10 +10396,10 @@
"required": ["value", "label", "provider"],
"title": "ModelInfo"
},
- "MyAgent": {
+ "MyUnpublishedAgent": {
"properties": {
- "agent_id": { "type": "string", "title": "Agent Id" },
- "agent_version": { "type": "integer", "title": "Agent Version" },
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_version": { "type": "integer", "title": "Graph Version" },
"agent_name": { "type": "string", "title": "Agent Name" },
"agent_image": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
@@ -10365,18 +10418,18 @@
},
"type": "object",
"required": [
- "agent_id",
- "agent_version",
+ "graph_id",
+ "graph_version",
"agent_name",
"description",
"last_edited"
],
- "title": "MyAgent"
+ "title": "MyUnpublishedAgent"
},
- "MyAgentsResponse": {
+ "MyUnpublishedAgentsResponse": {
"properties": {
"agents": {
- "items": { "$ref": "#/components/schemas/MyAgent" },
+ "items": { "$ref": "#/components/schemas/MyUnpublishedAgent" },
"type": "array",
"title": "Agents"
},
@@ -10384,7 +10437,7 @@
},
"type": "object",
"required": ["agents", "pagination"],
- "title": "MyAgentsResponse"
+ "title": "MyUnpublishedAgentsResponse"
},
"NeedLoginResponse": {
"properties": {
@@ -11270,43 +11323,51 @@
},
"Profile": {
"properties": {
- "name": { "type": "string", "title": "Name" },
"username": { "type": "string", "title": "Username" },
+ "name": { "type": "string", "title": "Name" },
"description": { "type": "string", "title": "Description" },
+ "avatar_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Avatar Url"
+ },
"links": {
"items": { "type": "string" },
"type": "array",
"title": "Links"
- },
- "avatar_url": { "type": "string", "title": "Avatar Url" },
- "is_featured": {
- "type": "boolean",
- "title": "Is Featured",
- "default": false
}
},
"type": "object",
- "required": ["name", "username", "description", "links", "avatar_url"],
- "title": "Profile"
+ "required": ["username", "name", "description", "avatar_url", "links"],
+ "title": "Profile",
+ "description": "Marketplace user profile (only attributes that the user can update)"
},
"ProfileDetails": {
"properties": {
- "name": { "type": "string", "title": "Name" },
"username": { "type": "string", "title": "Username" },
+ "name": { "type": "string", "title": "Name" },
"description": { "type": "string", "title": "Description" },
+ "avatar_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Avatar Url"
+ },
"links": {
"items": { "type": "string" },
"type": "array",
"title": "Links"
},
- "avatar_url": {
- "anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Avatar Url"
- }
+ "is_featured": { "type": "boolean", "title": "Is Featured" }
},
"type": "object",
- "required": ["name", "username", "description", "links"],
- "title": "ProfileDetails"
+ "required": [
+ "username",
+ "name",
+ "description",
+ "avatar_url",
+ "links",
+ "is_featured"
+ ],
+ "title": "ProfileDetails",
+ "description": "Marketplace user profile (including read-only fields)"
},
"Provider": {
"properties": {
@@ -11982,12 +12043,12 @@
"type": "array",
"title": "Versions"
},
- "agentGraphVersions": {
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_versions": {
"items": { "type": "string" },
"type": "array",
- "title": "Agentgraphversions"
+ "title": "Graph Versions"
},
- "agentGraphId": { "type": "string", "title": "Agentgraphid" },
"last_updated": {
"type": "string",
"format": "date-time",
@@ -11998,13 +12059,12 @@
"title": "Recommended Schedule Cron"
},
"active_version_id": {
- "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "type": "string",
"title": "Active Version Id"
},
"has_approved_version": {
"type": "boolean",
- "title": "Has Approved Version",
- "default": false
+ "title": "Has Approved Version"
},
"changelog": {
"anyOf": [
@@ -12033,9 +12093,11 @@
"runs",
"rating",
"versions",
- "agentGraphVersions",
- "agentGraphId",
- "last_updated"
+ "graph_id",
+ "graph_versions",
+ "last_updated",
+ "active_version_id",
+ "has_approved_version"
],
"title": "StoreAgentDetails"
},
@@ -12052,15 +12114,24 @@
"required": ["agents", "pagination"],
"title": "StoreAgentsResponse"
},
- "StoreListingWithVersions": {
+ "StoreAgentsSortOptions": {
+ "type": "string",
+ "enum": ["rating", "runs", "name", "updated_at"],
+ "title": "StoreAgentsSortOptions"
+ },
+ "StoreCreatorsSortOptions": {
+ "type": "string",
+ "enum": ["agent_rating", "agent_runs", "num_agents"],
+ "title": "StoreCreatorsSortOptions"
+ },
+ "StoreListingWithVersionsAdminView": {
"properties": {
"listing_id": { "type": "string", "title": "Listing Id" },
+ "graph_id": { "type": "string", "title": "Graph Id" },
"slug": { "type": "string", "title": "Slug" },
- "agent_id": { "type": "string", "title": "Agent Id" },
- "agent_version": { "type": "integer", "title": "Agent Version" },
- "active_version_id": {
+ "active_listing_version_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Active Version Id"
+ "title": "Active Listing Version Id"
},
"has_approved_version": {
"type": "boolean",
@@ -12073,27 +12144,29 @@
},
"latest_version": {
"anyOf": [
- { "$ref": "#/components/schemas/StoreSubmission" },
+ { "$ref": "#/components/schemas/StoreSubmissionAdminView" },
{ "type": "null" }
]
},
"versions": {
- "items": { "$ref": "#/components/schemas/StoreSubmission" },
+ "items": {
+ "$ref": "#/components/schemas/StoreSubmissionAdminView"
+ },
"type": "array",
"title": "Versions",
"default": []
}
},
"type": "object",
- "required": ["listing_id", "slug", "agent_id", "agent_version"],
- "title": "StoreListingWithVersions",
+ "required": ["listing_id", "graph_id", "slug"],
+ "title": "StoreListingWithVersionsAdminView",
"description": "A store listing with its version history"
},
- "StoreListingsWithVersionsResponse": {
+ "StoreListingsWithVersionsAdminViewResponse": {
"properties": {
"listings": {
"items": {
- "$ref": "#/components/schemas/StoreListingWithVersions"
+ "$ref": "#/components/schemas/StoreListingWithVersionsAdminView"
},
"type": "array",
"title": "Listings"
@@ -12102,7 +12175,7 @@
},
"type": "object",
"required": ["listings", "pagination"],
- "title": "StoreListingsWithVersionsResponse",
+ "title": "StoreListingsWithVersionsAdminViewResponse",
"description": "Response model for listings with version history"
},
"StoreReview": {
@@ -12136,36 +12209,58 @@
"StoreSubmission": {
"properties": {
"listing_id": { "type": "string", "title": "Listing Id" },
- "agent_id": { "type": "string", "title": "Agent Id" },
- "agent_version": { "type": "integer", "title": "Agent Version" },
+ "user_id": { "type": "string", "title": "User Id" },
+ "slug": { "type": "string", "title": "Slug" },
+ "listing_version_id": {
+ "type": "string",
+ "title": "Listing Version Id"
+ },
+ "listing_version": { "type": "integer", "title": "Listing Version" },
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_version": { "type": "integer", "title": "Graph Version" },
"name": { "type": "string", "title": "Name" },
"sub_heading": { "type": "string", "title": "Sub Heading" },
- "slug": { "type": "string", "title": "Slug" },
"description": { "type": "string", "title": "Description" },
"instructions": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Instructions"
},
+ "categories": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Categories"
+ },
"image_urls": {
"items": { "type": "string" },
"type": "array",
"title": "Image Urls"
},
- "date_submitted": {
- "type": "string",
- "format": "date-time",
- "title": "Date Submitted"
+ "video_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Video Url"
},
- "status": { "$ref": "#/components/schemas/SubmissionStatus" },
- "runs": { "type": "integer", "title": "Runs" },
- "rating": { "type": "number", "title": "Rating" },
- "store_listing_version_id": {
+ "agent_output_demo_url": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Store Listing Version Id"
+ "title": "Agent Output Demo Url"
},
- "version": {
- "anyOf": [{ "type": "integer" }, { "type": "null" }],
- "title": "Version"
+ "submitted_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Submitted At"
+ },
+ "changes_summary": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Changes Summary"
+ },
+ "status": { "$ref": "#/components/schemas/SubmissionStatus" },
+ "reviewed_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Reviewed At"
},
"reviewer_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
@@ -12175,52 +12270,152 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Review Comments"
},
- "internal_comments": {
+ "run_count": {
+ "type": "integer",
+ "title": "Run Count",
+ "default": 0
+ },
+ "review_count": {
+ "type": "integer",
+ "title": "Review Count",
+ "default": 0
+ },
+ "review_avg_rating": {
+ "type": "number",
+ "title": "Review Avg Rating",
+ "default": 0.0
+ }
+ },
+ "type": "object",
+ "required": [
+ "listing_id",
+ "user_id",
+ "slug",
+ "listing_version_id",
+ "listing_version",
+ "graph_id",
+ "graph_version",
+ "name",
+ "sub_heading",
+ "description",
+ "instructions",
+ "categories",
+ "image_urls",
+ "video_url",
+ "agent_output_demo_url",
+ "submitted_at",
+ "changes_summary",
+ "status"
+ ],
+ "title": "StoreSubmission"
+ },
+ "StoreSubmissionAdminView": {
+ "properties": {
+ "listing_id": { "type": "string", "title": "Listing Id" },
+ "user_id": { "type": "string", "title": "User Id" },
+ "slug": { "type": "string", "title": "Slug" },
+ "listing_version_id": {
+ "type": "string",
+ "title": "Listing Version Id"
+ },
+ "listing_version": { "type": "integer", "title": "Listing Version" },
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_version": { "type": "integer", "title": "Graph Version" },
+ "name": { "type": "string", "title": "Name" },
+ "sub_heading": { "type": "string", "title": "Sub Heading" },
+ "description": { "type": "string", "title": "Description" },
+ "instructions": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Internal Comments"
+ "title": "Instructions"
},
- "reviewed_at": {
+ "categories": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Categories"
+ },
+ "image_urls": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Image Urls"
+ },
+ "video_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Video Url"
+ },
+ "agent_output_demo_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Agent Output Demo Url"
+ },
+ "submitted_at": {
"anyOf": [
{ "type": "string", "format": "date-time" },
{ "type": "null" }
],
- "title": "Reviewed At"
+ "title": "Submitted At"
},
"changes_summary": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Changes Summary"
},
- "video_url": {
+ "status": { "$ref": "#/components/schemas/SubmissionStatus" },
+ "reviewed_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Reviewed At"
+ },
+ "reviewer_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Video Url"
+ "title": "Reviewer Id"
},
- "agent_output_demo_url": {
+ "review_comments": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Agent Output Demo Url"
+ "title": "Review Comments"
},
- "categories": {
- "items": { "type": "string" },
- "type": "array",
- "title": "Categories",
- "default": []
+ "run_count": {
+ "type": "integer",
+ "title": "Run Count",
+ "default": 0
+ },
+ "review_count": {
+ "type": "integer",
+ "title": "Review Count",
+ "default": 0
+ },
+ "review_avg_rating": {
+ "type": "number",
+ "title": "Review Avg Rating",
+ "default": 0.0
+ },
+ "internal_comments": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Internal Comments"
}
},
"type": "object",
"required": [
"listing_id",
- "agent_id",
- "agent_version",
+ "user_id",
+ "slug",
+ "listing_version_id",
+ "listing_version",
+ "graph_id",
+ "graph_version",
"name",
"sub_heading",
- "slug",
"description",
+ "instructions",
+ "categories",
"image_urls",
- "date_submitted",
+ "video_url",
+ "agent_output_demo_url",
+ "submitted_at",
+ "changes_summary",
"status",
- "runs",
- "rating"
+ "internal_comments"
],
- "title": "StoreSubmission"
+ "title": "StoreSubmissionAdminView"
},
"StoreSubmissionEditRequest": {
"properties": {
@@ -12270,17 +12465,17 @@
},
"StoreSubmissionRequest": {
"properties": {
- "agent_id": {
+ "graph_id": {
"type": "string",
"minLength": 1,
- "title": "Agent Id",
- "description": "Agent ID cannot be empty"
+ "title": "Graph Id",
+ "description": "Graph ID cannot be empty"
},
- "agent_version": {
+ "graph_version": {
"type": "integer",
"exclusiveMinimum": 0.0,
- "title": "Agent Version",
- "description": "Agent version must be greater than 0"
+ "title": "Graph Version",
+ "description": "Graph version must be greater than 0"
},
"slug": { "type": "string", "title": "Slug" },
"name": { "type": "string", "title": "Name" },
@@ -12325,8 +12520,8 @@
},
"type": "object",
"required": [
- "agent_id",
- "agent_version",
+ "graph_id",
+ "graph_version",
"slug",
"name",
"sub_heading"
diff --git a/autogpt_platform/frontend/src/components/__legacy__/FeaturedAgentCard.tsx b/autogpt_platform/frontend/src/components/__legacy__/FeaturedAgentCard.tsx
index 3d6010626f..ee498bc8ea 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/FeaturedAgentCard.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/FeaturedAgentCard.tsx
@@ -9,7 +9,7 @@ import {
CardTitle,
} from "@/components/__legacy__/ui/card";
import { useState } from "react";
-import { StoreAgent } from "@/lib/autogpt-server-api";
+import type { StoreAgent } from "@/app/api/__generated__/models/storeAgent";
interface FeaturedStoreCardProps {
agent: StoreAgent;
diff --git a/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx b/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
index 22934385ee..5d52449a8f 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
@@ -6,14 +6,15 @@ import Image from "next/image";
import { IconPersonFill } from "@/components/__legacy__/ui/icons";
import { Separator } from "@/components/__legacy__/ui/separator";
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-import { ProfileDetails } from "@/lib/autogpt-server-api/types";
+import { postV2UpdateUserProfile } from "@/app/api/__generated__/endpoints/store/store";
+import { postV2UploadSubmissionMedia } from "@/app/api/__generated__/endpoints/store/store";
+import { resolveResponse } from "@/app/api/helpers";
+import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
import { Button } from "./Button";
export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [profileData, setProfileData] = useState<ProfileDetails>(profile);
- const api = useBackendAPI();
async function submitForm() {
try {
@@ -28,8 +29,10 @@ export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
};
if (!isSubmitting) {
- const returnedProfile = await api.updateStoreProfile(updatedProfile);
- setProfileData(returnedProfile);
+ const returnedProfile = await resolveResponse(
+ postV2UpdateUserProfile(updatedProfile),
+ );
+ if (returnedProfile) setProfileData(returnedProfile);
}
} catch (error) {
console.error("Error updating profile:", error);
@@ -40,15 +43,20 @@ export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
async function handleImageUpload(file: File) {
try {
- const mediaUrl = await api.uploadStoreSubmissionMedia(file);
+ const mediaRes = await resolveResponse(
+ postV2UploadSubmissionMedia({ file }),
+ );
+ const mediaUrl = String(mediaRes ?? "");
const updatedProfile = {
...profileData,
avatar_url: mediaUrl,
};
- const returnedProfile = await api.updateStoreProfile(updatedProfile);
- setProfileData(returnedProfile);
+ const returnedProfile = await resolveResponse(
+ postV2UpdateUserProfile(updatedProfile),
+ );
+ if (returnedProfile) setProfileData(returnedProfile);
} catch (error) {
console.error("Error uploading image:", error);
}
diff --git a/autogpt_platform/frontend/src/components/__legacy__/RatingCard.tsx b/autogpt_platform/frontend/src/components/__legacy__/RatingCard.tsx
index 3caafd9ad6..82fa1870cb 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/RatingCard.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/RatingCard.tsx
@@ -3,7 +3,7 @@
import * as React from "react";
import { Cross1Icon } from "@radix-ui/react-icons";
import { IconStar, IconStarFilled } from "@/components/__legacy__/ui/icons";
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+import { postV2CreateAgentReview } from "@/app/api/__generated__/endpoints/store/store";
interface RatingCardProps {
agentName: string;
@@ -17,7 +17,6 @@ export const RatingCard: React.FC<RatingCardProps> = ({
const [rating, setRating] = React.useState<number>(0);
const [hoveredRating, setHoveredRating] = React.useState<number>(0);
const [isVisible, setIsVisible] = React.useState(true);
- const api = useBackendAPI();
const handleClose = () => {
setIsVisible(false);
@@ -28,7 +27,7 @@ export const RatingCard: React.FC<RatingCardProps> = ({
const handleSubmit = async (rating: number) => {
if (rating > 0) {
console.log(`Rating submitted for ${agentName}:`, rating);
- await api.reviewAgent("--", agentName, {
+ await postV2CreateAgentReview("--", agentName, {
store_listing_version_id: storeListingVersionId,
score: rating,
});
diff --git a/autogpt_platform/frontend/src/components/__legacy__/composite/FeaturedSection.tsx b/autogpt_platform/frontend/src/components/__legacy__/composite/FeaturedSection.tsx
index b38734b9e7..a6f21d39e4 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/composite/FeaturedSection.tsx
+++ b/autogpt_platform/frontend/src/components/__legacy__/composite/FeaturedSection.tsx
@@ -11,7 +11,7 @@ import {
CarouselIndicator,
} from "@/components/__legacy__/ui/carousel";
import { useCallback, useState } from "react";
-import { StoreAgent } from "@/lib/autogpt-server-api";
+import type { StoreAgent } from "@/app/api/__generated__/models/storeAgent";
import Link from "next/link";
const BACKGROUND_COLORS = [
diff --git a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/EditAgentModal.tsx b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/EditAgentModal.tsx
index 243b478f49..59c2066107 100644
--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/EditAgentModal.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/EditAgentModal.tsx
@@ -11,7 +11,7 @@ export interface EditAgentModalProps {
submission:
| (StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
})
| null;
onSuccess: (submission: StoreSubmission) => void;
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 5c0c4fa1de..bd2da0fade 100644
--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/EditAgentForm.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/EditAgentForm.tsx
@@ -13,7 +13,7 @@ import { useEditAgentForm } from "./useEditAgentForm";
interface EditAgentFormProps {
submission: StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
};
onClose: () => void;
onSuccess: (submission: StoreSubmission) => void;
@@ -70,7 +70,7 @@ export function EditAgentForm({
/>
<ThumbnailImages
- agentId={submission.agent_id}
+ agentId={submission.graph_id}
onImagesChange={handleImagesChange}
initialImages={Array.from(new Set(submission.image_urls || []))}
initialSelectedImage={submission.image_urls?.[0] || null}
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 4f2ea49506..ffb841b34c 100644
--- a/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts
+++ b/autogpt_platform/frontend/src/components/contextual/EditAgentModal/components/useEditAgentForm.ts
@@ -16,7 +16,7 @@ import z from "zod";
interface useEditAgentFormProps {
submission: StoreSubmissionEditRequest & {
store_listing_version_id: string | undefined;
- agent_id: string;
+ graph_id: string;
};
onSuccess: (submission: StoreSubmission) => void;
onClose: () => void;
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts
index 448e56d3ed..5c49081062 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/useThumbnailImages.ts
@@ -1,5 +1,9 @@
import { useState, useRef, useEffect } from "react";
-import BackendAPI from "@/lib/autogpt-server-api";
+import {
+ postV2UploadSubmissionMedia,
+ postV2GenerateSubmissionImage,
+} from "@/app/api/__generated__/endpoints/store/store";
+import { resolveResponse } from "@/app/api/helpers";
import { useToast } from "@/components/molecules/Toast/use-toast";
interface UseThumbnailImagesProps {
@@ -97,12 +101,10 @@ export function useThumbnailImages({
async function uploadImage(file: File) {
try {
- const api = new BackendAPI();
-
- const imageUrl = (await api.uploadStoreSubmissionMedia(file)).replace(
- /^"(.*)"$/,
- "$1",
+ const mediaRes = await resolveResponse(
+ postV2UploadSubmissionMedia({ file }),
);
+ const imageUrl = mediaRes.replace(/^"(.*)"$/, "$1");
setImagesWithValidation([...images, imageUrl]);
if (!selectedImage) {
@@ -122,11 +124,12 @@ export function useThumbnailImages({
setIsGenerating(true);
try {
- const api = new BackendAPI();
if (!agentId) {
throw new Error("Agent ID is required");
}
- const { image_url } = await api.generateStoreSubmissionImage(agentId);
+ const { image_url } = await resolveResponse(
+ postV2GenerateSubmissionImage({ graph_id: agentId }),
+ );
setImagesWithValidation([...images, image_url]);
if (!selectedImage) {
setSelectedImage(image_url);
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 448d65b195..ed886b1f67 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
@@ -2,7 +2,8 @@ import { useEffect, useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useToast } from "@/components/molecules/Toast/use-toast";
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
+import { postV2CreateStoreSubmission } from "@/app/api/__generated__/endpoints/store/store";
+import { okData } from "@/app/api/helpers";
import * as Sentry from "@sentry/nextjs";
import {
PublishAgentFormData,
@@ -32,7 +33,6 @@ export function useAgentInfoStep({
const [isSubmitting, setIsSubmitting] = useState(false);
const { toast } = useToast();
- const api = useBackendAPI();
const form = useForm<PublishAgentFormData>({
resolver: zodResolver(publishAgentSchemaFactory(isMarketplaceUpdate)),
@@ -115,21 +115,23 @@ export function useAgentInfoStep({
setIsSubmitting(true);
try {
- const response = await api.createStoreSubmission({
- name: data.title,
- sub_heading: data.subheader,
- description: data.description,
- instructions: data.instructions || null,
- image_urls: images,
- video_url: data.youtubeLink || "",
- agent_output_demo_url: data.agentOutputDemo || "",
- agent_id: selectedAgentId,
- agent_version: selectedAgentVersion,
- slug: (data.slug || "").replace(/\s+/g, "-"),
- categories: filteredCategories,
- recommended_schedule_cron: data.recommendedScheduleCron || null,
- changes_summary: data.changesSummary || null,
- } as any);
+ const response = okData(
+ await postV2CreateStoreSubmission({
+ slug: (data.slug || "").replace(/\s+/g, "-"),
+ graph_id: selectedAgentId,
+ graph_version: selectedAgentVersion,
+ name: data.title || "",
+ sub_heading: data.subheader || "",
+ description: data.description,
+ instructions: data.instructions || undefined,
+ categories: filteredCategories,
+ image_urls: images,
+ video_url: data.youtubeLink || undefined,
+ agent_output_demo_url: data.agentOutputDemo || undefined,
+ recommended_schedule_cron: data.recommendedScheduleCron || undefined,
+ changes_summary: data.changesSummary || undefined,
+ }),
+ );
onSuccess(response);
} catch (error) {
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentSelectStep/useAgentSelectStep.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentSelectStep/useAgentSelectStep.ts
index 88ac4b478f..d86771b734 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentSelectStep/useAgentSelectStep.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentSelectStep/useAgentSelectStep.ts
@@ -51,8 +51,8 @@ export function useAgentSelectStep({
?.agents.map(
(agent): Agent => ({
name: agent.agent_name,
- id: agent.agent_id,
- version: agent.agent_version,
+ id: agent.graph_id,
+ version: agent.graph_version,
lastEdited: agent.last_edited.toLocaleDateString(),
imageSrc: agent.agent_image || "https://picsum.photos/300/200",
description: agent.description || "",
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/usePublishAgentModal.ts b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/usePublishAgentModal.ts
index c4481d65c2..9521ce33e8 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/usePublishAgentModal.ts
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/usePublishAgentModal.ts
@@ -9,7 +9,7 @@ import {
getGetV2ListMySubmissionsQueryKey,
} from "@/app/api/__generated__/endpoints/store/store";
import { okData } from "@/app/api/helpers";
-import type { MyAgent } from "@/app/api/__generated__/models/myAgent";
+import type { MyUnpublishedAgent } from "@/app/api/__generated__/models/myUnpublishedAgent";
import { useQueryClient } from "@tanstack/react-query";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
@@ -114,14 +114,14 @@ export function usePublishAgentModal({
!preSelectedAgentVersion
)
return;
- const agentsData = okData(myAgents) as any;
- const submissionsData = okData(mySubmissions) as any;
+ const agentsData = okData(myAgents);
+ const submissionsData = okData(mySubmissions);
if (!agentsData || !submissionsData) return;
// Find the agent data
const agent = agentsData.agents?.find(
- (a: MyAgent) => a.agent_id === preSelectedAgentId,
+ (a: MyUnpublishedAgent) => a.graph_id === preSelectedAgentId,
);
if (!agent) return;
@@ -129,11 +129,11 @@ export function usePublishAgentModal({
const publishedSubmissionData = submissionsData.submissions
?.filter(
(s: StoreSubmission) =>
- s.status === "APPROVED" && s.agent_id === preSelectedAgentId,
+ s.status === "APPROVED" && s.graph_id === preSelectedAgentId,
)
.sort(
(a: StoreSubmission, b: StoreSubmission) =>
- b.agent_version - a.agent_version,
+ b.graph_version - a.graph_version,
)[0];
// Populate initial data (same logic as handleNextFromSelect)
diff --git a/autogpt_platform/frontend/src/components/contextual/RunAgentInputs/useRunAgentInputs.ts b/autogpt_platform/frontend/src/components/contextual/RunAgentInputs/useRunAgentInputs.ts
index 38fe30b9ea..5cc2ef2013 100644
--- a/autogpt_platform/frontend/src/components/contextual/RunAgentInputs/useRunAgentInputs.ts
+++ b/autogpt_platform/frontend/src/components/contextual/RunAgentInputs/useRunAgentInputs.ts
@@ -6,7 +6,7 @@ export function useRunAgentInputs() {
const [uploadProgress, setUploadProgress] = useState(0);
async function handleUploadFile(file: File) {
- const result = await api.uploadFile(file, "gcs", 24, (progress) =>
+ const result = await api.uploadFile(file, 24, (progress) =>
setUploadProgress(progress),
);
return result;
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/AgentActivityDropdown/helpers.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/AgentActivityDropdown/helpers.tsx
index ab2d5a9d03..06ebe199a9 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/AgentActivityDropdown/helpers.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/AgentActivityDropdown/helpers.tsx
@@ -1,6 +1,5 @@
import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";
import { GraphExecutionMeta as GeneratedGraphExecutionMeta } from "@/app/api/__generated__/models/graphExecutionMeta";
-import { MyAgent } from "@/app/api/__generated__/models/myAgent";
import type { GraphExecution } from "@/lib/autogpt-server-api/types";
// Time constants
@@ -64,33 +63,6 @@ export interface NotificationState {
totalCount: number;
}
-export function createAgentInfoMap(
- agents: MyAgent[],
-): Map<
- string,
- { name: string; description: string; library_agent_id?: string }
-> {
- const agentMap = new Map<
- string,
- { name: string; description: string; library_agent_id?: string }
- >();
-
- agents.forEach((agent) => {
- // Ensure we have valid agent data
- const agentName =
- agent.agent_name || `Agent ${agent.agent_id?.slice(0, 8)}`;
- const agentDescription = agent.description || "";
-
- agentMap.set(agent.agent_id, {
- name: agentName,
- description: agentDescription,
- library_agent_id: undefined, // MyAgent doesn't have library_agent_id
- });
- });
-
- return agentMap;
-}
-
export function enrichExecutionWithAgentInfo(
execution: GeneratedGraphExecutionMeta,
agentInfoMap: Map<
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
index 7478edeafb..961776e79e 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts
@@ -16,8 +16,6 @@ import type {
APIKeyPermission,
Block,
CreateAPIKeyResponse,
- CreatorDetails,
- CreatorsResponse,
Credentials,
CredentialsDeleteNeedConfirmationResponse,
CredentialsDeleteResponse,
@@ -43,26 +41,15 @@ import type {
LibraryAgentPresetUpdatable,
LibraryAgentResponse,
LibraryAgentSortEnum,
- MyAgentsResponse,
NodeExecutionResult,
NotificationPreference,
NotificationPreferenceDTO,
OttoQuery,
OttoResponse,
- ProfileDetails,
RefundRequest,
- ReviewSubmissionRequest,
Schedule,
ScheduleCreatable,
ScheduleID,
- StoreAgentsResponse,
- StoreListingsWithVersionsResponse,
- StoreReview,
- StoreReviewCreate,
- StoreSubmission,
- StoreSubmissionRequest,
- StoreSubmissionsResponse,
- SubmissionStatus,
TransactionHistory,
User,
UserPasswordCredentials,
@@ -445,86 +432,8 @@ export default class BackendAPI {
return this._request("POST", "/analytics/log_raw_analytics", analytic);
}
- ////////////////////////////////////////
- ///////////// V2 STORE API /////////////
- ////////////////////////////////////////
-
- async getStoreProfile(): Promise<ProfileDetails | null> {
- try {
- return await this._get("/store/profile");
- } catch (error) {
- if (!(error instanceof LogoutInterruptError)) {
- Sentry.captureException(error);
- }
- return null;
- }
- }
-
- getStoreAgents(params?: {
- featured?: boolean;
- creator?: string;
- sorted_by?: string;
- search_query?: string;
- category?: string;
- page?: number;
- page_size?: number;
- }): Promise<StoreAgentsResponse> {
- return this._get("/store/agents", params);
- }
-
- getGraphMetaByStoreListingVersionID(
- storeListingVersionID: string,
- ): Promise<GraphMeta> {
- return this._get(`/store/graph/${storeListingVersionID}`);
- }
-
- getStoreCreators(params?: {
- featured?: boolean;
- search_query?: string;
- sorted_by?: string;
- page?: number;
- page_size?: number;
- }): Promise<CreatorsResponse> {
- return this._get("/store/creators", params);
- }
-
- getStoreCreator(username: string): Promise<CreatorDetails> {
- return this._get(`/store/creator/${encodeURIComponent(username)}`);
- }
-
- getStoreSubmissions(params?: {
- page?: number;
- page_size?: number;
- }): Promise<StoreSubmissionsResponse> {
- return this._get("/store/submissions", params);
- }
-
- createStoreSubmission(
- submission: StoreSubmissionRequest,
- ): Promise<StoreSubmission> {
- return this._request("POST", "/store/submissions", submission);
- }
-
- generateStoreSubmissionImage(
- agent_id: string,
- ): Promise<{ image_url: string }> {
- return this._request(
- "POST",
- "/store/submissions/generate_image?agent_id=" + agent_id,
- );
- }
-
- deleteStoreSubmission(submission_id: string): Promise<boolean> {
- return this._request("DELETE", `/store/submissions/${submission_id}`);
- }
-
- uploadStoreSubmissionMedia(file: File): Promise<string> {
- return this._uploadFile("/store/submissions/media", file);
- }
-
- uploadFile(
+ async uploadFile(
file: File,
- provider: string = "gcs",
expiration_hours: number = 24,
onProgress?: (progress: number) => void,
): Promise<{
@@ -534,82 +443,22 @@ export default class BackendAPI {
content_type: string;
expires_in_hours: number;
}> {
- return this._uploadFileWithProgress(
+ const response = await this._uploadFileWithProgress(
"/files/upload",
file,
- {
- provider,
- expiration_hours,
- },
+ { expiration_hours },
onProgress,
- ).then((response) => {
- if (typeof response === "string") {
- return JSON.parse(response);
- }
- return response;
- });
- }
-
- updateStoreProfile(profile: ProfileDetails): Promise<ProfileDetails> {
- return this._request("POST", "/store/profile", profile);
- }
-
- reviewAgent(
- username: string,
- agentName: string,
- review: StoreReviewCreate,
- ): Promise<StoreReview> {
- return this._request(
- "POST",
- `/store/agents/${encodeURIComponent(username)}/${encodeURIComponent(
- agentName,
- )}/review`,
- review,
);
- }
-
- getMyAgents(params?: {
- page?: number;
- page_size?: number;
- }): Promise<MyAgentsResponse> {
- return this._get("/store/myagents", params);
- }
-
- downloadStoreAgent(
- storeListingVersionId: string,
- version?: number,
- ): Promise<BlobPart> {
- const url = version
- ? `/store/download/agents/${storeListingVersionId}?version=${version}`
- : `/store/download/agents/${storeListingVersionId}`;
-
- return this._get(url);
+ if (typeof response === "string") {
+ return JSON.parse(response);
+ }
+ return response;
}
/////////////////////////////////////////
/////////// Admin API ///////////////////
/////////////////////////////////////////
- getAdminListingsWithVersions(params?: {
- status?: SubmissionStatus;
- search?: string;
- page?: number;
- page_size?: number;
- }): Promise<StoreListingsWithVersionsResponse> {
- return this._get("/store/admin/listings", params);
- }
-
- reviewSubmissionAdmin(
- storeListingVersionId: string,
- review: ReviewSubmissionRequest,
- ): Promise<StoreSubmission> {
- return this._request(
- "POST",
- `/store/admin/submissions/${storeListingVersionId}/review`,
- review,
- );
- }
-
addUserCredits(
user_id: string,
amount: number,
@@ -631,12 +480,6 @@ export default class BackendAPI {
return this._get("/credits/admin/users_history", params);
}
- downloadStoreAgentAdmin(storeListingVersionId: string): Promise<BlobPart> {
- const url = `/store/admin/submissions/download/${storeListingVersionId}`;
-
- return this._get(url);
- }
-
////////////////////////////////////////
//////////// V2 LIBRARY API ////////////
////////////////////////////////////////
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index ffc21269e6..959f141845 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -1,15 +1,3 @@
-export enum SubmissionStatus {
- DRAFT = "DRAFT",
- PENDING = "PENDING",
- APPROVED = "APPROVED",
- REJECTED = "REJECTED",
-}
-export type ReviewSubmissionRequest = {
- store_listing_version_id: string;
- is_approved: boolean;
- comments: string; // External comments visible to creator
- internal_comments?: string; // Admin-only comments
-};
export type Category = {
category: string;
description: string;
@@ -778,102 +766,6 @@ export type Pagination = {
page_size: number;
};
-export type StoreAgent = {
- slug: string;
- agent_name: string;
- agent_image: string;
- creator: string;
- creator_avatar: string;
- sub_heading: string;
- description: string;
- runs: number;
- rating: number;
- updated_at: string;
-};
-
-export type StoreAgentsResponse = {
- agents: StoreAgent[];
- pagination: Pagination;
-};
-
-export type Creator = {
- name: string;
- username: string;
- description: string;
- avatar_url: string;
- num_agents: number;
- agent_rating: number;
- agent_runs: number;
-};
-
-export type CreatorsResponse = {
- creators: Creator[];
- pagination: Pagination;
-};
-
-export type CreatorDetails = {
- name: string;
- username: string;
- description: string;
- links: string[];
- avatar_url: string;
- agent_rating: number;
- agent_runs: number;
- top_categories: string[];
-};
-
-export type StoreSubmission = {
- agent_id: string;
- agent_version: number;
- name: string;
- sub_heading: string;
- description: string;
- instructions?: string;
- image_urls: string[];
- date_submitted: string;
- status: SubmissionStatus;
- runs: number;
- rating: number;
- slug: string;
- store_listing_version_id?: string;
- version?: number; // Actual version number from the database
-
- // Review information
- reviewer_id?: string;
- review_comments?: string;
- internal_comments?: string; // Admin-only comments
- reviewed_at?: string;
- changes_summary?: string;
-};
-
-export type StoreSubmissionsResponse = {
- submissions: StoreSubmission[];
- pagination: Pagination;
-};
-
-export type StoreSubmissionRequest = {
- agent_id: string;
- agent_version: number;
- slug: string;
- name: string;
- sub_heading: string;
- video_url?: string;
- image_urls: string[];
- description: string;
- instructions?: string | null;
- categories: string[];
- changes_summary?: string;
- recommended_schedule_cron?: string | null;
-};
-
-export type ProfileDetails = {
- name: string;
- username: string;
- description: string;
- links: string[];
- avatar_url: string;
-};
-
/* Mirror of backend/executor/scheduler.py:GraphExecutionJobInfo */
export type Schedule = {
id: ScheduleID;
@@ -900,32 +792,6 @@ export type ScheduleCreatable = {
credentials?: Record<string, CredentialsMetaInput>;
};
-export type MyAgent = {
- agent_id: GraphID;
- agent_version: number;
- agent_name: string;
- agent_image: string | null;
- last_edited: string;
- description: string;
- recommended_schedule_cron: string | null;
-};
-
-export type MyAgentsResponse = {
- agents: MyAgent[];
- pagination: Pagination;
-};
-
-export type StoreReview = {
- score: number;
- comments?: string;
-};
-
-export type StoreReviewCreate = {
- store_listing_version_id: string;
- score: number;
- comments?: string;
-};
-
// API Key Types
export enum APIKeyPermission {
@@ -1081,46 +947,6 @@ export interface OttoQuery {
graph_id?: string;
}
-export interface StoreListingWithVersions {
- listing_id: string;
- slug: string;
- agent_id: string;
- agent_version: number;
- active_version_id: string | null;
- has_approved_version: boolean;
- creator_email: string | null;
- latest_version: StoreSubmission | null;
- versions: StoreSubmission[];
-}
-
-export interface StoreListingsWithVersionsResponse {
- listings: StoreListingWithVersions[];
- pagination: Pagination;
-}
-
-// Admin API Types
-export type AdminSubmissionsRequest = {
- status?: SubmissionStatus;
- search?: string;
- page: number;
- page_size: number;
-};
-
-export type AdminListingHistoryRequest = {
- listing_id: string;
- page: number;
- page_size: number;
-};
-
-export type AdminSubmissionDetailsRequest = {
- store_listing_version_id: string;
-};
-
-export type AdminPendingSubmissionsRequest = {
- page: number;
- page_size: number;
-};
-
export enum CreditTransactionType {
TOP_UP = "TOP_UP",
USAGE = "USAGE",
diff --git a/docs/integrations/block-integrations/system/store_operations.md b/docs/integrations/block-integrations/system/store_operations.md
index 6ff47daca9..07687870fd 100644
--- a/docs/integrations/block-integrations/system/store_operations.md
+++ b/docs/integrations/block-integrations/system/store_operations.md
@@ -54,7 +54,7 @@ Search for agents in the store
### How it works
<!-- MANUAL: how_it_works -->
-This block searches the AutoGPT agent store using a query string. Filter results by category and sort by rating, runs, or name. Limit controls the maximum number of results returned.
+This block searches the AutoGPT agent store using a query string. Filter results by category and sort by rating, runs, name, or recency (`updated_at`). Limit controls the maximum number of results returned.
Results include basic agent information and are output both as a list and individually for workflow iteration.
<!-- END MANUAL -->