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.
fix(backend): carry marketplace name/description/image to downloaded library agents (#13680)
Abhimanyu Yadavfb1ad08c58ec
diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.pyindex 87e1f4ea13..0d741cc08a 100644--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py@@ -249,9 +249,12 @@ async def test_resolve_graph_admin_uses_get_graph_as_admin() -> None:):mock_prisma.return_value.find_unique = AsyncMock(return_value=mock_slv)- result = await resolve_graph_for_library(SLV_ID, ADMIN_USER_ID, admin=True)+ result, resolved_slv = await resolve_graph_for_library(+ SLV_ID, ADMIN_USER_ID, admin=True+ )assert result is mock_graph_model+ assert resolved_slv is mock_slvmock_admin.assert_awaited_once_with(graph_id=GRAPH_ID, version=GRAPH_VERSION, user_id=ADMIN_USER_ID)@@ -286,9 +289,12 @@ async def test_resolve_graph_regular_uses_get_graph() -> None:):mock_prisma.return_value.find_unique = AsyncMock(return_value=mock_slv)- result = await resolve_graph_for_library(SLV_ID, "regular-user-id", admin=False)+ result, resolved_slv = await resolve_graph_for_library(+ SLV_ID, "regular-user-id", admin=False+ )assert result is mock_graph_model+ assert resolved_slv is mock_slvmock_regular.assert_awaited_once_with(graph_id=GRAPH_ID, version=GRAPH_VERSION, user_id="regular-user-id")diff --git a/autogpt_platform/backend/backend/api/features/library/_add_to_library.py b/autogpt_platform/backend/backend/api/features/library/_add_to_library.pyindex e77e22c7f5..0ccc92446a 100644--- a/autogpt_platform/backend/backend/api/features/library/_add_to_library.py+++ b/autogpt_platform/backend/backend/api/features/library/_add_to_library.py@@ -26,11 +26,14 @@ async def resolve_graph_for_library(user_id: str,*,admin: bool,-) -> GraphModel:+) -> tuple[GraphModel, prisma.models.StoreListingVersion]:"""Look up a StoreListingVersion and resolve its graph.When ``admin=True``, uses ``get_graph_as_admin`` to bypass the marketplaceAPPROVED-only check. Otherwise uses the regular ``get_graph``.++ Returns the resolved graph together with the StoreListingVersion, so callers+ can snapshot marketplace metadata without re-querying it."""slv = await prisma.models.StoreListingVersion.prisma().find_unique(where={"id": store_listing_version_id}, include={"AgentGraph": True}@@ -52,13 +55,33 @@ async def resolve_graph_for_library(if not graph_model:raise NotFoundError(f"Graph #{ag.id} v{ag.version} not found or accessible")- return graph_model+ return graph_model, slv+++def _marketplace_metadata(+ store_listing_version: prisma.models.StoreListingVersion,+) -> dict[str, str | None]:+ """Snapshot the marketplace listing's title/description/image.++ Returns the published ``name``, ``description`` and first image URL so a+ downloaded agent shows up in the library exactly as it appears in the+ marketplace.+ """+ return {+ "name": store_listing_version.name,+ "description": store_listing_version.description,+ "imageUrl": (+ store_listing_version.imageUrls[0]+ if store_listing_version.imageUrls+ else None+ ),+ }async def add_graph_to_library(- store_listing_version_id: str,graph_model: GraphModel,user_id: str,+ store_listing_version: prisma.models.StoreListingVersion,) -> library_model.LibraryAgent:"""Check existing / restore soft-deleted / create new LibraryAgent.@@ -71,6 +94,7 @@ async def add_graph_to_library(_include = library_agent_include(user_id, include_nodes=False, include_executions=False)+ marketplace = _marketplace_metadata(store_listing_version)try:added_agent = await prisma.models.LibraryAgent.prisma().create(@@ -87,11 +111,15 @@ async def add_graph_to_library("isCreatedByUser": False,"useGraphIsActiveVersion": False,"settings": settings_json,+ "name": marketplace["name"],+ "description": marketplace["description"],+ "imageUrl": marketplace["imageUrl"],},include=_include,)except prisma.errors.UniqueViolationError:# Already exists — update to restore if previously soft-deleted/archived+ # and refresh the marketplace snapshot in case the listing changed.added_agent = await prisma.models.LibraryAgent.prisma().update(where={"userId_agentGraphId_agentGraphVersion": {@@ -104,6 +132,9 @@ async def add_graph_to_library("isDeleted": False,"isArchived": False,"settings": settings_json,+ "name": marketplace["name"],+ "description": marketplace["description"],+ "imageUrl": marketplace["imageUrl"],},include=_include,)@@ -115,7 +146,7 @@ async def add_graph_to_library(logger.debug(f"Added graph #{graph_model.id} v{graph_model.version} "- f"for store listing version #{store_listing_version_id} "+ f"for store listing version #{store_listing_version.id} "f"to library for user #{user_id}")schedule_info = await _fetch_schedule_info(user_id, graph_id=graph_model.id)diff --git a/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py b/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.pyindex dbb8a17626..f68d099012 100644--- a/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py+++ b/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py@@ -3,7 +3,24 @@ from unittest.mock import AsyncMock, MagicMock, patchimport prisma.errorsimport pytest-from ._add_to_library import add_graph_to_library+from ._add_to_library import _marketplace_metadata, add_graph_to_library+++def _make_slv(+ *,+ name: str = "Marketplace Title",+ description: str = "Marketplace description",+ image_urls: list[str] | None = None,+) -> MagicMock:+ slv = MagicMock(+ id="slv-id",+ description=description,+ imageUrls=(+ ["https://cdn.example.com/agent.png"] if image_urls is None else image_urls+ ),+ )+ slv.name = name # `name` is reserved in the MagicMock ctor+ return slv@pytest.mark.asyncio@@ -28,7 +45,7 @@ async def test_add_graph_to_library_create_new_agent() -> None:):mock_prisma.return_value.create = AsyncMock(return_value=created_agent)- result = await add_graph_to_library("slv-id", graph_model, "user-id")+ result = await add_graph_to_library(graph_model, "user-id", _make_slv())assert result is converted_agentmock_from_db.assert_called_once_with(created_agent, schedule_info={})@@ -41,6 +58,10 @@ async def test_add_graph_to_library_create_new_agent() -> None:}assert create_data["isCreatedByUser"] is Falseassert create_data["useGraphIsActiveVersion"] is False+ # Marketplace metadata is snapshotted onto the new LibraryAgent+ assert create_data["name"] == "Marketplace Title"+ assert create_data["description"] == "Marketplace description"+ assert create_data["imageUrl"] == "https://cdn.example.com/agent.png"@pytest.mark.asyncio@@ -70,7 +91,7 @@ async def test_add_graph_to_library_unique_violation_updates_existing() -> None:)mock_prisma.return_value.update = AsyncMock(return_value=updated_agent)- result = await add_graph_to_library("slv-id", graph_model, "user-id")+ result = await add_graph_to_library(graph_model, "user-id", _make_slv())assert result is converted_agentmock_from_db.assert_called_once_with(updated_agent, schedule_info={})@@ -86,3 +107,34 @@ async def test_add_graph_to_library_unique_violation_updates_existing() -> None:update_data = update_call.kwargs["data"]assert update_data["isDeleted"] is Falseassert update_data["isArchived"] is False+ # Restoring a soft-deleted agent refreshes the marketplace snapshot too+ assert update_data["name"] == "Marketplace Title"+ assert update_data["description"] == "Marketplace description"+ assert update_data["imageUrl"] == "https://cdn.example.com/agent.png"+++def test_marketplace_metadata_returns_first_image() -> None:+ """Pulls name/description and the first image URL from the listing version."""+ slv = _make_slv(+ image_urls=[+ "https://cdn.example.com/a.png",+ "https://cdn.example.com/b.png",+ ]+ )++ assert _marketplace_metadata(slv) == {+ "name": "Marketplace Title",+ "description": "Marketplace description",+ "imageUrl": "https://cdn.example.com/a.png",+ }+++def test_marketplace_metadata_without_images_yields_null_image() -> None:+ """A listing with no images snapshots a null imageUrl (graph image wins)."""+ slv = _make_slv(image_urls=[])++ assert _marketplace_metadata(slv) == {+ "name": "Marketplace Title",+ "description": "Marketplace description",+ "imageUrl": None,+ }diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex 7baaca282b..c225421bdd 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -189,7 +189,12 @@ async def list_library_agents(# Build search filter if applicableif search_term:+ # Match both the snapshotted marketplace name/description (shown on the+ # card for downloaded agents) and the underlying graph's own values, so+ # searching the displayed title always finds the agent.where_clause["OR"] = [+ {"name": {"contains": search_term, "mode": "insensitive"}},+ {"description": {"contains": search_term, "mode": "insensitive"}},{"AgentGraph": {"is": {"name": {"contains": search_term, "mode": "insensitive"}}@@ -1156,10 +1161,10 @@ async def add_store_agent_to_library(f"Adding agent from store listing version #{store_listing_version_id} "f"to library for user #{user_id}")- graph_model = await resolve_graph_for_library(+ graph_model, store_listing_version = await resolve_graph_for_library(store_listing_version_id, user_id, admin=False)- return await add_graph_to_library(store_listing_version_id, graph_model, user_id)+ return await add_graph_to_library(graph_model, user_id, store_listing_version)async def add_store_agent_to_library_as_admin(@@ -1173,10 +1178,10 @@ async def add_store_agent_to_library_as_admin(f"ADMIN adding agent from store listing version "f"#{store_listing_version_id} to library for user #{user_id}")- graph_model = await resolve_graph_for_library(+ graph_model, store_listing_version = await resolve_graph_for_library(store_listing_version_id, user_id, admin=True)- return await add_graph_to_library(store_listing_version_id, graph_model, user_id)+ return await add_graph_to_library(graph_model, user_id, store_listing_version)##############################################diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.pyindex 6268d7a5c0..836a83976f 100644--- a/autogpt_platform/backend/backend/api/features/library/db_test.py+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py@@ -133,6 +133,46 @@ async def test_list_library_agents_is_hidden_filter(assert where["isHidden"] is expected_in_where+async def test_list_library_agents_search_matches_snapshot_and_graph(mocker):+ """Search must match the snapshotted LibraryAgent name/description (shown on+ the card for downloaded agents) as well as the underlying graph's values."""+ mock_agent_graph = mocker.patch("prisma.models.AgentGraph.prisma")+ mock_agent_graph.return_value.find_many = mocker.AsyncMock(return_value=[])++ mock_find_many = mocker.AsyncMock(return_value=[])+ mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")+ mock_library_agent.return_value.find_many = mock_find_many+ mock_library_agent.return_value.count = mocker.AsyncMock(return_value=0)++ mocker.patch(+ "backend.api.features.library.db._fetch_execution_counts",+ new=mocker.AsyncMock(return_value={}),+ )++ await db.list_library_agents("test-user", search_term="Published Title")++ where = mock_find_many.call_args.kwargs["where"]+ assert {"name": {"contains": "Published Title", "mode": "insensitive"}} in where[+ "OR"+ ]+ assert {+ "description": {"contains": "Published Title", "mode": "insensitive"}+ } in where["OR"]+ assert {+ "AgentGraph": {+ "is": {"name": {"contains": "Published Title", "mode": "insensitive"}}+ }+ } in where["OR"]+ assert {+ "AgentGraph": {+ "is": {+ "description": {"contains": "Published Title", "mode": "insensitive"}+ }+ }+ } in where["OR"]++@pytest.mark.asyncio(loop_scope="session")async def test_add_agent_to_library(mocker):mocker.patch(diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.pyindex ce4e820b9f..143c52401b 100644--- a/autogpt_platform/backend/backend/api/features/library/model.py+++ b/autogpt_platform/backend/backend/api/features/library/model.py@@ -349,8 +349,16 @@ class LibraryAgent(pydantic.BaseModel):created_at=created_at,updated_at=updated_at,last_run_at=agent.lastRunAt,- name=graph.name,- description=graph.description,+ # Prefer the marketplace title/description snapshotted at download+ # time; fall back to the graph's own values for user-created agents+ # (which have no snapshot). `is not None` so an intentionally empty+ # published value is preserved rather than replaced by the graph's.+ name=agent.name if agent.name is not None else graph.name,+ description=(+ agent.description+ if agent.description is not None+ else graph.description+ ),instructions=graph.instructions,input_schema=graph.input_schema,output_schema=graph.output_schema,diff --git a/autogpt_platform/backend/backend/api/features/library/model_test.py b/autogpt_platform/backend/backend/api/features/library/model_test.pyindex 79a0c4942d..fcbb70eabb 100644--- a/autogpt_platform/backend/backend/api/features/library/model_test.py+++ b/autogpt_platform/backend/backend/api/features/library/model_test.py@@ -11,6 +11,8 @@ def _make_library_agent(*,graph_id: str = "g1",executions: list | None = None,+ name: str | None = None,+ description: str | None = None,) -> prisma.models.LibraryAgent:return prisma.models.LibraryAgent(id="la1",@@ -22,6 +24,8 @@ def _make_library_agent(isDeleted=False,isArchived=False,isHidden=False,+ name=name,+ description=description,createdAt=datetime.datetime.now(),updatedAt=datetime.datetime.now(),isFavorite=False,@@ -41,6 +45,42 @@ def _make_library_agent()+def test_from_db_prefers_marketplace_name_and_description():+ """Snapshotted marketplace title/description override the graph's own."""+ agent = _make_library_agent(+ name="Published Title",+ description="Published description",+ )++ result = library_model.LibraryAgent.from_db(agent)++ assert result.name == "Published Title"+ assert result.description == "Published description"+++def test_from_db_falls_back_to_graph_name_and_description():+ """User-created agents (no snapshot) fall back to the graph's values."""+ agent = _make_library_agent(name=None, description=None)++ result = library_model.LibraryAgent.from_db(agent)++ assert result.name == "Agent"+ assert result.description == "Desc"+++def test_from_db_preserves_empty_marketplace_description():+ """An intentionally-empty published value is kept, not replaced by the graph.++ Only a missing snapshot (None) falls back; an empty string is a real value.+ """+ agent = _make_library_agent(name="Published Title", description="")++ result = library_model.LibraryAgent.from_db(agent)++ assert result.name == "Published Title"+ assert result.description == ""++def test_from_db_execution_count_override_covers_success_rate():"""Covers execution_count_override is not None branch and executions/count > 0 block."""now = datetime.datetime.now(datetime.timezone.utc)diff --git a/autogpt_platform/backend/migrations/20260727120000_add_library_agent_marketplace_metadata/migration.sql b/autogpt_platform/backend/migrations/20260727120000_add_library_agent_marketplace_metadata/migration.sqlnew file mode 100644index 0000000000..85fde3cfea--- /dev/null+++ b/autogpt_platform/backend/migrations/20260727120000_add_library_agent_marketplace_metadata/migration.sql@@ -0,0 +1,7 @@+-- Snapshot the marketplace-published title/description onto the LibraryAgent at+-- download time so a downloaded agent appears in the library as it does in the+-- marketplace, instead of showing the creator's original graph name/description.+-- Nullable: user-created agents keep NULL and fall back to the graph's values.+-- AlterTable+ALTER TABLE "LibraryAgent" ADD COLUMN "name" TEXT;+ALTER TABLE "LibraryAgent" ADD COLUMN "description" TEXT;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 2f6c0014b1..81589775de 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -608,6 +608,12 @@ model LibraryAgent {imageUrl String?+ // Marketplace metadata snapshotted at download time, so a downloaded agent+ // shows its published title/description instead of the creator's originals.+ // Null for user-created agents, which fall back to the graph's own values.+ name String?+ description String?+agentGraphId StringagentGraphVersion IntAgentGraph AgentGraph @relation(fields: [agentGraphId, agentGraphVersion], references: [id, version], onDelete: Restrict)