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): Create User Profile in app layer instead of DB trigger (#13471)
Reinier van der Leerf91a7cf0f460
diff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.pyindex 510dfb1762..6c296a1e5e 100644--- a/autogpt_platform/backend/backend/api/features/store/db.py+++ b/autogpt_platform/backend/backend/api/features/store/db.py@@ -1164,9 +1164,34 @@ async def update_profile(where={"userId": user_id})if not existing_profile:- raise store_exceptions.ProfileNotFoundError(- f"Profile not found for user {user_id}. This should not be possible."+ # No Profile yet (e.g. a user whose auto-creation never ran). This+ # endpoint is the user's self-service path to a marketplace+ # profile, so create one from the submitted data instead of+ # failing — otherwise the user is left with no way to publish.+ logger.info(+ f"No profile for user {user_id}; creating one from submitted data")+ try:+ created_profile = await prisma.models.Profile.prisma().create(+ data=prisma.types.ProfileCreateInput(+ userId=user_id,+ name=profile.name,+ username=username,+ description=profile.description,+ links=profile.links,+ avatarUrl=profile.avatar_url,+ )+ )+ return store_model.ProfileDetails.from_db(created_profile)+ except prisma.errors.UniqueViolationError:+ # A concurrent request (or get_or_create_user) created the+ # Profile first. Re-fetch and fall through to update it with the+ # submitted data rather than failing the save.+ existing_profile = await prisma.models.Profile.prisma().find_first(+ where={"userId": user_id}+ )+ if not existing_profile:+ raise# Verify that the user is authorized to update this profileif existing_profile.userId != user_id:diff --git a/autogpt_platform/backend/backend/api/features/store/db_test.py b/autogpt_platform/backend/backend/api/features/store/db_test.pyindex a232270fc2..0d2233c9a9 100644--- a/autogpt_platform/backend/backend/api/features/store/db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py@@ -317,6 +317,100 @@ async def test_update_profile(mocker):mock_profile_db.return_value.update.assert_called_once()[email protected](loop_scope="session")+async def test_update_profile_creates_when_missing(mocker):+ """When a user has no Profile yet, update_profile creates one from the+ submitted data instead of raising — this is the user's self-service+ recovery path."""+ created_profile = prisma.models.Profile(+ id="new-profile-id",+ name="New Creator",+ username="newcreator",+ userId="user-id",+ description="Fresh start",+ links=[],+ avatarUrl=None,+ isFeatured=False,+ createdAt=datetime.now(),+ updatedAt=datetime.now(),+ )++ mock_profile_db = mocker.patch("prisma.models.Profile.prisma")+ mock_profile_db.return_value.find_first = AsyncMock(return_value=None)+ mock_profile_db.return_value.create = AsyncMock(return_value=created_profile)+ mock_profile_db.return_value.update = AsyncMock()++ profile = Profile(+ name="New Creator",+ username="newcreator",+ description="Fresh start",+ links=[],+ avatar_url=None,+ )++ result = await db.update_profile("user-id", profile)++ assert result.username == "newcreator"+ assert result.name == "New Creator"+ mock_profile_db.return_value.create.assert_called_once()+ mock_profile_db.return_value.update.assert_not_called()++[email protected](loop_scope="session")+async def test_update_profile_tolerates_create_race(mocker):+ """If a Profile is created concurrently between the existence check and our+ create(), update_profile re-fetches and updates it rather than failing."""+ raced_profile = prisma.models.Profile(+ id="raced-id",+ name="Old Name",+ username="raced",+ userId="user-id",+ description="Old",+ links=[],+ avatarUrl=None,+ isFeatured=False,+ createdAt=datetime.now(),+ updatedAt=datetime.now(),+ )+ updated_profile = prisma.models.Profile(+ id="raced-id",+ name="New Name",+ username="raced",+ userId="user-id",+ description="New desc",+ links=[],+ avatarUrl=None,+ isFeatured=False,+ createdAt=datetime.now(),+ updatedAt=datetime.now(),+ )++ mock_profile_db = mocker.patch("prisma.models.Profile.prisma")+ # First existence check: no profile → enter the create branch. The create+ # then loses the race (UniqueViolationError), so we re-fetch and find it.+ mock_profile_db.return_value.find_first = AsyncMock(+ side_effect=[None, raced_profile]+ )+ mock_profile_db.return_value.create = AsyncMock(+ side_effect=prisma.errors.UniqueViolationError({})+ )+ mock_profile_db.return_value.update = AsyncMock(return_value=updated_profile)++ profile = Profile(+ name="New Name",+ username="raced",+ description="New desc",+ links=[],+ avatar_url=None,+ )++ result = await db.update_profile("user-id", profile)++ assert result.name == "New Name"+ mock_profile_db.return_value.create.assert_called_once()+ mock_profile_db.return_value.update.assert_called_once()++@pytest.mark.asyncio(loop_scope="session")async def test_get_user_profile(mocker):# Mock datadiff --git a/autogpt_platform/backend/backend/copilot/tools/_test_data.py b/autogpt_platform/backend/backend/copilot/tools/_test_data.pyindex 9b39107db6..347f8189c8 100644--- a/autogpt_platform/backend/backend/copilot/tools/_test_data.py+++ b/autogpt_platform/backend/backend/copilot/tools/_test_data.py@@ -105,14 +105,24 @@ async def setup_test_data(server):# 1b. Create a profile with username for the user (required for store agent lookup)username = user.email.split("@")[0]- await prisma.profile.create(- data=ProfileCreateInput(- userId=user.id,- username=username,- name=f"Test User {username}",- description="Test user profile",- links=[], # Required field - empty array for test profiles- )+ await prisma.profile.upsert(+ where={"userId": user.id},+ data={+ # get_or_create_user auto-creates a default profile; tests need+ # this specific username for store agent lookups.+ "create": ProfileCreateInput(+ userId=user.id,+ username=username,+ name=f"Test User {username}",+ description="Test user profile",+ links=[],+ ),+ "update": {+ "username": username,+ "name": f"Test User {username}",+ "description": "Test user profile",+ },+ },)# 2. Create a test graph with agent input -> agent output@@ -231,14 +241,24 @@ async def setup_llm_test_data(server):# 1b. Create a profile with username for the user (required for store agent lookup)username = user.email.split("@")[0]- await prisma.profile.create(- data=ProfileCreateInput(- userId=user.id,- username=username,- name=f"Test User {username}",- description="Test user profile for LLM tests",- links=[], # Required field - empty array for test profiles- )+ await prisma.profile.upsert(+ where={"userId": user.id},+ data={+ # get_or_create_user auto-creates a default profile; tests need+ # this specific username for store agent lookups.+ "create": ProfileCreateInput(+ userId=user.id,+ username=username,+ name=f"Test User {username}",+ description="Test user profile for LLM tests",+ links=[],+ ),+ "update": {+ "username": username,+ "name": f"Test User {username}",+ "description": "Test user profile for LLM tests",+ },+ },)# 2. Create test OpenAI credentials for the user@@ -394,14 +414,24 @@ async def setup_firecrawl_test_data(server):# 1b. Create a profile with username for the user (required for store agent lookup)username = user.email.split("@")[0]- await prisma.profile.create(- data=ProfileCreateInput(- userId=user.id,- username=username,- name=f"Test User {username}",- description="Test user profile for Firecrawl tests",- links=[], # Required field - empty array for test profiles- )+ await prisma.profile.upsert(+ where={"userId": user.id},+ data={+ # get_or_create_user auto-creates a default profile; tests need+ # this specific username for store agent lookups.+ "create": ProfileCreateInput(+ userId=user.id,+ username=username,+ name=f"Test User {username}",+ description="Test user profile for Firecrawl tests",+ links=[],+ ),+ "update": {+ "username": username,+ "name": f"Test User {username}",+ "description": "Test user profile for Firecrawl tests",+ },+ },)# NOTE: We deliberately do NOT create Firecrawl credentials for this userdiff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex 6a67af3d87..706fc9ad4e 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -3,6 +3,8 @@ import base64import hashlibimport hmacimport logging+import random+import uuidfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Optional, castfrom urllib.parse import quote_plus@@ -10,8 +12,14 @@ from urllib.parse import quote_plusfrom autogpt_libs.auth.models import DEFAULT_USER_IDfrom fastapi import HTTPExceptionfrom prisma.enums import NotificationType+from prisma.errors import UniqueViolationErrorfrom prisma.models import User as PrismaUser-from prisma.types import JsonFilter, UserCreateInput, UserUpdateInput+from prisma.types import (+ JsonFilter,+ ProfileCreateInput,+ UserCreateInput,+ UserUpdateInput,+)from backend.data.db import prismafrom backend.data.model import User, UserIntegrations, UserMetadata@@ -53,11 +61,111 @@ async def get_or_create_user(user_data: dict) -> User:))+ # Ensure every user has a marketplace Profile (required to publish+ # agents). Best-effort: a failure must not block user resolution — the+ # user self-heals on their next request or via the profile settings page.+ try:+ await _ensure_user_profile(user.id, user.email)+ except Exception:+ logger.warning(+ "Failed to ensure marketplace profile for user %s",+ user.id,+ exc_info=True,+ )+return User.from_db(user)except Exception as e:raise DatabaseError(f"Failed to get or create user {user_data}: {e}") from e+# Word lists mirror the legacy generate_username() SQL function so that app-+# and DB-generated handles look consistent.+_PROFILE_USERNAME_ADJECTIVES = (+ "happy",+ "clever",+ "swift",+ "bright",+ "wise",+ "funny",+ "cool",+ "awesome",+ "amazing",+ "fantastic",+ "wonderful",+)+_PROFILE_USERNAME_ANIMALS = (+ "fox",+ "wolf",+ "bear",+ "eagle",+ "owl",+ "tiger",+ "lion",+ "elephant",+ "giraffe",+ "zebra",+)+++async def _ensure_user_profile(user_id: str, email: Optional[str]) -> None:+ """Create a default marketplace Profile for *user_id* if none exists.++ Idempotent and race-safe. A UniqueViolationError has two possible sources:+ a concurrent request that already created this user's Profile (done), or a+ collision on the unique username with *another* user (retry with a fresh+ handle — otherwise the user would be left without a Profile).+ """+ if await prisma.profile.find_unique(where={"userId": user_id}):+ return++ name = (email or "").split("@", 1)[0] or "user"+ for _ in range(3):+ try:+ await prisma.profile.create(+ data=ProfileCreateInput(+ userId=user_id,+ name=name,+ username=await _generate_profile_username(),+ description="I'm new here",+ links=[],+ avatarUrl="",+ )+ )+ return+ except UniqueViolationError:+ if await prisma.profile.find_unique(where={"userId": user_id}):+ # Another in-flight request (or the legacy auth.users trigger)+ # created this user's Profile — nothing to do.+ logger.debug(+ "Profile for user %s already created concurrently", user_id+ )+ return+ # The generated username collided with another user — loop and+ # retry with a fresh handle.+ logger.warning(+ "Failed to create a unique profile handle for user %s after retries",+ user_id,+ )+++async def _generate_profile_username() -> str:+ """Generate a human-friendly profile handle, avoiding obvious collisions.++ The unique constraint on Profile.username is the real guarantee; this+ pre-check just avoids retrying a create in the common case. Falls back to a+ UUID-based handle if we can't find a free friendly name.+ """+ for _ in range(10):+ candidate = (+ f"{random.choice(_PROFILE_USERNAME_ADJECTIVES)}-"+ f"{random.choice(_PROFILE_USERNAME_ANIMALS)}-"+ f"{random.randint(10000, 99999)}"+ )+ if not await prisma.profile.find_unique(where={"username": candidate}):+ return candidate+ return f"user-{uuid.uuid4().hex[:12]}"++@cache_user_lookupasync def get_user_by_id(user_id: str) -> User:user = await prisma.user.find_unique(where={"id": user_id})diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.pyindex b21bbad5f6..e805fb1a64 100644--- a/autogpt_platform/backend/backend/data/user_test.py+++ b/autogpt_platform/backend/backend/data/user_test.py@@ -3,6 +3,7 @@import asynciofrom unittest.mock import AsyncMock, MagicMock, patch+import prisma.errorsimport pytestfrom backend.data import user as user_module@@ -146,3 +147,104 @@ class TestUpdateUserTimezone:assert not user_module._background_tasks & set(spawned)warn_mock.assert_called_once()assert isinstance(warn_mock.call_args.kwargs["exc_info"], RuntimeError)+++class TestGetOrCreateUserProfile:+ """get_or_create_user must guarantee a marketplace Profile exists, since+ the auth.users trigger that used to do this is unreliable."""++ @pytest.mark.asyncio+ async def test_creates_profile_when_missing(self):+ user_module.get_or_create_user.cache_clear()+ db_user = MagicMock(id="user-new", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(user_module.User, "from_db", return_value=MagicMock()),+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)+ # No existing profile, and the generated username is free.+ mock_prisma.profile.find_unique = AsyncMock(return_value=None)+ mock_prisma.profile.create = AsyncMock()++ await user_module.get_or_create_user(+ {"sub": "user-new", "email": "[email protected]"}+ )++ mock_prisma.profile.create.assert_awaited_once()+ created = mock_prisma.profile.create.await_args.kwargs["data"]+ assert created["userId"] == "user-new"+ # name defaults to the email local-part+ assert created["name"] == "alice"+ assert created["username"]++ @pytest.mark.asyncio+ async def test_does_not_create_profile_when_one_exists(self):+ user_module.get_or_create_user.cache_clear()+ db_user = MagicMock(id="user-has", email="[email protected]", name="Bob")++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(user_module.User, "from_db", return_value=MagicMock()),+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)+ mock_prisma.profile.find_unique = AsyncMock(return_value=MagicMock())+ mock_prisma.profile.create = AsyncMock()++ await user_module.get_or_create_user(+ {"sub": "user-has", "email": "[email protected]"}+ )++ mock_prisma.profile.create.assert_not_called()++ @pytest.mark.asyncio+ async def test_profile_creation_failure_does_not_block_user(self):+ """Profile creation is best-effort: a failure is logged but the user+ is still resolved so login/auth isn't broken."""+ user_module.get_or_create_user.cache_clear()+ db_user = MagicMock(id="user-err", email="[email protected]", name=None)+ sentinel_user = MagicMock()++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(user_module.User, "from_db", return_value=sentinel_user),+ patch.object(user_module.logger, "warning") as warn_mock,+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)+ mock_prisma.profile.find_unique = AsyncMock(return_value=None)+ mock_prisma.profile.create = AsyncMock(+ side_effect=RuntimeError("db hiccup")+ )++ result = await user_module.get_or_create_user(+ {"sub": "user-err", "email": "[email protected]"}+ )++ assert result is sentinel_user+ warn_mock.assert_called_once()++ @pytest.mark.asyncio+ async def test_retries_profile_create_on_username_collision(self):+ """A UniqueViolationError from a username clash (not a userId race)+ must retry with a fresh handle so the user still gets a Profile."""+ user_module.get_or_create_user.cache_clear()+ db_user = MagicMock(id="user-clash", email="[email protected]", name=None)++ with (+ patch.object(user_module, "prisma") as mock_prisma,+ patch.object(user_module.User, "from_db", return_value=MagicMock()),+ ):+ mock_prisma.user.find_unique = AsyncMock(return_value=db_user)+ # userId never resolves to a Profile (so the clash is on username),+ # and generated usernames pre-check as free.+ mock_prisma.profile.find_unique = AsyncMock(return_value=None)+ # First create() collides on username, the retry succeeds.+ mock_prisma.profile.create = AsyncMock(+ side_effect=[prisma.errors.UniqueViolationError({}), None]+ )++ await user_module.get_or_create_user(+ {"sub": "user-clash", "email": "[email protected]"}+ )++ assert mock_prisma.profile.create.await_count == 2diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsxindex 8668090230..28dd1f8a88 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/__tests__/main.test.tsx@@ -1,3 +1,4 @@+import { http, HttpResponse } from "msw";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import {@@ -132,6 +133,30 @@ describe("SettingsProfilePage - data loading", () => {await screen.findByRole("heading", { name: /^profile$/i, level: 1 }),).toBeDefined();});++ test("renders an empty form (not an error) when the user has no profile yet", async () => {+ // A 404 from the profile endpoint means "no profile yet" — the page must+ // render the empty form so the user can create one, not an error card.+ server.use(+ http.get("http://localhost:3000/api/proxy/api/store/profile", () =>+ HttpResponse.json(+ { detail: "User does not have a profile yet" },+ { status: 404 },+ ),+ ),+ );++ render(<SettingsProfilePage />);++ const nameInput = (await screen.findByLabelText(+ /display name/i,+ )) as HTMLInputElement;+ expect(nameInput.value).toBe("");+ expect((screen.getByLabelText(/^handle$/i) as HTMLInputElement).value).toBe(+ "",+ );+ expect(screen.queryByText(/something went wrong/i)).toBeNull();+ });});describe("SettingsProfilePage - validation", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.tsindex 4d5619a69e..395b323a45 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/settings/profile/useProfilePage.ts@@ -11,7 +11,7 @@ import {} from "@/app/api/__generated__/endpoints/store/store";import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";import { toast } from "@/components/molecules/Toast/use-toast";-import { isLogoutInProgress } from "@/lib/autogpt-server-api/helpers";+import { ApiError, isLogoutInProgress } from "@/lib/autogpt-server-api/helpers";import { useSupabase } from "@/lib/supabase/hooks/useSupabase";import {@@ -48,6 +48,14 @@ export function useProfilePage() {},});+ // A 404 means the user simply has no marketplace profile yet — a valid state,+ // not an error. Treat it as "empty profile" so the page renders the form+ // (rather than an error card), letting the user create one on Save.+ const isProfileNotFound =+ profileQuery.isError &&+ profileQuery.error instanceof ApiError &&+ profileQuery.error.status === 404;+const [formState, setFormState] = useState<ProfileFormState>(EMPTY_FORM);// Pristine baseline for dirty detection + Discard. Held as state (not a// ref) so dirty re-derives when it changes; pinned to the current@@ -202,7 +210,7 @@ export function useProfilePage() {return {user,isLoading: profileQuery.isLoading,- isError: profileQuery.isError,+ isError: profileQuery.isError && !isProfileNotFound,error: profileQuery.error,refetch: profileQuery.refetch,formState,