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(platform): create a new user's profile on its first read instead of 404ing (#15426)
Nicholas Tindlebc671d371823
diff --git a/.github/scripts/test_e2e_seed_cache_contract.py b/.github/scripts/test_e2e_seed_cache_contract.pyindex 5a440d24a6..2319452b9f 100644--- a/.github/scripts/test_e2e_seed_cache_contract.py+++ b/.github/scripts/test_e2e_seed_cache_contract.py@@ -121,7 +121,7 @@ class E2ECoverageContractTests(unittest.TestCase):).read_text(encoding="utf-8")self.assertIn("--min-tests ${{ matrix.min_tests }}", workflow)self.assertEqual(_matrix_leg(workflow, "smoke")["min_tests"], "28")- self.assertEqual(_matrix_leg(workflow, "journeys")["min_tests"], "4")+ self.assertEqual(_matrix_leg(workflow, "journeys")["min_tests"], "5")# Smoke stays strict: no test.fail() known failures.self.assertEqual(_matrix_leg(workflow, "smoke")["known_failures"], "false")diff --git a/.github/workflows/platform-fullstack-ci.yml b/.github/workflows/platform-fullstack-ci.ymlindex 56c1ec64f8..a464b453d8 100644--- a/.github/workflows/platform-fullstack-ci.yml+++ b/.github/workflows/platform-fullstack-ci.yml@@ -201,7 +201,7 @@ jobs:# selfhost-journey asserts nothing hosted-only exists; it needs a# self-hosted stack (TODO in src/playwright/journeys/README.md).playwright_args: --project hosted- min_tests: 4+ min_tests: 5embeddings: false# Journeys sign up their own users and need no seeded data.seed: falsediff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.pyindex 69de921c10..e555730f5d 100644--- a/autogpt_platform/backend/backend/api/features/store/db.py+++ b/autogpt_platform/backend/backend/api/features/store/db.py@@ -19,6 +19,7 @@ from backend.data.graph import ()from backend.data.includes import AGENT_GRAPH_INCLUDEfrom backend.data.notifications import NotificationEventModel, VerdictData+from backend.data.profile import ensure_user_profilefrom backend.notifications.queue import queue_notification_asyncfrom backend.util.exceptions import DatabaseError, NotFoundError, PreconditionFailedfrom backend.util.settings import Settings@@ -1218,6 +1219,22 @@ async def get_user_profile(raise DatabaseError("Failed to get user profile") from e+async def get_or_create_user_profile(+ user_id: str,+) -> store_model.ProfileDetails | None:+ """The user's profile, creating their default one if they have none yet.++ A brand-new user's first page asks for it as soon as the session exists,+ which can be before account setup (``POST /auth/user``) has created it.+ None only for an id with no platform user, or if no free handle was found.+ """+ profile = await get_user_profile(user_id)+ if profile is not None:+ return profile+ await ensure_user_profile(user_id)+ return await get_user_profile(user_id)++async def update_profile(user_id: str, profile: store_model.Profile) -> store_model.ProfileDetails:diff --git a/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.py b/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.pynew file mode 100644index 0000000000..555e5ccdb8--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.py@@ -0,0 +1,293 @@+"""A new user's marketplace profile, read before account setup has made it.++Better Auth issues the session as soon as the identity exists, when the auth+hook has inserted only a bare ``User`` row. The Profile comes from account+setup (``POST /auth/user``), so the first page's ``GET /store/profile`` 404'd+whenever it beat setup, and for good if setup's best-effort insert failed.+The read now creates the default profile itself. These run on the real+database: the race is between real inserts on ``Profile.userId``'s unique index.+"""++import asyncio+import random+import uuid+from contextvars import ContextVar+from typing import Literal++import pytest+import pytest_asyncio+from prisma.actions import ProfileActions+from pydantic import BaseModel, ConfigDict++from backend.api.features.store import db as store_db+from backend.api.features.store import model as store_model+from backend.api.features.store.routes import get_profile+from backend.data import db+from backend.data import profile as profile_module+from backend.data.db import prisma+from backend.data.user import get_or_create_user_with_status+from backend.util.test import SpinTestServer++_STALL = 5.0+_SEEDS = 200++_Role = Literal["read", "setup", "save"]+_ROLES: tuple[_Role, ...] = ("read", "setup", "save")+++@pytest_asyncio.fixture(scope="module", loop_scope="session", autouse=True)+async def _fresh_connections(server: SpinTestServer):+ """Start on a fresh connection pool. These tests make inserts fail on+ purpose (the race's losing side), and a test earlier in the session can+ leave a pooled connection inside a transaction it never closed: one failure+ there aborts it for every later query, in this module and after it."""+ await db.disconnect()+ await db.connect()+ yield++[email protected](loop_scope="session")+async def test_a_profile_read_while_setup_creates_it_gets_the_one_profile(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):+ user_id, email = await _signed_up_user()++ # Hold account setup just before it inserts the profile.+ entered = asyncio.Event()+ release = asyncio.Event()+ create = ProfileActions.create++ async def hold_the_first_insert(self, *args, **kwargs):+ if not entered.is_set():+ entered.set()+ await release.wait()+ return await create(self, *args, **kwargs)++ monkeypatch.setattr(ProfileActions, "create", hold_the_first_insert)+ setup = asyncio.create_task(get_or_create_user_with_status(_claims(user_id, email)))+ try:+ await _wait_for(entered, "account setup to start inserting the profile")+ profile = await asyncio.wait_for(get_profile(user_id=user_id), timeout=_STALL)+ finally:+ release.set()+ await asyncio.wait_for(setup, timeout=_STALL)++ assert profile.name == email.split("@")[0]+ rows = await prisma.profile.find_many(where={"userId": user_id})+ assert [row.username for row in rows] == [profile.username]++[email protected](loop_scope="session")+async def test_a_profile_read_heals_an_account_whose_setup_could_not_create_it(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):+ user_id, email = await _signed_up_user()++ async def fail(self, *args, **kwargs):+ raise RuntimeError("injected: the profile insert failed")++ with monkeypatch.context() as patched:+ patched.setattr(ProfileActions, "create", fail)+ # Setup treats the profile as best-effort, so it still succeeds, and+ # its personal org means no later org-scoped request re-runs it.+ await get_or_create_user_with_status(_claims(user_id, email))+ assert await prisma.profile.find_unique(where={"userId": user_id}) is None++ profile = await get_profile(user_id=user_id)++ assert profile.name == email.split("@")[0]+ assert await prisma.profile.count(where={"userId": user_id}) == 1++[email protected](loop_scope="session")+async def test_first_page_profile_reads_never_404_under_random_interleavings(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):+ """Reads race account setup (whose profile insert may fail) and the user+ saving their profile, with random yields before every Profile query and+ handles that collide with another user's. Every read gets a profile, the+ user ends with exactly one, and a read never replaces what they saved."""+ _interleave_profile_queries(monkeypatch, await _a_taken_handle())+ run = uuid.uuid4().hex[:6]++ for seed in range(_SEEDS):+ user_id, email = await _signed_up_user()+ racers = _plan(seed)+ failures, seen = await _race(run, seed, user_id, email, racers)++ context = f"seed {seed}, racers {[racer.role for racer in racers]}"+ assert not failures, f"{context}: {failures}"+ rows = await prisma.profile.find_many(where={"userId": user_id})+ assert len(rows) == 1, f"{context}: {len(rows)} profiles"+ saved = {_saved_name(seed, i) for i, r in enumerate(racers) if r.role == "save"}+ default = email.split("@")[0]+ assert rows[0].name in (+ saved or {default}+ ), f"{context}: ended as {rows[0].name!r}"+ assert set(seen) <= saved | {default}, f"{context}: reads saw {seen}"+++_RACER: ContextVar["_Racer | None"] = ContextVar("first_load_racer", default=None)+++class _Racer(BaseModel):+ """One request of a new user's first page load, and what goes wrong for it."""++ model_config = ConfigDict(arbitrary_types_allowed=True)++ role: _Role+ jitter: random.Random+ setup_insert_fails: bool+ handle_taken: bool+++def _plan(seed: int) -> list[_Racer]:+ rng = random.Random(seed)+ roles: list[_Role] = [+ "read",+ *rng.choices(_ROLES, weights=[5, 3, 2], k=rng.randint(1, 4)),+ ]+ rng.shuffle(roles)+ return [+ _Racer(+ role=role,+ jitter=random.Random(rng.getrandbits(32)),+ setup_insert_fails=rng.random() < 0.3,+ handle_taken=rng.random() < 0.2,+ )+ for role in roles+ ]+++async def _race(+ run: str, seed: int, user_id: str, email: str, racers: list[_Racer]+) -> tuple[list[str], list[str]]:+ """Run *racers* at once; return what failed and the names the reads saw."""+ seen: list[str] = []++ async def act(index: int, racer: _Racer) -> None:+ _RACER.set(racer)+ await _yield_randomly()+ if racer.role == "read":+ seen.append((await get_profile(user_id=user_id)).name)+ elif racer.role == "setup":+ await get_or_create_user_with_status(_claims(user_id, email))+ else:+ await store_db.update_profile(user_id, _saved(run, seed, index))++ results = await asyncio.wait_for(+ asyncio.gather(+ *(act(i, racer) for i, racer in enumerate(racers)),+ return_exceptions=True,+ ),+ timeout=_STALL * 4,+ )+ failures = [+ f"{racer.role}: {result!r}"+ for racer, result in zip(racers, results)+ if result is not None+ ]+ return failures, seen+++def _saved(run: str, seed: int, index: int) -> store_model.Profile:+ return store_model.Profile(+ username=f"saved-{run}-{seed}-{index}",+ name=_saved_name(seed, index),+ description="Saved from the profile page",+ links=[],+ avatar_url=None,+ )+++def _saved_name(seed: int, index: int) -> str:+ return f"Saved {seed}-{index}"+++def _interleave_profile_queries(+ monkeypatch: pytest.MonkeyPatch, taken_handle: str+) -> None:+ """Yield a random number of times before every Profile query, fail account+ setup's insert when its racer says so, and offer an already-taken handle+ first when the racer says so."""+ find_unique = _after_yielding(ProfileActions.find_unique)+ monkeypatch.setattr(ProfileActions, "find_unique", find_unique)+ find_first = _after_yielding(ProfileActions.find_first)+ monkeypatch.setattr(ProfileActions, "find_first", find_first)+ monkeypatch.setattr(+ ProfileActions, "update", _after_yielding(ProfileActions.update)+ )+ create = ProfileActions.create++ async def insert_or_fail(self, *args, **kwargs):+ await _yield_randomly()+ racer = _RACER.get()+ if racer is not None and racer.role == "setup" and racer.setup_insert_fails:+ raise RuntimeError("injected: account setup's profile insert failed")+ return await create(self, *args, **kwargs)++ monkeypatch.setattr(ProfileActions, "create", insert_or_fail)+ generate = profile_module._generate_profile_username++ async def taken_handle_first() -> str:+ racer = _RACER.get()+ if racer is not None and racer.handle_taken:+ racer.handle_taken = False+ return taken_handle+ return await generate()++ monkeypatch.setattr(+ profile_module, "_generate_profile_username", taken_handle_first+ )+++def _after_yielding(query):+ async def yielding(self, *args, **kwargs):+ await _yield_randomly()+ return await query(self, *args, **kwargs)++ return yielding+++async def _yield_randomly() -> None:+ racer = _RACER.get()+ if racer is None:+ return+ for _ in range(racer.jitter.randint(0, 3)):+ await asyncio.sleep(0)+++async def _signed_up_user() -> tuple[str, str]:+ """A user as sign-up leaves them before account setup: a bare ``User`` row."""+ user_id = str(uuid.uuid4())+ email = f"first-load-{uuid.uuid4().hex[:8]}@example.com"+ await prisma.user.create(data={"id": user_id, "email": email})+ return user_id, email+++async def _a_taken_handle() -> str:+ """A handle another user's profile already holds."""+ squatter_id, _ = await _signed_up_user()+ handle = f"taken-{uuid.uuid4().hex[:8]}"+ await prisma.profile.create(+ data={+ "userId": squatter_id,+ "name": "Squatter",+ "username": handle,+ "description": "",+ "links": [],+ "avatarUrl": "",+ }+ )+ return handle+++def _claims(user_id: str, email: str) -> dict:+ return {"sub": user_id, "email": email}+++async def _wait_for(event: asyncio.Event, what: str) -> None:+ try:+ await asyncio.wait_for(event.wait(), timeout=_STALL)+ except TimeoutError:+ pytest.fail(f"timed out after {_STALL}s waiting for {what}")diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.pyindex 6d7d60dd0a..1ffdf1cd06 100644--- a/autogpt_platform/backend/backend/api/features/store/routes.py+++ b/autogpt_platform/backend/backend/api/features/store/routes.py@@ -49,8 +49,9 @@ SubmissionSortDir = Literal["asc", "desc"]async def get_profile(user_id: str = Security(autogpt_libs.auth.get_user_id),) -> store_model.ProfileDetails:- """Get the profile details for the authenticated user."""- profile = await store_db.get_user_profile(user_id)+ """Get the profile details for the authenticated user, creating their+ default profile if account setup hasn't yet."""+ profile = await store_db.get_or_create_user_profile(user_id)if profile is None:raise NotFoundError("User does not have a profile yet")return profilediff --git a/autogpt_platform/backend/backend/data/org_migration.py b/autogpt_platform/backend/backend/data/org_migration.pyindex f89f0f7dc4..bf3db600ae 100644--- a/autogpt_platform/backend/backend/data/org_migration.py+++ b/autogpt_platform/backend/backend/data/org_migration.py@@ -269,7 +269,7 @@ async def ensure_personal_org(user_id: str) -> bool:number of concurrent callers sees ``True`` for a given user.On ``UniqueViolationError`` there are two possibilities, distinguished by a- re-check (same pattern as ``data.user._ensure_user_profile``): a concurrent+ re-check (same pattern as ``data.profile.ensure_profile``): a concurrentfirst-request already bootstrapped this user (done), or the resolved slugcollided with a *different* user's org (loop and retry — ``_resolve_unique_slug``now sees the taken slug and picks a fresh suffix).diff --git a/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py b/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.pyindex 41ac7c12b3..25dc790f3c 100644--- a/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py+++ b/autogpt_platform/backend/backend/data/posthog_lifecycle_hooks_test.py@@ -208,7 +208,7 @@ async def test_signup_schedules_only_a_new_user(existing: bool):app_user = MagicMock(id="user-1")with (patch.object(user_module, "prisma") as prisma,- patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),+ patch.object(user_module, "ensure_profile", new_callable=AsyncMock),patch.object(user_module,"ensure_personal_org",diff --git a/autogpt_platform/backend/backend/data/profile.py b/autogpt_platform/backend/backend/data/profile.pynew file mode 100644index 0000000000..3ca0398e5f--- /dev/null+++ b/autogpt_platform/backend/backend/data/profile.py@@ -0,0 +1,116 @@+"""The marketplace Profile every user has, created with a default handle."""++import logging+import random+import uuid+from typing import Optional++from prisma.errors import UniqueViolationError+from prisma.types import ProfileCreateInput++from backend.data.db import prisma++logger = logging.getLogger(__name__)++# 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) -> None:+ """Give *user_id* their default marketplace Profile if they have none yet.++ Account setup (``get_or_create_user``, via ``POST /auth/user``) creates it,+ but Better Auth issues the session as soon as the identity exists, so a+ first page can ask for the Profile before that call has run, or after its+ best-effort attempt failed. The default name comes from the user's own+ row, never from a token's claims, so it is also right for an admin acting+ as the user. No-op for an id with no platform ``User`` row.+ """+ user = await prisma.user.find_unique(where={"id": user_id})+ if user is None:+ return+ await ensure_profile(user.id, user.email)+++async def ensure_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]}"diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex 727d8a2eb5..44004ffee4 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -3,8 +3,6 @@ import base64import hashlibimport hmacimport logging-import random-import uuidfrom datetime import datetime, timedelta, timezonefrom typing import TYPE_CHECKING, Optional, castfrom urllib.parse import quote_plus@@ -16,13 +14,7 @@ from prisma.enums import BriefingFrequency, SubscriptionTierfrom prisma.errors import RecordNotFoundError, UniqueViolationErrorfrom prisma.models import AuthAccount, AuthUserfrom prisma.models import User as PrismaUser-from prisma.types import (- JsonFilter,- ProfileCreateInput,- UserCreateInput,- UserUpdateInput,- UserWhereInput,-)+from prisma.types import JsonFilter, UserCreateInput, UserUpdateInput, UserWhereInputfrom pydantic import BaseModel, ConfigDictfrom backend.data.db import prisma, query_raw_with_schema, transaction@@ -40,6 +32,7 @@ from backend.data.notifications import ()from backend.data.org_migration import ensure_personal_orgfrom backend.data.posthog_lifecycle_sync import schedule_posthog_lifecycle_sync+from backend.data.profile import ensure_profilefrom backend.data.subscription_trial import get_subscription_trialfrom backend.notifications.audience_enrichment import points_at_excluded_countryfrom backend.notifications.queue import queue_audience_change@@ -115,7 +108,7 @@ async def _get_or_create_user(user_data: dict) -> UserCreationResult:# 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)+ await ensure_profile(user.id, user.email)except Exception:logger.warning("Failed to ensure marketplace profile for user %s",@@ -188,94 +181,6 @@ def _legacy_signup_method(user_data: dict) -> str | None:return provider if isinstance(provider, str) and provider else None-# 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 d198683088..4fea585ff1 100644--- a/autogpt_platform/backend/backend/data/user_test.py+++ b/autogpt_platform/backend/backend/data/user_test.py@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock, call, patchimport prisma.errorsimport pytest+from backend.data import profile as profile_modulefrom backend.data import user as user_modulefrom backend.data.notifications import AudienceAction, NotificationResultfrom backend.data.user import (@@ -1126,7 +1127,7 @@ class TestGetOrCreateUserStatus:@pytest.fixture(autouse=True)def stub_user_provisioning(self):with (- patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),+ patch.object(user_module, "ensure_profile", new_callable=AsyncMock),patch.object(user_module,"ensure_personal_org",@@ -1393,6 +1394,7 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,+ patch.object(profile_module, "prisma", mock_prisma),patch.object(user_module.User,"from_db",@@ -1422,6 +1424,7 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,+ patch.object(profile_module, "prisma", mock_prisma),patch.object(user_module.User,"from_db",@@ -1448,6 +1451,7 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,+ patch.object(profile_module, "prisma", mock_prisma),patch.object(user_module.User, "from_db", return_value=sentinel_user),patch.object(user_module.logger, "warning") as warn_mock,):@@ -1473,6 +1477,7 @@ class TestGetOrCreateUserProfile:with (patch.object(user_module, "prisma") as mock_prisma,+ patch.object(profile_module, "prisma", mock_prisma),patch.object(user_module.User,"from_db",@@ -1515,7 +1520,7 @@ class TestGetOrCreateUserPersonalOrg:"from_db",return_value=_application_user("user-org", "[email protected]"),),- patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),+ patch.object(user_module, "ensure_profile", new_callable=AsyncMock),patch.object(user_module,"ensure_personal_org",@@ -1541,7 +1546,7 @@ class TestGetOrCreateUserPersonalOrg:with (patch.object(user_module, "prisma") as mock_prisma,patch.object(user_module.User, "from_db", return_value=MagicMock()),- patch.object(user_module, "_ensure_user_profile", new_callable=AsyncMock),+ patch.object(user_module, "ensure_profile", new_callable=AsyncMock),patch.object(user_module,"ensure_personal_org",diff --git a/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py b/autogpt_platform/backend/backend/notifications/subscriber_fields_test.pyindex f815fc70ac..525203fa04 100644--- a/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py+++ b/autogpt_platform/backend/backend/notifications/subscriber_fields_test.py@@ -128,7 +128,7 @@ async def _get_or_create(existing):with (patch.object(user_data, "prisma", prisma),- patch.object(user_data, "_ensure_user_profile", AsyncMock()),+ patch.object(user_data, "ensure_profile", AsyncMock()),patch.object(user_data, "ensure_personal_org", AsyncMock(return_value=False)),patch.object(user_data, "schedule_posthog_lifecycle_sync", MagicMock()),patch.object(user_data.User, "from_db", MagicMock()),diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 830cb2c862..bfccd3c7b0 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15646,7 +15646,7 @@"get": {"tags": ["v2", "store", "private"],"summary": "Get user profile",- "description": "Get the profile details for the authenticated user.",+ "description": "Get the profile details for the authenticated user, creating their\ndefault profile if account setup hasn't yet.","operationId": "getV2Get user profile","responses": {"200": {diff --git a/autogpt_platform/frontend/src/playwright/journeys/first-login-journey.spec.ts b/autogpt_platform/frontend/src/playwright/journeys/first-login-journey.spec.tsnew file mode 100644index 0000000000..4e75deafd1--- /dev/null+++ b/autogpt_platform/frontend/src/playwright/journeys/first-login-journey.spec.ts@@ -0,0 +1,65 @@+import type { Page } from "@playwright/test";+import { expect, test } from "./fixtures";+import { type JourneyUser, signUpBeforeAccountSetup } from "./journey-user";++test.describe("first login journey", () => {+ // The user's first page asks for their marketplace profile straight away,+ // and nothing promises that account setup, which creates it, has run by+ // then. The guard fails the journey on any failed request, so a 404 for+ // the profile fails it even when a retry later fills the menu in.+ test("a brand-new user's first page names them in the account menu without a failed request, and the next page works too", async ({+ page,+ }) => {+ const user = await signUpBeforeAccountSetup(page);+ await answerTheProfileReadFirst(page);++ await page.goto("/");+ await expect(page).toHaveURL(/\/home/);+ await expect(+ page.getByRole("textbox", { name: "Chat message input" }),+ ).toBeVisible();+ await expectAccountMenuToName(page, user);++ await page.getByRole("link", { name: "Marketplace" }).click();+ await expect(page).toHaveURL(/\/marketplace/);+ await expect(page.getByTestId("store-search-input")).toBeVisible();+ await expectAccountMenuToName(page, user);+ });+});++// The page's other API calls can run account setup on the way in (an+// org-scoped route sets up an account that has no org yet), so holding them+// until the profile read is answered makes that read land before setup every+// time, not only when it happens to win the race.+async function answerTheProfileReadFirst(page: Page) {+ const profileAnswered = page+ .waitForResponse((response) => isProfileRead(new URL(response.url())))+ .catch(() => undefined);+ await page.route(+ (url) =>+ url.pathname.startsWith("/api/") &&+ !url.pathname.startsWith("/api/auth/") &&+ !isProfileRead(url),+ async (route) => {+ await profileAnswered;+ await route.continue();+ },+ );+}++function isProfileRead(url: URL) {+ return url.pathname === "/api/proxy/api/store/profile";+}++// Until the profile loads, the menu shows placeholders instead of who you are.+async function expectAccountMenuToName(page: Page, user: JourneyUser) {+ const trigger = page.getByTestId("profile-popout-menu-trigger");+ const menu = page.getByTestId("account-menu-popover");+ await trigger.click();+ const profileName = user.email.split("@")[0];+ await expect(menu.getByText(profileName, { exact: true })).toBeVisible();+ await expect(menu.getByText(user.email, { exact: true })).toBeVisible();+ // The trigger, not Escape: in CI, Escape sometimes left the menu open.+ await trigger.click();+ await expect(menu).toBeHidden();+}diff --git a/autogpt_platform/frontend/src/playwright/journeys/journey-user.ts b/autogpt_platform/frontend/src/playwright/journeys/journey-user.tsindex d027785c4c..c7c1070e55 100644--- a/autogpt_platform/frontend/src/playwright/journeys/journey-user.ts+++ b/autogpt_platform/frontend/src/playwright/journeys/journey-user.ts@@ -50,6 +50,21 @@ export async function provisionJourneyUser(page: Page): Promise<JourneyUser> {return user;}+/**+ * Signs up a brand-new user who has finished onboarding but not the account+ * setup (POST /auth/user) that the app's sign-up runs before the first page.+ * A Google or email-link sign-in is in this state until /auth/callback has+ * run, and stays in it if that redirect is lost.+ */+export async function signUpBeforeAccountSetup(+ page: Page,+): Promise<JourneyUser> {+ const user = await signUp(page, newJourneyUser());+ if (user.id) await grantSubscriptionTier(user.id);+ await completeOnboarding(page);+ return user;+}+function newJourneyUser(): JourneyUser {const id = `${Date.now()}-${randomBytes(3).toString("hex")}`;return {@@ -94,8 +109,8 @@ async function signIn(page: Page, user: JourneyUser) {return { ...user, id: body.user?.id };}-// The app does this on a user's first page load; among other things it-// creates their marketplace profile. Done here so a journey doesn't race it.+// The app's sign-up, sign-in and /auth/callback do this before the user's+// first page; among other things it creates their personal org.async function finishAccountSetup(page: Page) {const response = await page.request.post("/api/proxy/api/auth/user");expect(