AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat: allow admins to download agents for review (#9881)
Nicholas Tindle8fdfd75cc409
diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex c77e79e179..cfc9d53073 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -736,6 +736,58 @@ async def get_graph(return GraphModel.from_db(graph, for_export)+async def get_graph_as_admin(+ graph_id: str,+ version: int | None = None,+ user_id: str | None = None,+ for_export: bool = False,+) -> GraphModel | None:+ """+ Intentionally parallels the get_graph but should only be used for admin tasks, because can return any graph that's been submitted+ Retrieves a graph from the DB.+ Defaults to the version with `is_active` if `version` is not passed.++ Returns `None` if the record is not found.+ """+ logger.warning(f"Getting {graph_id=} {version=} as ADMIN {user_id=} {for_export=}")+ where_clause: AgentGraphWhereInput = {+ "id": graph_id,+ }++ if version is not None:+ where_clause["version"] = version++ graph = await AgentGraph.prisma().find_first(+ where=where_clause,+ include=AGENT_GRAPH_INCLUDE,+ order={"version": "desc"},+ )++ # For access, the graph must be owned by the user or listed in the store+ if graph is None or (+ graph.userId != user_id+ and not (+ await StoreListingVersion.prisma().find_first(+ where={+ "agentGraphId": graph_id,+ "agentGraphVersion": version or graph.version,+ }+ )+ )+ ):+ return None++ if for_export:+ sub_graphs = await get_sub_graphs(graph)+ return GraphModel.from_db(+ graph=graph,+ sub_graphs=sub_graphs,+ for_export=for_export,+ )++ return GraphModel.from_db(graph, for_export)++async def get_sub_graphs(graph: AgentGraph) -> list[AgentGraph]:"""Iteratively fetches all sub-graphs of a given graph, and flattens them into a list.diff --git a/autogpt_platform/backend/backend/server/v2/admin/store_admin_routes.py b/autogpt_platform/backend/backend/server/v2/admin/store_admin_routes.pyindex f413d4114a..e59b0c4805 100644--- a/autogpt_platform/backend/backend/server/v2/admin/store_admin_routes.py+++ b/autogpt_platform/backend/backend/server/v2/admin/store_admin_routes.py@@ -1,4 +1,5 @@import logging+import tempfileimport typingimport autogpt_libs.auth.depends@@ -9,6 +10,7 @@ import prisma.enumsimport backend.server.v2.store.dbimport backend.server.v2.store.exceptionsimport backend.server.v2.store.model+import backend.util.jsonlogger = logging.getLogger(__name__)@@ -98,3 +100,47 @@ async def review_submission(status_code=500,content={"detail": "An error occurred while reviewing the submission"},)+++ "/submissions/download/{store_listing_version_id}",+ tags=["store", "admin"],+ dependencies=[fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user)],+)+async def admin_download_agent_file(+ user: typing.Annotated[+ autogpt_libs.auth.models.User,+ fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user),+ ],+ 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 backend.server.v2.store.db.get_agent(+ user_id=user.user_id,+ store_listing_version_id=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"+ )diff --git a/autogpt_platform/backend/backend/server/v2/store/db.py b/autogpt_platform/backend/backend/server/v2/store/db.pyindex 233ed05421..a2d0a693f9 100644--- a/autogpt_platform/backend/backend/server/v2/store/db.py+++ b/autogpt_platform/backend/backend/server/v2/store/db.py@@ -1361,3 +1361,31 @@ async def get_admin_listings_with_versions(page_size=page_size,),)+++async def get_agent_as_admin(+ user_id: str | None,+ 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}+ )+ )++ if not store_listing_version:+ raise ValueError(f"Store listing version {store_listing_version_id} not found")++ graph = await backend.data.graph.get_graph_as_admin(+ user_id=user_id,+ graph_id=store_listing_version.agentGraphId,+ version=store_listing_version.agentGraphVersion,+ for_export=True,+ )+ if not graph:+ raise ValueError(+ f"Agent {store_listing_version.agentGraphId} v{store_listing_version.agentGraphVersion} not found"+ )++ return graphdiff --git a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.tsindex 182cb2adbf..ad7f48f24c 100644--- a/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/admin/marketplace/actions.ts@@ -56,3 +56,9 @@ export async function getAdminListingsWithVersions(const response = await api.getAdminListingsWithVersions(data);return response;}++export async function downloadAsAdmin(storeListingVersion: string) {+ const api = new BackendApi();+ const file = await api.downloadStoreAgentAdmin(storeListingVersion);+ return file;+}diff --git a/autogpt_platform/frontend/src/components/admin/marketplace/download-agent-button.tsx b/autogpt_platform/frontend/src/components/admin/marketplace/download-agent-button.tsxnew file mode 100644index 0000000000..bb1dfac958--- /dev/null+++ b/autogpt_platform/frontend/src/components/admin/marketplace/download-agent-button.tsx@@ -0,0 +1,58 @@+"use client";++import { downloadAsAdmin } from "@/app/(platform)/admin/marketplace/actions";+import { Button } from "@/components/ui/button";+import { ExternalLink } from "lucide-react";+import { useState } from "react";++export function DownloadAgentAdminButton({+ storeListingVersionId,+}: {+ storeListingVersionId: string;+}) {+ const [isLoading, setIsLoading] = useState(false);++ const handleDownload = async () => {+ try {+ setIsLoading(true);+ // Call the server action to get the data+ const fileData = await downloadAsAdmin(storeListingVersionId);++ // Client-side download logic+ const jsonData = JSON.stringify(fileData, null, 2);+ const blob = new Blob([jsonData], { type: "application/json" });++ // Create a temporary URL for the Blob+ const url = window.URL.createObjectURL(blob);++ // Create a temporary anchor element+ const a = document.createElement("a");+ a.href = url;+ a.download = `agent_${storeListingVersionId}.json`;++ // Append the anchor to the body, click it, and remove it+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);++ // Revoke the temporary URL+ window.URL.revokeObjectURL(url);+ } catch (error) {+ console.error("Download failed:", error);+ } finally {+ setIsLoading(false);+ }+ };++ return (+ <Button+ size="sm"+ variant="outline"+ onClick={handleDownload}+ disabled={isLoading}+ >+ <ExternalLink className="mr-2 h-4 w-4" />+ {isLoading ? "Downloading..." : "Download"}+ </Button>+ );+}diff --git a/autogpt_platform/frontend/src/components/admin/marketplace/expandable-row.tsx b/autogpt_platform/frontend/src/components/admin/marketplace/expandable-row.tsxindex a06cfb0fd7..bc42c43686 100644--- a/autogpt_platform/frontend/src/components/admin/marketplace/expandable-row.tsx+++ b/autogpt_platform/frontend/src/components/admin/marketplace/expandable-row.tsx@@ -19,6 +19,8 @@ import {SubmissionStatus,} from "@/lib/autogpt-server-api/types";import { ApproveRejectButtons } from "./approve-reject-buttons";+import { downloadAsAdmin } from "@/app/(platform)/admin/marketplace/actions";+import { DownloadAgentAdminButton } from "./download-agent-button";// Moved the getStatusBadge function into the client componentconst getStatusBadge = (status: SubmissionStatus) => {@@ -77,10 +79,11 @@ export function ExpandableRow({</TableCell><TableCell className="text-right"><div className="flex justify-end gap-2">- <Button size="sm" variant="outline">- <ExternalLink className="mr-2 h-4 w-4" />- Builder- </Button>+ {latestVersion?.store_listing_version_id && (+ <DownloadAgentAdminButton+ storeListingVersionId={latestVersion.store_listing_version_id}+ />+ )}{latestVersion?.status === SubmissionStatus.PENDING && (<ApproveRejectButtons version={latestVersion} />@@ -180,17 +183,13 @@ export function ExpandableRow({{/* <TableCell>{version.categories.join(", ")}</TableCell> */}<TableCell className="text-right"><div className="flex justify-end gap-2">- <Button- size="sm"- variant="outline"- onClick={() =>- (window.location.href = `/admin/agents/${version.store_listing_version_id}`)- }- >- <ExternalLink className="mr-2 h-4 w-4" />- Builder- </Button>-+ {version.store_listing_version_id && (+ <DownloadAgentAdminButton+ storeListingVersionId={+ version.store_listing_version_id+ }+ />+ )}{version.status === SubmissionStatus.PENDING && (<ApproveRejectButtons version={version} />)}diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.tsindex 77046a64ed..3f2c5a3d95 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/client.ts@@ -563,6 +563,12 @@ export default class BackendAPI {);}+ downloadStoreAgentAdmin(storeListingVersionId: string): Promise<BlobPart> {+ const url = `/store/admin/submissions/download/${storeListingVersionId}`;++ return this._get(url);+ }+//////////////////////////////////////////////////// V2 LIBRARY API ////////////////////////////////////////////////////