Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend,backend): add button to generate data to admin dashboard on local dev (#11791)

Nicholas Tindlec91105ff365c
diff --git a/autogpt_platform/backend/backend/api/features/admin/test_data_routes.py b/autogpt_platform/backend/backend/api/features/admin/test_data_routes.py
new file mode 100644
index 0000000000..45ea441e0e
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/admin/test_data_routes.py
@@ -0,0 +1,176 @@
+import importlib.util
+import logging
+from enum import Enum
+from pathlib import Path
+from types import ModuleType
+
+from autogpt_libs.auth import get_user_id, requires_admin_user
+from fastapi import APIRouter, HTTPException, Security
+from pydantic import BaseModel
+
+from backend.data.db import prisma
+from backend.util.metrics import DiscordChannel, discord_send_alert
+from backend.util.settings import AppEnvironment, BehaveAs, Settings
+
+logger = logging.getLogger(__name__)
+settings = Settings()
+
+# The dev-only seeding scripts live in backend/test/, outside the importable
+# package tree, so they are loaded by file path via importlib at request time.
+_TEST_SCRIPT_DIR = Path(__file__).resolve().parents[4] / "test"
+
+
+class TestDataScriptType(str, Enum):
+ """Available test data generation scripts."""
+
+ FULL = "full" # test_data_creator.py - creates 100+ users, comprehensive data
+ E2E = "e2e" # e2e_test_data.py - creates a set of users with API functions
+
+
+class GenerateTestDataRequest(BaseModel):
+ """Request model for test data generation."""
+
+ script_type: TestDataScriptType = TestDataScriptType.E2E
+
+
+class GenerateTestDataResponse(BaseModel):
+ """Response model for test data generation."""
+
+ success: bool
+ message: str
+ details: dict | None = None
+
+
+router = APIRouter(
+ prefix="/admin",
+ tags=["test-data"],
+ dependencies=[Security(requires_admin_user)],
+)
+
+
+ "/generate-test-data",
+ response_model=GenerateTestDataResponse,
+ summary="Generate Test Data",
+)
+async def generate_test_data(
+ request: GenerateTestDataRequest,
+ admin_user_id: str = Security(get_user_id),
+) -> GenerateTestDataResponse:
+ """
+ Generate test data for the platform.
+
+ This endpoint runs the test data generation scripts to populate the database
+ with sample users, agents, graphs, executions, store listings, and more.
+
+ Available script types:
+ - `e2e`: Creates a set of test users with graphs, library agents, presets,
+ and store submissions. Uses API functions for better compatibility.
+ - `full`: Creates 100+ users with comprehensive test data using direct Prisma
+ calls. Generates more data but may take longer.
+
+ **Warning**: This will add significant data to your database. Use with caution.
+ **Note**: This endpoint is only available in local environments; requests from
+ any shared/cloud environment are rejected and alerted on.
+ """
+ await _guard_local_only(admin_user_id, request.script_type)
+
+ logger.info(
+ f"Admin user {admin_user_id} is generating test data "
+ f"with script type: {request.script_type}"
+ )
+
+ try:
+ if request.script_type == TestDataScriptType.E2E:
+ return await _run_e2e_generation()
+ return await _run_full_generation()
+ except Exception:
+ logger.exception("Error generating test data")
+ raise HTTPException(
+ status_code=500,
+ detail="Failed to generate test data. Check the server logs for details.",
+ )
+
+
+async def _guard_local_only(
+ admin_user_id: str, script_type: TestDataScriptType
+) -> None:
+ """Reject and alert on any test-data generation outside a local environment."""
+ is_local = (
+ settings.config.app_env == AppEnvironment.LOCAL
+ and settings.config.behave_as == BehaveAs.LOCAL
+ )
+ if is_local:
+ return
+
+ logger.warning(
+ "Test data generation blocked outside local environment. Admin: %s",
+ admin_user_id,
+ )
+ alert_message = (
+ f"🚨 **SECURITY ALERT**: Test data generation attempted outside a local "
+ f"environment!\n"
+ f"Admin User ID: `{admin_user_id}`\n"
+ f"Environment: `{settings.config.app_env}` / `{settings.config.behave_as}`\n"
+ f"Script Type: `{script_type}`\n"
+ f"Action: Request was blocked."
+ )
+ try:
+ await discord_send_alert(alert_message, DiscordChannel.PLATFORM)
+ except Exception:
+ logger.exception("Failed to send Discord alert for blocked test-data request")
+
+ raise HTTPException(
+ status_code=403,
+ detail="Test data generation is only available in local environments.",
+ )
+
+
+async def _run_e2e_generation() -> GenerateTestDataResponse:
+ """Run the E2E seeding script against the shared Prisma connection."""
+ creator_class = getattr(_load_test_script("e2e_test_data"), "TestDataCreator")
+
+ if not prisma.is_connected():
+ await prisma.connect()
+
+ creator = creator_class()
+ await creator.create_all_test_data()
+
+ return GenerateTestDataResponse(
+ success=True,
+ message="E2E test data generated successfully",
+ details={
+ "users_created": len(creator.users),
+ "graphs_created": len(creator.agent_graphs),
+ "library_agents_created": len(creator.library_agents),
+ "store_submissions_created": len(creator.store_submissions),
+ "presets_created": len(creator.presets),
+ "api_keys_created": len(creator.api_keys),
+ },
+ )
+
+
+async def _run_full_generation() -> GenerateTestDataResponse:
+ """Run the comprehensive seeding script (owns its own Prisma lifecycle)."""
+ run_full = getattr(_load_test_script("test_data_creator"), "main")
+ await run_full()
+
+ return GenerateTestDataResponse(
+ success=True,
+ message="Full test data generated successfully",
+ details={
+ "script": "test_data_creator.py",
+ "note": "Created 100+ users with comprehensive test data",
+ },
+ )
+
+
+def _load_test_script(module_name: str) -> ModuleType:
+ """Load a dev-only seeding script from backend/test/ by file path."""
+ script_path = _TEST_SCRIPT_DIR / f"{module_name}.py"
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"Could not load test-data script '{module_name}'")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
diff --git a/autogpt_platform/backend/backend/api/features/admin/test_data_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/test_data_routes_test.py
new file mode 100644
index 0000000000..4331cea5b8
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/admin/test_data_routes_test.py
@@ -0,0 +1,215 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+import pytest_mock
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
+
+from backend.util.settings import AppEnvironment, BehaveAs
+
+from .test_data_routes import _load_test_script
+from .test_data_routes import router as test_data_router
+
+app = fastapi.FastAPI()
+app.include_router(test_data_router)
+
+client = fastapi.testclient.TestClient(app)
+
+_MODULE = "backend.api.features.admin.test_data_routes"
+_ENDPOINT = "/admin/generate-test-data"
+
+
[email protected](autouse=True)
+def setup_app_admin_auth(mock_jwt_admin):
+ """Run every request as an authenticated admin user by default."""
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_admin["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
+def local_env(mocker: pytest_mock.MockerFixture):
+ """Force the endpoint to consider itself running locally."""
+ settings_mock = MagicMock()
+ settings_mock.config.app_env = AppEnvironment.LOCAL
+ settings_mock.config.behave_as = BehaveAs.LOCAL
+ mocker.patch(f"{_MODULE}.settings", settings_mock)
+ return settings_mock
+
+
+def non_local_env(mocker: pytest_mock.MockerFixture):
+ """Force a shared/cloud environment where generation must be blocked."""
+ settings_mock = MagicMock()
+ settings_mock.config.app_env = AppEnvironment.DEVELOPMENT
+ settings_mock.config.behave_as = BehaveAs.CLOUD
+ mocker.patch(f"{_MODULE}.settings", settings_mock)
+ return settings_mock
+
+
+class _FakeE2ECreator:
+ def __init__(self):
+ # Distinct lengths so a field->attribute mapping bug is detectable.
+ self.users = list(range(7))
+ self.agent_graphs = list(range(5))
+ self.library_agents = list(range(4))
+ self.store_submissions = list(range(3))
+ self.presets = list(range(2))
+ self.api_keys = list(range(6))
+
+ async def create_all_test_data(self):
+ return None
+
+
+def fake_scripts(mocker: pytest_mock.MockerFixture):
+ """Stub the file-path script loader with in-memory fake modules."""
+ e2e_module = SimpleNamespace(TestDataCreator=_FakeE2ECreator)
+ full_module = SimpleNamespace(main=AsyncMock(return_value=None))
+ loader = mocker.patch(
+ f"{_MODULE}._load_test_script",
+ side_effect=lambda name: {
+ "e2e_test_data": e2e_module,
+ "test_data_creator": full_module,
+ }[name],
+ )
+ prisma_mock = MagicMock()
+ prisma_mock.is_connected.return_value = False
+ prisma_mock.connect = AsyncMock()
+ mocker.patch(f"{_MODULE}.prisma", prisma_mock)
+ return SimpleNamespace(
+ loader=loader, e2e=e2e_module, full=full_module, prisma=prisma_mock
+ )
+
+
+def test_e2e_generation_maps_all_detail_fields(local_env, fake_scripts):
+ response = client.post(_ENDPOINT, json={"script_type": "e2e"})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["success"] is True
+ assert body["message"] == "E2E test data generated successfully"
+ assert body["details"] == {
+ "users_created": 7,
+ "graphs_created": 5,
+ "library_agents_created": 4,
+ "store_submissions_created": 3,
+ "presets_created": 2,
+ "api_keys_created": 6,
+ }
+ fake_scripts.prisma.connect.assert_awaited_once()
+
+
+def test_defaults_to_e2e_when_script_type_omitted(local_env, fake_scripts):
+ response = client.post(_ENDPOINT, json={})
+
+ assert response.status_code == 200
+ assert response.json()["message"] == "E2E test data generated successfully"
+
+
+def test_full_generation_success(local_env, fake_scripts):
+ response = client.post(_ENDPOINT, json={"script_type": "full"})
+
+ assert response.status_code == 200
+ assert response.json()["message"] == "Full test data generated successfully"
+ fake_scripts.full.main.assert_awaited_once()
+
+
+def test_skips_connect_when_prisma_already_connected(local_env, fake_scripts):
+ fake_scripts.prisma.is_connected.return_value = True
+
+ response = client.post(_ENDPOINT, json={"script_type": "e2e"})
+
+ assert response.status_code == 200
+ fake_scripts.prisma.connect.assert_not_awaited()
+
+
+def test_generation_failure_returns_500(local_env, fake_scripts):
+ fake_scripts.full.main.side_effect = RuntimeError("boom")
+
+ response = client.post(_ENDPOINT, json={"script_type": "full"})
+
+ assert response.status_code == 500
+ assert "boom" not in response.json()["detail"]
+
+
+def test_e2e_generation_failure_returns_500(local_env, fake_scripts, mocker):
+ mocker.patch.object(
+ _FakeE2ECreator,
+ "create_all_test_data",
+ new=AsyncMock(side_effect=RuntimeError("boom")),
+ )
+
+ response = client.post(_ENDPOINT, json={"script_type": "e2e"})
+
+ assert response.status_code == 500
+ assert "boom" not in response.json()["detail"]
+
+
+def test_blocked_outside_local_returns_403_without_running_scripts(
+ non_local_env, mocker: pytest_mock.MockerFixture
+):
+ loader = mocker.patch(f"{_MODULE}._load_test_script")
+ alert = mocker.patch(f"{_MODULE}.discord_send_alert", new_callable=AsyncMock)
+
+ response = client.post(_ENDPOINT, json={"script_type": "full"})
+
+ assert response.status_code == 403
+ assert "local" in response.json()["detail"].lower()
+ alert.assert_awaited_once()
+ loader.assert_not_called()
+
+
+def test_block_still_returns_403_when_discord_alert_fails(
+ non_local_env, mocker: pytest_mock.MockerFixture
+):
+ mocker.patch(
+ f"{_MODULE}.discord_send_alert",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("discord down"),
+ )
+
+ response = client.post(_ENDPOINT, json={"script_type": "e2e"})
+
+ assert response.status_code == 403
+
+
+def test_non_admin_is_rejected(local_env, fake_scripts, mock_jwt_user):
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+
+ response = client.post(_ENDPOINT, json={"script_type": "e2e"})
+
+ assert response.status_code == 403
+ fake_scripts.loader.assert_not_called()
+
+
+def test_rejects_invalid_script_type(local_env):
+ response = client.post(_ENDPOINT, json={"script_type": "not-a-real-script"})
+
+ assert response.status_code == 422
+
+
+def test_real_seeding_scripts_expose_the_entrypoints_the_route_uses():
+ """Loader smoke test: catches drift in the out-of-tree seeding scripts.
+
+ Every other test stubs `_load_test_script`, so without this the route would
+ keep passing while `backend/test/` moved or renamed its entrypoints.
+ """
+ e2e_module = _load_test_script("e2e_test_data")
+ full_module = _load_test_script("test_data_creator")
+
+ creator_class = getattr(e2e_module, "TestDataCreator")
+ assert callable(getattr(creator_class, "create_all_test_data"))
+ for attribute in (
+ "users",
+ "agent_graphs",
+ "library_agents",
+ "store_submissions",
+ "presets",
+ "api_keys",
+ ):
+ assert attribute in creator_class().__dict__
+
+ assert callable(getattr(full_module, "main"))
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index b4cb607202..fbfaaffdff 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -27,6 +27,7 @@ import backend.api.features.admin.memory_admin_routes
import backend.api.features.admin.platform_cost_routes
import backend.api.features.admin.rate_limit_admin_routes
import backend.api.features.admin.store_admin_routes
+import backend.api.features.admin.test_data_routes
import backend.api.features.auth_email.routes as auth_email_routes
import backend.api.features.briefings.routes
import backend.api.features.builder
@@ -448,6 +449,15 @@ app.include_router(
tags=["v2", "admin"],
prefix="/api",
)
+# Dev-only surface: the test-data seeder is never mounted outside a local
+# app_env, matching how docs_url/metrics are gated above. The runtime
+# `_guard_local_only` check stays as defense-in-depth for LOCAL+CLOUD drift.
+if settings.config.app_env == backend.util.settings.AppEnvironment.LOCAL:
+ app.include_router(
+ backend.api.features.admin.test_data_routes.router,
+ tags=["v2", "admin"],
+ prefix="/api",
+ )
app.include_router(
backend.api.features.executions.review.routes.router,
tags=["v2", "executions", "review"],
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminMobileNav.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminMobileNav.test.tsx
index 6d9750573e..097b18772e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminMobileNav.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminMobileNav.test.tsx
@@ -43,7 +43,7 @@ vi.mock("next/link", () => ({
}));
import { AdminMobileNav } from "../components/AdminMobileNav/AdminMobileNav";
-import { adminNavItems } from "../components/AdminSidebar/helpers";
+import { getAdminNavItems } from "../components/AdminSidebar/helpers";
describe("AdminMobileNav", () => {
beforeEach(() => {
@@ -64,7 +64,7 @@ describe("AdminMobileNav", () => {
expect(
screen.getByRole("button", { name: /admin navigation/i }).textContent,
- ).toContain(adminNavItems[0].label);
+ ).toContain(getAdminNavItems()[0].label);
});
it("opens a popover listing every admin section", async () => {
@@ -72,7 +72,7 @@ describe("AdminMobileNav", () => {
fireEvent.click(screen.getByRole("button", { name: /admin navigation/i }));
- for (const { label } of adminNavItems) {
+ for (const { label } of getAdminNavItems()) {
expect(
await screen.findByRole("link", { name: new RegExp(label, "i") }),
).toBeDefined();
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminSidebar.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminSidebar.test.tsx
index 132d8a1ab0..6856ad72f7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminSidebar.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/AdminSidebar.test.tsx
@@ -38,7 +38,7 @@ vi.mock("next/link", () => ({
}));
import { AdminSidebar } from "../components/AdminSidebar/AdminSidebar";
-import { adminNavItems } from "../components/AdminSidebar/helpers";
+import { getAdminNavItems } from "../components/AdminSidebar/helpers";
describe("AdminSidebar", () => {
beforeEach(() => {
@@ -51,7 +51,7 @@ describe("AdminSidebar", () => {
const back = screen.getByRole("link", { name: /back/i });
expect(back.getAttribute("href")).toBe("/copilot");
- for (const { label, href } of adminNavItems) {
+ for (const { label, href } of getAdminNavItems()) {
const link = screen.getByRole("link", { name: new RegExp(label, "i") });
expect(link.getAttribute("href")).toBe(href);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx
index 0667c7aafc..6f7143ea82 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/__tests__/layout.test.tsx
@@ -1,5 +1,6 @@
import { render, screen } from "@/tests/integrations/test-utils";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import * as testDataHelpers from "../test-data/helpers";
import AdminLayout from "../layout";
const ADMIN_LINKS = [
@@ -17,6 +18,10 @@ const ADMIN_LINKS = [
];
describe("AdminLayout", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
it("renders child content", () => {
render(
<AdminLayout>
@@ -39,4 +44,32 @@ describe("AdminLayout", () => {
expect(link?.textContent).toContain(text);
}
});
+
+ it("shows the Test Data link on a local stack", () => {
+ vi.spyOn(testDataHelpers, "isTestDataSurfaceEnabled").mockReturnValue(true);
+ render(
+ <AdminLayout>
+ <div />
+ </AdminLayout>,
+ );
+ const link = screen
+ .getAllByRole("link")
+ .find((el) => el.getAttribute("href") === "/admin/test-data");
+ expect(link).toBeDefined();
+ });
+
+ it("hides the Test Data link outside a local stack", () => {
+ vi.spyOn(testDataHelpers, "isTestDataSurfaceEnabled").mockReturnValue(
+ false,
+ );
+ render(
+ <AdminLayout>
+ <div />
+ </AdminLayout>,
+ );
+ const link = screen
+ .getAllByRole("link")
+ .find((el) => el.getAttribute("href") === "/admin/test-data");
+ expect(link).toBeUndefined();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx
index 65427bcffd..4205c6ccef 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminClassicShell.tsx
@@ -3,6 +3,7 @@ import { IconSliders } from "@/components/__legacy__/ui/icons";
import {
BrainIcon,
Calculator01Icon,
+ Database01Icon,
DollarSignIcon,
File02Icon,
GaugeIcon,
@@ -15,73 +16,89 @@ import {
import { ReactNode } from "react";
import { Icon } from "@/components/atoms/Icon/Icon";
+import { isTestDataSurfaceEnabled } from "../test-data/helpers";
-const sidebarLinkGroups = [
- {
- links: [
- {
- text: "Marketplace Management",
- href: "/admin/marketplace",
- icon: <Icon icon={UserMultipleIcon} className="h-6 w-6" />,
- },
- {
- text: "User Spending",
- href: "/admin/spending",
- icon: <Icon icon={DollarSignIcon} className="h-6 w-6" />,
- },
- {
- text: "System Diagnostics",
- href: "/admin/diagnostics",
- icon: <Icon icon={Pulse01Icon} className="h-6 w-6" />,
- },
- {
- text: "User Impersonation",
- href: "/admin/impersonation",
- icon: <Icon icon={Search01Icon} className="h-6 w-6" />,
- },
- {
- text: "Rate Limits",
- href: "/admin/rate-limits",
- icon: <Icon icon={GaugeIcon} className="h-6 w-6" />,
- },
- {
- text: "Platform Costs",
- href: "/admin/platform-costs",
- icon: <Icon icon={ReceiptTextIcon} className="h-6 w-6" />,
- },
- {
- text: "Execution Analytics",
- href: "/admin/execution-analytics",
- icon: <Icon icon={File02Icon} className="h-6 w-6" />,
- },
- {
- text: "Bot Analytics",
- href: "/admin/bots",
- icon: <Icon icon={Robot01Icon} className="h-6 w-6" />,
- },
- {
- text: "Block Cost Estimates",
- href: "/admin/block-cost-estimates",
- icon: <Icon icon={Calculator01Icon} className="h-6 w-6" />,
- },
- {
- text: "Memory Inspector",
- href: "/admin/memory",
- icon: <Icon icon={BrainIcon} className="h-6 w-6" />,
- },
- {
- text: "Admin User Management",
- href: "/admin/settings",
- icon: <IconSliders className="h-6 w-6" />,
- },
- ],
- },
-];
+// Built per render so the local-only Test Data link follows the live
+// environment check instead of the value at module load.
+function getSidebarLinkGroups() {
+ return [
+ {
+ links: [
+ {
+ text: "Marketplace Management",
+ href: "/admin/marketplace",
+ icon: <Icon icon={UserMultipleIcon} className="h-6 w-6" />,
+ },
+ {
+ text: "User Spending",
+ href: "/admin/spending",
+ icon: <Icon icon={DollarSignIcon} className="h-6 w-6" />,
+ },
+ {
+ text: "System Diagnostics",
+ href: "/admin/diagnostics",
+ icon: <Icon icon={Pulse01Icon} className="h-6 w-6" />,
+ },
+ {
+ text: "User Impersonation",
+ href: "/admin/impersonation",
+ icon: <Icon icon={Search01Icon} className="h-6 w-6" />,
+ },
+ {
+ text: "Rate Limits",
+ href: "/admin/rate-limits",
+ icon: <Icon icon={GaugeIcon} className="h-6 w-6" />,
+ },
+ {
+ text: "Platform Costs",
+ href: "/admin/platform-costs",
+ icon: <Icon icon={ReceiptTextIcon} className="h-6 w-6" />,
+ },
+ {
+ text: "Execution Analytics",
+ href: "/admin/execution-analytics",
+ icon: <Icon icon={File02Icon} className="h-6 w-6" />,
+ },
+ {
+ text: "Bot Analytics",
+ href: "/admin/bots",
+ icon: <Icon icon={Robot01Icon} className="h-6 w-6" />,
+ },
+ {
+ text: "Block Cost Estimates",
+ href: "/admin/block-cost-estimates",
+ icon: <Icon icon={Calculator01Icon} className="h-6 w-6" />,
+ },
+ {
+ text: "Memory Inspector",
+ href: "/admin/memory",
+ icon: <Icon icon={BrainIcon} className="h-6 w-6" />,
+ },
+ {
+ text: "Admin User Management",
+ href: "/admin/settings",
+ icon: <IconSliders className="h-6 w-6" />,
+ },
+ // Test data seeding only exists on local stacks; hide the entry point
+ // everywhere else so cloud admins don't hit a guaranteed 403/404.
+ ...(isTestDataSurfaceEnabled()
+ ? [
+ {
+ text: "Test Data",
+ href: "/admin/test-data",
+ icon: <Icon icon={Database01Icon} className="h-6 w-6" />,
+ },
+ ]
+ : []),
+ ],
+ },
+ ];
+}
export function AdminClassicShell({ children }: { children: ReactNode }) {
return (
<div className="flex h-full w-full flex-col lg:flex-row">
- <Sidebar linkGroups={sidebarLinkGroups} />
+ <Sidebar linkGroups={getSidebarLinkGroups()} />
<div className="flex-1 pl-4">{children}</div>
</div>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts
index 3dcf1a4aa2..1762d4991b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/helpers.ts
@@ -1,6 +1,7 @@
import {
BrainIcon,
Calculator01Icon,
+ Database01Icon,
DollarSignIcon,
File02Icon,
GaugeIcon,
@@ -11,6 +12,8 @@ import {
SlidersHorizontalIcon,
UserMultipleIcon,
} from "@hugeicons/core-free-icons";
+
+import { isTestDataSurfaceEnabled } from "../../test-data/helpers";
import type { IconSvgElement } from "@hugeicons/react";
export interface AdminNavItem {
@@ -19,44 +22,53 @@ export interface AdminNavItem {
Icon: IconSvgElement;
}
-export const adminNavItems: AdminNavItem[] = [
- {
- label: "Marketplace Management",
- href: "/admin/marketplace",
- Icon: UserMultipleIcon,
- },
- { label: "User Spending", href: "/admin/spending", Icon: DollarSignIcon },
- {
- label: "System Diagnostics",
- href: "/admin/diagnostics",
- Icon: Pulse01Icon,
- },
- {
- label: "User Impersonation",
- href: "/admin/impersonation",
- Icon: Search01Icon,
- },
- { label: "Rate Limits", href: "/admin/rate-limits", Icon: GaugeIcon },
- {
- label: "Platform Costs",
- href: "/admin/platform-costs",
- Icon: ReceiptTextIcon,
- },
- {
- label: "Execution Analytics",
- href: "/admin/execution-analytics",
- Icon: File02Icon,
- },
- { label: "Bot Analytics", href: "/admin/bots", Icon: Robot01Icon },
- {
- label: "Block Cost Estimates",
- href: "/admin/block-cost-estimates",
- Icon: Calculator01Icon,
- },
- { label: "Memory Inspector", href: "/admin/memory", Icon: BrainIcon },
- {
- label: "Admin User Management",
- href: "/admin/settings",
- Icon: SlidersHorizontalIcon,
- },
-];
+// Built per call so the local-only Test Data link follows the live
+// environment check instead of the value at module load.
+export function getAdminNavItems(): AdminNavItem[] {
+ return [
+ {
+ label: "Marketplace Management",
+ href: "/admin/marketplace",
+ Icon: UserMultipleIcon,
+ },
+ { label: "User Spending", href: "/admin/spending", Icon: DollarSignIcon },
+ {
+ label: "System Diagnostics",
+ href: "/admin/diagnostics",
+ Icon: Pulse01Icon,
+ },
+ {
+ label: "User Impersonation",
+ href: "/admin/impersonation",
+ Icon: Search01Icon,
+ },
+ { label: "Rate Limits", href: "/admin/rate-limits", Icon: GaugeIcon },
+ {
+ label: "Platform Costs",
+ href: "/admin/platform-costs",
+ Icon: ReceiptTextIcon,
+ },
+ {
+ label: "Execution Analytics",
+ href: "/admin/execution-analytics",
+ Icon: File02Icon,
+ },
+ { label: "Bot Analytics", href: "/admin/bots", Icon: Robot01Icon },
+ {
+ label: "Block Cost Estimates",
+ href: "/admin/block-cost-estimates",
+ Icon: Calculator01Icon,
+ },
+ { label: "Memory Inspector", href: "/admin/memory", Icon: BrainIcon },
+ {
+ label: "Admin User Management",
+ href: "/admin/settings",
+ Icon: SlidersHorizontalIcon,
+ },
+ // Test data seeding only exists on local stacks; hide the entry point
+ // everywhere else so cloud admins don't hit a guaranteed 403/404.
+ ...(isTestDataSurfaceEnabled()
+ ? [{ label: "Test Data", href: "/admin/test-data", Icon: Database01Icon }]
+ : []),
+ ];
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/useAdminSidebar.ts b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/useAdminSidebar.ts
index 5d5c5de147..4e7a08c1bd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/useAdminSidebar.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/components/AdminSidebar/useAdminSidebar.ts
@@ -1,11 +1,11 @@
import { matchesRoute } from "@/lib/utils";
import { usePathname } from "next/navigation";
-import { adminNavItems } from "./helpers";
+import { getAdminNavItems } from "./helpers";
export function useAdminSidebar() {
const pathname = usePathname();
- const items = adminNavItems.map((item) => ({
+ const items = getAdminNavItems().map((item) => ({
...item,
isActive: matchesRoute(pathname, item.href),
}));
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/__tests__/page.test.tsx
new file mode 100644
index 0000000000..08ea09b38b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/__tests__/page.test.tsx
@@ -0,0 +1,76 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import * as testDataHelpers from "../helpers";
+
+// The shared next/navigation mock has no notFound(); re-declare it here with
+// the same router surface plus the export this page depends on.
+const notFoundMock = vi.hoisted(() => vi.fn());
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ push: vi.fn(),
+ replace: vi.fn(),
+ prefetch: vi.fn(),
+ back: vi.fn(),
+ forward: vi.fn(),
+ refresh: vi.fn(),
+ }),
+ usePathname: () => "/admin/test-data",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+ notFound: () => {
+ notFoundMock();
+ throw new Error("NEXT_NOT_FOUND");
+ },
+}));
+
+// Bypass server-side admin auth wrapper.
+vi.mock("@/lib/withRoleAccess", () => ({
+ withRoleAccess: () =>
+ Promise.resolve((Component: React.ComponentType) =>
+ Promise.resolve(Component),
+ ),
+}));
+
+// The button owns the mutation hook; stub it so the page test stays focused on
+// the dashboard layout.
+vi.mock("../components/GenerateTestDataButton", () => ({
+ GenerateTestDataButton: () => (
+ <button type="button">Generate Test Data</button>
+ ),
+}));
+
+import TestDataDashboardPage from "../page";
+
+describe("TestDataDashboardPage", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ notFoundMock.mockClear();
+ });
+
+ it("404s outside a local stack instead of rendering a dead-end page", async () => {
+ vi.spyOn(testDataHelpers, "isTestDataSurfaceEnabled").mockReturnValue(
+ false,
+ );
+
+ await expect(TestDataDashboardPage()).rejects.toThrow("NEXT_NOT_FOUND");
+ expect(notFoundMock).toHaveBeenCalled();
+ });
+
+ it("renders the dashboard heading and script descriptions", async () => {
+ render(await TestDataDashboardPage());
+
+ expect(screen.getByText("Test Data Generation")).toBeDefined();
+ expect(screen.getByText("Available Script Types:")).toBeDefined();
+ expect(screen.getByText(/E2E Test Data:/i)).toBeDefined();
+ expect(screen.getByText(/Full Test Data:/i)).toBeDefined();
+ expect(screen.getByText("What data is created?")).toBeDefined();
+ });
+
+ it("renders the generate action", async () => {
+ render(await TestDataDashboardPage());
+
+ expect(
+ screen.getByRole("button", { name: "Generate Test Data" }),
+ ).toBeDefined();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/GenerateTestDataButton.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/GenerateTestDataButton.tsx
new file mode 100644
index 0000000000..5a86a7e302
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/GenerateTestDataButton.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { Select, SelectOption } from "@/components/atoms/Select/Select";
+import { Text } from "@/components/atoms/Text/Text";
+import { Alert } from "@/components/molecules/Alert/Alert";
+import type { TestDataScriptType } from "@/app/api/__generated__/models/testDataScriptType";
+import { useGenerateTestDataButton } from "./useGenerateTestDataButton";
+
+const scriptTypeOptions: SelectOption[] = [
+ {
+ value: "e2e",
+ label:
+ "E2E Test Data - up to 15 users with graphs, agents, and store submissions",
+ },
+ {
+ value: "full",
+ label: "Full Test Data - 100+ users with comprehensive data (takes longer)",
+ },
+];
+
+export function GenerateTestDataButton() {
+ const {
+ isDialogOpen,
+ scriptType,
+ setScriptType,
+ result,
+ isPending,
+ openDialog,
+ closeDialog,
+ generate,
+ } = useGenerateTestDataButton();
+
+ return (
+ <>
+ <Button size="large" variant="primary" onClick={openDialog}>
+ Generate Test Data
+ </Button>
+
+ <Dialog
+ title="Generate Test Data"
+ controlled={{
+ isOpen: isDialogOpen,
+ set: (open) => {
+ if (!open) closeDialog();
+ },
+ }}
+ styling={{ maxWidth: "32rem" }}
+ >
+ <Dialog.Content>
+ <Text variant="body" className="pb-4 text-neutral-600">
+ This will populate the database with sample test data including
+ users, agents, graphs, store listings, and more.
+ </Text>
+
+ <div className="grid gap-4 py-4">
+ <Select
+ label="Script Type"
+ id="scriptType"
+ value={scriptType}
+ onValueChange={(value) =>
+ setScriptType(value as TestDataScriptType)
+ }
+ disabled={isPending}
+ options={scriptTypeOptions}
+ />
+
+ <Alert variant="warning">
+ <Text variant="small" as="span">
+ <Text variant="small-medium" as="span">
+ Warning:
+ </Text>{" "}
+ This will add significant data to your database. This endpoint
+ is only available in local environments.
+ </Text>
+ </Alert>
+
+ {result && (
+ <Alert
+ role="status"
+ variant={result.success ? "default" : "error"}
+ >
+ <Text variant="small-medium">{result.message}</Text>
+ {result.details && (
+ <ul className="mt-2 list-inside list-disc">
+ {Object.entries(result.details).map(([key, value]) => (
+ <li key={key}>
+ <Text variant="small" as="span">
+ {key.replace(/_/g, " ")}: {String(value)}
+ </Text>
+ </li>
+ ))}
+ </ul>
+ )}
+ </Alert>
+ )}
+ </div>
+
+ <Dialog.Footer>
+ <Button
+ variant="outline"
+ onClick={closeDialog}
+ disabled={isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ onClick={generate}
+ disabled={isPending}
+ loading={isPending}
+ >
+ {isPending ? "Generating..." : "Generate Test Data"}
+ </Button>
+ </Dialog.Footer>
+ </Dialog.Content>
+ </Dialog>
+ </>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/__tests__/GenerateTestDataButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/__tests__/GenerateTestDataButton.test.tsx
new file mode 100644
index 0000000000..993a80fb2b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/__tests__/GenerateTestDataButton.test.tsx
@@ -0,0 +1,94 @@
+import { render, screen, fireEvent } from "@/tests/integrations/test-utils";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { GenerateTestDataResponse } from "@/app/api/__generated__/models/generateTestDataResponse";
+
+const hookState = vi.hoisted(() => ({
+ isDialogOpen: false,
+ scriptType: "e2e" as const,
+ result: null as GenerateTestDataResponse | null,
+ isPending: false,
+ setScriptType: vi.fn(),
+ openDialog: vi.fn(),
+ closeDialog: vi.fn(),
+ generate: vi.fn(),
+}));
+
+vi.mock("../useGenerateTestDataButton", () => ({
+ useGenerateTestDataButton: () => hookState,
+}));
+
+import { GenerateTestDataButton } from "../GenerateTestDataButton";
+
+beforeEach(() => {
+ hookState.isDialogOpen = false;
+ hookState.result = null;
+ hookState.isPending = false;
+ hookState.setScriptType.mockReset();
+ hookState.openDialog.mockReset();
+ hookState.closeDialog.mockReset();
+ hookState.generate.mockReset();
+});
+
+describe("GenerateTestDataButton", () => {
+ test("renders the trigger button and opens the dialog on click", () => {
+ render(<GenerateTestDataButton />);
+ const trigger = screen.getByRole("button", { name: "Generate Test Data" });
+ fireEvent.click(trigger);
+ expect(hookState.openDialog).toHaveBeenCalledTimes(1);
+ });
+
+ test("shows the script selector and warning when the dialog is open", () => {
+ hookState.isDialogOpen = true;
+ render(<GenerateTestDataButton />);
+ expect(screen.getByText("Script Type")).toBeDefined();
+ expect(
+ screen.getByText(/only available in local environments/i),
+ ).toBeDefined();
+ });
+
+ test("invokes generate from the dialog action", () => {
+ hookState.isDialogOpen = true;
+ render(<GenerateTestDataButton />);
+ const actions = screen.getAllByRole("button", {
+ name: "Generate Test Data",
+ });
+ fireEvent.click(actions[actions.length - 1]);
+ expect(hookState.generate).toHaveBeenCalledTimes(1);
+ });
+
+ test("shows a loading label and disables actions while pending", () => {
+ hookState.isDialogOpen = true;
+ hookState.isPending = true;
+ render(<GenerateTestDataButton />);
+ const generating = screen.getByRole("button", { name: "Generating..." });
+ expect(generating).toBeDefined();
+ expect((generating as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ test("renders a successful result with details", () => {
+ hookState.isDialogOpen = true;
+ hookState.result = {
+ success: true,
+ message: "E2E test data generated successfully",
+ details: { users_created: 7 },
+ };
+ render(<GenerateTestDataButton />);
+ expect(
+ screen.getByText("E2E test data generated successfully"),
+ ).toBeDefined();
+ expect(screen.getByText(/users created/i)).toBeDefined();
+ });
+
+ test("renders a failed result message", () => {
+ hookState.isDialogOpen = true;
+ hookState.result = {
+ success: false,
+ message: "Failed to generate test data: local environments only",
+ };
+ render(<GenerateTestDataButton />);
+ expect(
+ screen.getByText("Failed to generate test data: local environments only"),
+ ).toBeDefined();
+ expect(screen.queryByText(/users created/i)).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/helpers.ts
new file mode 100644
index 0000000000..c91245054c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/helpers.ts
@@ -0,0 +1,6 @@
+const FALLBACK_ERROR_DETAIL = "Failed to generate test data. Please try again.";
+
+export function getErrorDetail(error: unknown) {
+ if (error instanceof Error && error.message) return error.message;
+ return FALLBACK_ERROR_DETAIL;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/useGenerateTestDataButton.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/useGenerateTestDataButton.test.ts
new file mode 100644
index 0000000000..a5ebb0eb7a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/useGenerateTestDataButton.test.ts
@@ -0,0 +1,139 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+type MutationCallbacks = {
+ onSuccess: (response: { status: number; data: unknown }) => void;
+ onError: (error: unknown) => void;
+};
+
+const hoisted = vi.hoisted(() => ({
+ toastSpy: vi.fn(),
+ mutateSpy: vi.fn(),
+ captured: { mutation: undefined as MutationCallbacks | undefined },
+}));
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: hoisted.toastSpy }),
+ toast: hoisted.toastSpy,
+}));
+
+vi.mock("@/app/api/__generated__/endpoints/admin/admin", () => ({
+ usePostV2GenerateTestData: (opts: { mutation: MutationCallbacks }) => {
+ hoisted.captured.mutation = opts.mutation;
+ return { mutate: hoisted.mutateSpy, isPending: false };
+ },
+}));
+
+import { useGenerateTestDataButton } from "./useGenerateTestDataButton";
+
+beforeEach(() => {
+ hoisted.toastSpy.mockReset();
+ hoisted.mutateSpy.mockReset();
+ hoisted.captured.mutation = undefined;
+});
+
+describe("useGenerateTestDataButton", () => {
+ test("submits the default e2e script type", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() => result.current.generate());
+ expect(hoisted.mutateSpy).toHaveBeenCalledWith({
+ data: { script_type: "e2e" },
+ });
+ });
+
+ test("submits the selected full script type", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() => result.current.setScriptType("full"));
+ act(() => result.current.generate());
+ expect(hoisted.mutateSpy).toHaveBeenCalledWith({
+ data: { script_type: "full" },
+ });
+ });
+
+ test("stores the result and toasts success on a successful response", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() =>
+ hoisted.captured.mutation?.onSuccess({
+ status: 200,
+ data: { success: true, message: "done", details: { users_created: 7 } },
+ }),
+ );
+ expect(result.current.result?.message).toBe("done");
+ expect(hoisted.toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Success" }),
+ );
+ });
+
+ test("toasts a destructive error when the API reports failure", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() =>
+ hoisted.captured.mutation?.onSuccess({
+ status: 200,
+ data: { success: false, message: "nope" },
+ }),
+ );
+ expect(result.current.result?.success).toBe(false);
+ expect(hoisted.toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Error", variant: "destructive" }),
+ );
+ });
+
+ test("ignores non-200 success responses", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() =>
+ hoisted.captured.mutation?.onSuccess({
+ status: 403,
+ data: { detail: "forbidden" },
+ }),
+ );
+ expect(result.current.result).toBeNull();
+ expect(hoisted.toastSpy).not.toHaveBeenCalled();
+ });
+
+ test("surfaces the error detail when the mutation throws", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() => hoisted.captured.mutation?.onError(new Error("network blip")));
+ expect(result.current.result?.message).toContain("network blip");
+ expect(hoisted.toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Error", variant: "destructive" }),
+ );
+ });
+
+ test("puts the server detail in the toast instead of a generic retry hint", () => {
+ renderHook(() => useGenerateTestDataButton());
+ act(() =>
+ hoisted.captured.mutation?.onError(
+ new Error(
+ "Test data generation is only available in local environments.",
+ ),
+ ),
+ );
+ expect(hoisted.toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description:
+ "Test data generation is only available in local environments.",
+ }),
+ );
+ });
+
+ test("falls back to a generic message when the error carries no detail", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() => hoisted.captured.mutation?.onError({}));
+ expect(result.current.result?.message).toContain(
+ "Failed to generate test data. Please try again.",
+ );
+ });
+
+ test("openDialog clears any prior result and opens the dialog", () => {
+ const { result } = renderHook(() => useGenerateTestDataButton());
+ act(() =>
+ hoisted.captured.mutation?.onSuccess({
+ status: 200,
+ data: { success: true, message: "done" },
+ }),
+ );
+ act(() => result.current.openDialog());
+ expect(result.current.isDialogOpen).toBe(true);
+ expect(result.current.result).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/useGenerateTestDataButton.ts b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/useGenerateTestDataButton.ts
new file mode 100644
index 0000000000..052256533a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/components/useGenerateTestDataButton.ts
@@ -0,0 +1,70 @@
+import { useState } from "react";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { usePostV2GenerateTestData } from "@/app/api/__generated__/endpoints/admin/admin";
+import type { GenerateTestDataResponse } from "@/app/api/__generated__/models/generateTestDataResponse";
+import type { TestDataScriptType } from "@/app/api/__generated__/models/testDataScriptType";
+import { getErrorDetail } from "./helpers";
+
+export function useGenerateTestDataButton() {
+ const { toast } = useToast();
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const [scriptType, setScriptType] = useState<TestDataScriptType>("e2e");
+ const [result, setResult] = useState<GenerateTestDataResponse | null>(null);
+
+ const { mutate, isPending } = usePostV2GenerateTestData({
+ mutation: {
+ onSuccess: (response) => {
+ // The mutation types response.data as a status-discriminated union;
+ // onSuccess only fires for 2xx, so narrow to the 200 body.
+ if (response.status !== 200) return;
+ const data = response.data;
+ setResult(data);
+ toast({
+ title: data.success ? "Success" : "Error",
+ description: data.message,
+ variant: data.success ? undefined : "destructive",
+ });
+ },
+ onError: (error) => {
+ // ApiError.message carries the backend's `detail` string, so a 403
+ // surfaces "only available in local environments" rather than a
+ // misleading "please try again".
+ const detail = getErrorDetail(error);
+ setResult({
+ success: false,
+ message: `Failed to generate test data: ${detail}`,
+ });
+ toast({
+ title: "Error",
+ description: detail,
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ function openDialog() {
+ setResult(null);
+ setIsDialogOpen(true);
+ }
+
+ function closeDialog() {
+ setIsDialogOpen(false);
+ }
+
+ function generate() {
+ setResult(null);
+ mutate({ data: { script_type: scriptType } });
+ }
+
+ return {
+ isDialogOpen,
+ scriptType,
+ setScriptType,
+ result,
+ isPending,
+ openDialog,
+ closeDialog,
+ generate,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/helpers.test.ts
new file mode 100644
index 0000000000..0bae1dd5b0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/helpers.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, describe, expect, test, vi } from "vitest";
+import { AppEnv, environment } from "@/services/environment";
+import { isTestDataSurfaceEnabled } from "./helpers";
+
+function stub(isLocal: boolean, appEnv: AppEnv) {
+ vi.spyOn(environment, "isLocal").mockReturnValue(isLocal);
+ vi.spyOn(environment, "getAppEnv").mockReturnValue(appEnv);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("isTestDataSurfaceEnabled", () => {
+ test("enabled only when both behave-as and app-env are local", () => {
+ stub(true, AppEnv.LOCAL);
+ expect(isTestDataSurfaceEnabled()).toBe(true);
+ });
+
+ test("disabled when app-env is not local even if behave-as is", () => {
+ // The backend only mounts the router on app_env LOCAL, so this combination
+ // would render a page whose endpoint 404s.
+ stub(true, AppEnv.DEV);
+ expect(isTestDataSurfaceEnabled()).toBe(false);
+ });
+
+ test("disabled when behave-as is cloud even if app-env is local", () => {
+ stub(false, AppEnv.LOCAL);
+ expect(isTestDataSurfaceEnabled()).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/helpers.ts
new file mode 100644
index 0000000000..c86ea3d172
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/helpers.ts
@@ -0,0 +1,9 @@
+import { AppEnv, environment } from "@/services/environment";
+
+// Mirror the backend exactly: the router is only mounted when app_env is
+// LOCAL (rest_api.py), and _guard_local_only additionally requires
+// behave_as LOCAL. Checking only one of the two would show a page whose
+// endpoint 404s or 403s.
+export function isTestDataSurfaceEnabled() {
+ return environment.isLocal() && environment.getAppEnv() === AppEnv.LOCAL;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/admin/test-data/page.tsx b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/page.tsx
new file mode 100644
index 0000000000..1840e79fe3
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/admin/test-data/page.tsx
@@ -0,0 +1,166 @@
+import { notFound } from "next/navigation";
+import { withRoleAccess } from "@/lib/withRoleAccess";
+import { GenerateTestDataButton } from "./components/GenerateTestDataButton";
+import { Text } from "@/components/atoms/Text/Text";
+import { isTestDataSurfaceEnabled } from "./helpers";
+
+function TestDataDashboard() {
+ return (
+ <div className="mx-auto p-6">
+ <div className="flex flex-col gap-6">
+ <div className="flex items-center justify-between">
+ <div>
+ <Text variant="h1" className="text-3xl">
+ Test Data Generation
+ </Text>
+ <Text variant="body" className="text-gray-500">
+ Generate sample data for testing and development
+ </Text>
+ </div>
+ </div>
+
+ <div className="rounded-lg border bg-white p-6 shadow-sm">
+ <Text variant="h2" className="mb-4 text-xl">
+ Generate Test Data
+ </Text>
+ <Text variant="body" className="mb-6 text-gray-600">
+ Use this tool to populate the database with sample test data. This
+ is useful for development and testing purposes.
+ </Text>
+
+ <div className="mb-6">
+ <Text variant="body-medium" className="mb-2">
+ Available Script Types:
+ </Text>
+ <ul className="list-inside list-disc space-y-2 text-gray-600">
+ <li>
+ <Text variant="body" as="span">
+ <Text variant="body-medium" as="span">
+ E2E Test Data:
+ </Text>{" "}
+ Creates up to 15 test users with graphs, library agents,
+ presets, store submissions, and API keys. Uses API functions
+ for better compatibility.
+ </Text>
+ </li>
+ <li>
+ <Text variant="body" as="span">
+ <Text variant="body-medium" as="span">
+ Full Test Data:
+ </Text>{" "}
+ Creates 100+ users with comprehensive test data including
+ agent blocks, nodes, executions, analytics, and more. Takes
+ longer to complete.
+ </Text>
+ </li>
+ </ul>
+ </div>
+
+ <GenerateTestDataButton />
+ </div>
+
+ <div className="rounded-lg border bg-gray-50 p-6">
+ <Text variant="body-medium" className="mb-2 text-gray-700">
+ What data is created?
+ </Text>
+ <div className="grid gap-4 text-sm text-gray-600 md:grid-cols-2">
+ <div>
+ <Text variant="body-medium">E2E Script:</Text>
+ <ul className="mt-1 list-inside list-disc">
+ <li>
+ <Text variant="small" as="span">
+ Up to 15 test users
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ 15 graphs per user
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Library agents
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Agent presets
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Store submissions
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ API keys
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Creator profiles
+ </Text>
+ </li>
+ </ul>
+ </div>
+ <div>
+ <Text variant="body-medium">Full Script:</Text>
+ <ul className="mt-1 list-inside list-disc">
+ <li>
+ <Text variant="small" as="span">
+ 100 users
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ 100 agent blocks
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Multiple graphs per user
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Agent nodes and links
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Graph executions
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Store listings and reviews
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Analytics data
+ </Text>
+ </li>
+ <li>
+ <Text variant="small" as="span">
+ Credit transactions
+ </Text>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default async function TestDataDashboardPage() {
+ // The backend route only exists on local stacks, so the page 404s elsewhere
+ // instead of rendering a button that can only ever return 403/404.
+ if (!isTestDataSurfaceEnabled()) notFound();
+ const withAdminAccess = await withRoleAccess(["admin"]);
+ const ProtectedTestDataDashboard = await withAdminAccess(TestDataDashboard);
+ return <ProtectedTestDataDashboard />;
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 222c3df55f..5f6854e668 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1220,6 +1220,48 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/admin/generate-test-data": {
+ "post": {
+ "tags": ["v2", "admin", "test-data"],
+ "summary": "Generate Test Data",
+ "description": "Generate test data for the platform.\n\nThis endpoint runs the test data generation scripts to populate the database\nwith sample users, agents, graphs, executions, store listings, and more.\n\nAvailable script types:\n- `e2e`: Creates a set of test users with graphs, library agents, presets,\n and store submissions. Uses API functions for better compatibility.\n- `full`: Creates 100+ users with comprehensive test data using direct Prisma\n calls. Generates more data but may take longer.\n\n**Warning**: This will add significant data to your database. Use with caution.\n**Note**: This endpoint is only available in local environments; requests from\nany shared/cloud environment are rejected and alerted on.",
+ "operationId": "postV2Generate test data",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GenerateTestDataRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GenerateTestDataResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/admin/impersonation/notify": {
"post": {
"tags": ["v2", "admin", "admin", "impersonation"],
@@ -20029,6 +20071,34 @@
"required": ["uuid", "forgotten"],
"title": "ForgetFactResponse"
},
+ "GenerateTestDataRequest": {
+ "properties": {
+ "script_type": {
+ "$ref": "#/components/schemas/TestDataScriptType",
+ "default": "e2e"
+ }
+ },
+ "type": "object",
+ "title": "GenerateTestDataRequest",
+ "description": "Request model for test data generation."
+ },
+ "GenerateTestDataResponse": {
+ "properties": {
+ "success": { "type": "boolean", "title": "Success" },
+ "message": { "type": "string", "title": "Message" },
+ "details": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Details"
+ }
+ },
+ "type": "object",
+ "required": ["success", "message"],
+ "title": "GenerateTestDataResponse",
+ "description": "Response model for test data generation."
+ },
"GlobalSearchResponse": {
"properties": {
"agents": {
@@ -27133,6 +27203,12 @@
],
"title": "TeamResponse"
},
+ "TestDataScriptType": {
+ "type": "string",
+ "enum": ["full", "e2e"],
+ "title": "TestDataScriptType",
+ "description": "Available test data generation scripts."
+ },
"TimezoneResponse": {
"properties": {
"timezone": {