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(platform): move onboarding paywall after personalization (#15196)
Toran Bruce Richards72921384e2e9
diff --git a/autogpt_platform/backend/backend/api/features/onboarding/profile_test.py b/autogpt_platform/backend/backend/api/features/onboarding/profile_test.pyindex d60d27d96d..b61b5b0853 100644--- a/autogpt_platform/backend/backend/api/features/onboarding/profile_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding/profile_test.py@@ -1,96 +1,253 @@from unittest.mock import AsyncMock, MagicMockimport fastapi-import fastapi.testclient+import httpximport pytest+from autogpt_libs.auth import get_user_id, requires_user+from backend.api.features.onboarding import routesfrom backend.api.features.onboarding.routes import routerfrom backend.data.onboarding_role import OnboardingRole+from backend.data.understanding import BusinessUnderstanding, BusinessUnderstandingInputapp = fastapi.FastAPI()app.include_router(router)-client = fastapi.testclient.TestClient(app)-ROUTES = "backend.api.features.onboarding.routes"+USER_ID = "user-1"+++async def client():+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://test"+ ) as session:+ yield session++[email protected](autouse=True)+def profile_dependencies(mocker):+ existing = mocker.patch.object(+ routes, "get_business_understanding", new=AsyncMock(return_value=None)+ )+ admission = mocker.patch.object(+ routes, "enforce_personalization_budget", new=AsyncMock()+ )+ return existing, admission@pytest.fixture(autouse=True)-def setup_app_auth(mock_jwt_user):- from autogpt_libs.auth.jwt_utils import get_jwt_payload+def role_writes(mocker):+ """The kept pick's copy, and its MailerLite and PostHog writes."""+ return {+ "save": mocker.patch.object(routes, "save_onboarding_role", new=AsyncMock()),+ "queue": mocker.patch.object(routes, "queue_onboarding_role", new=AsyncMock()),+ "posthog": mocker.patch.object(routes, "set_onboarding_role", new=MagicMock()),+ }+- app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"][email protected](autouse=True)+def setup_app_auth():+ async def authenticated_user():+ return USER_ID++ async def authenticated():+ return None++ app.dependency_overrides[get_user_id] = authenticated_user+ app.dependency_overrides[requires_user] = authenticatedyieldapp.dependency_overrides.clear()-def profile(mocker):- from backend.data.understanding import BusinessUnderstandingInput-- mocks = {- name: mocker.patch(f"{ROUTES}.{name}", new_callable=AsyncMock)- for name in (- "extract_business_understanding",- "upsert_business_understanding",- "save_onboarding_role",- "queue_onboarding_role",- )- }- mocks["set_onboarding_role"] = mocker.patch(- f"{ROUTES}.set_onboarding_role", new_callable=MagicMock+async def test_onboarding_profile_success(mocker, client):+ mock_extract = mocker.patch(+ "backend.api.features.onboarding.routes.extract_business_understanding",+ new_callable=AsyncMock,)- # The extraction's own idea of the role, which AutoPilot-side rewrites- # look like; the kept pick comes from the request.- mocks["extract_business_understanding"].return_value = (- BusinessUnderstandingInput.model_construct(- user_name="John",- user_role="decision maker",- pain_points=["Finding leads"],- suggested_prompts={"Learn": ["How do I automate lead gen?"]},- )+ mock_upsert = mocker.patch(+ "backend.api.features.onboarding.routes.upsert_business_understanding",+ new_callable=AsyncMock,)- return mocks+ mock_extract.return_value = BusinessUnderstandingInput.model_construct(+ user_name="John",+ user_role="Founder/CEO",+ pain_points=["Finding leads"],+ suggested_prompts={"Learn": ["How do I automate lead gen?"]},+ )+ mock_upsert.return_value = AsyncMock()-def _submit(user_role: str):- return client.post(+ response = await client.post("/onboarding/profile",json={"user_name": "John",- "user_role": user_role,+ "user_role": "Founder/CEO","pain_points": ["Finding leads", "Email & outreach"],},)---def test_onboarding_profile_success(profile):- response = _submit("Founder/CEO")assert response.status_code == 200- profile["extract_business_understanding"].assert_awaited_once()- profile["upsert_business_understanding"].assert_awaited_once()+ mock_extract.assert_awaited_once()+ mock_upsert.assert_awaited_once()@pytest.mark.parametrize(- "user_role, role",+ "user_role, kept",[("Founder/CEO", OnboardingRole(choice="Founder/CEO")),("Dentist", OnboardingRole(choice="Other", other="Dentist")),],)-def test_the_pick_is_kept_and_sent_to_mailerlite_and_posthog(- profile, test_user_id, user_role, role+async def test_the_pick_is_kept_and_sent_to_mailerlite_and_posthog(+ mocker, role_writes, user_role, kept, client+):+ # The extraction's own idea of the role, which AutoPilot-side rewrites+ # look like; the kept pick comes from the request.+ mocker.patch.object(+ routes,+ "extract_business_understanding",+ new=AsyncMock(+ return_value=BusinessUnderstandingInput.model_construct(+ user_role="decision maker"+ )+ ),+ )+ mocker.patch.object(routes, "upsert_business_understanding", new=AsyncMock())+ response = await client.post(+ "/onboarding/profile",+ json={+ "user_name": "John",+ "user_role": user_role,+ "pain_points": ["Finding leads"],+ },+ )+ assert response.status_code == 200+ role_writes["save"].assert_awaited_once_with(USER_ID, kept)+ role_writes["queue"].assert_awaited_once_with(USER_ID, kept)+ role_writes["posthog"].assert_called_once_with(user_id=USER_ID, role=kept)+++async def test_an_unchanged_profile_still_keeps_the_pick(+ profile_dependencies, role_writes, client):- assert _submit(user_role).status_code == 200- profile["save_onboarding_role"].assert_awaited_once_with(test_user_id, role)- profile["queue_onboarding_role"].assert_awaited_once_with(test_user_id, role)- profile["set_onboarding_role"].assert_called_once_with(- user_id=test_user_id, role=role+ """A retry after a lost write, or a profile first saved before the pick+ was kept, still keeps it."""+ existing, _ = profile_dependencies+ existing.return_value = BusinessUnderstanding.model_construct(+ user_name="John", user_role="Dentist", pain_points=["Finding leads"]+ )+ response = await client.post(+ "/onboarding/profile",+ json={+ "user_name": "John",+ "user_role": "Dentist",+ "pain_points": ["Finding leads"],+ },)+ assert response.status_code == 200+ kept = OnboardingRole(choice="Other", other="Dentist")+ role_writes["save"].assert_awaited_once_with(USER_ID, kept)+ role_writes["queue"].assert_awaited_once_with(USER_ID, kept)+ role_writes["posthog"].assert_called_once_with(user_id=USER_ID, role=kept)-def test_onboarding_profile_missing_fields():- response = client.post(+async def test_onboarding_profile_missing_fields(client):+ response = await client.post("/onboarding/profile",json={"user_name": "John"},)assert response.status_code == 422++[email protected]("length, status", [(2000, 200), (2001, 422)])+async def test_profile_pain_point_size_is_bounded(+ mocker, profile_dependencies, length, status, client+):+ _, admission = profile_dependencies+ extract = mocker.patch.object(+ routes,+ "extract_business_understanding",+ new=AsyncMock(return_value=BusinessUnderstandingInput.model_construct()),+ )+ mocker.patch.object(routes, "upsert_business_understanding", new=AsyncMock())+ response = await client.post(+ "/onboarding/profile",+ json={+ "user_name": "John",+ "user_role": "Founder",+ "pain_points": ["a" * length],+ },+ )+ assert response.status_code == status+ if status == 422:+ admission.assert_not_awaited()+ extract.assert_not_awaited()+++async def test_identical_saved_profile_does_not_repeat_personalization(+ mocker, profile_dependencies, client+):+ existing, admission = profile_dependencies+ existing.return_value = BusinessUnderstanding.model_construct(+ user_name="John", user_role="Founder/CEO", pain_points=["Finding leads"]+ )+ extract = mocker.patch.object(+ routes, "extract_business_understanding", new=AsyncMock()+ )+ response = await client.post(+ "/onboarding/profile",+ json={+ "user_name": "John",+ "user_role": "Founder/CEO",+ "pain_points": ["Finding leads"],+ },+ )+ assert response.status_code == 200+ admission.assert_not_awaited()+ extract.assert_not_awaited()+++ "changed",+ [{"user_name": "Jane"}, {"user_role": "Developer"}, {"pain_points": ["Email"]}],+)+async def test_changed_profile_still_checks_budget(+ mocker, profile_dependencies, changed, client+):+ existing, admission = profile_dependencies+ original = {+ "user_name": "John",+ "user_role": "Founder/CEO",+ "pain_points": ["Finding leads"],+ }+ existing.return_value = BusinessUnderstanding.model_construct(**original)+ admission.side_effect = fastapi.HTTPException(429, "Try again")+ extract = mocker.patch.object(+ routes, "extract_business_understanding", new=AsyncMock()+ )+ response = await client.post("/onboarding/profile", json={**original, **changed})+ assert response.status_code == 429+ admission.assert_awaited_once()+ extract.assert_not_awaited()++[email protected]("status", [429, 503])+async def test_profile_rejection_is_not_swallowed_by_extraction_fallback(+ mocker, profile_dependencies, status, client+):+ _, admission = profile_dependencies+ admission.side_effect = fastapi.HTTPException(+ status, "Try again", headers={"Retry-After": "30"}+ )+ extract = mocker.patch.object(+ routes, "extract_business_understanding", new=AsyncMock()+ )+ upsert = mocker.patch.object(+ routes, "upsert_business_understanding", new=AsyncMock()+ )+ response = await client.post(+ "/onboarding/profile", json={"user_name": "John", "user_role": "Founder/CEO"}+ )+ assert response.status_code == status+ assert response.headers["Retry-After"] == "30"+ extract.assert_not_awaited()+ upsert.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/api/features/onboarding/routes.py b/autogpt_platform/backend/backend/api/features/onboarding/routes.pyindex df529ce2bf..b103576524 100644--- a/autogpt_platform/backend/backend/api/features/onboarding/routes.py+++ b/autogpt_platform/backend/backend/api/features/onboarding/routes.py@@ -4,6 +4,9 @@ import pydanticfrom autogpt_libs.auth import get_user_id, requires_userfrom fastapi import APIRouter, HTTPException, Security+from backend.api.features.onboarding_dump.rate_limit import (+ enforce_personalization_budget,+)from backend.api.features.store.model import StoreAgentDetailsfrom backend.data.model import UserOnboardingfrom backend.data.onboarding import (@@ -19,9 +22,11 @@ from backend.data.onboarding import ()from backend.data.onboarding_audience import queue_onboarding_rolefrom backend.data.onboarding_role import OnboardingRole, save_onboarding_role+from backend.data.onboarding_wizard import OnboardingWizardConflictfrom backend.data.tally import extract_business_understandingfrom backend.data.understanding import (BusinessUnderstandingInput,+ get_business_understanding,upsert_business_understanding,)from backend.util.product_analytics import set_onboarding_role@@ -46,11 +51,15 @@ async def get_onboarding(user_id: Annotated[str, Security(get_user_id)]):summary="Update onboarding state",tags=["onboarding"],response_model=UserOnboarding,+ responses={409: {"description": "The wizard draft changed in another session"}},)async def update_onboarding(user_id: Annotated[str, Security(get_user_id)], data: UserOnboardingUpdate):- return await update_user_onboarding(user_id, data)+ try:+ return await update_user_onboarding(user_id, data)+ except OnboardingWizardConflict as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc@router.post(@@ -82,7 +91,9 @@ class OnboardingProfileRequest(pydantic.BaseModel):user_name: str = pydantic.Field(min_length=1, max_length=100)user_role: str = pydantic.Field(min_length=1, max_length=100)- pain_points: list[str] = pydantic.Field(default_factory=list, max_length=20)+ pain_points: list[Annotated[str, pydantic.StringConstraints(max_length=2000)]] = (+ pydantic.Field(default_factory=list, max_length=20)+ )class OnboardingStatusResponse(pydantic.BaseModel):@@ -126,6 +137,16 @@ async def submit_onboarding_profile(data: OnboardingProfileRequest,user_id: Annotated[str, Security(get_user_id)],):+ existing = await get_business_understanding(user_id)+ if (+ existing+ and existing.user_name == data.user_name+ and existing.user_role == data.user_role+ and existing.pain_points == data.pain_points+ ):+ await _keep_role(user_id, data.user_role)+ return {"status": "ok"}+ await enforce_personalization_budget(user_id)formatted = format_onboarding_for_extraction(user_name=data.user_name,user_role=data.user_role,@@ -144,11 +165,16 @@ async def submit_onboarding_profile(understanding_input.pain_points = data.pain_pointsawait upsert_business_understanding(user_id, understanding_input)+ await _keep_role(user_id, data.user_role)++ return {"status": "ok"}+- # Kept apart from the understanding, whose copy AutoPilot rewrites.- role = OnboardingRole.from_answer(data.user_role)+async def _keep_role(user_id: str, answer: str) -> None:+ """Keep the pick apart from the understanding, whose copy AutoPilot+ rewrites, and send it to MailerLite and PostHog. An unchanged profile+ keeps it too, so a retry repairs a write an earlier attempt lost."""+ role = OnboardingRole.from_answer(answer)await save_onboarding_role(user_id, role)await queue_onboarding_role(user_id, role)set_onboarding_role(user_id=user_id, role=role)-- return {"status": "ok"}diff --git a/autogpt_platform/backend/backend/api/features/onboarding/step_test.py b/autogpt_platform/backend/backend/api/features/onboarding/step_test.pyindex d5d4b1ee0b..5d0e71e2a1 100644--- a/autogpt_platform/backend/backend/api/features/onboarding/step_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding/step_test.py@@ -214,7 +214,7 @@ def test_update_onboarding_rejects_invalid_notified_step(mocker):async def test_update_user_onboarding_merges_notified_as_plain_strings(mocker):mocker.patch.object(onboarding_module,- "get_user_onboarding",+ "ensure_user_onboarding",new_callable=AsyncMock,return_value=UserOnboarding.model_construct(notified=["WELCOME"]),)diff --git a/autogpt_platform/backend/backend/api/features/onboarding/wizard_test.py b/autogpt_platform/backend/backend/api/features/onboarding/wizard_test.pynew file mode 100644index 0000000000..0428e42223--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding/wizard_test.py@@ -0,0 +1,68 @@+from unittest.mock import AsyncMock++import pytest+from autogpt_libs.auth import get_user_id, requires_user+from fastapi import FastAPI+from httpx import ASGITransport, AsyncClient++from backend.api.features.onboarding.routes import router+from backend.data.onboarding_wizard import OnboardingWizardConflict+++async def authenticated_user() -> str:+ return "authenticated-user"+++async def authenticated() -> None:+ return None+++async def test_draft_conflict_returns_409_for_authenticated_user(mocker):+ update = mocker.patch(+ "backend.api.features.onboarding.routes.update_user_onboarding",+ AsyncMock(side_effect=OnboardingWizardConflict()),+ )+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[requires_user] = authenticated+ app.dependency_overrides[get_user_id] = authenticated_user++ async with AsyncClient(+ transport=ASGITransport(app=app), base_url="http://test"+ ) as client:+ response = await client.patch(+ "/onboarding",+ json={+ "wizardProgress": None,+ "wizardRevision": 3,+ "wizardUserId": "authenticated-user",+ "userId": "another-user",+ },+ )++ assert response.status_code == 409+ assert "changed in another session" in response.json()["detail"]+ assert update.await_args.args[0] == "authenticated-user"+++async def test_draft_without_revision_returns_422_without_writing(mocker):+ update = mocker.patch(+ "backend.api.features.onboarding.routes.update_user_onboarding", AsyncMock()+ )+ app = FastAPI()+ app.include_router(router)+ app.dependency_overrides[requires_user] = authenticated+ app.dependency_overrides[get_user_id] = authenticated_user++ async with AsyncClient(+ transport=ASGITransport(app=app), base_url="http://test"+ ) as client:+ response = await client.patch(+ "/onboarding",+ json={"wizardProgress": None, "wizardUserId": "authenticated-user"},+ )++ assert response.status_code == 422+ update.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/admission_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/admission_test.pynew file mode 100644index 0000000000..716265ecb5--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/admission_test.py@@ -0,0 +1,104 @@+from unittest.mock import AsyncMock++import pytest+from fastapi import BackgroundTasks, HTTPException+from prisma.enums import BrainDumpInputMode, BrainDumpStatus++from backend.api.features.onboarding_dump import service+from backend.api.features.onboarding_dump.service_test import DumpStore+++def pipeline(mocker):+ store = DumpStore()+ for name, method in (+ ("get_dump", store.get_dump),+ ("start_dump", store.start_dump),+ ("claim_transition", store.claim_transition),+ ("mark_failed", store.mark_failed),+ ):+ mocker.patch.object(service.db, name, new=method)+ admission = mocker.patch.object(+ service, "enforce_personalization_budget", new=AsyncMock()+ )+ assemble = mocker.patch.object(+ service.storage, "assemble_parts", new=AsyncMock(return_value=b"")+ )+ discard = mocker.patch.object(service.storage, "discard_parts", new=AsyncMock())+ quality = mocker.patch.object(+ service.quality, "check_transcript_quality", new=AsyncMock(return_value=None)+ )+ return store, admission, assemble, discard, quality++[email protected]("status", [429, 503])[email protected]("mode", [BrainDumpInputMode.voice, BrainDumpInputMode.typed])+async def test_rejected_processing_keeps_recording_and_can_retry(+ pipeline, status, mode+):+ store, admission, assemble, discard, quality = pipeline+ await store.start_dump("user", "recording", mode)+ admission.side_effect = HTTPException(+ status, "Try again", headers={"Retry-After": "30"}+ )+ tasks = BackgroundTasks()++ async def finalize():+ if mode == BrainDumpInputMode.voice:+ return await service.finalize_voice_dump(+ "user", "recording", 12, None, tasks+ )+ return await service.finalize_typed_dump(+ "user", "recording", "My bakery", tasks+ )++ with pytest.raises(HTTPException) as caught:+ await finalize()+ assert caught.value.status_code == status+ assert store.row is not None+ assert store.row.status == BrainDumpStatus.failed+ assert store.row.recordingId == "recording"+ assemble.assert_not_awaited()+ discard.assert_not_awaited()+ quality.assert_not_awaited()+ assert tasks.tasks == []++ admission.side_effect = None+ if mode == BrainDumpInputMode.voice:+ # The voice retry replays part zero before finalizing the same take.+ await store.start_dump("user", "recording", mode)+ await finalize()+ assert admission.await_count == 2+ if mode == BrainDumpInputMode.voice:+ assemble.assert_awaited_once()+ else:+ assert len(tasks.tasks) == 1+++ "status", [BrainDumpStatus.transcribing, BrainDumpStatus.completed]+)[email protected]("mode", [BrainDumpInputMode.voice, BrainDumpInputMode.typed])+async def test_existing_processing_and_results_bypass_budget(pipeline, status, mode):+ store, admission, _, _, _ = pipeline+ row = await store.start_dump("user", "recording", mode)+ row.status = status+ if mode == BrainDumpInputMode.voice:+ await service.finalize_voice_dump(+ "user", "recording", 12, None, BackgroundTasks()+ )+ else:+ await service.finalize_typed_dump(+ "user", "recording", "My bakery", BackgroundTasks()+ )+ admission.assert_not_awaited()+++async def test_skip_bypasses_budget(pipeline, mocker):+ store, admission, _, _, _ = pipeline+ mocker.patch.object(service.db, "update_dump", new=store.update_dump)+ await service.finalize_skipped_dump("user", "recording")+ admission.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/rate_limit.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/rate_limit.pynew file mode 100644index 0000000000..6b6c404440--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/rate_limit.py@@ -0,0 +1,117 @@+"""Bound new prepayment personalization work; saved drafts and retries stay usable."""++import asyncio+import hashlib+import logging+from collections.abc import Awaitable+from datetime import UTC, datetime+from typing import cast++from fastapi import HTTPException+from prisma.enums import SubscriptionTier++from backend.data.redis_client import get_redis_async+from backend.data.user import get_user_subscription_tier+from backend.monitoring.instrumentation import record_rate_limit_hit+from backend.util.feature_flag import Flag, evaluate_feature_flag+from backend.util.settings import BehaveAs, Settings++logger = logging.getLogger(__name__)+settings = Settings()++HOURLY_ATTEMPTS = 10+DAILY_ATTEMPTS = 30+REDIS_TIMEOUT_SECONDS = 0.25++# Both counters share a cluster slot. Rejection changes neither counter, and+# admission checks/increments both atomically across API workers.+_ADMIT = """+local hourly = tonumber(redis.call('GET', KEYS[1]) or '0')+local daily = tonumber(redis.call('GET', KEYS[2]) or '0')+local retry_after = 0+if hourly >= tonumber(ARGV[1]) then retry_after = tonumber(ARGV[3]) end+if daily >= tonumber(ARGV[2]) then+ retry_after = math.max(retry_after, tonumber(ARGV[4]))+end+if retry_after > 0 then return retry_after end+if redis.call('INCR', KEYS[1]) == 1 then+ redis.call('EXPIRE', KEYS[1], ARGV[3])+end+if redis.call('INCR', KEYS[2]) == 1 then+ redis.call('EXPIRE', KEYS[2], ARGV[4])+end+return 0+"""+++async def enforce_personalization_budget(user_id: str) -> None:+ try:+ if not await _requires_budget(user_id):+ return+ retry_after = await asyncio.wait_for(+ _admit(user_id), timeout=REDIS_TIMEOUT_SECONDS+ )+ except Exception as exc:+ logger.warning(f"Onboarding personalization admission unavailable: {exc}")+ raise HTTPException(+ status_code=503,+ detail="Personalization is temporarily unavailable. Your progress is saved; please retry shortly.",+ headers={"Retry-After": "30"},+ ) from exc++ if retry_after:+ record_rate_limit_hit("/api/onboarding/personalization", user_id)+ raise HTTPException(+ status_code=429,+ detail="You have made several personalization attempts. Your progress is saved; please try again later.",+ headers={"Retry-After": str(retry_after)},+ )+++async def _requires_budget(user_id: str) -> bool:+ if settings.config.behave_as == BehaveAs.LOCAL:+ return False+ try:+ tier = await get_user_subscription_tier(user_id)+ except ValueError:+ tier = SubscriptionTier.NO_TIER+ if tier != SubscriptionTier.NO_TIER:+ return False+ enabled, authoritative = await evaluate_feature_flag(+ Flag.ENABLE_PLATFORM_PAYMENT, user_id+ )+ if not authoritative:+ raise RuntimeError("Payment flag could not be evaluated")+ return enabled+++async def _admit(user_id: str) -> int:+ hourly_key, daily_key, hourly_ttl, daily_ttl = _budget_windows(+ user_id, datetime.now(UTC)+ )+ redis = await get_redis_async()+ return await cast(+ Awaitable[int],+ redis.eval(+ _ADMIT,+ 2,+ hourly_key,+ daily_key,+ str(HOURLY_ATTEMPTS),+ str(DAILY_ATTEMPTS),+ str(hourly_ttl),+ str(daily_ttl),+ ),+ )+++def _budget_windows(user_id: str, now: datetime) -> tuple[str, str, int, int]:+ identity = hashlib.sha256(user_id.encode()).hexdigest()+ prefix = f"onboarding:personalization:{{{identity}}}"+ timestamp = int(now.timestamp())+ return (+ f"{prefix}:hour:{timestamp // 3600}",+ f"{prefix}:day:{timestamp // 86400}",+ 3600 - timestamp % 3600,+ 86400 - timestamp % 86400,+ )diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/rate_limit_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/rate_limit_test.pynew file mode 100644index 0000000000..1c81a25dfa--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/rate_limit_test.py@@ -0,0 +1,154 @@+import asyncio+from datetime import UTC, datetime+from unittest.mock import AsyncMock, MagicMock++import pytest+from fastapi import HTTPException+from prisma.enums import SubscriptionTier+from redis.cluster import key_slot+from redis.exceptions import RedisClusterException, RedisError++from backend.api.features.onboarding_dump import rate_limit+from backend.util.settings import BehaveAs+++def admission(mocker):+ mocker.patch.object(rate_limit.settings.config, "behave_as", BehaveAs.CLOUD)+ payments = mocker.patch.object(+ rate_limit, "evaluate_feature_flag", new=AsyncMock(return_value=(True, True))+ )+ tier_lookup = mocker.patch.object(+ rate_limit,+ "get_user_subscription_tier",+ new=AsyncMock(return_value=SubscriptionTier.NO_TIER),+ )+ redis = MagicMock()+ redis.eval = AsyncMock(return_value=0)+ connect = mocker.patch.object(+ rate_limit, "get_redis_async", new=AsyncMock(return_value=redis)+ )+ return payments, tier_lookup, redis, connect+++async def test_admitted_personalization_uses_one_atomic_budget(admission):+ _, _, redis, _ = admission+ await rate_limit.enforce_personalization_budget("user-1")+ redis.eval.assert_awaited_once()+ args = redis.eval.await_args.args+ assert args[1] == 2+ assert key_slot(args[2].encode()) == key_slot(args[3].encode())+ assert "user-1" not in args[2]+ assert args[4:6] == ("10", "30")++[email protected]("retry_after", [1, 3600, 86400])+async def test_quota_rejection_exposes_retry_after(admission, retry_after):+ _, _, redis, _ = admission+ redis.eval.return_value = retry_after+ with pytest.raises(HTTPException) as caught:+ await rate_limit.enforce_personalization_budget("user-1")+ assert caught.value.status_code == 429+ assert caught.value.headers == {"Retry-After": str(retry_after)}+++async def test_active_plan_does_not_use_budget(admission):+ _, tier_lookup, _, connect = admission+ tier_lookup.return_value = SubscriptionTier.PRO+ await rate_limit.enforce_personalization_budget("user-1")+ connect.assert_not_awaited()+++async def test_self_host_does_not_read_tier_or_use_budget(admission, mocker):+ payments, tier_lookup, _, connect = admission+ mocker.patch.object(rate_limit.settings.config, "behave_as", BehaveAs.LOCAL)+ await rate_limit.enforce_personalization_budget("user-1")+ tier_lookup.assert_not_awaited()+ payments.assert_not_awaited()+ connect.assert_not_awaited()+++async def test_authoritatively_disabled_payments_do_not_use_budget(admission):+ payments, _, _, connect = admission+ payments.return_value = (False, True)+ await rate_limit.enforce_personalization_budget("user-1")+ connect.assert_not_awaited()++[email protected]("fallback", [False, True])+async def test_unavailable_cloud_flag_cannot_bypass_budget(admission, fallback):+ payments, _, _, connect = admission+ payments.return_value = (fallback, False)+ with pytest.raises(HTTPException) as caught:+ await rate_limit.enforce_personalization_budget("user-1")+ assert caught.value.status_code == 503+ connect.assert_not_awaited()+++async def test_active_plan_does_not_depend_on_flag_availability(admission):+ payments, tier_lookup, _, connect = admission+ tier_lookup.return_value = SubscriptionTier.PRO+ payments.side_effect = RuntimeError("flag vendor down")+ await rate_limit.enforce_personalization_budget("user-1")+ payments.assert_not_awaited()+ connect.assert_not_awaited()++[email protected]("error", [RedisError("down"), RedisClusterException("down")])+async def test_redis_error_blocks_new_paid_work_with_retry(admission, error):+ _, _, redis, _ = admission+ redis.eval.side_effect = error+ with pytest.raises(HTTPException) as caught:+ await rate_limit.enforce_personalization_budget("user-1")+ assert caught.value.status_code == 503+ assert caught.value.headers == {"Retry-After": "30"}+++async def test_entitlement_error_cannot_bypass_budget(admission):+ _, tier_lookup, _, connect = admission+ tier_lookup.side_effect = RuntimeError("tier unavailable")+ with pytest.raises(HTTPException) as caught:+ await rate_limit.enforce_personalization_budget("user-1")+ assert caught.value.status_code == 503+ connect.assert_not_awaited()+++async def test_redis_timeout_is_bounded(admission, mocker):+ _, _, _, connect = admission++ async def stalled():+ await asyncio.sleep(10)++ connect.side_effect = stalled+ mocker.patch.object(rate_limit, "REDIS_TIMEOUT_SECONDS", 0.01)+ with pytest.raises(HTTPException) as caught:+ await asyncio.wait_for(+ rate_limit.enforce_personalization_budget("user-1"), timeout=1+ )+ assert caught.value.status_code == 503+++def test_windows_are_per_user_and_roll_over_independently():+ now = datetime(2026, 10, 6, 12, 30, tzinfo=UTC)+ hour_later = datetime(2026, 10, 6, 13, 30, tzinfo=UTC)+ tomorrow = datetime(2026, 10, 7, 12, 30, tzinfo=UTC)+ first = rate_limit._budget_windows("user-1", now)+ other = rate_limit._budget_windows("user-2", now)+ later = rate_limit._budget_windows("user-1", hour_later)+ next_day = rate_limit._budget_windows("user-1", tomorrow)+ assert first[0] != other[0]+ assert first[1] != other[1]+ assert first[0] != later[0]+ assert first[1] == later[1]+ assert first[1] != next_day[1]+ assert first[2:] == (1800, 41400)diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.pyindex bd6b728fae..19f476e097 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/routes_test.py@@ -169,6 +169,14 @@ def flag_on(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv(FLAG_ENV_VAR, "true")[email protected](autouse=True)+def personalization_admission(mocker: MockerFixture) -> AsyncMock:+ return mocker.patch(+ "backend.api.features.onboarding_dump.service.enforce_personalization_budget",+ new=AsyncMock(),+ )++@pytest.fixture(autouse=True)def dumps(mocker: MockerFixture) -> DumpStore:store = DumpStore()@@ -364,7 +372,7 @@ def test_part_over_the_per_part_limit_is_rejected():def test_part_pushing_the_recording_over_the_total_limit_is_rejected(- storage_mocks: dict[str, AsyncMock]+ storage_mocks: dict[str, AsyncMock],):storage_mocks["buffered_size"].return_value = MAX_RECORDING_BYTES@@ -376,7 +384,7 @@ def test_part_pushing_the_recording_over_the_total_limit_is_rejected(def test_a_racing_part_that_blows_the_total_limit_is_rejected_after_the_write(- storage_mocks: dict[str, AsyncMock]+ storage_mocks: dict[str, AsyncMock],):"""The pre-check races; the post-check is the authoritative one.diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/service.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/service.pyindex 79743f446b..bd6e2e3f97 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/service.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/service.py@@ -9,7 +9,7 @@ import asyncioimport loggingimport time-from fastapi import BackgroundTasks+from fastapi import BackgroundTasks, HTTPExceptionfrom prisma import Jsonfrom prisma.enums import BrainDumpInputMode, BrainDumpStatusfrom prisma.models import OnboardingBrainDump@@ -36,6 +36,9 @@ from backend.api.features.onboarding_dump.models import (RecommendedProvidersResponse,SuggestedPrompt,)+from backend.api.features.onboarding_dump.rate_limit import (+ enforce_personalization_budget,+)from backend.copilot.db import user_has_any_sessionfrom backend.data.onboarding import format_brain_dump_for_extractionfrom backend.data.tally import extract_business_understanding@@ -125,6 +128,7 @@ async def finalize_voice_dump(current.status, current.transcript, BrainDumpInputMode.voice)+ await _admit_processing(user_id, recording_id)audio = await storage.assemble_parts(user_id, recording_id)if not audio:# Nothing buffered server-side. The browser still holds every part@@ -270,6 +274,7 @@ async def finalize_typed_dump()return _pipeline_response(current.status, current.transcript, current.inputMode)+ await _admit_processing(user_id, recording_id)# Typed dumps skip transcription but not the gate: a keyboard can# produce "asdf asdf asdf" just as easily as a silent mic produces a# hallucinated transcript. Only the claim winner reaches this point,@@ -292,6 +297,17 @@ async def finalize_typed_dump()+async def _admit_processing(user_id: str, recording_id: str) -> None:+ try:+ await enforce_personalization_budget(user_id)+ except HTTPException as exc:+ code = (+ "rate_limited" if exc.status_code == 429 else "personalization_unavailable"+ )+ await db.mark_failed(user_id, recording_id, code)+ raise++async def _quality_rejection(user_id: str,recording_id: str,diff --git a/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.py b/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.pyindex 5bec205ac5..ba85930c0a 100644--- a/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.py+++ b/autogpt_platform/backend/backend/api/features/onboarding_dump/service_test.py@@ -157,6 +157,13 @@ class DumpStore:self.greeting_seen_writes += 1[email protected](autouse=True)+def personalization_admission(mocker: MockerFixture) -> AsyncMock:+ return mocker.patch.object(+ service, "enforce_personalization_budget", new=AsyncMock()+ )++@pytest.fixture(autouse=True)def dumps(mocker: MockerFixture) -> DumpStore:store = DumpStore()@@ -315,7 +322,7 @@ async def test_transcript_lands_in_the_business_understanding(@pytest.mark.asyncioasync def test_typed_dump_is_labelled_as_typed_in_the_understanding(- extraction: dict[str, AsyncMock]+ extraction: dict[str, AsyncMock],):background = BackgroundTasks()await service.finalize_typed_dump(@@ -454,6 +461,7 @@ async def test_two_concurrent_voice_finalizes_only_process_the_take_once(dumps: DumpStore,storage_mocks: dict[str, AsyncMock],transcribe: AsyncMock,+ personalization_admission: AsyncMock,):"""Only the caller that wins the atomic claim does the work.@@ -475,11 +483,15 @@ async def test_two_concurrent_voice_finalizes_only_process_the_take_once(transcribe.assert_awaited_once()storage_mocks["store_audio"].assert_awaited_once()+ personalization_admission.assert_awaited_once_with(USER_ID)@pytest.mark.asyncioasync def test_two_concurrent_typed_finalizes_only_queue_one_pipeline(- mocker: MockerFixture, dumps: DumpStore, extraction: dict[str, AsyncMock]+ mocker: MockerFixture,+ dumps: DumpStore,+ extraction: dict[str, AsyncMock],+ personalization_admission: AsyncMock,):await dumps.start_dump(USER_ID, RECORDING_ID, BrainDumpInputMode.typed)release_both_past_the_guard(mocker, dumps)@@ -500,6 +512,7 @@ async def test_two_concurrent_typed_finalizes_only_queue_one_pipeline(# One winner queues the extraction/greeting pair; the loser queues# nothing, so the understanding is written exactly once.assert extraction["upsert_business_understanding"].await_count == 1+ personalization_admission.assert_awaited_once_with(USER_ID)@pytest.mark.asyncio@@ -1359,8 +1372,8 @@ async def test_a_failed_team_job_still_stores_an_answer("""templates.side_effect = RuntimeError("database down")generate_team.side_effect = (- lambda transcript, *, user_role, pain_points, templates: (- ExpertRecommendations(source="fallback")+ lambda transcript, *, user_role, pain_points, templates: ExpertRecommendations(+ source="fallback"))await start_voice_take(dumps)diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.pyindex ba6d0b33b7..ed54842cd3 100644--- a/autogpt_platform/backend/backend/data/model.py+++ b/autogpt_platform/backend/backend/data/model.py@@ -42,6 +42,7 @@ from pydantic_core import (from typing_extensions import TypedDictfrom backend.data.onboarding_steps import OnboardingStep+from backend.data.onboarding_wizard import OnboardingWizardProgressfrom backend.integrations.providers import ProviderNamefrom backend.util.exceptions import ExecutionFailureReasonfrom backend.util.json import loads as json_loads@@ -1112,6 +1113,8 @@ class UserExecutionSummaryStats(BaseModel):class UserOnboarding(BaseModel):userId: str+ wizardProgress: OnboardingWizardProgress | None = None+ wizardRevision: int = 0# Steps are typed as ``OnboardingStep`` so the API exposes a typed enum to# the frontend (the DB stores plain strings). The rename migration keeps# existing rows within the enum, and writes are validated on the completiondiff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.pyindex 2fa1e3c248..badd99d3f8 100644--- a/autogpt_platform/backend/backend/data/onboarding.py+++ b/autogpt_platform/backend/backend/data/onboarding.py@@ -11,6 +11,7 @@ from prisma.types import UserOnboardingCreateInput, UserOnboardingUpdateInputfrom backend.api.features.store.model import StoreAgentDetailsfrom backend.api.model import OnboardingNotificationPayloadfrom backend.data.credit import get_user_credit_model+from backend.data.db import transactionfrom backend.data.notification_bus import (AsyncRedisNotificationEventBus,NotificationEvent,@@ -19,6 +20,10 @@ from backend.data.onboarding_steps import (FrontendOnboardingStep as FrontendOnboardingStep,)from backend.data.onboarding_steps import OnboardingStep+from backend.data.onboarding_wizard import (+ OnboardingWizardConflict,+ OnboardingWizardProgress,+)from backend.data.subscription_trial import get_subscription_trialfrom backend.data.user import get_user_by_idfrom backend.util.cache import cached@@ -43,6 +48,11 @@ MIN_AGENT_COUNT = 2 # Minimum number of marketplace agents to enable onboardingclass UserOnboardingUpdate(pydantic.BaseModel):+ wizardProgress: OnboardingWizardProgress | None = None+ wizardRevision: int | None = pydantic.Field(default=None, ge=0, strict=True)+ wizardUserId: str | None = pydantic.Field(+ default=None, min_length=1, max_length=128, strict=True+ )walletShown: Optional[bool] = None# Typed enum so the PATCH endpoint validates step names at the boundary# (invalid values get a 422 instead of being stored and then 500-ing reads,@@ -56,6 +66,14 @@ class UserOnboardingUpdate(pydantic.BaseModel):agentInput: Optional[dict[str, Any]] = NoneonboardingAgentExecutionId: Optional[str] = None+ @pydantic.model_validator(mode="after")+ def require_wizard_revision(self) -> "UserOnboardingUpdate":+ if "wizardProgress" in self.model_fields_set and self.wizardRevision is None:+ raise ValueError("wizardRevision is required when saving wizardProgress")+ if "wizardProgress" in self.model_fields_set and self.wizardUserId is None:+ raise ValueError("wizardUserId is required when saving wizardProgress")+ return self+async def get_user_onboarding(user_id: str) -> UserOnboarding:"""Read a user's onboarding state, creating nothing.@@ -100,6 +118,7 @@ def _default_user_onboarding(user_id: str) -> UserOnboarding:integrations=[],agentRuns=0,consecutiveRunDays=0,+ wizardRevision=0,userId=user_id,)@@ -111,6 +130,8 @@ async def reset_user_onboarding(user_id: str):"create": UserOnboardingCreateInput(userId=user_id),"update": {"completedSteps": [],+ "wizardProgress": None,+ "wizardRevision": {"increment": 1},"walletShown": False,"notified": [],"usageReason": None,@@ -128,8 +149,12 @@ async def reset_user_onboarding(user_id: str):async def update_user_onboarding(user_id: str, data: UserOnboardingUpdate):+ if "wizardProgress" in data.model_fields_set and data.wizardUserId != user_id:+ raise OnboardingWizardConflict()update: UserOnboardingUpdateInput = {}- onboarding = await get_user_onboarding(user_id)+ # A write path: the draft save below is a conditional update, which has no+ # row to match for a user whose first write this is.+ onboarding = await ensure_user_onboarding(user_id)if data.walletShown:update["walletShown"] = data.walletShownif data.notified is not None:@@ -151,6 +176,15 @@ async def update_user_onboarding(user_id: str, data: UserOnboardingUpdate):update["agentInput"] = SafeJson(data.agentInput)if data.onboardingAgentExecutionId is not None:update["onboardingAgentExecutionId"] = data.onboardingAgentExecutionId+ if "wizardProgress" in data.model_fields_set:+ update["wizardProgress"] = (+ SafeJson(data.wizardProgress.model_dump(mode="json"))+ if data.wizardProgress is not None+ else None+ )+ if data.wizardRevision is None:+ raise ValueError("wizardRevision is required when saving wizardProgress")+ return await _save_wizard_progress(user_id, data.wizardRevision, update)return await UserOnboarding.prisma().upsert(where={"userId": user_id},@@ -161,6 +195,19 @@ async def update_user_onboarding(user_id: str, data: UserOnboardingUpdate):)+async def _save_wizard_progress(+ user_id: str, revision: int, update: UserOnboardingUpdateInput+) -> UserOnboarding:+ async with transaction() as tx:+ changed = await tx.useronboarding.update_many(+ where={"userId": user_id, "wizardRevision": revision},+ data={**update, "wizardRevision": {"increment": 1}},+ )+ if changed != 1:+ raise OnboardingWizardConflict()+ return await tx.useronboarding.find_unique_or_raise(where={"userId": user_id})++async def _reward_user(user_id: str, onboarding: UserOnboarding, step: OnboardingStep):"""Internal grant: callers must derive user_id from authenticated identityor a verified webhook's stored owner, never an untrusted request field."""diff --git a/autogpt_platform/backend/backend/data/onboarding_wizard.py b/autogpt_platform/backend/backend/data/onboarding_wizard.pynew file mode 100644index 0000000000..a539814ecc--- /dev/null+++ b/autogpt_platform/backend/backend/data/onboarding_wizard.py@@ -0,0 +1,45 @@+from typing import Annotated, Literal++from pydantic import BaseModel, ConfigDict, Field+++class OnboardingWizardConflict(RuntimeError):+ def __init__(self) -> None:+ super().__init__(+ "Onboarding progress changed in another session. Reload before saving."+ )+++WizardStep = Literal[+ "team",+ "autopilot",+ "role",+ "painPoints",+ "hire",+ "subscription",+ "connect",+ "preparing",+]+WizardText = Annotated[str, Field(pattern=r"^[^\x00-\x08\x0b\x0c\x0e-\x1f\x7f]*$")]+++class OnboardingWizardProgress(BaseModel):+ """Saved wizard answers and navigation, independent of completion or access."""++ model_config = ConfigDict(extra="forbid", strict=True)++ version: Literal[1]+ currentStep: WizardStep+ completedSteps: list[WizardStep] = Field(max_length=8)+ role: WizardText = Field(max_length=100)+ otherRole: WizardText = Field(max_length=100)+ painPoints: list[Annotated[WizardText, Field(min_length=1, max_length=200)]] = (+ Field(max_length=20)+ )+ otherPainPoint: WizardText = Field(max_length=2000)+ selectedBilling: Literal["monthly", "yearly"]+ hasUserSelectedBilling: bool+ selectedCountryCode: str = Field(min_length=2, max_length=2, pattern="^[A-Z]{2}$")+ hiredTemplateIds: list[+ Annotated[WizardText, Field(min_length=1, max_length=128)]+ ] = Field(max_length=100)diff --git a/autogpt_platform/backend/backend/data/onboarding_wizard_test.py b/autogpt_platform/backend/backend/data/onboarding_wizard_test.pynew file mode 100644index 0000000000..f5d2468463--- /dev/null+++ b/autogpt_platform/backend/backend/data/onboarding_wizard_test.py@@ -0,0 +1,277 @@+from typing import Any+from unittest.mock import AsyncMock, MagicMock, Mock++import pytest+from pydantic import ValidationError++from backend.data.model import UserOnboarding+from backend.data.onboarding import (+ UserOnboardingUpdate,+ get_user_onboarding,+ reset_user_onboarding,+ update_user_onboarding,+)+from backend.util.json import SafeJson+++def wizard_progress(**changes: Any) -> dict[str, Any]:+ return {+ "version": 1,+ "currentStep": "subscription",+ "completedSteps": ["team", "autopilot", "role", "painPoints", "hire"],+ "role": "Founder",+ "otherRole": "",+ "painPoints": ["Research"],+ "otherPainPoint": "",+ "selectedBilling": "monthly",+ "hasUserSelectedBilling": False,+ "selectedCountryCode": "US",+ "hiredTemplateIds": ["template-1"],+ **changes,+ }+++def test_wizard_progress_survives_request_validation():+ payload = wizard_progress()+ update = UserOnboardingUpdate.model_validate(+ {"wizardProgress": payload, "wizardRevision": 0, "wizardUserId": "user-one"}+ )++ assert update.model_dump()["wizardProgress"] == payload+++ "changes",+ [+ {"version": 2},+ {"currentStep": "ONBOARDING_COMPLETE"},+ {"completedSteps": ["ONBOARDING_COMPLETE"]},+ {"completedSteps": ["role"] * 9},+ {"role": "a" * 101},+ {"otherRole": "a" * 101},+ {"painPoints": ["a" * 201]},+ {"painPoints": ["\x00"]},+ {"painPoints": ["Research"] * 21},+ {"otherPainPoint": "a" * 2001},+ {"selectedBilling": "weekly"},+ {"selectedCountryCode": "USA"},+ {"selectedCountryCode": "us"},+ {"hasUserSelectedBilling": "false"},+ {"hiredTemplateIds": ["a" * 129]},+ {"hiredTemplateIds": ["\x00"]},+ {"hiredTemplateIds": ["template"] * 101},+ {"userId": "another-user"},+ {"subscriptionTier": "MAX"},+ ],+)+def test_wizard_progress_rejects_malformed_or_authoritative_fields(changes):+ with pytest.raises(ValidationError):+ UserOnboardingUpdate.model_validate(+ {+ "wizardProgress": wizard_progress(**changes),+ "wizardRevision": 0,+ "wizardUserId": "user-one",+ }+ )+++def draft_transaction(mocker):+ tx = Mock()+ tx.useronboarding.update_many = AsyncMock(return_value=1)+ tx.useronboarding.find_unique_or_raise = AsyncMock()+ context = MagicMock()+ context.__aenter__ = AsyncMock(return_value=tx)+ context.__aexit__ = AsyncMock(return_value=False)+ mocker.patch("backend.data.onboarding.transaction", return_value=context)+ return tx++[email protected](loop_scope="function")+async def test_saving_draft_scopes_user_and_never_completes_or_rewards(+ mocker, draft_transaction+):+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.upsert = AsyncMock(return_value=Mock(notified=[]))+ reward = mocker.patch("backend.data.onboarding._reward_user", AsyncMock())+ credit = mocker.patch("backend.data.onboarding.get_user_credit_model", AsyncMock())+ notify = mocker.patch(+ "backend.data.onboarding._send_onboarding_notification", AsyncMock()+ )+ completed = mocker.patch("backend.data.onboarding.track_onboarding_completed")+ payload = wizard_progress()++ await update_user_onboarding(+ "authenticated-user",+ UserOnboardingUpdate.model_validate(+ {+ "wizardProgress": payload,+ "wizardRevision": 3,+ "wizardUserId": "authenticated-user",+ "userId": "another-user",+ }+ ),+ )++ calls = prisma.return_value.upsert.call_args_list+ assert all(+ call.kwargs["where"] == {"userId": "authenticated-user"} for call in calls+ )+ assert len(calls) == 1+ draft_transaction.useronboarding.update_many.assert_awaited_once_with(+ where={"userId": "authenticated-user", "wizardRevision": 3},+ data={"wizardProgress": SafeJson(payload), "wizardRevision": {"increment": 1}},+ )+ draft_transaction.useronboarding.find_unique_or_raise.assert_awaited_once_with(+ where={"userId": "authenticated-user"}+ )+ reward.assert_not_awaited()+ credit.assert_not_awaited()+ notify.assert_not_awaited()+ completed.assert_not_called()++[email protected](loop_scope="function")+async def test_reading_draft_scopes_each_authenticated_user(mocker):+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.find_unique = AsyncMock(return_value=None)++ first = await get_user_onboarding("user-one")+ second = await get_user_onboarding("user-two")++ calls = prisma.return_value.find_unique.call_args_list+ assert [call.kwargs["where"] for call in calls] == [+ {"userId": "user-one"},+ {"userId": "user-two"},+ ]+ # Reads create nothing: a user with no row reads as an empty draft at the+ # column's starting revision, which the first save then matches.+ assert (first.userId, first.wizardProgress, first.wizardRevision) == (+ "user-one",+ None,+ 0,+ )+ assert second.userId == "user-two"++[email protected](loop_scope="function")+async def test_reset_clears_only_the_authenticated_users_draft(mocker):+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.upsert = AsyncMock()++ await reset_user_onboarding("authenticated-user")++ call = prisma.return_value.upsert.call_args+ assert call.kwargs["where"] == {"userId": "authenticated-user"}+ assert call.kwargs["data"]["update"]["wizardProgress"] is None+ assert call.kwargs["data"]["update"]["wizardRevision"] == {"increment": 1}++[email protected](loop_scope="function")+async def test_unrelated_update_does_not_overwrite_draft(mocker):+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.upsert = AsyncMock(return_value=Mock(notified=[]))++ await update_user_onboarding("user-one", UserOnboardingUpdate(walletShown=True))++ assert prisma.return_value.upsert.call_args.kwargs["data"]["update"] == {+ "walletShown": True+ }++[email protected](loop_scope="function")+async def test_explicit_null_clears_draft(mocker, draft_transaction):+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.upsert = AsyncMock(return_value=Mock(notified=[]))++ await update_user_onboarding(+ "user-one",+ UserOnboardingUpdate.model_validate(+ {"wizardProgress": None, "wizardRevision": 0, "wizardUserId": "user-one"}+ ),+ )++ assert draft_transaction.useronboarding.update_many.call_args.kwargs["data"] == {+ "wizardProgress": None,+ "wizardRevision": {"increment": 1},+ }+++def test_response_exposes_nullable_typed_progress():+ schema = UserOnboarding.model_json_schema()++ assert schema["properties"]["wizardProgress"]["anyOf"] == [+ {"$ref": "#/$defs/OnboardingWizardProgress"},+ {"type": "null"},+ ]++[email protected]("revision", [None, -1, "0", True])+def test_draft_requires_a_valid_revision(revision):+ with pytest.raises(ValidationError):+ UserOnboardingUpdate.model_validate(+ {+ "wizardProgress": wizard_progress(),+ "wizardRevision": revision,+ "wizardUserId": "user-one",+ }+ )++[email protected](loop_scope="function")+async def test_stale_writer_cannot_overwrite_newer_draft(mocker, draft_transaction):+ prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ prisma.return_value.upsert = AsyncMock(return_value=Mock(notified=[]))+ tx = draft_transaction+ tx.useronboarding.update_many = AsyncMock(return_value=0)++ with pytest.raises(RuntimeError, match="Onboarding progress changed"):+ await update_user_onboarding(+ "user-one",+ UserOnboardingUpdate.model_validate(+ {+ "wizardProgress": wizard_progress(),+ "wizardRevision": 3,+ "wizardUserId": "user-one",+ }+ ),+ )++ tx.useronboarding.update_many.assert_awaited_once()+ tx.useronboarding.find_unique_or_raise.assert_not_awaited()+ assert prisma.return_value.upsert.await_count == 1++[email protected](loop_scope="function")+async def test_cookie_account_switch_cannot_save_previous_users_draft(+ mocker, draft_transaction+):+ read = mocker.patch(+ "backend.data.onboarding.get_user_onboarding",+ AsyncMock(return_value=Mock(notified=[])),+ )+ update = UserOnboardingUpdate.model_validate(+ {+ "wizardProgress": wizard_progress(),+ "wizardRevision": 0,+ "wizardUserId": "previous-user",+ }+ )++ with pytest.raises(RuntimeError, match="Onboarding progress changed"):+ await update_user_onboarding("authenticated-user", update)++ read.assert_not_awaited()+ draft_transaction.useronboarding.update_many.assert_not_awaited()++[email protected]("owner", [None, "", 42, "a" * 129])+def test_draft_requires_a_valid_captured_user(owner):+ with pytest.raises(ValidationError):+ UserOnboardingUpdate.model_validate(+ {+ "wizardProgress": wizard_progress(),+ "wizardRevision": 0,+ "wizardUserId": owner,+ }+ )diff --git a/autogpt_platform/backend/migrations/20261006120000_add_onboarding_wizard_progress/migration.sql b/autogpt_platform/backend/migrations/20261006120000_add_onboarding_wizard_progress/migration.sqlnew file mode 100644index 0000000000..9649938375--- /dev/null+++ b/autogpt_platform/backend/migrations/20261006120000_add_onboarding_wizard_progress/migration.sql@@ -0,0 +1,3 @@+ALTER TABLE "UserOnboarding"+ ADD COLUMN "wizardProgress" JSONB,+ ADD COLUMN "wizardRevision" INTEGER NOT NULL DEFAULT 0;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 7d2ddd88bd..e359d9d18b 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -325,6 +325,8 @@ model UserOnboarding {// means renames/adds/retires are code-only — legacy values become inert// strings instead of stuck enum members. See SECRT-2355.completedSteps String[] @default([])+ wizardProgress Json?+ wizardRevision Int @default(0)walletShown Boolean @default(false)notified String[] @default([])rewardedFor String[] @default([])diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsxindex e065cf9570..739734f27a 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsx@@ -13,10 +13,12 @@ import {} from "@/tests/integrations/test-utils";import userEvent from "@testing-library/user-event";import { http, HttpResponse } from "msw";+import type { ReactNode } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import OnboardingPage from "../page";-import { NO_PAYWALL_STEPS, PAYWALL_FIRST_STEPS } from "../store";+import { NO_PAYWALL_STEPS, PAYWALL_LAST_STEPS } from "../store";import { useOnboardingWizardStore } from "../store";+import { makeProgress } from "./progress-fixture";// IndexedDB does not exist in happy-dom and `fake-indexeddb` is not a// devDependency here, so the recording store is replaced with an@@ -102,6 +104,21 @@ vi.mock("posthog-js", () => ({default: { capture: vi.fn() },}));+// AnimatePresence can retain the outgoing timer in happy-dom even after the+// recovery controls render. These flow tests assert the current headline and+// actions independently of the decorative exit animation.+vi.mock("@/components/atoms/SwapFade/SwapFade", () => ({+ SwapFade: function SwapFade({+ children,+ className,+ }: {+ children: ReactNode;+ className?: string;+ }) {+ return <div className={className}>{children}</div>;+ },+}));+vi.mock("../steps/RoleStep", () => ({RoleStep: () => <div data-testid="step-role" />,}));@@ -129,22 +146,38 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({useAuth: () => ({isLoggedIn: true,isUserLoading: false,- user: null,+ user: { id: "brain-user", email: "[email protected]", user_metadata: {} },refreshSession: mockRefreshSession,}),}));vi.mock("@/app/api/__generated__/endpoints/onboarding/onboarding", () => ({getV1OnboardingState: () =>- Promise.resolve({ status: 200, data: { completedSteps: [] } }),+ Promise.resolve({+ status: 200,+ data: {+ userId: "brain-user",+ completedSteps: [],+ wizardRevision: 0,+ wizardProgress: makeProgress({+ currentStep: "painPoints",+ completedSteps: ["role"],+ }),+ },+ }),getV1CheckIfOnboardingIsCompleted: () =>Promise.resolve({ status: 200, data: false }),- patchV1UpdateOnboardingState: () => Promise.resolve({ status: 200 }),+ patchV1UpdateOnboardingState: () =>+ Promise.resolve({+ status: 200,+ data: { userId: "brain-user", wizardRevision: 1 },+ }),postV1CompleteOnboardingStep: () => Promise.resolve({ status: 200 }),postV1SubmitOnboardingProfile: () => Promise.resolve({ status: 200 }),}));vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({+ getGetSubscriptionStatusQueryKey: () => ["/api/credits/subscription"],useGetSubscriptionStatus: (opts: {query: { select: (res: { status: number; data: unknown }) => unknown };}) => ({@@ -348,6 +381,7 @@ beforeEach(() => {recordingStoreState.parts = [];recordingStoreState.finalizedIds = [];useOnboardingWizardStore.getState().reset();+ localStorage.clear();window.sessionStorage.removeItem(STEP_STORAGE_KEY);window.sessionStorage.removeItem(INTRO_PATH_KEY);});@@ -842,10 +876,10 @@ describe("onboarding brain dump — insufficient content", () => {describe("onboarding step map integrity", () => {it("keeps the step constants identical regardless of the brain-dump flag", () => {- expect(PAYWALL_FIRST_STEPS).toEqual({- subscription: 1,- role: 2,- painPoints: 3,+ expect(PAYWALL_LAST_STEPS).toEqual({+ role: 1,+ painPoints: 2,+ subscription: 3,preparing: 4,});expect(NO_PAYWALL_STEPS).toEqual({diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/helpers.test.tsnew file mode 100644index 0000000000..18b7fb09fb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/helpers.test.ts@@ -0,0 +1,15 @@+import { describe, expect, test } from "vitest";+import { normalizeOnboardingProfile } from "../helpers";++describe("normalizeOnboardingProfile", () => {+ test("cuts an Other role to the 100 code points the profile accepts", () => {+ // The API counts code points, so 100 emoji fit; a UTF-16 cut keeps 50.+ const { role } = normalizeOnboardingProfile({+ role: "Other",+ otherRole: "🙂".repeat(150),+ painPoints: [],+ otherPainPoint: "",+ });+ expect(role).toBe("🙂".repeat(100));+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/layout.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/layout.test.tsnew file mode 100644index 0000000000..3fae1a072e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/layout.test.ts@@ -0,0 +1,174 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { Flag } from "@/services/feature-flags/use-get-flag";+import { useOnboardingLayout } from "../useOnboardingLayout";++const source = vi.hoisted(() => ({+ flags: {} as Record<string, { value: boolean; resolved: boolean }>,+ local: false,+ paid: false,+}));++vi.mock("@/services/feature-flags/flag-source", () => ({+ useFlagSource: (key: string) =>+ source.flags[key] ?? { value: undefined, resolved: false },+}));+vi.mock("@/app/(platform)/marketplace/components/HeroSection/helpers", () => ({+ DEFAULT_SEARCH_TERMS: [],+}));+vi.mock("@/services/environment", () => ({+ environment: {+ areFeatureFlagsEnabled: () => true,+ isLocal: () => source.local,+ },+}));+vi.mock("../usePaidCheckoutStatus", () => ({+ usePaidCheckoutStatus: () => ({+ active: source.paid,+ isLoading: false,+ ready: true,+ }),+}));++const layoutFlags = [+ Flag.ENABLE_PLATFORM_PAYMENT,+ Flag.ONBOARDING_BRAIN_DUMP,+ Flag.ONBOARDING_EXPERT_TEAM,+ Flag.HIRE_EXPERTS,+];+const initialProps = {+ userID: "first-user",+ isLoggedIn: true,+ isUserLoading: false,+ trialConfirmation: { ready: true, active: false },+};++beforeEach(() => {+ source.flags = Object.fromEntries(+ layoutFlags.map((flag) => [flag, { value: true, resolved: true }]),+ );+ source.local = false;+ source.paid = false;+});++describe("onboarding layout readiness", () => {+ it.each(layoutFlags)("waits for %s before freezing the layout", (flag) => {+ delete source.flags[flag];+ const { result, rerender } = renderHook(useOnboardingLayout, {+ initialProps,+ });++ expect(result.current.isReady).toBe(false);++ source.flags[flag] = { value: true, resolved: true };+ rerender(initialProps);++ expect(result.current.isReady).toBe(true);+ expect(result.current.isBrainDumpEnabled).toBe(true);+ expect(result.current.steps).toEqual({+ team: 1,+ autopilot: 2,+ role: 3,+ painPoints: 4,+ hire: 5,+ subscription: 6,+ preparing: 7,+ });+ });++ it("keeps the active account's step order after flags change", () => {+ const { result, rerender } = renderHook(useOnboardingLayout, {+ initialProps,+ });+ const steps = result.current.steps;++ source.flags = Object.fromEntries(+ layoutFlags.map((flag) => [flag, { value: false, resolved: true }]),+ );+ rerender(initialProps);++ expect(result.current.isReady).toBe(true);+ expect(result.current.steps).toEqual(steps);+ expect(result.current.isBrainDumpEnabled).toBe(true);+ });++ it("uses the existing bounded fallback if a layout flag never resolves", () => {+ vi.useFakeTimers();+ try {+ delete source.flags[Flag.ONBOARDING_BRAIN_DUMP];+ const { result, unmount } = renderHook(useOnboardingLayout, {+ initialProps,+ });+ expect(result.current.isReady).toBe(false);++ act(() => vi.advanceTimersByTime(5000));++ expect(result.current.isReady).toBe(true);+ expect(result.current.isBrainDumpEnabled).toBe(false);+ expect(result.current.steps.hire).toBeUndefined();+ expect(result.current.steps.subscription).toBe(5);+ unmount();+ } finally {+ vi.useRealTimers();+ }+ });++ it("waits for the next account's flags instead of retaining the old layout", () => {+ const { result, rerender } = renderHook(useOnboardingLayout, {+ initialProps,+ });+ expect(result.current.steps.hire).toBe(5);++ source.flags = {};+ const nextUser = { ...initialProps, userID: "second-user" };+ rerender({ ...nextUser, isUserLoading: true });+ expect(result.current.isReady).toBe(false);++ source.flags[Flag.ENABLE_PLATFORM_PAYMENT] = {+ value: true,+ resolved: true,+ };+ rerender(nextUser);+ expect(result.current.isReady).toBe(false);++ source.flags[Flag.ONBOARDING_BRAIN_DUMP] = { value: true, resolved: true };+ source.flags[Flag.ONBOARDING_EXPERT_TEAM] = { value: true, resolved: true };+ source.flags[Flag.HIRE_EXPERTS] = { value: false, resolved: true };+ rerender(nextUser);++ expect(result.current.isReady).toBe(true);+ expect(result.current.isBrainDumpEnabled).toBe(true);+ expect(result.current.steps).toEqual({+ role: 1,+ painPoints: 2,+ subscription: 3,+ preparing: 4,+ });+ });++ it.each([+ ["unpaid hosted", false, false, false, true],+ ["paid hosted", false, true, false, false],+ ["active trial", false, false, true, false],+ ["self-hosted", true, false, false, false],+ ] as const)(+ "preserves the %s checkout layout",+ (_name, local, paid, trial, paywall) => {+ source.local = local;+ source.paid = paid;+ source.flags[Flag.ENABLE_PLATFORM_PAYMENT].value = !local;+ const { result } = renderHook(useOnboardingLayout, {+ initialProps: {+ ...initialProps,+ trialConfirmation: { ready: true, active: trial },+ },+ });++ expect(result.current.isReady).toBe(true);+ expect(result.current.isPaymentEnabled).toBe(paywall);+ expect(result.current.steps.subscription !== undefined).toBe(paywall);+ expect(result.current.steps.connect !== undefined).toBe(local);+ expect(result.current.steps.hire).toBe(5);+ },+ );+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsxindex a5c3b18491..77f486d824 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx@@ -7,42 +7,82 @@ import {screen,waitFor,} from "@/tests/integrations/test-utils";+import type { User } from "@/lib/auth/types";+import type { OnboardingWizardProgress } from "@/app/api/__generated__/models/onboardingWizardProgress";import {installGtagShim,removeGtagShim,} from "@/tests/integrations/gtag-shim";-import type { User } from "@/lib/auth/types";import OnboardingPage from "../page";import { useOnboardingWizardStore } from "../store";+import { progressStorageKey } from "../progress";+import { makeProgress } from "./progress-fixture";vi.mock("../steps/RoleStep", () => ({- RoleStep: () => <div data-testid="step-role" />,+ RoleStep: () => (+ <button+ data-testid="step-role"+ onClick={() => useOnboardingWizardStore.getState().nextStep()}+ >+ Continue+ </button>+ ),}));vi.mock("../steps/PainPointsStep", () => ({- PainPointsStep: () => <div data-testid="step-painpoints" />,+ PainPointsStep: () => (+ <button+ data-testid="step-painpoints"+ onClick={() => useOnboardingWizardStore.getState().nextStep()}+ >+ Continue+ </button>+ ),+}));+vi.mock("../steps/BrainDumpStep/BrainDumpStep", () => ({+ BrainDumpStep: () => (+ <button+ data-testid="step-braindump"+ onClick={() => useOnboardingWizardStore.getState().nextStep()}+ >+ Continue+ </button>+ ),}));vi.mock("../steps/ConnectStep/ConnectStep", () => ({ConnectStep: () => <div data-testid="step-connect" />,}));-vi.mock("../steps/SubscriptionStep/SubscriptionStep", () => ({SubscriptionStep: () => <div data-testid="step-subscription" />,}));vi.mock("../steps/IntroStep/IntroStep", () => ({IntroStep: ({ slide }: { slide: string }) => (- <div data-testid={`step-${slide}`} />+ <button+ data-testid={`step-${slide}`}+ onClick={() => useOnboardingWizardStore.getState().nextStep()}+ >+ Continue+ </button>),}));vi.mock("../steps/HireStep/HireStep", () => ({- HireStep: () => <div data-testid="step-hire" />,+ HireStep: () => (+ <button+ data-testid="step-hire"+ onClick={() => useOnboardingWizardStore.getState().nextStep()}+ >+ Continue+ </button>+ ),}));vi.mock("../steps/PreparingStep", () => ({PreparingStep: ({ onComplete }: { onComplete: () => void }) => (- <button data-testid="step-preparing" onClick={onComplete} />+ <button data-testid="step-preparing" onClick={onComplete}>+ Finish+ </button>),}));-let currentSearchParams = new URLSearchParams();+let params = new URLSearchParams();const routerReplace = vi.fn();vi.mock("next/navigation", () => ({useRouter: () => ({@@ -50,734 +90,697 @@ vi.mock("next/navigation", () => ({push: vi.fn(),refresh: vi.fn(),}),- useSearchParams: () => currentSearchParams,+ useSearchParams: () => params,usePathname: () => "/onboarding",}));--let mockAuthState = { isLoggedIn: true, isUserLoading: false };-let mockUser: User | null = null;+let user: User | null;+let authLoading = false;vi.mock("@/lib/auth/hooks/useAuth", () => ({useAuth: () => ({- ...mockAuthState,- user: mockUser,- refreshSession: vi.fn(() => Promise.resolve({ user: null })),+ isLoggedIn: !!user,+ isUserLoading: authLoading,+ user,+ refreshSession: vi.fn(),}),}));--let mockCompletedSteps: string[] = [];-const { completeOnboardingStep, submitOnboardingProfile } = vi.hoisted(() => ({- completeOnboardingStep: vi.fn(() => Promise.resolve({ status: 200 })),- submitOnboardingProfile: vi.fn(() => Promise.resolve({ status: 200 })),-}));+let serverDraft: OnboardingWizardProgress | null = null;+let completed = false;+let revision = 0;+const { getState, patchState, completeStep, submitProfile } = vi.hoisted(+ () => ({+ getState: vi.fn(),+ patchState: vi.fn(),+ completeStep: vi.fn(),+ submitProfile: vi.fn(),+ }),+);vi.mock("@/app/api/__generated__/endpoints/onboarding/onboarding", () => ({- getV1OnboardingState: () =>- Promise.resolve({- status: 200,- data: { completedSteps: mockCompletedSteps },- }),+ getV1OnboardingState: getState,+ patchV1UpdateOnboardingState: patchState,+ postV1CompleteOnboardingStep: completeStep,+ postV1SubmitOnboardingProfile: submitProfile,getV1CheckIfOnboardingIsCompleted: () =>Promise.resolve({ status: 200, data: false }),- patchV1UpdateOnboardingState: () => Promise.resolve({ status: 200 }),- postV1CompleteOnboardingStep: completeOnboardingStep,- postV1SubmitOnboardingProfile: submitOnboardingProfile,}));--let mockSubscriptionTier: string = "NO_TIER";+let tier = "NO_TIER";vi.mock("@/app/api/__generated__/endpoints/credits/credits", () => ({+ getGetSubscriptionStatusQueryKey: () => ["/api/credits/subscription"],useGetSubscriptionStatus: (opts: {query: { select: (res: { status: number; data: unknown }) => unknown };}) => ({- data: opts.query.select({- status: 200,- data: { tier: mockSubscriptionTier },- }),+ data: opts.query.select({ status: 200, data: { tier } }),isLoading: false,}),}));--vi.mock("@/app/api/helpers", () => ({- resolveResponse: (p: Promise<{ data: unknown }>) => p.then((r) => r.data),+let trial = {+ ready: true,+ active: false,+ error: undefined as string | undefined,+ retry: vi.fn(),+};+vi.mock("@/services/trials/useTrialCheckoutReturn", () => ({+ useTrialCheckoutReturn: () => trial,}));--// Answers per-flag rather than returning one shared boolean: these tests-// only mean to toggle the paywall, and a blanket `true` would also switch-// on every other gated flag — including the brain dump, which replaces-// the pillbox step this file asserts on.-let mockFlagValue = false;-let mockExpertTeamEnabled = false;-let mockHireExpertsEnabled = true;-let mockBrainDumpEnabled = false;+let flags: Record<string, boolean> = {};vi.mock("@/services/feature-flags/use-get-flag", () => ({Flag: {- ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",- ONBOARDING_BRAIN_DUMP: "ONBOARDING_BRAIN_DUMP",- ONBOARDING_EXPERT_TEAM: "ONBOARDING_EXPERT_TEAM",- HIRE_EXPERTS: "HIRE_EXPERTS",+ ENABLE_PLATFORM_PAYMENT: "payment",+ ONBOARDING_BRAIN_DUMP: "brain",+ ONBOARDING_EXPERT_TEAM: "team",+ HIRE_EXPERTS: "hire",},- useGetFlag: (flag: string) => resolveFlag(flag),- useFlagStatus: (flag: string) => ({- enabled: resolveFlag(flag),- ready: true,- }),-}));--function resolveFlag(flag: string) {- if (flag === "ENABLE_PLATFORM_PAYMENT") return mockFlagValue;- if (flag === "ONBOARDING_EXPERT_TEAM") return mockExpertTeamEnabled;- if (flag === "HIRE_EXPERTS") return mockHireExpertsEnabled;- if (flag === "ONBOARDING_BRAIN_DUMP") return mockBrainDumpEnabled;- return false;-}--// The brain dump step is the real one when its flag is on; the page tests-// only care which slot it occupies.-vi.mock("../steps/BrainDumpStep/BrainDumpStep", () => ({- BrainDumpStep: () => <div data-testid="step-braindump" />,+ useGetFlag: (flag: string) => !!flags[flag],+ useFlagStatus: (flag: string) => ({ enabled: !!flags[flag], ready: true }),}));-+let local = false;vi.mock("@/services/environment", async (importOriginal) => {const actual =await importOriginal<typeof import("@/services/environment")>();return {...actual,- environment: { ...actual.environment, isLocal: () => mockIsLocal },+ environment: { ...actual.environment, isLocal: () => local },};});-vi.mock("launchdarkly-react-client-sdk", () => ({- useLDClient: () => ({- waitForInitialization: () => Promise.resolve(),- }),+ useLDClient: () => ({ waitForInitialization: () => Promise.resolve() }),}));-const STEP_STORAGE_KEY = "autogpt:onboarding-highest-step";-let mockIsLocal = false;-beforeEach(() => {- currentSearchParams = new URLSearchParams();- mockFlagValue = false;- mockExpertTeamEnabled = false;- mockHireExpertsEnabled = true;- mockBrainDumpEnabled = false;- mockIsLocal = false;- mockSubscriptionTier = "NO_TIER";- mockAuthState = { isLoggedIn: true, isUserLoading: false };- mockUser = null;- mockCompletedSteps = [];- routerReplace.mockClear();- completeOnboardingStep.mockReset();- completeOnboardingStep.mockResolvedValue({ status: 200 });- submitOnboardingProfile.mockClear();+ user = {+ id: "u1",+ email: "[email protected]",+ user_metadata: { name: "Reinier Bot" },+ };+ params = new URLSearchParams();+ authLoading = false;+ tier = "NO_TIER";+ local = false;+ flags = { payment: true };+ completed = false;+ revision = 0;+ serverDraft = null;+ trial = { ready: true, active: false, error: undefined, retry: vi.fn() };+ localStorage.clear();+ sessionStorage.clear();useOnboardingWizardStore.getState().reset();- window.sessionStorage.removeItem(STEP_STORAGE_KEY);+ vi.clearAllMocks();+ getState.mockImplementation(() =>+ Promise.resolve({+ status: 200,+ data: {+ userId: user?.id,+ completedSteps: completed ? ["ONBOARDING_COMPLETE"] : [],+ wizardProgress: serverDraft,+ wizardRevision: revision,+ },+ }),+ );+ patchState.mockImplementation(+ ({ wizardProgress }: { wizardProgress: OnboardingWizardProgress }) => {+ serverDraft = wizardProgress;+ return Promise.resolve({+ status: 200,+ data: { userId: user?.id, wizardRevision: ++revision },+ });+ },+ );+ completeStep.mockResolvedValue({ status: 200 });+ submitProfile.mockResolvedValue({ status: 200 });});-afterEach(() => {cleanup();- // Not at the end of each test body: an assertion that throws above would- // leak the shim and NEXT_PUBLIC_GOOGLE_ADS_ID into every later test here.removeGtagShim();vi.unstubAllEnvs();});-describe("OnboardingPage — intro steps", () => {- it("starts on the Team step when the expert team is on", async () => {- mockExpertTeamEnabled = true;- render(<OnboardingPage />);- expect(await screen.findByTestId("step-team")).toBeDefined();- expect(screen.queryByTestId("step-role")).toBeNull();- });-- it("walks Team → Meet Otto → Role, tracking each as a step", async () => {- mockExpertTeamEnabled = true;- render(<OnboardingPage />);- expect(await screen.findByTestId("step-team")).toBeDefined();-- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-autopilot")).toBeDefined();- await waitFor(() => {- expect(routerReplace).toHaveBeenCalledWith("/onboarding?step=2", {- scroll: false,- });- });-- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();- expect(window.sessionStorage.getItem(STEP_STORAGE_KEY)).toBe("3");+function atPaywall() {+ serverDraft = makeProgress({+ currentStep: "subscription",+ completedSteps: ["role", "painPoints"],});+}- it("lets Back return from Role to Meet Otto", async () => {- mockExpertTeamEnabled = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");+describe("onboarding before payment", () => {+ it("collects role and pain points before showing the card requirement", async () => {render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();-+ fireEvent.click(await screen.findByTestId("step-role"));+ fireEvent.click(await screen.findByTestId("step-painpoints"));+ expect(await screen.findByTestId("step-subscription")).toBeDefined();+ expect(completeStep).not.toHaveBeenCalled();+ expect(submitProfile).not.toHaveBeenCalled();fireEvent.click(screen.getByRole("button", { name: "Back" }));- expect(await screen.findByTestId("step-autopilot")).toBeDefined();- });-- it("hides Back on the Team step", async () => {- mockExpertTeamEnabled = true;- render(<OnboardingPage />);- expect(await screen.findByTestId("step-team")).toBeDefined();- expect(screen.queryByRole("button", { name: "Back" })).toBeNull();- });-- it("resumes on Meet Otto when that is the highest step reached", async () => {- mockExpertTeamEnabled = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "2");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-autopilot")).toBeDefined();- expect(screen.queryByTestId("step-team")).toBeNull();+ expect(await screen.findByTestId("step-painpoints")).toBeDefined();});- it("puts the paywall before the intro steps and Preparing last", async () => {- mockExpertTeamEnabled = true;- mockFlagValue = true;+ it("keeps the brain dump and real hire step before the paywall", async () => {+ flags = { payment: true, team: true, brain: true, hire: true };render(<OnboardingPage />);+ for (const key of ["team", "autopilot", "role", "braindump", "hire"]) {+ fireEvent.click(await screen.findByTestId(`step-${key}`));+ }expect(await screen.findByTestId("step-subscription")).toBeDefined();-- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-team")).toBeDefined();-- act(() => useOnboardingWizardStore.getState().goToStep(6));- expect(await screen.findByTestId("step-preparing")).toBeDefined();+ expect(useOnboardingWizardStore.getState().completedSteps).toContain(+ "hire",+ );});- it("has no intro steps when the expert team flag is off", async () => {+ it("restores answers, hires and semantic progress in a fresh session", async () => {+ serverDraft = makeProgress({+ currentStep: "subscription",+ completedSteps: ["role", "painPoints"],+ otherRole: "Platform",+ selectedBilling: "yearly",+ hiredTemplateIds: ["maria"],+ });render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-team")).toBeNull();+ expect(await screen.findByTestId("step-subscription")).toBeDefined();+ expect(useOnboardingWizardStore.getState()).toMatchObject({+ role: "Engineering",+ otherRole: "Platform",+ painPoints: ["Reporting"],+ selectedBilling: "yearly",+ hiredTemplateIds: ["maria"],+ });});-});-describe("OnboardingPage — hire step", () => {- it("follows the brain dump with the hire step, then Preparing", async () => {- mockExpertTeamEnabled = true;- mockBrainDumpEnabled = true;- mockFlagValue = true;- // Paywall 1, Team 2, Meet Otto 3, Role 4, Brain dump 5, Hire 6,- // Preparing 7.- window.sessionStorage.setItem(STEP_STORAGE_KEY, "5");- currentSearchParams = new URLSearchParams("step=5");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-braindump")).toBeDefined();+ it.each(["subscription", "trial"])(+ "restores a cancelled %s checkout at the final paywall",+ async (kind) => {+ atPaywall();+ params = new URLSearchParams(`${kind}=cancelled`);+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-subscription")).toBeDefined();+ expect(useOnboardingWizardStore.getState().role).toBe("Engineering");+ expect(completeStep).not.toHaveBeenCalled();+ },+ );- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-hire")).toBeDefined();- await waitFor(() => {- expect(routerReplace).toHaveBeenCalledWith("/onboarding?step=6", {- scroll: false,+ it.each(["subscription", "trial"])(+ "resumes after a verified %s checkout without replaying onboarding",+ async (kind) => {+ atPaywall();+ params = new URLSearchParams(`${kind}=success&step=preparing`);+ if (kind === "trial") trial.active = true;+ else tier = "PRO";+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-preparing")).toBeDefined();+ await waitFor(() =>+ expect(submitProfile).toHaveBeenCalledWith(+ {+ user_name: "Reinier",+ user_role: "Engineering",+ pain_points: ["Reporting"],+ },+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ ),+ );+ fireEvent.click(screen.getByTestId("step-preparing"));+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ expect(completeStep).toHaveBeenCalledWith({+ step: "ONBOARDING_COMPLETE",});- });+ },+ );- act(() => useOnboardingWizardStore.getState().nextStep());+ it("waits for trial confirmation before changing its return URL", async () => {+ atPaywall();+ params = new URLSearchParams("trial=success");+ trial.ready = false;+ const view = render(<OnboardingPage />);+ expect(+ screen.getByText("Confirming your trial and card setup…"),+ ).toBeDefined();+ expect(routerReplace).not.toHaveBeenCalled();+ trial = { ...trial, ready: true, active: true };+ view.rerender(<OnboardingPage />);expect(await screen.findByTestId("step-preparing")).toBeDefined();});- it("lets Back return from the hire step to the brain dump", async () => {- mockExpertTeamEnabled = true;- mockBrainDumpEnabled = true;- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "6");- currentSearchParams = new URLSearchParams("step=6");+ it("never trusts success query parameters or completed subscription drafts as entitlement", async () => {+ serverDraft = makeProgress({+ currentStep: "preparing",+ completedSteps: ["role", "painPoints", "subscription"],+ });+ params = new URLSearchParams("step=preparing&subscription=success");render(<OnboardingPage />);- expect(await screen.findByTestId("step-hire")).toBeDefined();-- fireEvent.click(screen.getByRole("button", { name: "Back" }));- expect(await screen.findByTestId("step-braindump")).toBeDefined();+ expect(screen.getByText("Confirming your subscription…")).toBeDefined();+ expect(completeStep).not.toHaveBeenCalled();+ expect(screen.queryByTestId("step-preparing")).toBeNull();});- it("has no hire step without the brain dump it reads from", async () => {- mockExpertTeamEnabled = true;- mockFlagValue = true;- // Paywall 1, Team 2, Meet Otto 3, Role 4, Pain points 5, Preparing 6.- window.sessionStorage.setItem(STEP_STORAGE_KEY, "5");- currentSearchParams = new URLSearchParams("step=5");+ it("remaps a payment slot removed by a paid plan without skipping content", async () => {+ tier = "PRO";+ serverDraft = makeProgress({+ currentStep: "subscription",+ completedSteps: ["role"],+ });render(<OnboardingPage />);expect(await screen.findByTestId("step-painpoints")).toBeDefined();-- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-hire")).toBeNull();- });-- it("has no hire step when the expert team is off, even with the dump on", async () => {- mockBrainDumpEnabled = true;- mockFlagValue = true;- // Paywall 1, Role 2, Brain dump 3, Preparing 4.- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-braindump")).toBeDefined();-- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-hire")).toBeNull();- });-});--describe("OnboardingPage — flag-gated SubscriptionStep", () => {- it("renders Role at step 1 by default in flag-off mode", async () => {- mockFlagValue = false;- render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();expect(screen.queryByTestId("step-subscription")).toBeNull();});- it("clamps ?step=5 to step 1 when payments are gated off", async () => {- mockFlagValue = false;- currentSearchParams = new URLSearchParams("step=5");+ it("restores the earliest incomplete step when optional intro steps become enabled", async () => {+ atPaywall();+ flags.team = true;+ flags.hire = true;render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-preparing")).toBeNull();+ expect(await screen.findByTestId("step-team")).toBeDefined();});- it("treats step 3 as Preparing when payments are gated off", async () => {- mockFlagValue = false;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");+ it.each(["7", "2.5", "foo", "preparing"])(+ "ignores unsafe legacy or unreached progress %s",+ async (step) => {+ params = new URLSearchParams(`step=${step}`);+ sessionStorage.setItem("autogpt:onboarding-highest-step", "7");+ sessionStorage.setItem(+ "onboarding-wizard",+ JSON.stringify({ state: { role: "Another user" } }),+ );+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-role")).toBeDefined();+ expect(useOnboardingWizardStore.getState().role).toBe("");+ },+ );++ it("keeps self-host connection after personalization", async () => {+ flags.payment = false;+ local = true;+ serverDraft = makeProgress({+ currentStep: "connect",+ completedSteps: ["role", "painPoints"],+ });render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();+ expect(await screen.findByTestId("step-connect")).toBeDefined();});- it("renders SubscriptionStep first (step 1) when payments are enabled", async () => {- mockFlagValue = true;- currentSearchParams = new URLSearchParams("step=1");+ it("holds onboarding while authentication is loading", () => {+ authLoading = true;render(<OnboardingPage />);- expect(await screen.findByTestId("step-subscription")).toBeDefined();expect(screen.queryByTestId("step-role")).toBeNull();- expect(screen.queryByTestId("step-preparing")).toBeNull();+ expect(screen.getByRole("status").textContent).toBe("Loading your setup…");+ expect(getState).not.toHaveBeenCalled();});- it("renders Role at step 2 when payments are enabled — after the paywall", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "2");- currentSearchParams = new URLSearchParams("step=2");+ it("redirects completed users without rendering or resaving their draft", async () => {+ completed = true;render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();- expect(screen.queryByTestId("step-preparing")).toBeNull();+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ // /copilot redirects to /home, and that second navigation from this page+ // crashes the App Router (#15155).+ expect(routerReplace).not.toHaveBeenCalledWith("/copilot");+ expect(screen.queryByTestId("step-role")).toBeNull();+ expect(patchState).not.toHaveBeenCalled();});- it("treats step 4 as Preparing when payments are enabled", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");- currentSearchParams = new URLSearchParams("step=4");+ it("does not drop progress or redirect when completion fails", async () => {+ atPaywall();+ tier = "PRO";+ completeStep.mockRejectedValue(new Error("offline"));render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();+ fireEvent.click(await screen.findByTestId("step-preparing"));+ expect(await screen.findByText(/couldn't finish setting up/)).toBeDefined();+ expect(routerReplace).not.toHaveBeenCalledWith("/home");+ expect(localStorage.getItem(progressStorageKey("u1"))).not.toBeNull();});+});- it("clamps ?step=4 to the user's highest reached step (no fast-forward)", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=4");+describe("draft recovery", () => {+ it("saves each step in the background without holding navigation", async () => {+ patchState.mockImplementation(() => new Promise(() => {}));render(<OnboardingPage />);- // Highest reached is 3 (pain points), so manually editing the URL to- // step=4 should land the user back on step 3, not let them skip ahead.- expect(await screen.findByTestId("step-painpoints")).toBeDefined();- expect(screen.queryByTestId("step-preparing")).toBeNull();- });-- it("resumes from the highest reached step when ?step= is omitted", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- // No step param — user navigated to /onboarding directly.+ fireEvent.click(await screen.findByTestId("step-role"));+ fireEvent.click(await screen.findByTestId("step-painpoints"));+ expect(await screen.findByTestId("step-subscription")).toBeDefined();+ const localDraft = JSON.parse(+ localStorage.getItem(progressStorageKey("u1"))!,+ );+ expect(localDraft.progress.currentStep).toBe("subscription");+ expect(localDraft.pending).toBe(true);+ });++ it("recovers unsaved local answers over an older server snapshot", async () => {+ localStorage.setItem(+ progressStorageKey("u1"),+ JSON.stringify({+ pending: true,+ revision: 0,+ progress: makeProgress({+ currentStep: "painPoints",+ completedSteps: ["role"],+ role: "Design",+ }),+ }),+ );+ serverDraft = makeProgress({ role: "Old answer" });render(<OnboardingPage />);expect(await screen.findByTestId("step-painpoints")).toBeDefined();- expect(screen.queryByTestId("step-preparing")).toBeNull();+ expect(useOnboardingWizardStore.getState().role).toBe("Design");+ await waitFor(() =>+ expect(patchState).toHaveBeenCalledWith(+ expect.objectContaining({+ wizardProgress: expect.objectContaining({ role: "Design" }),+ }),+ expect.anything(),+ ),+ );});- it("rejects decimal step values and falls back to step 1 (paywall)", async () => {- mockFlagValue = true;- currentSearchParams = new URLSearchParams("step=2.5");+ it("surfaces failed loads instead of overwriting an inaccessible account draft", async () => {+ getState.mockRejectedValue(new Error("offline"));render(<OnboardingPage />);- expect(await screen.findByTestId("step-subscription")).toBeDefined();+ expect(await screen.findByText(/couldn't restore/)).toBeDefined();expect(screen.queryByTestId("step-role")).toBeNull();+ expect(patchState).not.toHaveBeenCalled();});- it("rejects non-numeric step values and falls back to step 1 (paywall)", async () => {- mockFlagValue = true;- currentSearchParams = new URLSearchParams("step=foo");+ it("surfaces save failures while allowing continuation", async () => {+ patchState.mockRejectedValue(new Error("offline"));render(<OnboardingPage />);+ fireEvent.click(await screen.findByTestId("step-role"));+ expect(+ await screen.findByText(/couldn't save your progress/),+ ).toBeDefined();+ fireEvent.click(screen.getByTestId("step-painpoints"));expect(await screen.findByTestId("step-subscription")).toBeDefined();});- it("lets ?step=2&subscription=success land on Role past the paywall", async () => {- // Simulates returning from a successful Stripe checkout. The highest- // reached step before the redirect was 1 (the paywall). Without the- // success-bypass, ceiling=min(1,2)=1 would clamp the user back onto the- // paywall they just paid through.- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "1");- currentSearchParams = new URLSearchParams("step=2&subscription=success");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();- });-- it("does not let a subscription=success return skip past the step after the paywall", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "1");- currentSearchParams = new URLSearchParams("step=4&subscription=success");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-preparing")).toBeNull();- });-- it("returns to SubscriptionStep on ?step=1&subscription=cancelled", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "1");- currentSearchParams = new URLSearchParams("step=1&subscription=cancelled");- render(<OnboardingPage />);+ it("discards in-memory answers on account switch and never saves them for the next user", async () => {+ atPaywall();+ const view = render(<OnboardingPage />);expect(await screen.findByTestId("step-subscription")).toBeDefined();- expect(useOnboardingWizardStore.getState().selectedPlan).toBeNull();+ await act(async () => {+ await useOnboardingWizardStore.getState().flushProgress?.();+ });+ user = { id: "u2", email: "[email protected]", user_metadata: {} };+ serverDraft = null;+ patchState.mockClear();+ view.rerender(<OnboardingPage />);+ expect(await screen.findByTestId("step-role")).toBeDefined();+ expect(useOnboardingWizardStore.getState().role).toBe("");+ fireEvent.click(screen.getByTestId("step-role"));+ await act(async () => {+ await useOnboardingWizardStore.getState().flushProgress?.();+ });+ expect(patchState).toHaveBeenCalledWith(+ expect.objectContaining({+ wizardProgress: expect.objectContaining({ role: "" }),+ }),+ expect.anything(),+ );});+});- it("skips SubscriptionStep when the user is already on a paid tier", async () => {- // Regression for paying users (admin-granted Pro, or accounts that- // pre-date ONBOARDING_COMPLETE) being kicked through onboarding and asked to- // pay again to escape. With ENABLE_PLATFORM_PAYMENT on and tier=PRO,- // step 3 must render Preparing — not SubscriptionStep.- mockFlagValue = true;- mockSubscriptionTier = "PRO";- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();- });+it("holds a paid-checkout return until its webhook updates entitlement", async () => {+ atPaywall();+ params = new URLSearchParams("subscription=success&step=preparing");+ const view = render(<OnboardingPage />);+ expect(screen.getByText("Confirming your subscription…")).toBeDefined();+ expect(screen.queryByTestId("step-subscription")).toBeNull();+ tier = "PRO";+ view.rerender(<OnboardingPage />);+ expect(await screen.findByTestId("step-preparing")).toBeDefined();+ expect(useOnboardingWizardStore.getState().role).toBe("Engineering");+});- it("clamps ?step=4 to preparingStep=3 for paid users", async () => {- // For paid users the wizard is 2-step (preparingStep=3). A URL pointing- // at the paywall layout's preparingStep must clamp down to 3, not strand- // the user above the ceiling.- mockFlagValue = true;- mockSubscriptionTier = "MAX";- window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");- currentSearchParams = new URLSearchParams("step=4");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-subscription")).toBeNull();+it("ignores a late draft response from an account that has been switched away", async () => {+ let release: ((value: unknown) => void) | undefined;+ getState.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),+ );+ const view = render(<OnboardingPage />);+ user = { id: "u2", email: "[email protected]", user_metadata: {} };+ view.rerender(<OnboardingPage />);+ expect(await screen.findByTestId("step-role")).toBeDefined();+ await act(async () => {+ release?.({+ status: 200,+ data: {+ userId: "u1",+ completedSteps: [],+ wizardRevision: 0,+ wizardProgress: makeProgress({ role: "Private old answer" }),+ },+ });});+ expect(useOnboardingWizardStore.getState().role).toBe("");+ expect(useOnboardingWizardStore.getState().userID).toBe("u2");+});- it("still shows SubscriptionStep for NO_TIER users with payments enabled", async () => {- mockFlagValue = true;- mockSubscriptionTier = "NO_TIER";- currentSearchParams = new URLSearchParams("step=1");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-subscription")).toBeDefined();- expect(screen.queryByTestId("step-role")).toBeNull();- });+it("asks before replacing a stale local draft with another session's progress", async () => {+ localStorage.setItem(+ progressStorageKey("u1"),+ JSON.stringify({+ pending: true,+ revision: 0,+ progress: makeProgress({ role: "Local answer" }),+ }),+ );+ serverDraft = makeProgress({ role: "Newer answer" });+ revision = 2;+ render(<OnboardingPage />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Reload latest progress" }),+ );+ expect(await screen.findByTestId("step-role")).toBeDefined();+ expect(useOnboardingWizardStore.getState().role).toBe("Newer answer");+});- it("waits for auth before initialising (no premature step lock)", async () => {- // Regression: LD can resolve while auth is still loading. Without- // gating on isUserLoading, isReady flips true (the !isLoggedIn branch- // short-circuits), init runs against the pre-tier preparingStep (5)- // and a returning user with highestStep=5 lands on currentStep=5.- // When tier resolves to PRO, preparingStep becomes 4 — but the- // hasInitialized guard blocks re-init, leaving currentStep=5 with- // no matching step guard (blank page).- mockFlagValue = true;- mockSubscriptionTier = "PRO";- mockAuthState = { isLoggedIn: false, isUserLoading: true };- window.sessionStorage.setItem(STEP_STORAGE_KEY, "5");- render(<OnboardingPage />);- // Nothing should render while auth is still loading.- expect(screen.queryByTestId("step-welcome")).toBeNull();- expect(screen.queryByTestId("step-preparing")).toBeNull();- expect(screen.queryByTestId("step-subscription")).toBeNull();- // After init defers (auth not ready), currentStep stays at the- // store default of 1 — no premature jump to 5.- expect(useOnboardingWizardStore.getState().currentStep).toBe(1);+it("recognizes a successful save whose response was lost before navigation", async () => {+ const draft = makeProgress({+ currentStep: "painPoints",+ completedSteps: ["role"],});+ localStorage.setItem(+ progressStorageKey("u1"),+ JSON.stringify({ pending: true, revision: 0, progress: draft }),+ );+ serverDraft = draft;+ revision = 1;+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-painpoints")).toBeDefined();+ expect(+ screen.queryByRole("button", { name: "Reload latest progress" }),+ ).toBeNull();+ await act(async () => {+ await useOnboardingWizardStore.getState().flushProgress?.();+ });+ expect(patchState).not.toHaveBeenCalled();+ expect(+ JSON.parse(localStorage.getItem(progressStorageKey("u1"))!),+ ).toMatchObject({+ pending: false,+ revision: 1,+ });+ await act(async () => {+ useOnboardingWizardStore.getState().setRole("Design");+ await useOnboardingWizardStore.getState().flushProgress?.();+ });+ expect(patchState).toHaveBeenCalledWith(+ expect.objectContaining({ wizardRevision: 1 }),+ expect.anything(),+ );+});- it("submits the profile under the account's name on reaching Preparing", async () => {- // The wizard no longer asks for a name, so the profile carries what the- // account already knows.- mockFlagValue = false;- mockUser = {- id: "u1",- email: "[email protected]",- user_metadata: { name: "Reinier Bot" },- };- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- useOnboardingWizardStore.setState({- role: "Engineering",- painPoints: ["slow builds"],- });- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- await waitFor(() => {- expect(submitOnboardingProfile).toHaveBeenCalledWith({- user_name: "Reinier",- user_role: "Engineering",- pain_points: ["slow builds"],- });- });- });+it("surfaces a revision conflict without overwriting newer server answers", async () => {+ patchState.mockRejectedValue({ status: 409 });+ render(<OnboardingPage />);+ fireEvent.click(await screen.findByTestId("step-role"));+ expect(+ await screen.findByRole("button", { name: "Reload latest progress" }),+ ).toBeDefined();+ expect(screen.queryByTestId("step-role")).toBeNull();+ expect(+ JSON.parse(localStorage.getItem(progressStorageKey("u1"))!).pending,+ ).toBe(true);+});- it("cuts a restored Other role to the 100 code points the profile accepts", async () => {- mockFlagValue = false;- mockUser = {- id: "u1",- email: "[email protected]",- user_metadata: { name: "Reinier Bot" },- };- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- useOnboardingWizardStore.setState({- role: "Other",- otherRole: "🙂".repeat(150),- painPoints: ["slow builds"],- });- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- await waitFor(() => {- expect(submitOnboardingProfile).toHaveBeenCalledWith({- user_name: "Reinier",- user_role: "🙂".repeat(100),- pain_points: ["slow builds"],- });- });- });+it("reports onboarding completion to Google Ads once after confirmed completion", async () => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv(+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",+ "onboarding_complete=OC",+ );+ const calls = installGtagShim();+ atPaywall();+ tier = "PRO";+ render(<OnboardingPage />);+ const finish = await screen.findByTestId("step-preparing");+ fireEvent.click(finish);+ fireEvent.click(finish);+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ expect(calls.filter((call) => call[1] === "conversion")).toHaveLength(1);+ expect(completeStep).toHaveBeenCalledOnce();+});- it("does not submit a profile when no role was chosen", async () => {- mockFlagValue = false;- mockUser = { id: "u1", email: "[email protected]", user_metadata: {} };- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(submitOnboardingProfile).not.toHaveBeenCalled();- });+it("reports no Ads completion when the server rejects completion", async () => {+ vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");+ vi.stubEnv(+ "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",+ "onboarding_complete=OC",+ );+ const calls = installGtagShim();+ atPaywall();+ tier = "PRO";+ completeStep.mockRejectedValue(new Error("offline"));+ render(<OnboardingPage />);+ fireEvent.click(await screen.findByTestId("step-preparing"));+ expect(await screen.findByText(/couldn't finish setting up/)).toBeDefined();+ expect(calls.filter((call) => call[1] === "conversion")).toEqual([]);+});- it("redirects straight to /home when onboarding is already complete", async () => {- mockCompletedSteps = ["ONBOARDING_COMPLETE"];- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- render(<OnboardingPage />);- await waitFor(() => {- expect(routerReplace).toHaveBeenCalledWith("/home");+it.each(["", "Other"])(+ "returns an incomplete %s role to editing before completing onboarding",+ async (role) => {+ serverDraft = makeProgress({+ currentStep: "preparing",+ completedSteps: ["role", "painPoints"],+ role,+ otherRole: " ",});- // The wizard never renders and the resume ceiling is cleared.- expect(screen.queryByTestId("step-role")).toBeNull();- expect(window.sessionStorage.getItem(STEP_STORAGE_KEY)).toBeNull();- });-- it("marks ONBOARDING_COMPLETE and redirects when Preparing finishes", async () => {- mockFlagValue = false;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");+ tier = "PRO";render(<OnboardingPage />);+ expect(await screen.findByTestId("step-role")).toBeDefined();+ expect(submitProfile).not.toHaveBeenCalled();+ expect(completeStep).not.toHaveBeenCalled();+ act(() => useOnboardingWizardStore.getState().setRole("Design"));+ fireEvent.click(screen.getByTestId("step-role"));+ fireEvent.click(await screen.findByTestId("step-painpoints"));fireEvent.click(await screen.findByTestId("step-preparing"));- await waitFor(() => {- expect(routerReplace).toHaveBeenCalledWith("/home");- });- expect(completeOnboardingStep).toHaveBeenCalledWith({- step: "ONBOARDING_COMPLETE",- });- expect(window.sessionStorage.getItem(STEP_STORAGE_KEY)).toBeNull();+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ expect(submitProfile).toHaveBeenCalledWith(+ expect.objectContaining({ user_role: "Design" }),+ expect.anything(),+ );+ expect(completeStep).toHaveBeenCalledOnce();+ },+);++it("rejects a response for another signed-in account without hydrating or caching it", async () => {+ getState.mockResolvedValue({+ status: 200,+ data: {+ userId: "another-user",+ wizardRevision: 0,+ completedSteps: [],+ wizardProgress: makeProgress({ role: "Private answer" }),+ },});+ render(<OnboardingPage />);+ expect(await screen.findByText(/signed-in account changed/)).toBeDefined();+ expect(useOnboardingWizardStore.getState().role).toBe("");+ expect(localStorage.getItem(progressStorageKey("u1"))).toBeNull();+ expect(patchState).not.toHaveBeenCalled();+});- it("reports onboarding_complete to Google Ads when Preparing finishes", async () => {- vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");- vi.stubEnv(- "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",- "onboarding_complete=OC",+describe("profile saving before completion", () => {+ it("waits for the in-flight profile save before completing or clearing the draft", async () => {+ atPaywall();+ tier = "PRO";+ let release: ((value: unknown) => void) | undefined;+ submitProfile.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),);- const gtagCalls = installGtagShim();- mockFlagValue = false;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");render(<OnboardingPage />);fireEvent.click(await screen.findByTestId("step-preparing"));- await waitFor(() => {- expect(routerReplace).toHaveBeenCalledWith("/home");+ await act(async () => {+ await useOnboardingWizardStore.getState().flushProgress?.();});+ expect(submitProfile).toHaveBeenCalledOnce();+ expect(completeStep).not.toHaveBeenCalled();+ expect(routerReplace).not.toHaveBeenCalledWith("/home");+ expect(localStorage.getItem(progressStorageKey("u1"))).not.toBeNull();+ await act(async () => release?.({ status: 200 }));+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ expect(submitProfile).toHaveBeenCalledOnce();+ expect(completeStep).toHaveBeenCalledOnce();+ expect(localStorage.getItem(progressStorageKey("u1"))).toBeNull();+ });++ it.each(["network", "http"])(+ "keeps a %s profile-save failure visible and retries before completion",+ async (failure) => {+ atPaywall();+ tier = "PRO";+ if (failure === "network")+ submitProfile.mockRejectedValue(new Error("offline"));+ else submitProfile.mockResolvedValue({ status: 503 });+ render(<OnboardingPage />);+ expect(+ await screen.findByText(/couldn't save your profile/i),+ ).toBeDefined();+ fireEvent.click(screen.getByTestId("step-preparing"));+ await waitFor(() => expect(submitProfile).toHaveBeenCalledTimes(2));+ expect(completeStep).not.toHaveBeenCalled();+ expect(routerReplace).not.toHaveBeenCalledWith("/home");+ expect(localStorage.getItem(progressStorageKey("u1"))).not.toBeNull();+ submitProfile.mockResolvedValue({ status: 200 });+ fireEvent.click(screen.getByRole("button", { name: /try again/i }));+ await waitFor(() => expect(routerReplace).toHaveBeenCalledWith("/home"));+ expect(submitProfile).toHaveBeenCalledTimes(3);+ expect(completeStep).toHaveBeenCalledOnce();+ },+ );- expect(gtagCalls).toContainEqual([- "event",- "conversion",- { send_to: "AW-123/OC" },- ]);- });-- it("reports no onboarding_complete when the API never confirms", async () => {- vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");- vi.stubEnv(- "NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS",- "onboarding_complete=OC",+ it("does not complete either account when an old profile save resolves after switching users", async () => {+ atPaywall();+ tier = "PRO";+ let release: ((value: unknown) => void) | undefined;+ submitProfile.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),);- const gtagCalls = installGtagShim();- // All three attempts fail: the user still lands on /home, but the- // backend never recorded the milestone, so nothing converted.- completeOnboardingStep.mockRejectedValue(new Error("500"));- mockFlagValue = false;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);+ const view = render(<OnboardingPage />);fireEvent.click(await screen.findByTestId("step-preparing"));- await waitFor(- () => {- expect(routerReplace).toHaveBeenCalledWith("/home");- },- { timeout: 5000 },- );-- expect(completeOnboardingStep).toHaveBeenCalledTimes(3);- expect(gtagCalls.filter((call) => call[1] === "conversion")).toEqual([]);- }, 10000);-- it("preserves form data on mount (zustand persist; no reset-on-init)", async () => {- // Regression test for the 422 caused by init's old `reset()` wiping- // the role on every mount. With zustand persist, refreshing mid-wizard- // must preserve what the user already chose.- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- useOnboardingWizardStore.setState({- role: "Engineering",- painPoints: ["slow builds"],+ await act(async () => {+ await useOnboardingWizardStore.getState().flushProgress?.();});- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-painpoints")).toBeDefined();- const state = useOnboardingWizardStore.getState();- expect(state.role).toBe("Engineering");- expect(state.painPoints).toEqual(["slow builds"]);- });-});--describe("OnboardingPage — self-host closes with the connection", () => {- it("renders Role first on a self-host install", async () => {- mockIsLocal = true;- currentSearchParams = new URLSearchParams("step=1");- render(<OnboardingPage />);+ user = { id: "u2", email: "[email protected]", user_metadata: {} };+ serverDraft = null;+ view.rerender(<OnboardingPage />);expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-connect")).toBeNull();- });-- it("puts ConnectStep last (step 3), after the profile", async () => {- mockIsLocal = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-connect")).toBeDefined();- expect(screen.queryByTestId("step-painpoints")).toBeNull();- expect(screen.queryByTestId("step-preparing")).toBeNull();- });-- it("treats step 4 as Preparing on self-host", async () => {- mockIsLocal = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "4");- currentSearchParams = new URLSearchParams("step=4");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-connect")).toBeNull();- });-- it("does not insert it on cloud", async () => {- mockIsLocal = false;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-connect")).toBeNull();+ await act(async () => release?.({ status: 200 }));+ expect(completeStep).not.toHaveBeenCalled();+ expect(routerReplace).not.toHaveBeenCalledWith("/home");+ expect(useOnboardingWizardStore.getState().userID).toBe("u2");+ expect(localStorage.getItem(progressStorageKey("u1"))).not.toBeNull();});-- it("yields to the paywall rather than showing both model steps", async () => {- // Payments and self-host are mutually exclusive in practice; if a- // deployment ever had both, only one step can take the slot.- mockIsLocal = true;- mockFlagValue = true;- currentSearchParams = new URLSearchParams("step=1");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-subscription")).toBeDefined();- expect(screen.queryByTestId("step-connect")).toBeNull();- });-});--it("never offers Back into the paywall, with or without the intro", async () => {- mockFlagValue = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "2");- currentSearchParams = new URLSearchParams("step=2");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByRole("button", { name: "Back" })).toBeNull();- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-painpoints")).toBeDefined();- fireEvent.click(screen.getByRole("button", { name: "Back" }));- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByRole("button", { name: "Back" })).toBeNull();});-it("hides Back on the first intro after the paywall", async () => {- mockFlagValue = true;- mockExpertTeamEnabled = true;- window.sessionStorage.setItem(STEP_STORAGE_KEY, "2");- currentSearchParams = new URLSearchParams("step=2");- render(<OnboardingPage />);- expect(await screen.findByTestId("step-team")).toBeDefined();- expect(screen.queryByRole("button", { name: "Back" })).toBeNull();-});--it("skips both intro and hire when hiring is disabled independently of the team flag", async () => {- mockExpertTeamEnabled = true;- mockHireExpertsEnabled = false;- mockBrainDumpEnabled = true;- render(<OnboardingPage />);- expect(await screen.findByTestId("step-role")).toBeDefined();- expect(screen.queryByTestId("step-team")).toBeNull();- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-braindump")).toBeDefined();- act(() => useOnboardingWizardStore.getState().nextStep());- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(screen.queryByTestId("step-hire")).toBeNull();-});--it("submits the profile once if account data arrives after Preparing", async () => {- window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");- currentSearchParams = new URLSearchParams("step=3");- useOnboardingWizardStore.setState({- role: "Engineering",- painPoints: ["slow builds"],- });- const { rerender } = render(<OnboardingPage />);- expect(await screen.findByTestId("step-preparing")).toBeDefined();- expect(submitOnboardingProfile).not.toHaveBeenCalled();- mockUser = {- id: "u1",- email: "[email protected]",- user_metadata: { name: "Reinier Bot" },- };- rerender(<OnboardingPage />);- await waitFor(() =>- expect(submitOnboardingProfile).toHaveBeenCalledWith({- user_name: "Reinier",- user_role: "Engineering",- pain_points: ["slow builds"],- }),+it("lets a new account finish while the previous account's profile save is outstanding", async () => {+ atPaywall();+ tier = "PRO";+ let release: ((value: unknown) => void) | undefined;+ submitProfile.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),);- mockUser = { ...mockUser };- rerender(<OnboardingPage />);- expect(submitOnboardingProfile).toHaveBeenCalledTimes(1);+ const view = render(<OnboardingPage />);+ fireEvent.click(await screen.findByTestId("step-preparing"));+ await act(async () => {+ await useOnboardingWizardStore.getState().flushProgress?.();+ });+ user = { id: "u2", email: "[email protected]", user_metadata: {} };+ serverDraft = makeProgress({+ currentStep: "preparing",+ completedSteps: ["role", "painPoints"],+ role: "Design",+ });+ view.rerender(<OnboardingPage />);+ await waitFor(() => expect(submitProfile).toHaveBeenCalledTimes(2));+ fireEvent.click(await screen.findByTestId("step-preparing"));+ await waitFor(() => expect(completeStep).toHaveBeenCalledOnce());+ expect(routerReplace).toHaveBeenCalledWith("/home");+ await act(async () => release?.({ status: 200 }));+ expect(completeStep).toHaveBeenCalledOnce();+ expect(screen.queryByText(/couldn't save your profile/i)).toBeNull();});--it.each([1, 2])(- "preserves reached step %s on a checkout return when payment is disabled",- async (highest) => {- window.sessionStorage.setItem(STEP_STORAGE_KEY, String(highest));- currentSearchParams = new URLSearchParams("step=4&subscription=success");- render(<OnboardingPage />);- expect(- await screen.findByTestId(- highest === 1 ? "step-role" : "step-painpoints",- ),- ).toBeDefined();- expect(screen.queryByTestId("step-preparing")).toBeNull();- },-);diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress-fixture.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress-fixture.tsnew file mode 100644index 0000000000..d64640c513--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress-fixture.ts@@ -0,0 +1,20 @@+import type { OnboardingWizardProgress } from "@/app/api/__generated__/models/onboardingWizardProgress";++export function makeProgress(+ overrides: Partial<OnboardingWizardProgress> = {},+): OnboardingWizardProgress {+ return {+ version: 1,+ currentStep: "role",+ completedSteps: [],+ role: "Engineering",+ otherRole: "",+ painPoints: ["Reporting"],+ otherPainPoint: "",+ selectedBilling: "monthly",+ hasUserSelectedBilling: false,+ selectedCountryCode: "US",+ hiredTemplateIds: [],+ ...overrides,+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress-saver.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress-saver.test.tsnew file mode 100644index 0000000000..cc3b8664f7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress-saver.test.ts@@ -0,0 +1,147 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createProgressSaver } from "../progress-saver";+import { readLocalProgress } from "../progress";+import { makeProgress } from "./progress-fixture";++beforeEach(() => {+ vi.useFakeTimers();+ localStorage.clear();+});+afterEach(() => {+ vi.useRealTimers();+});++describe("onboarding draft outbox", () => {+ it("serializes writes and keeps the newest progress while an older write is pending", async () => {+ let release: ((revision: number) => void) | undefined;+ const save = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<number>((resolve) => {+ release = resolve;+ }),+ )+ .mockResolvedValue(2);+ const saver = createProgressSaver({+ initialRevision: 0,+ onConflict: vi.fn(),+ userID: "one",+ save,+ onError: vi.fn(),+ });+ saver.enqueue(makeProgress({ role: "First" }));+ const flushing = saver.flush();+ saver.enqueue(+ makeProgress({+ role: "Latest",+ currentStep: "painPoints",+ completedSteps: ["role"],+ }),+ );+ expect(save).toHaveBeenCalledTimes(1);+ expect(readLocalProgress("one")?.pending).toBe(true);+ release?.(1);+ await flushing;+ expect(save).toHaveBeenCalledTimes(2);+ expect(save.mock.calls[1][0].role).toBe("Latest");+ expect(readLocalProgress("one")).toMatchObject({+ pending: false,+ progress: { role: "Latest" },+ });+ saver.dispose();+ });++ it("keeps failed writes durable and retries without another user interaction", async () => {+ const save = vi+ .fn()+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValue(2);+ const onError = vi.fn();+ const saver = createProgressSaver({+ initialRevision: 0,+ onConflict: vi.fn(),+ userID: "one",+ save,+ onError,+ });+ saver.enqueue(makeProgress());+ await expect(saver.flush()).rejects.toThrow("offline");+ expect(readLocalProgress("one")?.pending).toBe(true);+ await vi.advanceTimersByTimeAsync(1000);+ expect(save).toHaveBeenCalledTimes(2);+ expect(onError).toHaveBeenLastCalledWith(null);+ expect(readLocalProgress("one")?.pending).toBe(false);+ saver.dispose();+ });++ it("aborts an old account request and leaves its draft scoped to that account", async () => {+ let release: ((revision: number) => void) | undefined;+ const save = vi.fn(+ (_progress: unknown, _revision: number, _signal: AbortSignal) =>+ new Promise<number>((resolve) => {+ release = resolve;+ }),+ );+ const saver = createProgressSaver({+ initialRevision: 0,+ onConflict: vi.fn(),+ userID: "one",+ save,+ onError: vi.fn(),+ });+ saver.enqueue(makeProgress({ role: "Private answer" }));+ const flushing = saver.flush();+ saver.dispose();+ expect(save.mock.calls[0][2].aborted).toBe(true);+ release?.(1);+ await expect(flushing).rejects.toThrow("account changed");+ await vi.advanceTimersByTimeAsync(30_000);+ expect(save).toHaveBeenCalledTimes(1);+ expect(readLocalProgress("one")?.pending).toBe(true);+ expect(readLocalProgress("two")).toBeNull();+ });+});++it("times out a hung request so checkout flush can recover", async () => {+ const save = vi.fn(+ (_progress: unknown, _revision: number, _signal: AbortSignal) =>+ new Promise<number>(() => {}),+ );+ const saver = createProgressSaver({+ initialRevision: 0,+ onConflict: vi.fn(),+ userID: "one",+ save,+ onError: vi.fn(),+ });+ saver.enqueue(makeProgress());+ const rejected = expect(saver.flush()).rejects.toThrow("timed out");+ await vi.advanceTimersByTimeAsync(10_000);+ await rejected;+ expect(save.mock.calls[0][2].aborted).toBe(true);+ expect(readLocalProgress("one")?.pending).toBe(true);+ saver.dispose();+});++it("stops automatic retries when another session has updated the server revision", async () => {+ const save = vi.fn().mockRejectedValue({ status: 409 });+ const onConflict = vi.fn();+ const saver = createProgressSaver({+ initialRevision: 3,+ userID: "one",+ save,+ onError: vi.fn(),+ onConflict,+ });+ saver.enqueue(makeProgress());+ await expect(saver.flush()).rejects.toEqual({ status: 409 });+ await vi.advanceTimersByTimeAsync(30_000);+ expect(save).toHaveBeenCalledOnce();+ expect(onConflict).toHaveBeenCalledOnce();+ expect(readLocalProgress("one")).toMatchObject({+ revision: 3,+ pending: true,+ });+ saver.dispose();+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress.test.tsnew file mode 100644index 0000000000..c0c6ff3366--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/progress.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { readProgress, resumeStep } from "../progress";+import { buildStepLayout } from "../store";+import { makeProgress } from "./progress-fixture";++it.each([+ null,+ {},+ { version: 0 },+ { currentStep: 7 },+ { ...makeProgress(), completedSteps: [7] },+])("rejects malformed or old numeric drafts", (value) => {+ expect(readProgress(value)).toBeNull();+});++describe("semantic progress", () => {+ it("resumes after an optional hire step disappears", () => {+ expect(+ resumeStep({+ progress: makeProgress({+ currentStep: "hire",+ completedSteps: ["role", "painPoints"],+ }),+ steps: buildStepLayout({ hasPaywall: true }),+ }),+ ).toBe(3);+ });+ it("honors a previous-step URL without allowing an incomplete step to be skipped", () => {+ const progress = makeProgress({+ currentStep: "subscription",+ completedSteps: ["role", "painPoints"],+ });+ const steps = buildStepLayout({ hasPaywall: true });+ expect(resumeStep({ progress, steps, requestedStep: "role" })).toBe(1);+ expect(resumeStep({ progress, steps, requestedStep: "preparing" })).toBe(3);+ });+});++it.each([+ { painPoints: [""] },+ { hiredTemplateIds: [""] },+ { role: "bad\u0000input" },+ { otherRole: "x".repeat(101) },+])("rejects drafts the API cannot save", (fields) => {+ expect(readProgress(makeProgress(fields))).toBeNull();+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/store.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/store.test.tsindex fcdc22c453..889c62074b 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/store.test.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/store.test.ts@@ -197,27 +197,27 @@ describe("useOnboardingWizardStore", () => {});describe("buildStepLayout", () => {- it("leads with the paywall and slots the hire step after the brain dump", () => {+ it("places the paywall after personalization and hiring", () => {expect(buildStepLayout({ hasIntro: true, hasHire: true, hasPaywall: true }),).toEqual({- subscription: 1,- team: 2,- autopilot: 3,- role: 4,- painPoints: 5,- hire: 6,+ team: 1,+ autopilot: 2,+ role: 3,+ painPoints: 4,+ hire: 5,+ subscription: 6,preparing: 7,});});it("leaves the hire step out when it is off", () => {expect(buildStepLayout({ hasIntro: true, hasPaywall: true })).toEqual({- subscription: 1,- team: 2,- autopilot: 3,- role: 4,- painPoints: 5,+ team: 1,+ autopilot: 2,+ role: 3,+ painPoints: 4,+ subscription: 5,preparing: 6,});});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.tsindex 33cca00a54..d0f37e1e51 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/tracking.test.ts@@ -16,22 +16,21 @@ vi.mock("posthog-js", () => ({ default: posthog }));import {buildStepLayout,NO_PAYWALL_STEPS,- PAYWALL_FIRST_STEPS,+ PAYWALL_LAST_STEPS,} from "../store";import { onboardingStepKey, trackOnboardingStep } from "../tracking";describe("onboardingStepKey", () => {- // Pain points is step 3 with the paywall and step 2 without it, so the- // number alone can't identify a step across cohorts.+ // Optional steps shift numeric positions; analytics keeps stable names.it("maps the same key across both step layouts", () => {expect(- onboardingStepKey(PAYWALL_FIRST_STEPS, PAYWALL_FIRST_STEPS.painPoints),+ onboardingStepKey(PAYWALL_LAST_STEPS, PAYWALL_LAST_STEPS.painPoints),).toBe("pain_points");expect(onboardingStepKey(NO_PAYWALL_STEPS, NO_PAYWALL_STEPS.painPoints),).toBe("pain_points");expect(- onboardingStepKey(PAYWALL_FIRST_STEPS, PAYWALL_FIRST_STEPS.preparing),+ onboardingStepKey(PAYWALL_LAST_STEPS, PAYWALL_LAST_STEPS.preparing),).toBe("preparing");expect(onboardingStepKey(NO_PAYWALL_STEPS, NO_PAYWALL_STEPS.preparing),@@ -40,10 +39,11 @@ describe("onboardingStepKey", () => {it("names the intro steps when the layout has them", () => {const steps = buildStepLayout({ hasIntro: true, hasPaywall: true });- expect(onboardingStepKey(steps, 1)).toBeNull();- expect(onboardingStepKey(steps, 2)).toBe("team");- expect(onboardingStepKey(steps, 3)).toBe("autopilot");- expect(onboardingStepKey(steps, 4)).toBe("role");+ expect(onboardingStepKey(steps, 1)).toBe("team");+ expect(onboardingStepKey(steps, 2)).toBe("autopilot");+ expect(onboardingStepKey(steps, 3)).toBe("role");+ expect(onboardingStepKey(steps, 4)).toBe("pain_points");+ expect(onboardingStepKey(steps, 5)).toBeNull();expect(onboardingStepKey(steps, 6)).toBe("preparing");});@@ -53,7 +53,8 @@ describe("onboardingStepKey", () => {hasHire: true,hasPaywall: true,});- expect(onboardingStepKey(steps, 6)).toBe("hire");+ expect(onboardingStepKey(steps, 5)).toBe("hire");+ expect(onboardingStepKey(steps, 6)).toBeNull();expect(onboardingStepKey(steps, 7)).toBe("preparing");});@@ -61,7 +62,7 @@ describe("onboardingStepKey", () => {// double-count the top of the funnel.it("returns null for the subscription step", () => {expect(- onboardingStepKey(PAYWALL_FIRST_STEPS, PAYWALL_FIRST_STEPS.subscription),+ onboardingStepKey(PAYWALL_LAST_STEPS, PAYWALL_LAST_STEPS.subscription),).toBeNull();});});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/wizard-progress.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/wizard-progress.test.tsxnew file mode 100644index 0000000000..c3c4ba06e2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/wizard-progress.test.tsx@@ -0,0 +1,248 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { readLocalProgress, writeLocalProgress } from "../progress";+import { PAYWALL_LAST_STEPS, useOnboardingWizardStore } from "../store";+import { useWizardProgress } from "../useWizardProgress";+import { makeProgress } from "./progress-fixture";++const { getState, patchState } = vi.hoisted(() => ({+ getState: vi.fn(),+ patchState: vi.fn(),+}));+vi.mock("@/app/api/__generated__/endpoints/onboarding/onboarding", () => ({+ getV1OnboardingState: getState,+ patchV1UpdateOnboardingState: patchState,+}));+let params = new URLSearchParams();+vi.mock("next/navigation", () => ({+ useRouter: () => ({ replace: vi.fn() }),+ useSearchParams: () => params,+}));++function response(progress = makeProgress(), revision = 4, userID = "u1") {+ return {+ status: 200,+ data: {+ userId: userID,+ completedSteps: [],+ wizardProgress: progress,+ wizardRevision: revision,+ },+ };+}++function mountWizard(userID = "u1") {+ return renderHook(+ ({ userID }) =>+ useWizardProgress({+ userID,+ ready: true,+ steps: PAYWALL_LAST_STEPS,+ }),+ { initialProps: { userID } },+ );+}++async function settle() {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.resetAllMocks();+ params = new URLSearchParams();+ localStorage.clear();+ useOnboardingWizardStore.getState().reset();+ getState.mockResolvedValue(response());+ patchState.mockImplementation(({ wizardRevision, wizardUserId }) =>+ Promise.resolve({+ status: 200,+ data: { userId: wizardUserId, wizardRevision: wizardRevision + 1 },+ }),+ );+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++it("restores a server draft without saving or depending on property order", async () => {+ const reordered = Object.fromEntries(+ Object.entries(makeProgress()).reverse(),+ );+ getState.mockResolvedValue({+ ...response(),+ data: { ...response().data, wizardProgress: reordered },+ });+ const { result } = mountWizard();+ await settle();+ expect(result.current.isReady).toBe(true);+ expect(patchState).not.toHaveBeenCalled();+ expect(readLocalProgress("u1")).toEqual({+ progress: makeProgress(),+ revision: 4,+ pending: false,+ });+});++it("does not save an empty wizard until its first edit", async () => {+ getState.mockResolvedValue({+ ...response(),+ data: { ...response().data, wizardProgress: null, wizardRevision: 0 },+ });+ mountWizard();+ await settle();+ expect(patchState).not.toHaveBeenCalled();+ act(() => useOnboardingWizardStore.getState().setRole("Founder"));+ await settle();+ expect(patchState).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ wizardProgress: expect.objectContaining({ role: "Founder" }),+ wizardRevision: 0,+ wizardUserId: "u1",+ }),+ expect.anything(),+ );+});++it("saves the first edit after a clean restore with the loaded revision", async () => {+ mountWizard();+ await settle();+ act(() => useOnboardingWizardStore.getState().setOtherRole("Founder"));+ await settle();+ expect(patchState).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ wizardProgress: makeProgress({ otherRole: "Founder" }),+ wizardRevision: 4,+ }),+ expect.anything(),+ );+});++it.each([false, true])(+ "replays pending changes when offline=%s",+ async (offline) => {+ const changed = makeProgress({ role: "Founder" });+ writeLocalProgress("u1", changed, true, 4);+ if (offline) getState.mockRejectedValue(new Error("Offline"));+ mountWizard();+ await settle();+ expect(patchState).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ wizardProgress: changed, wizardRevision: 4 }),+ expect.anything(),+ );+ },+);++it("acknowledges an uncertain save already present on the server without another write", async () => {+ writeLocalProgress("u1", makeProgress(), true, 3);+ mountWizard();+ await settle();+ expect(patchState).not.toHaveBeenCalled();+ expect(readLocalProgress("u1")).toEqual({+ progress: makeProgress(),+ revision: 4,+ pending: false,+ });+});++it("keeps a clean offline cache clean and saves subsequent edits", async () => {+ writeLocalProgress("u1", makeProgress(), false, 4);+ getState.mockRejectedValue(new Error("Offline"));+ const { result } = mountWizard();+ await settle();+ expect(patchState).not.toHaveBeenCalled();+ expect(result.current.error).not.toMatch(/retrying/i);+ act(() => useOnboardingWizardStore.getState().setRole("Founder"));+ await settle();+ expect(patchState).toHaveBeenCalledOnce();+});++it("persists a requested-step correction", async () => {+ params = new URLSearchParams("step=role");+ getState.mockResolvedValue(+ response(+ makeProgress({+ currentStep: "subscription",+ completedSteps: ["role", "painPoints"],+ }),+ ),+ );+ mountWizard();+ await settle();+ expect(patchState).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ wizardProgress: makeProgress({+ currentStep: "role",+ completedSteps: ["role", "painPoints"],+ }),+ wizardRevision: 4,+ }),+ expect.anything(),+ );+});++it("does not acknowledge a different outbox written by another tab during restore", async () => {+ writeLocalProgress("u1", makeProgress(), true, 3);+ getState.mockImplementation(async () => {+ writeLocalProgress("u1", makeProgress({ role: "Newer tab" }), true, 4);+ return response();+ });+ mountWizard();+ await settle();+ expect(patchState).not.toHaveBeenCalled();+ expect(readLocalProgress("u1")).toEqual({+ progress: makeProgress({ role: "Newer tab" }),+ revision: 4,+ pending: true,+ });+});++it("retains stale-draft conflict handling and reloads without a redundant write", async () => {+ writeLocalProgress("u1", makeProgress({ role: "Stale" }), true, 3);+ const { result } = mountWizard();+ await settle();+ expect(result.current.conflict).toBe(true);+ expect(patchState).not.toHaveBeenCalled();+ act(() => result.current.retry());+ await settle();+ expect(result.current.isReady).toBe(true);+ expect(patchState).not.toHaveBeenCalled();+ expect(readLocalProgress("u1")?.pending).toBe(false);+});++it("rejects a restored draft belonging to another signed-in account", async () => {+ getState.mockResolvedValue(response(makeProgress(), 4, "u2"));+ const { result } = mountWizard();+ await settle();+ expect(result.current.isReady).toBe(false);+ expect(result.current.error).toMatch(/account changed/i);+ expect(readLocalProgress("u1")).toBeNull();+ expect(patchState).not.toHaveBeenCalled();+});++it("ignores a delayed restore after the account changes", async () => {+ let resolveFirst!: (value: ReturnType<typeof response>) => void;+ getState.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveFirst = resolve;+ }),+ );+ getState.mockResolvedValueOnce(+ response(makeProgress({ role: "Other account" }), 6, "u2"),+ );+ const { rerender } = mountWizard();+ rerender({ userID: "u2" });+ await settle();+ await act(async () => {+ resolveFirst(response());+ });+ expect(useOnboardingWizardStore.getState()).toMatchObject({+ userID: "u2",+ role: "Other account",+ });+ expect(readLocalProgress("u1")).toBeNull();+ expect(patchState).not.toHaveBeenCalled();+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressError.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressError.tsxnew file mode 100644index 0000000000..73e8fbdc52--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/components/ProgressError.tsx@@ -0,0 +1,22 @@+import { Button } from "@/components/atoms/Button/Button";+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";++interface Props {+ message: string;+ conflict: boolean;+ retry: () => void;+}++export function ProgressError({ message, conflict, retry }: Props) {+ return (+ <div className="flex flex-col items-center gap-3">+ <ErrorCard+ context="your onboarding progress"+ responseError={{ message }}+ isOurProblem={!conflict}+ onRetry={retry}+ />+ {conflict && <Button onClick={retry}>Reload latest progress</Button>}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/loadWizardProgress.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/loadWizardProgress.tsnew file mode 100644index 0000000000..c4b3f44e8b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/loadWizardProgress.ts@@ -0,0 +1,88 @@+import { getV1OnboardingState } from "@/app/api/__generated__/endpoints/onboarding/onboarding";+import type { OnboardingWizardProgress } from "@/app/api/__generated__/models/onboardingWizardProgress";+import {+ clearLocalProgress,+ readLocalProgress,+ readProgress,+ sameProgress,+ writeLocalProgress,+} from "./progress";++type LoadedWizardProgress =+ | { kind: "complete" | "accountChanged" | "conflict" | "unavailable" }+ | {+ kind: "ready";+ progress: OnboardingWizardProgress | null;+ revision: number;+ offline: boolean;+ needsSync: boolean;+ };++export async function loadWizardProgress(+ userID: string,+ reloadLatest: boolean,+ abort: AbortController,+): Promise<LoadedWizardProgress> {+ const cached = readLocalProgress(userID);+ const local = reloadLatest ? null : cached;+ try {+ const timeout = setTimeout(() => abort.abort(), 10_000);+ let result;+ try {+ result = await getV1OnboardingState({ signal: abort.signal });+ } finally {+ clearTimeout(timeout);+ }+ if (result.status !== 200) throw new Error("Could not load onboarding.");+ if (result.data.userId !== userID) return { kind: "accountChanged" };+ if (result.data.completedSteps.includes("ONBOARDING_COMPLETE"))+ return { kind: "complete" };+ const revision = result.data.wizardRevision ?? 0;+ const serverProgress = readProgress(result.data.wizardProgress);+ if (+ local?.pending &&+ local.revision !== revision &&+ !sameProgress(local.progress, serverProgress)+ ) {+ return { kind: "conflict" };+ }+ const needsSync =+ !!local?.pending && !sameProgress(local.progress, serverProgress);+ if (!needsSync && !abort.signal.aborted)+ cacheConfirmedProgress(userID, serverProgress, revision, cached);+ return {+ kind: "ready",+ progress: local?.pending ? local.progress : serverProgress,+ revision,+ offline: false,+ needsSync,+ };+ } catch {+ return local+ ? {+ kind: "ready",+ progress: local.progress,+ revision: local.revision,+ offline: true,+ needsSync: local.pending,+ }+ : { kind: "unavailable" };+ }+}++function cacheConfirmedProgress(+ userID: string,+ progress: OnboardingWizardProgress | null,+ revision: number,+ cached: ReturnType<typeof readLocalProgress>,+) {+ const current = readLocalProgress(userID);+ if (+ current?.revision !== cached?.revision ||+ current?.pending !== cached?.pending ||+ (current && !sameProgress(current.progress, cached?.progress ?? null))+ )+ return;+ if (progress) writeLocalProgress(userID, progress, false, revision);+ else clearLocalProgress(userID);+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsxindex 8c99aebc12..4cabb0ec58 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx@@ -1,4 +1,5 @@"use client";+import { ProgressError } from "./components/ProgressError";import { ProgressBar } from "./components/ProgressBar";import { StepIndicator } from "./components/StepIndicator";import { BrainDumpStep } from "./steps/BrainDumpStep/BrainDumpStep";@@ -29,21 +30,50 @@ export default function OnboardingPage() {preparingStep,totalSteps,trialConfirmation,+ paidConfirmation,+ progressError,+ progressConflict,+ retryProgress,+ completionError,} = useOnboardingPage();const prevStep = useOnboardingWizardStore((s) => s.prevStep);const isStepBusy = useOnboardingWizardStore((s) => s.isStepBusy);+ if (isLoading && paidConfirmation.error)+ return (+ <ErrorCard+ context="your payment"+ responseError={{ message: paidConfirmation.error }}+ onRetry={paidConfirmation.retry}+ />+ );+ if (isLoading && paidConfirmation.pending)+ return (+ <Text variant="body" role="status">+ Confirming your subscription…+ </Text>+ );if (isLoading)return !trialConfirmation.ready ? (<Text variant="body" role="status">Confirming your trial and card setup…</Text>- ) : null;+ ) : progressError ? (+ <ProgressError+ message={progressError}+ conflict={progressConflict}+ retry={retryProgress}+ />+ ) : (+ <Text variant="body" role="status">+ Loading your setup…+ </Text>+ );// ProgressBar + StepIndicator track only the user-interactive steps.// PreparingStep is a transition view that hides both indicators.const showDots = currentStep <= totalSteps;- // Back is hidden on the first content step (never back into the paywall)+ // Back is hidden on the first content step// and while the current step is mid-flight (brain dump processing) — there// is nothing coherent to go back to. Read from the layout so it tracks// buildStepLayout rather than a hardcoded position.@@ -55,6 +85,20 @@ export default function OnboardingPage() {return (<div className="flex min-h-screen w-full flex-col items-center">+ {progressError && (+ <ProgressError+ message={progressError}+ conflict={progressConflict}+ retry={retryProgress}+ />+ )}+ {completionError && (+ <ErrorCard+ context="your account setup"+ responseError={{ message: completionError }}+ onRetry={handlePreparingComplete}+ />+ )}{trialConfirmation.error ? (<ErrorCardcontext="your trial"diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/progress-saver.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/progress-saver.tsnew file mode 100644index 0000000000..77d1fc8702--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/progress-saver.ts@@ -0,0 +1,136 @@+import type { OnboardingWizardProgress } from "@/app/api/__generated__/models/onboardingWizardProgress";+import {+ readLocalProgress,+ sameProgress,+ writeLocalProgress,+} from "./progress";++export function createProgressSaver({+ userID,+ save,+ onError,+ onConflict,+ initialRevision,+}: {+ userID: string;+ initialRevision: number;+ onConflict: () => void;+ save: (+ progress: OnboardingWizardProgress,+ revision: number,+ signal: AbortSignal,+ ) => Promise<number>;+ onError: (message: string | null) => void;+}) {+ let revision = initialRevision;+ let conflicted = false;+ let pending: OnboardingWizardProgress | null = null;+ let inFlight: Promise<void> | null = null;+ let timer: ReturnType<typeof setTimeout> | undefined;+ let disposed = false;+ let failures = 0;+ let controller: AbortController | null = null;++ function schedule(delay: number) {+ clearTimeout(timer);+ timer = setTimeout(() => void flush().catch(() => undefined), delay);+ }++ function enqueue(progress: OnboardingWizardProgress) {+ if (disposed || conflicted) return;+ pending = progress;+ if (!writeLocalProgress(userID, progress, true, revision)) {+ onError(+ "Your progress hasn't been saved yet. Please keep this page open while we retry.",+ );+ }+ schedule(200);+ }++ async function saveWithTimeout(progress: OnboardingWizardProgress) {+ const request = new AbortController();+ controller = request;+ let timeout: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ save(progress, revision, request.signal),+ new Promise<never>((_resolve, reject) => {+ timeout = setTimeout(() => {+ request.abort();+ reject(new Error("Saving onboarding timed out. Please retry."));+ }, 10_000);+ }),+ ]);+ } finally {+ clearTimeout(timeout);+ if (controller === request) controller = null;+ }+ }++ async function drain() {+ while (pending && !disposed) {+ const progress = pending;+ try {+ const previousRevision = revision;+ revision = await saveWithTimeout(progress);+ if (disposed) return;+ const latest = pending ?? progress;+ const local = readLocalProgress(userID);+ const ownsLocal =+ local?.revision === previousRevision &&+ sameProgress(latest, local.progress);+ if (pending === progress) pending = null;+ if (ownsLocal)+ writeLocalProgress(userID, latest, pending !== null, revision);+ failures = 0;+ onError(null);+ } catch (error) {+ if (disposed) return;+ if (isProgressConflict(error)) {+ conflicted = true;+ onConflict();+ throw error;+ }+ failures += 1;+ onError(+ "We couldn't save your progress to your account. We'll keep retrying; you can continue here.",+ );+ schedule(Math.min(30_000, 1000 * 2 ** (failures - 1)));+ throw error;+ }+ }+ }++ async function flush() {+ clearTimeout(timer);+ if (conflicted)+ throw new Error(+ "Another session updated onboarding. Reload the latest progress.",+ );+ if (disposed)+ throw new Error("Your account changed. Please reload onboarding.");+ if (!inFlight)+ inFlight = drain().finally(() => {+ inFlight = null;+ });+ await inFlight;+ if (pending) await flush();+ }++ function dispose() {+ disposed = true;+ clearTimeout(timer);+ controller?.abort();+ }++ return { enqueue, flush, dispose };+}++export function isProgressConflict(error: unknown) {+ return (+ typeof error === "object" &&+ error !== null &&+ "status" in error &&+ error.status === 409+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/progress.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/progress.tsnew file mode 100644index 0000000000..4fca366052--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/progress.ts@@ -0,0 +1,157 @@+import type { OnboardingWizardProgress } from "@/app/api/__generated__/models/onboardingWizardProgress";+import type { Step, StepLayout } from "./store";+import { z } from "zod";+import { normalizeOnboardingProfile } from "./helpers";++export type WizardStepKey = keyof StepLayout;+const STEP_KEYS: WizardStepKey[] = [+ "team",+ "autopilot",+ "role",+ "painPoints",+ "hire",+ "subscription",+ "connect",+ "preparing",+];++export function stepKey(steps: StepLayout, step: number): WizardStepKey {+ return STEP_KEYS.find((key) => steps[key] === step) ?? "role";+}++export function orderedSteps(steps: StepLayout) {+ return STEP_KEYS.filter((key) => steps[key] !== undefined).sort(+ (a, b) => steps[a]! - steps[b]!,+ );+}++const stepSchema = z.enum([+ "team",+ "autopilot",+ "role",+ "painPoints",+ "hire",+ "subscription",+ "connect",+ "preparing",+]);+function isAllowedCharacter(character: string) {+ const code = character.charCodeAt(0);+ return (+ (code >= 32 && code !== 127) || code === 9 || code === 10 || code === 13+ );+}++export function cleanWizardText(value: string, limit: number) {+ return Array.from(value).filter(isAllowedCharacter).join("").slice(0, limit);+}++function wizardText(max: number, min = 0) {+ return z+ .string()+ .min(min)+ .max(max)+ .refine((value) => Array.from(value).every(isAllowedCharacter));+}++const progressSchema = z+ .object({+ version: z.literal(1),+ currentStep: stepSchema,+ completedSteps: z.array(stepSchema).max(8),+ role: wizardText(100),+ otherRole: wizardText(100),+ painPoints: z.array(wizardText(200, 1)).max(20),+ otherPainPoint: wizardText(2000),+ selectedBilling: z.enum(["monthly", "yearly"]),+ hasUserSelectedBilling: z.boolean(),+ selectedCountryCode: z.string().regex(/^[A-Z]{2}$/),+ hiredTemplateIds: z.array(wizardText(128, 1)).max(100),+ })+ .strict();++export function readProgress(value: unknown): OnboardingWizardProgress | null {+ const result = progressSchema.safeParse(value);+ return result.success ? result.data : null;+}++export function resumeStep({+ progress,+ steps,+ requestedStep,+}: {+ progress: OnboardingWizardProgress | null;+ steps: StepLayout;+ requestedStep?: string | null;+}): Step {+ const order = orderedSteps(steps);+ const completed = new Set(progress?.completedSteps ?? []);+ // Payment must be confirmed by the subscription query, never by draft data+ // or a success query parameter. A confirmed plan removes this layout slot.+ completed.delete("subscription");+ if (progress && !normalizeOnboardingProfile(progress).role.trim())+ completed.delete("role");+ const ceilingKey = order.find((key) => !completed.has(key)) ?? "preparing";+ const ceiling = steps[ceilingKey]!;+ const requested = order.find((key) => key === requestedStep);+ const saved = progress?.currentStep;+ const target =+ requested ?? (saved && steps[saved] !== undefined ? saved : ceilingKey);+ return Math.min(steps[target]!, ceiling) as Step;+}++export function progressStorageKey(userID: string) {+ return `autogpt:onboarding-progress:${userID}`;+}++export function readLocalProgress(userID: string) {+ try {+ const value = JSON.parse(+ localStorage.getItem(progressStorageKey(userID)) ?? "null",+ );+ const progress = readProgress(value?.progress);+ return progress && Number.isInteger(value.revision) && value.revision >= 0+ ? {+ progress,+ pending: value.pending === true,+ revision: value.revision as number,+ }+ : null;+ } catch {+ return null;+ }+}++export function writeLocalProgress(+ userID: string,+ progress: OnboardingWizardProgress,+ pending: boolean,+ revision: number,+) {+ try {+ localStorage.setItem(+ progressStorageKey(userID),+ JSON.stringify({ progress, pending, revision }),+ );+ return true;+ } catch {+ return false;+ }+}++export function clearLocalProgress(userID: string) {+ try {+ localStorage.removeItem(progressStorageKey(userID));+ } catch {+ // A confirmed server completion still prevents re-entering the wizard.+ }+}++export function sameProgress(+ left: OnboardingWizardProgress,+ right: OnboardingWizardProgress | null,+) {+ return (+ JSON.stringify(readProgress(left)) === JSON.stringify(readProgress(right))+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsxindex ddfd18cb0c..b12ccd6fb6 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/SubscriptionStep.tsx@@ -5,11 +5,32 @@ import { getEligibleTrialOffer } from "@/components/organisms/SubscriptionPlans/import { SubscriptionPlans } from "@/components/organisms/SubscriptionPlans/SubscriptionPlans";import { TrialCardContent } from "@/components/organisms/TrialCard/TrialCard";import { useTrialCard } from "@/components/organisms/TrialCard/useTrialCard";+import { useOnboardingWizardStore } from "../../store";+import { useState } from "react";import { useSubscriptionStep } from "./useSubscriptionStep";export function SubscriptionStep() {const subscription = useSubscriptionStep();const trial = useTrialCard("onboarding");+ const [saving, setSaving] = useState(false);+ const [saveError, setSaveError] = useState<string | null>(null);+ async function startTrial() {+ if (saving) return;+ setSaving(true);+ setSaveError(null);+ try {+ const ownerID = useOnboardingWizardStore.getState().userID;+ await useOnboardingWizardStore.getState().flushProgress?.();+ if (useOnboardingWizardStore.getState().userID !== ownerID) return;+ await trial.startTrial();+ } catch {+ setSaveError(+ "We couldn't save your progress. Please try again before continuing to checkout.",+ );+ } finally {+ setSaving(false);+ }+ }const offer = getEligibleTrialOffer(trial, subscription.plans);return (@@ -23,12 +44,20 @@ export function SubscriptionStep() {isUpdatingTier={subscription.isUpdatingTier}selectedPlan={subscription.selectedPlan}trialOffer={offer}- onStartTrial={trial.startTrial}- isStartingTrial={trial.isStarting}- trialError={trial.error}+ onStartTrial={startTrial}+ isStartingTrial={trial.isStarting || saving}+ trialError={saveError ?? trial.error}trialStatus={!offer && (- <TrialCardContent returnTo="onboarding" controller={trial} />+ <TrialCardContent+ returnTo="onboarding"+ controller={{+ ...trial,+ startTrial,+ isStarting: trial.isStarting || saving,+ error: saveError ?? trial.error,+ }}+ />)}/>diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.tsindex 71482726d0..34114d977b 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/SubscriptionStep/useSubscriptionStep.ts@@ -1,4 +1,7 @@-import { useUpdateSubscriptionTier } from "@/app/api/__generated__/endpoints/credits/credits";+import {+ getGetSubscriptionStatusQueryKey,+ useUpdateSubscriptionTier,+} from "@/app/api/__generated__/endpoints/credits/credits";import type { SubscriptionTierRequestTier } from "@/app/api/__generated__/models/subscriptionTierRequestTier";import { toast } from "@/components/molecules/Toast/use-toast";import {@@ -7,6 +10,7 @@ import {} from "@/services/analytics/google-ads";import { environment } from "@/services/environment";import { useState } from "react";+import { useQueryClient } from "@tanstack/react-query";import { useSearchParams } from "next/navigation";import { useOnboardingWizardStore } from "../../store";import { COUNTRIES } from "@/components/molecules/PlanCard/countries";@@ -37,6 +41,7 @@ interface CheckoutResponse {}export function useSubscriptionStep() {+ const queryClient = useQueryClient();const setSelectedBilling = useOnboardingWizardStore((s) => s.setSelectedBilling,);@@ -46,8 +51,6 @@ export function useSubscriptionStep() {const setSelectedPlan = useOnboardingWizardStore((s) => s.setSelectedPlan);const nextStep = useOnboardingWizardStore((s) => s.nextStep);const selectedPlan = useOnboardingWizardStore((s) => s.selectedPlan);- const steps = useOnboardingWizardStore((s) => s.steps);- const currentStep = useOnboardingWizardStore((s) => s.currentStep);const { mutateAsync: updateTier, isPending: isUpdatingTier } =useUpdateSubscriptionTier();@@ -112,22 +115,20 @@ export function useSubscriptionStep() {const cycle = isYearly ? "yearly" : "monthly";try {- // The paywall is the first step, so there's no profile to submit yet —- // role and pain points are collected after payment. On a successful- // checkout Stripe returns the user to the step after the paywall to- // begin onboarding; on cancel, back to this paywall. Stripe fills- // {CHECKOUT_SESSION_ID}; plan and cycle let the return page report the- // subscription to Google Ads.+ const ownerID = useOnboardingWizardStore.getState().userID;+ await useOnboardingWizardStore.getState().flushProgress?.();+ if (useOnboardingWizardStore.getState().userID !== ownerID) return;const baseUrl = `${window.location.origin}/onboarding`;const result = await updateTier({data: {tier,- success_url: `${baseUrl}?step=${(steps.subscription ?? currentStep) + 1}&subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${planKey}&cycle=${cycle}`,- cancel_url: `${baseUrl}?step=${steps.subscription ?? currentStep}&subscription=cancelled`,+ success_url: `${baseUrl}?step=preparing&subscription=success&session_id={CHECKOUT_SESSION_ID}&plan=${planKey}&cycle=${cycle}`,+ cancel_url: `${baseUrl}?step=subscription&subscription=cancelled`,billing_cycle: cycle,surface: "onboarding",},});+ if (useOnboardingWizardStore.getState().userID !== ownerID) return;const url = (result?.data as CheckoutResponse | undefined)?.url;if (url) {// A Checkout URL is the only proof that Stripe Checkout actually@@ -142,8 +143,11 @@ export function useSubscriptionStep() {window.location.href = url;return;}- // Backend modified the subscription in place (no Checkout URL) —- // proceed to the preparing step as if the user had clicked through.+ await queryClient.invalidateQueries(+ { queryKey: getGetSubscriptionStatusQueryKey() },+ { throwOnError: true },+ );+ if (useOnboardingWizardStore.getState().userID !== ownerID) return;nextStep();} catch (error) {toast({diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsxindex 5f9e66edc3..38519881a4 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.test.tsx@@ -1,5 +1,6 @@import { http, HttpResponse } from "msw";import {+ act,fireEvent,render,screen,@@ -217,7 +218,7 @@ describe("SubscriptionStep", () => {expect(screen.queryByText(/Charged today/i)).toBeNull();});- test("selecting Pro persists selectedPlan and redirects to Stripe Checkout (Role on success, paywall on cancel)", async () => {+ test("selecting Pro persists selectedPlan and returns to Preparing on success, paywall on cancel", async () => {let capturedTierBody: {tier?: string;success_url?: string;@@ -247,21 +248,19 @@ describe("SubscriptionStep", () => {expect(useOnboardingWizardStore.getState().selectedPlan).toBe("PRO");expect(capturedTierBody!.tier).toBe("PRO");- // Success moves on to the step after the paywall (step 2) to begin- // onboarding; cancel returns to the paywall (step 1).+ // Checkout returns to semantic steps so optional layout changes are safe.expect(capturedTierBody!.success_url).toContain(- "/onboarding?step=2&subscription=success",+ "/onboarding?step=preparing&subscription=success",);expect(capturedTierBody!.cancel_url).toContain(- "/onboarding?step=1&subscription=cancelled",+ "/onboarding?step=subscription&subscription=cancelled",);// Stripe fills {CHECKOUT_SESSION_ID}; plan and cycle let the return page// report the subscription value to Google Ads.expect(capturedTierBody!.success_url).toContain("&session_id={CHECKOUT_SESSION_ID}&plan=PRO&cycle=monthly",);- // Nothing is POSTed here — the profile is collected after payment and- // the Preparing step submits it.+ // Answers have already been collected; Preparing submits the final profile.expect(profileCalled).toBe(false);});@@ -296,6 +295,45 @@ describe("SubscriptionStep", () => {);});+ test.each(["https://checkout.stripe.com/pay/old_account", null])(+ "ignores an old account's checkout response with URL %s",+ async (url) => {+ const location = stubLocation();+ let resolveResponse: (() => void) | undefined;+ const pending = new Promise<void>((resolve) => {+ resolveResponse = resolve;+ });+ const received = vi.fn();+ server.use(+ http.post("*/api/credits/subscription", async () => {+ received();+ await pending;+ return HttpResponse.json({ url });+ }),+ );+ useOnboardingWizardStore.setState({ userID: "previous-user" });+ render(<SubscriptionStep />);+ fireEvent.click(screen.getByRole("button", { name: /Get Pro/i }));+ await waitFor(() => expect(received).toHaveBeenCalledOnce());+ act(() => {+ useOnboardingWizardStore.setState({+ userID: "next-user",+ currentStep: 1,+ });+ resolveResponse?.();+ });+ await waitFor(() =>+ expect(+ screen+ .getByRole("button", { name: /Upgrade to Max/i })+ .hasAttribute("disabled"),+ ).toBe(false),+ );+ expect(location.href).toBe("http://localhost/");+ expect(useOnboardingWizardStore.getState().currentStep).toBe(1);+ },+ );+test("reports no begin_checkout when Stripe returns no Checkout URL", async () => {vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_ID", "AW-123");vi.stubEnv("NEXT_PUBLIC_GOOGLE_ADS_CONVERSION_LABELS", "begin_checkout=BC");diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsxindex 523a6db0d5..09b6c9fd86 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/__tests__/SubscriptionStep.trial.test.tsx@@ -324,3 +324,68 @@ test.each(["BASIC", "BUSINESS"] as const)().toBeNull();},);++test("saves the personalized onboarding draft before starting trial checkout", async () => {+ mockStatus();+ let releaseSave: (() => void) | undefined;+ const flush = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ releaseSave = resolve;+ }),+ );+ useOnboardingWizardStore.setState({ flushProgress: flush });+ const checkout = vi.fn();+ server.use(+ getPostTrialsStartTrialCheckoutMockHandler200(() => {+ checkout();+ return { url: "https://checkout.stripe.com/trial" };+ }),+ );+ render(<SubscriptionStep />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Start 7-day trial" }),+ );+ expect(flush).toHaveBeenCalledOnce();+ expect(checkout).not.toHaveBeenCalled();+ releaseSave?.();+ await waitFor(() =>+ expect(checkoutLocation.assign).toHaveBeenCalledWith(+ "https://checkout.stripe.com/trial",+ ),+ );+});++test("keeps the trial checkout available for retry if saving the draft fails", async () => {+ mockStatus();+ useOnboardingWizardStore.setState({+ flushProgress: vi.fn().mockRejectedValue(new Error("offline")),+ });+ render(<SubscriptionStep />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Start 7-day trial" }),+ );+ expect(await screen.findByText(/couldn't save your progress/)).toBeDefined();+ expect(checkoutLocation.assign).not.toHaveBeenCalled();+ expect(+ screen+ .getByRole("button", { name: "Start 7-day trial" })+ .hasAttribute("disabled"),+ ).toBe(false);+});++test("also flushes the draft from the standalone fallback trial card", async () => {+ mockStatus(eligible({ ...trialOffer, tier: "BASIC" }));+ const flush = vi.fn().mockRejectedValue(new Error("offline"));+ useOnboardingWizardStore.setState({ flushProgress: flush });+ render(<SubscriptionStep />);+ const card = within(+ await screen.findByRole("region", { name: "AutoGPT trial" }),+ );+ fireEvent.click(+ await card.findByRole("button", { name: "Start 7-day trial" }),+ );+ expect(flush).toHaveBeenCalledOnce();+ expect(await card.findByRole("alert")).toBeDefined();+ expect(checkoutLocation.assign).not.toHaveBeenCalled();+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.tsindex ff96799ff4..228aae8d8b 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts@@ -1,5 +1,6 @@import { create } from "zustand";-import { createJSONStorage, persist } from "zustand/middleware";+import type { OnboardingWizardProgress } from "@/app/api/__generated__/models/onboardingWizardProgress";+import { cleanWizardText, stepKey, type WizardStepKey } from "./progress";export const MAX_PAIN_POINT_SELECTIONS = 3;export type Step = 1 | 2 | 3 | 4 | 5 | 6 | 7;@@ -19,13 +20,6 @@ export interface StepLayout {preparing: number;}-// Builds the layout for a deployment: the paywall comes FIRST on cloud so-// nobody without a plan gets into the wizard, the two intro steps (team, meet-// Otto) follow when the expert team is on, then the profile steps, then-// Otto's hire recommendations right after the brain dump they are read-// from. Self-host has no paywall and instead closes with the "connect a plan-// you already pay for" step, right before Preparing. Numbering is derived, so-// nothing can drift.export function buildStepLayout({hasIntro = false,hasHire = false,@@ -38,11 +32,11 @@ export function buildStepLayout({hasConnect?: boolean;}): StepLayout {const order: (keyof StepLayout)[] = [- ...(hasPaywall ? (["subscription"] as const) : []),...(hasIntro ? (["team", "autopilot"] as const) : []),"role","painPoints",...(hasHire ? (["hire"] as const) : []),+ ...(hasPaywall ? (["subscription"] as const) : []),...(!hasPaywall && hasConnect ? (["connect"] as const) : []),"preparing",];@@ -55,10 +49,10 @@ export function buildStepLayout({// The three layouts without the intro steps, spelled out for tests and for// the store's default.-export const PAYWALL_FIRST_STEPS = {- subscription: 1,- role: 2,- painPoints: 3,+export const PAYWALL_LAST_STEPS = {+ role: 1,+ painPoints: 2,+ subscription: 3,preparing: 4,} as const;@@ -79,6 +73,9 @@ export const SELF_HOST_STEPS = {interface OnboardingWizardState {currentStep: Step;+ userID: string | null;+ completedSteps: WizardStepKey[];+ flushProgress: (() => Promise<void>) | null;// The numbering in force for this session, set by the page hook once the// flags resolve; steps that need to name another step (the paywall's// Stripe return URLs) read it from here.@@ -116,127 +113,123 @@ interface OnboardingWizardState {}export const useOnboardingWizardStore = create<OnboardingWizardState>()(- persist(- (set) => ({- currentStep: 1,- steps: PAYWALL_FIRST_STEPS,- role: "",- otherRole: "",- painPoints: [],- otherPainPoint: "",- selectedPlan: null,- selectedBilling: "monthly",- hasUserSelectedBilling: false,- selectedCountryCode: "US",- hiredTemplateIds: [],- isStepBusy: false,- setStepBusy(busy) {- set({ isStepBusy: busy });- },- setSteps(steps) {- set({ steps });- },- setRole(role) {- set({ role });- },- setOtherRole(otherRole) {- set({ otherRole });- },- togglePainPoint(painPoint) {- set((state) => {- const exists = state.painPoints.includes(painPoint);- if (!exists && state.painPoints.length >= MAX_PAIN_POINT_SELECTIONS)- return state;- return {- painPoints: exists- ? state.painPoints.filter((p) => p !== painPoint)- : [...state.painPoints, painPoint],- };- });- },- setOtherPainPoint(otherPainPoint) {- set({ otherPainPoint });- },- setSelectedPlan(plan) {- set({ selectedPlan: plan });- },- setSelectedBilling(billing) {- set({ selectedBilling: billing, hasUserSelectedBilling: true });- },- applyPricingExperimentBilling(billing) {- set((state) =>- state.hasUserSelectedBilling ? state : { selectedBilling: billing },- );- },- setSelectedCountryCode(code) {- set({ selectedCountryCode: code });- },- markHired(templateId) {- set((state) =>- state.hiredTemplateIds.includes(templateId)- ? state- : { hiredTemplateIds: [...state.hiredTemplateIds, templateId] },- );- },- nextStep() {- set((state) => ({- currentStep: Math.min(MAX_STEP, state.currentStep + 1) as Step,- }));- },- prevStep() {- set((state) => ({- currentStep: Math.max(1, state.currentStep - 1) as Step,- }));- },- goToStep(step) {- set({ currentStep: step });- },- reset() {- set({- currentStep: 1,- role: "",- otherRole: "",- painPoints: [],- otherPainPoint: "",- selectedPlan: null,- selectedBilling: "monthly",- hasUserSelectedBilling: false,- selectedCountryCode: "US",- hiredTemplateIds: [],- });- },- }),- {- name: "onboarding-wizard",- version: 1,- // sessionStorage (not localStorage) so abandoning the wizard and- // closing the tab gives a clean slate next time, matching the- // STEP_STORAGE_KEY ceiling in useOnboardingPage. SSR-safe: a no-op- // stub runs during Next.js SSR / vitest where window is undefined —- // returning undefined would make zustand throw on first getItem.- storage: createJSONStorage(() =>- typeof window !== "undefined" && window.sessionStorage- ? window.sessionStorage- : { getItem: () => null, setItem: () => {}, removeItem: () => {} },- ),- // currentStep is intentionally excluded — the URL is the source of- // truth for which step the user is on, and the page hook syncs the- // store from the URL on mount.- // selectedPlan is also excluded — it's only meaningful while a- // Stripe Checkout request is in flight (gated by isUpdatingTier in- // SubscriptionStep). The full-page Stripe redirect doesn't survive- // in-memory state anyway, so persisting it serves no purpose and- // would resurface a stale "selected" plan after cancel-and-return.- partialize: (state) => ({- role: state.role,- otherRole: state.otherRole,- painPoints: state.painPoints,- otherPainPoint: state.otherPainPoint,- selectedBilling: state.selectedBilling,- hasUserSelectedBilling: state.hasUserSelectedBilling,- selectedCountryCode: state.selectedCountryCode,- hiredTemplateIds: state.hiredTemplateIds,- }),+ (set) => ({+ currentStep: 1,+ userID: null,+ completedSteps: [],+ flushProgress: null,+ steps: PAYWALL_LAST_STEPS,+ role: "",+ otherRole: "",+ painPoints: [],+ otherPainPoint: "",+ selectedPlan: null,+ selectedBilling: "monthly",+ hasUserSelectedBilling: false,+ selectedCountryCode: "US",+ hiredTemplateIds: [],+ isStepBusy: false,+ setStepBusy(busy) {+ set({ isStepBusy: busy });+ },+ setSteps(steps) {+ set({ steps });+ },+ setRole(role) {+ set({ role: cleanWizardText(role, 100) });+ },+ setOtherRole(otherRole) {+ set({ otherRole: cleanWizardText(otherRole, 100) });+ },+ togglePainPoint(painPoint) {+ set((state) => {+ const exists = state.painPoints.includes(painPoint);+ if (!exists && state.painPoints.length >= MAX_PAIN_POINT_SELECTIONS)+ return state;+ return {+ painPoints: exists+ ? state.painPoints.filter((p) => p !== painPoint)+ : [...state.painPoints, painPoint],+ };+ });+ },+ setOtherPainPoint(otherPainPoint) {+ set({ otherPainPoint: cleanWizardText(otherPainPoint, 2000) });+ },+ setSelectedPlan(plan) {+ set({ selectedPlan: plan });},- ),+ setSelectedBilling(billing) {+ set({ selectedBilling: billing, hasUserSelectedBilling: true });+ },+ applyPricingExperimentBilling(billing) {+ set((state) =>+ state.hasUserSelectedBilling ? state : { selectedBilling: billing },+ );+ },+ setSelectedCountryCode(code) {+ set({ selectedCountryCode: code });+ },+ markHired(templateId) {+ set((state) =>+ state.hiredTemplateIds.includes(templateId)+ ? state+ : { hiredTemplateIds: [...state.hiredTemplateIds, templateId] },+ );+ },+ nextStep() {+ set((state) => ({+ currentStep: Math.min(MAX_STEP, state.currentStep + 1) as Step,+ completedSteps: Array.from(+ new Set([+ ...state.completedSteps,+ stepKey(state.steps, state.currentStep),+ ]),+ ),+ }));+ },+ prevStep() {+ set((state) => ({+ currentStep: Math.max(1, state.currentStep - 1) as Step,+ }));+ },+ goToStep(step) {+ set({ currentStep: step });+ },+ reset() {+ set({+ currentStep: 1,+ userID: null,+ completedSteps: [],+ flushProgress: null,+ isStepBusy: false,+ role: "",+ otherRole: "",+ painPoints: [],+ otherPainPoint: "",+ selectedPlan: null,+ selectedBilling: "monthly",+ hasUserSelectedBilling: false,+ selectedCountryCode: "US",+ hiredTemplateIds: [],+ });+ },+ }),);++export function snapshotProgress(): OnboardingWizardProgress {+ const state = useOnboardingWizardStore.getState();+ return {+ version: 1,+ currentStep: stepKey(state.steps, state.currentStep),+ completedSteps: state.completedSteps,+ role: state.role,+ otherRole: state.otherRole,+ painPoints: state.painPoints,+ otherPainPoint: state.otherPainPoint,+ selectedBilling: state.selectedBilling,+ hasUserSelectedBilling: state.hasUserSelectedBilling,+ selectedCountryCode: state.selectedCountryCode,+ hiredTemplateIds: state.hiredTemplateIds,+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingLayout.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingLayout.tsnew file mode 100644index 0000000000..1338b18ac6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingLayout.ts@@ -0,0 +1,71 @@+import { environment } from "@/services/environment";+import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";+import { useRef } from "react";+import { usePaidCheckoutStatus } from "./usePaidCheckoutStatus";+import { buildStepLayout, type Step } from "./store";++export function useOnboardingLayout({+ userID,+ isLoggedIn,+ isUserLoading,+ trialConfirmation,+}: {+ userID: string | null;+ isLoggedIn: boolean;+ isUserLoading: boolean;+ trialConfirmation: { ready: boolean; active: boolean | undefined };+}) {+ const payment = useFlagStatus(Flag.ENABLE_PLATFORM_PAYMENT);+ const brain = useFlagStatus(Flag.ONBOARDING_BRAIN_DUMP);+ const expertTeam = useFlagStatus(Flag.ONBOARDING_EXPERT_TEAM);+ const hireExperts = useFlagStatus(Flag.HIRE_EXPERTS);+ const flagsReady =+ payment.ready && brain.ready && expertTeam.ready && hireExperts.ready;+ const snapshot = useRef<{+ userID: string | null;+ payment: boolean;+ brain: boolean;+ team: boolean;+ } | null>(null);+ if (snapshot.current?.userID !== userID) snapshot.current = null;+ // Resolve once per account: flag changes must not reorder an active wizard.+ if (!snapshot.current && flagsReady && !isUserLoading) {+ snapshot.current = {+ userID,+ payment: payment.enabled,+ brain: brain.enabled,+ team: expertTeam.enabled && hireExperts.enabled,+ };+ }+ const paidConfirmation = usePaidCheckoutStatus(+ userID,+ !!snapshot.current?.payment && !environment.isLocal(),+ );+ const userHasActivePlan = trialConfirmation.active || paidConfirmation.active;+ const isPaymentEnabled = !!snapshot.current?.payment && !userHasActivePlan;+ const isBrainDumpEnabled = snapshot.current?.brain ?? false;+ const isExpertTeamEnabled = snapshot.current?.team ?? false;+ const isSelfHostConnectEnabled = !isPaymentEnabled && environment.isLocal();+ const steps = buildStepLayout({+ hasIntro: isExpertTeamEnabled,+ hasHire: isExpertTeamEnabled && isBrainDumpEnabled,+ hasPaywall: isPaymentEnabled,+ hasConnect: isSelfHostConnectEnabled,+ });+ return {+ steps,+ preparingStep: steps.preparing as Step,+ totalSteps: steps.preparing - 1,+ isReady:+ flagsReady &&+ !isUserLoading &&+ (!isLoggedIn || !paidConfirmation.isLoading) &&+ trialConfirmation.ready &&+ paidConfirmation.ready,+ paidConfirmation,+ isPaymentEnabled,+ isSelfHostConnectEnabled,+ isBrainDumpEnabled,+ isExpertTeamEnabled,+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.tsindex 32f52f64cb..67c6c882d5 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts@@ -1,322 +1,147 @@-import { useGetSubscriptionStatus } from "@/app/api/__generated__/endpoints/credits/credits";-import {- getV1OnboardingState,- postV1CompleteOnboardingStep,- postV1SubmitOnboardingProfile,-} from "@/app/api/__generated__/endpoints/onboarding/onboarding";-import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";-import { resolveResponse } from "@/app/api/helpers";+import { postV1CompleteOnboardingStep } from "@/app/api/__generated__/endpoints/onboarding/onboarding";import { useAuth } from "@/lib/auth/hooks/useAuth";import { trackAdsConversion } from "@/services/analytics/google-ads";import { trackTrialCheckoutAbandoned } from "@/services/analytics/monetization-analytics";import { environment } from "@/services/environment";import { useTrialCheckoutReturn } from "@/services/trials/useTrialCheckoutReturn";-import {- Flag,- useFlagStatus,- useGetFlag,-} from "@/services/feature-flags/use-get-flag";import { useRouter, useSearchParams } from "next/navigation";import { useEffect, useRef, useState } from "react";-import { accountDisplayName, normalizeOnboardingProfile } from "./helpers";-import { buildStepLayout, Step, useOnboardingWizardStore } from "./store";+import { Step, useOnboardingWizardStore } from "./store";import { onboardingStepKey, trackOnboardingStep } from "./tracking";--// SessionStorage ceiling for the wizard. The backend's `completedSteps`-// only records ONBOARDING_COMPLETE at the very end (the 5 in-wizard steps-// aren't tracked individually), so resume / fast-forward guardrails are-// enforced client-side: the user can only land on a step they've previously-// reached.-const STEP_STORAGE_KEY = "autogpt:onboarding-highest-step";--function parseStepParam(value: string | null, maxStep: number): Step | null {- const n = Number(value);- if (Number.isInteger(n) && n >= 1 && n <= maxStep) return n as Step;- return null;-}--function readHighestStep(): number {- if (typeof window === "undefined") return 1;- const raw = window.sessionStorage.getItem(STEP_STORAGE_KEY);- const n = Number(raw);- return Number.isInteger(n) && n >= 1 ? n : 1;-}--function writeHighestStep(step: number) {- if (typeof window === "undefined") return;- window.sessionStorage.setItem(STEP_STORAGE_KEY, String(step));-}--function clearHighestStep() {- if (typeof window === "undefined") return;- window.sessionStorage.removeItem(STEP_STORAGE_KEY);-}+import { stepKey } from "./progress";+import { useWizardProgress } from "./useWizardProgress";+import { useOnboardingLayout } from "./useOnboardingLayout";+import { useOnboardingProfile } from "./useOnboardingProfile";export function useOnboardingPage() {const router = useRouter();const searchParams = useSearchParams();const { isLoggedIn, isUserLoading, user } = useAuth();const trialConfirmation = useTrialCheckoutReturn();- const currentStep = useOnboardingWizardStore((s) => s.currentStep);+ const storedStep = useOnboardingWizardStore((s) => s.currentStep);const goToStep = useOnboardingWizardStore((s) => s.goToStep);- const setSteps = useOnboardingWizardStore((s) => s.setSteps);-- // Wait for the flag vendor before initialising the wizard from the URL.- // Without this, the init effect runs against the default flag value- // (false) on first render and clamps e.g. ?step=5 down to step 1; once- // the flag resolves to true, the hasInitialized guard blocks re-init- // and the user is stuck on step 1.- //- // Snapshot the value once it resolves so an admin toggling- // ENABLE_PLATFORM_PAYMENT mid-session can't shuffle steps under a user- // who is already inside the wizard.- const { enabled: livePaymentEnabled, ready: areFlagsReady } = useFlagStatus(- Flag.ENABLE_PLATFORM_PAYMENT,- );- const paymentEnabledSnapshot = useRef<boolean | null>(null);- if (paymentEnabledSnapshot.current === null && areFlagsReady) {- paymentEnabledSnapshot.current = livePaymentEnabled;- }-- // Snapshotted for the same reason as the paywall flag: the brain dump- // and the pillboxes occupy the same step, and swapping them under a- // user who is already recording would drop the take.- const liveBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);- const brainDumpEnabledSnapshot = useRef<boolean | null>(null);- if (brainDumpEnabledSnapshot.current === null && areFlagsReady) {- brainDumpEnabledSnapshot.current = liveBrainDumpEnabled;- }- const isBrainDumpEnabled = brainDumpEnabledSnapshot.current ?? false;-- // Child of HIRE_EXPERTS: adds the two intro steps up front and makes the- // preparing screen wait on the team job. Snapshotted like the others so the- // numbering can't shift under a user mid-wizard.- const isExpertTeamFlagOn = useGetFlag(Flag.ONBOARDING_EXPERT_TEAM);- const isHireExpertsFlagOn = useGetFlag(Flag.HIRE_EXPERTS);- const expertTeamSnapshot = useRef<boolean | null>(null);- if (expertTeamSnapshot.current === null && areFlagsReady) {- expertTeamSnapshot.current = Boolean(- isExpertTeamFlagOn && isHireExpertsFlagOn,- );- }- const isExpertTeamEnabled = expertTeamSnapshot.current ?? false;- // Skip the paywall for users already on a paid tier (admin grants or- // pre-ONBOARDING_COMPLETE accounts) so they aren't asked to pay again to escape.- const { data: tier, isLoading: isTierLoading } = useGetSubscriptionStatus({- query: {- enabled: isLoggedIn,- select: (res) =>- res.status === 200- ? (res.data as SubscriptionStatusResponse).tier- : null,- },+ const {+ steps,+ preparingStep,+ totalSteps,+ isReady,+ isPaymentEnabled,+ isSelfHostConnectEnabled,+ isBrainDumpEnabled,+ isExpertTeamEnabled,+ paidConfirmation,+ } = useOnboardingLayout({+ userID: user?.id ?? null,+ isLoggedIn,+ isUserLoading,+ trialConfirmation,});- const userHasActivePlan =- trialConfirmation.active || (!!tier && tier !== "NO_TIER");- const isPaymentEnabled =- (paymentEnabledSnapshot.current ?? false) && !userHasActivePlan;- // A self-host install has no paywall and no model until someone gives it- // one, so it leads with the connection instead. Payments and self-host are- // mutually exclusive in practice; the check is ordered anyway so a- // deployment that somehow had both still only inserts one first step.- const isSelfHostConnectEnabled = !isPaymentEnabled && environment.isLocal();- // The recommendations are read off the brain dump, and the endpoint that- // serves them lives behind the same flag — no dump, no hire step.- const isHireStepEnabled = isExpertTeamEnabled && isBrainDumpEnabled;- const steps = buildStepLayout({- hasIntro: isExpertTeamEnabled,- hasHire: isHireStepEnabled,- hasPaywall: isPaymentEnabled,- hasConnect: isSelfHostConnectEnabled,+ const progress = useWizardProgress({+ userID: user?.id ?? null,+ ready: isReady,+ steps,});- const preparingStep = steps.preparing as Step;- // Every step before Preparing is one the user acts on and gets a dot for.- const totalSteps = steps.preparing - 1;-- // Wait for auth too — without !isUserLoading, LD can resolve while- // isLoggedIn is transiently false, the tier query stays disabled- // (isTierLoading=false), and init fires with the wrong preparingStep.- const isReady =- areFlagsReady &&- !isUserLoading &&- (!isLoggedIn || !isTierLoading) &&- trialConfirmation.ready;+ const currentStep =+ isPaymentEnabled && !environment.isLocal()+ ? (Math.min(storedStep, steps.subscription!) as Step)+ : storedStep;+ const profile = useOnboardingProfile({+ user,+ enabled: progress.isReady && currentStep === preparingStep,+ });+ const completion = useRef<{ userID: string | undefined } | null>(null);+ const activeUserID = useRef(user?.id);+ activeUserID.current = user?.id;+ const [completionError, setCompletionError] = useState<{+ userID: string | undefined;+ message: string;+ } | null>(null);- const [isOnboardingStateLoading, setIsOnboardingStateLoading] =- useState(true);- const hasSubmitted = useRef(false);- const hasInitialized = useRef(false);- // Distinct from the `hasInitialized` ref above: that guards init running- // once, this says the chosen step has landed. Set in the same batch as the- // init effect's `goToStep`, so the first render where it is true already- // carries the settled step.- const [isStepSettled, setIsStepSettled] = useState(false);+ useEffect(() => {+ return () => {+ completion.current = null;+ };+ }, [user?.id]);- // Initialise store from URL on mount, clamp ?step= to the highest step- // the user has actually reached. No-step URL resumes from the highest- // reached so refreshes don't drop the user back to step 1. Form data is- // persisted (zustand persist), so we no longer reset on mount — that- // would defeat the point of persistence by wiping the user's name/role- // every time they refresh mid-wizard.useEffect(() => {- if (!isReady || hasInitialized.current) return;- hasInitialized.current = true;- // Read before the URL sync below rewrites the query to `?step=N`.+ if (!progress.isReady) return;+ if (currentStep !== storedStep) goToStep(currentStep);if (searchParams.get("trial") === "cancelled") {trackTrialCheckoutAbandoned("onboarding");}- const urlStep = parseStepParam(searchParams.get("step"), preparingStep);- // The paywall is the first step, so a successful Stripe checkout return- // is a trusted intent to advance past it onto the step after it and start- // the actual onboarding — without this, the highestStep ceiling (capped- // at the subscription step before redirect) would clamp the user back- // onto the paywall they just paid through.- const isSubscriptionSuccess =- searchParams.get("subscription") === "success" ||- trialConfirmation.active;- const ceiling =- isSubscriptionSuccess && steps.subscription !== undefined- ? (Math.min(steps.subscription + 1, preparingStep) as Step)- : (Math.min(readHighestStep(), preparingStep) as Step);- const target = (- urlStep === null ? ceiling : Math.min(urlStep, ceiling)- ) as Step;- goToStep(target);- setIsStepSettled(true);+ const key = stepKey(steps, currentStep);+ if (searchParams.get("step") !== key) {+ router.replace(`/onboarding?step=${key}`, { scroll: false });+ }}, [- isReady,- searchParams,+ progress.isReady,+ currentStep,+ storedStep,goToStep,- preparingStep,- steps.subscription,- trialConfirmation.active,- ]);-- // Publish the numbering so steps that must name another step (the- // paywall's Stripe return URLs) agree with the page.- useEffect(() => {- if (!isReady) return;- setSteps(- buildStepLayout({- hasIntro: isExpertTeamEnabled,- hasHire: isHireStepEnabled,- hasPaywall: isPaymentEnabled,- hasConnect: isSelfHostConnectEnabled,- }),- );- }, [- isReady,- setSteps,- isExpertTeamEnabled,- isHireStepEnabled,- isPaymentEnabled,- isSelfHostConnectEnabled,+ steps,+ searchParams,+ router,]);- // Report the step the wizard is actually showing. `isOnboardingStateLoading`- // is the same gate the page renders on — it also covers the window holding- // the ONBOARDING_COMPLETE check that redirects finished users to /home —- // and `isStepSettled` means the step above has landed, so a user resuming- // at Preparing never reports the store's default of Welcome on the way past.- // Repeat visits to a step are dropped by `trackOnboardingStep` itself, so- // going back and forward reports nothing new.- const stepKey = onboardingStepKey(steps, currentStep);+ const trackingKey = onboardingStepKey(steps, currentStep);useEffect(() => {- if (isOnboardingStateLoading || !isStepSettled) return;- if (stepKey) trackOnboardingStep(stepKey);- }, [isOnboardingStateLoading, isStepSettled, stepKey]);-- // Sync store → URL when step changes; record the new ceiling.- useEffect(() => {- if (!isReady) return;- const urlStep = parseStepParam(searchParams.get("step"), preparingStep);- if (currentStep !== urlStep) {- router.replace(`/onboarding?step=${currentStep}`, { scroll: false });- }- if (currentStep > readHighestStep()) {- writeHighestStep(currentStep);- }- }, [isReady, currentStep, router, searchParams, preparingStep]);-- // Check if onboarding already completed- useEffect(() => {- if (!isLoggedIn) return;-- async function checkCompletion() {- try {- const onboarding = await resolveResponse(getV1OnboardingState());- if (onboarding.completedSteps.includes("ONBOARDING_COMPLETE")) {- clearHighestStep();- // Clear the persisted form data without touching in-memory state.- // `reset()` would set currentStep=1 and trip the URL-sync effect- // into racing with the /home redirect (the spurious- // /onboarding?step=1 replace wins, stranding the user on Welcome- // until they refresh).- useOnboardingWizardStore.persist.clearStorage();- router.replace("/home");- return;- }- } catch {- // If we can't check, show onboarding anyway- }- setIsOnboardingStateLoading(false);- }-- checkCompletion();- }, [isLoggedIn, router]);-- // Submit profile when entering the Preparing step- useEffect(() => {- if (currentStep !== preparingStep || hasSubmitted.current) return;- const { role, painPoints } = normalizeOnboardingProfile(- useOnboardingWizardStore.getState(),- );- const userName = accountDisplayName(user);-- // The profile is only ever submitted here, once, on reaching Preparing.- // Guard against an empty role so a stray Preparing visit can't blank a- // previously-saved profile.- if (!role.trim() || !userName) return;- hasSubmitted.current = true;-- postV1SubmitOnboardingProfile({- user_name: userName,- user_role: role,- pain_points: painPoints,- }).catch(() => {- // Best effort — profile data is non-critical for accessing copilot- });- }, [currentStep, preparingStep, user]);+ if (progress.isReady && trackingKey) trackOnboardingStep(trackingKey);+ }, [progress.isReady, trackingKey]);async function handlePreparingComplete() {- for (let attempt = 0; attempt < 3; attempt++) {- try {- await postV1CompleteOnboardingStep({ step: "ONBOARDING_COMPLETE" });- // Only a confirmed completion counts: the fall-through below still- // sends the user to the copilot after three failures, but the backend- // never recorded the milestone.- trackAdsConversion("onboarding_complete", {- transactionID: user?.id,- email: user?.email,- });- clearHighestStep();- useOnboardingWizardStore.persist.clearStorage();- router.replace("/home");- return;- } catch {- if (attempt < 2) await new Promise((r) => setTimeout(r, 1000));- }+ if (+ !progress.isReady ||+ completion.current?.userID === user?.id ||+ (isPaymentEnabled && !environment.isLocal())+ )+ return;+ const attempt = { userID: user?.id };+ completion.current = attempt;+ function isCurrent() {+ return (+ completion.current === attempt && activeUserID.current === user?.id+ );+ }+ setCompletionError(null);+ try {+ await useOnboardingWizardStore.getState().flushProgress?.();+ if (!isCurrent()) return;+ await profile.ensureSaved();+ if (!isCurrent()) return;+ const result = await postV1CompleteOnboardingStep({+ step: "ONBOARDING_COMPLETE",+ });+ if (!isCurrent()) return;+ if (result.status !== 200) throw new Error("Completion failed");+ trackAdsConversion("onboarding_complete", {+ transactionID: user?.id,+ email: user?.email,+ });+ progress.finish();+ router.replace("/home");+ } catch {+ if (!isCurrent()) return;+ setCompletionError({+ userID: user?.id,+ message:+ "We couldn't finish setting up your account. Your progress is saved; please retry.",+ });+ } finally {+ if (completion.current === attempt) completion.current = null;}- clearHighestStep();- useOnboardingWizardStore.persist.clearStorage();- router.replace("/home");}return {currentStep,- isLoading: isOnboardingStateLoading || !isReady,+ isLoading: !progress.isReady || !isReady,+ progressError: progress.error,+ progressConflict: progress.conflict,+ retryProgress: progress.retry,+ completionError:+ profile.error ??+ (completionError?.userID === user?.id ? completionError?.message : null),handlePreparingComplete,isPaymentEnabled,isSelfHostConnectEnabled,@@ -326,5 +151,6 @@ export function useOnboardingPage() {preparingStep,totalSteps,trialConfirmation,+ paidConfirmation,};}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingProfile.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingProfile.tsnew file mode 100644index 0000000000..cdf5366f31--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingProfile.ts@@ -0,0 +1,99 @@+import { postV1SubmitOnboardingProfile } from "@/app/api/__generated__/endpoints/onboarding/onboarding";+import type { User } from "@/lib/auth/types";+import { useEffect, useRef, useState } from "react";+import { accountDisplayName, normalizeOnboardingProfile } from "./helpers";+import { useOnboardingWizardStore } from "./store";++const SAVE_ERROR =+ "We couldn't save your profile. Your answers are saved; please retry before continuing.";++export function useOnboardingProfile({+ user,+ enabled,+}: {+ user: User | null;+ enabled: boolean;+}) {+ const userID = user?.id ?? null;+ const activeUserID = useRef(userID);+ activeUserID.current = userID;+ const submission = useRef<{+ key: string;+ abort: AbortController;+ promise: Promise<void>;+ } | null>(null);+ const [failure, setFailure] = useState<{+ userID: string;+ message: string;+ } | null>(null);++ useEffect(() => {+ return () => {+ submission.current?.abort.abort();+ submission.current = null;+ };+ }, [userID]);++ useEffect(() => {+ if (enabled && accountDisplayName(user))+ void ensureSaved().catch(() => undefined);+ }, [enabled, user]);++ async function ensureSaved() {+ if (+ !enabled ||+ !userID ||+ activeUserID.current !== userID ||+ useOnboardingWizardStore.getState().userID !== userID+ ) {+ throw new Error("Your account changed. Please reload onboarding.");+ }+ const { role, painPoints } = normalizeOnboardingProfile(+ useOnboardingWizardStore.getState(),+ );+ const userName = accountDisplayName(user);+ if (!role.trim() || !userName) {+ setFailure({ userID, message: SAVE_ERROR });+ throw new Error(SAVE_ERROR);+ }+ const profile = {+ user_name: userName,+ user_role: role,+ pain_points: painPoints,+ };+ const key = JSON.stringify({ userID, profile });+ if (submission.current?.key === key) return submission.current.promise;+ submission.current?.abort.abort();+ const abort = new AbortController();+ setFailure(null);+ function isCurrent() {+ return (+ submission.current?.abort === abort &&+ !abort.signal.aborted &&+ activeUserID.current === userID &&+ useOnboardingWizardStore.getState().userID === userID+ );+ }+ async function save() {+ const result = await postV1SubmitOnboardingProfile(profile, {+ signal: abort.signal,+ });+ if (!isCurrent()) throw new Error("Your account changed.");+ if (result.status !== 200) throw new Error(SAVE_ERROR);+ }+ const promise = save().catch((error: unknown) => {+ if (isCurrent()) {+ submission.current = null;+ setFailure({ userID, message: SAVE_ERROR });+ }+ throw error;+ });+ submission.current = { key, abort, promise };+ return promise;+ }++ return {+ ensureSaved,+ error: failure?.userID === userID ? failure.message : null,+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/usePaidCheckoutStatus.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/usePaidCheckoutStatus.tsnew file mode 100644index 0000000000..047e5e3b3f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/usePaidCheckoutStatus.ts@@ -0,0 +1,62 @@+import {+ getGetSubscriptionStatusQueryKey,+ useGetSubscriptionStatus,+} from "@/app/api/__generated__/endpoints/credits/credits";+import type { SubscriptionStatusResponse } from "@/app/api/__generated__/models/subscriptionStatusResponse";+import { useSearchParams } from "next/navigation";+import { useEffect, useRef, useState } from "react";++export function usePaidCheckoutStatus(+ userID: string | null,+ paymentEnabled: boolean,+) {+ const params = useSearchParams();+ const returning = useRef(params.get("subscription") === "success");+ const previousUserID = useRef(userID);+ if (previousUserID.current && previousUserID.current !== userID)+ returning.current = false;+ previousUserID.current = userID;+ const [timedOut, setTimedOut] = useState(false);+ const [attempt, setAttempt] = useState(0);+ const waitingForPayment = returning.current && paymentEnabled;+ const query = useGetSubscriptionStatus({+ query: {+ enabled: !!userID,+ queryKey: [...getGetSubscriptionStatusQueryKey(), userID],+ select: (res) =>+ res.status === 200+ ? (res.data as SubscriptionStatusResponse).tier+ : null,+ refetchInterval: (state) => {+ const response = state.state.data;+ const confirmed =+ response?.status === 200 && response.data.tier !== "NO_TIER";+ return waitingForPayment && !timedOut && !confirmed ? 1000 : false;+ },+ },+ });+ const active = !!query.data && query.data !== "NO_TIER";+ const unconfirmed = waitingForPayment && !active;+ useEffect(() => {+ if (!unconfirmed) return;+ const timer = setTimeout(() => setTimedOut(true), 15_000);+ return () => clearTimeout(timer);+ }, [unconfirmed, attempt]);++ function retry() {+ setTimedOut(false);+ setAttempt((value) => value + 1);+ void query.refetch();+ }+ return {+ active,+ isLoading: query.isLoading,+ ready: !unconfirmed,+ pending: unconfirmed && !timedOut,+ error:+ unconfirmed && timedOut+ ? "Your payment is still being confirmed. Please retry to check its status."+ : null,+ retry,+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useWizardProgress.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useWizardProgress.tsnew file mode 100644index 0000000000..1ecb0de4d7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useWizardProgress.ts@@ -0,0 +1,204 @@+import { patchV1UpdateOnboardingState } from "@/app/api/__generated__/endpoints/onboarding/onboarding";+import { useRouter, useSearchParams } from "next/navigation";+import { useEffect, useRef, useState } from "react";+import { clearLocalProgress, resumeStep, sameProgress } from "./progress";+import { loadWizardProgress } from "./loadWizardProgress";+import { createProgressSaver } from "./progress-saver";+import {+ snapshotProgress,+ type StepLayout,+ useOnboardingWizardStore,+} from "./store";++export function useWizardProgress({+ userID,+ ready,+ steps,+}: {+ userID: string | null;+ ready: boolean;+ steps: StepLayout;+}) {+ const router = useRouter();+ const params = useSearchParams();+ const currentUserID = useRef(userID);+ currentUserID.current = userID;+ const latest = useRef({ steps, params, router });+ latest.current = { steps, params, router };+ const layout = JSON.stringify(steps);+ const reloadLatest = useRef(false);+ const accountChanged = useRef(false);+ const [attempt, setAttempt] = useState(0);+ const [status, setStatus] = useState({+ userID,+ layout: "",+ loaded: false,+ loadError: false,+ conflict: false,+ error: null as string | null,+ });+ const saver = useRef<ReturnType<typeof createProgressSaver> | null>(null);++ useEffect(() => {+ if (!ready || !userID) return;+ let active = true;+ let unsubscribe: (() => void) | undefined;+ const abort = new AbortController();+ const { steps, params, router } = latest.current;+ const isCurrent = () => active && currentUserID.current === userID;+ useOnboardingWizardStore.getState().reset();+ setStatus({+ userID,+ layout,+ loaded: false,+ loadError: false,+ conflict: false,+ error: null,+ });++ function conflict() {+ if (isCurrent())+ setStatus({+ userID,+ layout,+ loaded: false,+ loadError: true,+ conflict: true,+ error:+ "Onboarding was updated in another session. Reload its latest progress to continue. This device's unsaved answers will be replaced.",+ });+ }++ async function initialize() {+ const result = await loadWizardProgress(+ userID!,+ reloadLatest.current,+ abort,+ );+ if (!isCurrent()) return;+ if (result.kind === "complete") {+ clearLocalProgress(userID!);+ router.replace("/home");+ return;+ }+ if (result.kind === "conflict") {+ conflict();+ return;+ }+ if (result.kind !== "ready") {+ accountChanged.current = result.kind === "accountChanged";+ setStatus({+ userID,+ layout,+ loaded: false,+ loadError: true,+ conflict: false,+ error: accountChanged.current+ ? "Your signed-in account changed. Reload the page to restore its progress."+ : "We couldn't restore your onboarding progress. Please retry.",+ });+ return;+ }+ const { progress, revision, offline, needsSync } = result;+ if (!offline) reloadLatest.current = false;+ const controller = createProgressSaver({+ userID: userID!,+ initialRevision: revision,+ onConflict: conflict,+ async save(wizardProgress, wizardRevision, signal) {+ if (!isCurrent()) throw new Error("Your account changed.");+ const result = await patchV1UpdateOnboardingState(+ { wizardProgress, wizardRevision, wizardUserId: userID! },+ { signal },+ );+ if (result.status !== 200) {+ throw Object.assign(new Error("Could not save onboarding."), {+ status: result.status,+ });+ }+ if (result.data.userId !== userID) {+ accountChanged.current = true;+ throw Object.assign(new Error("Your signed-in account changed."), {+ status: 409,+ });+ }+ return result.data.wizardRevision ?? wizardRevision + 1;+ },+ onError(error) {+ if (isCurrent()) setStatus((state) => ({ ...state, error }));+ },+ });+ saver.current = controller;+ const currentStep = resumeStep({+ progress,+ steps,+ requestedStep: params.get("step"),+ });+ const { currentStep: savedStep, version, ...fields } = progress ?? {};+ void savedStep;+ void version;+ useOnboardingWizardStore.setState({+ ...fields,+ userID,+ steps,+ currentStep,+ flushProgress: controller.flush,+ });+ setStatus({+ userID,+ layout,+ loaded: true,+ loadError: false,+ conflict: false,+ error: offline+ ? "Your saved progress is available on this device. Changes will sync when the connection returns."+ : null,+ });+ let previous = snapshotProgress();+ if (needsSync || (progress && !sameProgress(previous, progress)))+ controller.enqueue(previous);+ unsubscribe = useOnboardingWizardStore.subscribe((state) => {+ if (!isCurrent() || state.userID !== userID) return;+ const snapshot = snapshotProgress();+ if (sameProgress(snapshot, previous)) return;+ previous = snapshot;+ controller.enqueue(snapshot);+ });+ }+ void initialize();+ return () => {+ active = false;+ abort.abort();+ unsubscribe?.();+ saver.current?.dispose();+ saver.current = null;+ if (currentUserID.current !== userID)+ useOnboardingWizardStore.getState().reset();+ };+ }, [userID, ready, layout, attempt]);++ function retry() {+ if (accountChanged.current) {+ window.location.reload();+ return;+ }+ if (status.loadError) {+ reloadLatest.current = status.conflict;+ setAttempt((value) => value + 1);+ } else void saver.current?.flush().catch(() => undefined);+ }++ function finish() {+ saver.current?.dispose();+ if (userID) clearLocalProgress(userID);+ }++ return {+ isReady:+ status.loaded && status.userID === userID && status.layout === layout,+ error: status.userID === userID ? status.error : null,+ conflict: status.userID === userID && status.conflict,+ retry,+ finish,+ };+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 2736285dca..073ba9e845 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -11679,6 +11679,9 @@"401": {"$ref": "#/components/responses/HTTP401NotAuthenticatedError"},+ "409": {+ "description": "The wizard draft changed in another session"+ },"422": {"description": "Validation Error","content": {@@ -26880,7 +26883,7 @@"title": "User Role"},"pain_points": {- "items": { "type": "string" },+ "items": { "type": "string", "maxLength": 2000 },"type": "array","maxItems": 20,"title": "Pain Points"@@ -26934,6 +26937,116 @@"title": "OnboardingStep","description": "Application-level onboarding step identifiers."},+ "OnboardingWizardProgress": {+ "properties": {+ "version": { "type": "integer", "const": 1, "title": "Version" },+ "currentStep": {+ "type": "string",+ "enum": [+ "team",+ "autopilot",+ "role",+ "painPoints",+ "hire",+ "subscription",+ "connect",+ "preparing"+ ],+ "title": "Currentstep"+ },+ "completedSteps": {+ "items": {+ "type": "string",+ "enum": [+ "team",+ "autopilot",+ "role",+ "painPoints",+ "hire",+ "subscription",+ "connect",+ "preparing"+ ]+ },+ "type": "array",+ "maxItems": 8,+ "title": "Completedsteps"+ },+ "role": {+ "type": "string",+ "maxLength": 100,+ "pattern": "^[^\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]*$",+ "title": "Role"+ },+ "otherRole": {+ "type": "string",+ "maxLength": 100,+ "pattern": "^[^\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]*$",+ "title": "Otherrole"+ },+ "painPoints": {+ "items": {+ "type": "string",+ "maxLength": 200,+ "minLength": 1,+ "pattern": "^[^\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]*$"+ },+ "type": "array",+ "maxItems": 20,+ "title": "Painpoints"+ },+ "otherPainPoint": {+ "type": "string",+ "maxLength": 2000,+ "pattern": "^[^\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]*$",+ "title": "Otherpainpoint"+ },+ "selectedBilling": {+ "type": "string",+ "enum": ["monthly", "yearly"],+ "title": "Selectedbilling"+ },+ "hasUserSelectedBilling": {+ "type": "boolean",+ "title": "Hasuserselectedbilling"+ },+ "selectedCountryCode": {+ "type": "string",+ "maxLength": 2,+ "minLength": 2,+ "pattern": "^[A-Z]{2}$",+ "title": "Selectedcountrycode"+ },+ "hiredTemplateIds": {+ "items": {+ "type": "string",+ "maxLength": 128,+ "minLength": 1,+ "pattern": "^[^\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]*$"+ },+ "type": "array",+ "maxItems": 100,+ "title": "Hiredtemplateids"+ }+ },+ "additionalProperties": false,+ "type": "object",+ "required": [+ "version",+ "currentStep",+ "completedSteps",+ "role",+ "otherRole",+ "painPoints",+ "otherPainPoint",+ "selectedBilling",+ "hasUserSelectedBilling",+ "selectedCountryCode",+ "hiredTemplateIds"+ ],+ "title": "OnboardingWizardProgress",+ "description": "Saved wizard answers and navigation, independent of completion or access."+ },"OrgAliasResponse": {"properties": {"id": { "type": "string", "title": "Id" },@@ -33450,6 +33563,17 @@"UserOnboarding": {"properties": {"userId": { "type": "string", "title": "Userid" },+ "wizardProgress": {+ "anyOf": [+ { "$ref": "#/components/schemas/OnboardingWizardProgress" },+ { "type": "null" }+ ]+ },+ "wizardRevision": {+ "type": "integer",+ "title": "Wizardrevision",+ "default": 0+ },"completedSteps": {"items": { "$ref": "#/components/schemas/OnboardingStep" },"type": "array",@@ -33528,6 +33652,26 @@},"UserOnboardingUpdate": {"properties": {+ "wizardProgress": {+ "anyOf": [+ { "$ref": "#/components/schemas/OnboardingWizardProgress" },+ { "type": "null" }+ ]+ },+ "wizardRevision": {+ "anyOf": [+ { "type": "integer", "minimum": 0.0 },+ { "type": "null" }+ ],+ "title": "Wizardrevision"+ },+ "wizardUserId": {+ "anyOf": [+ { "type": "string", "maxLength": 128, "minLength": 1 },+ { "type": "null" }+ ],+ "title": "Wizarduserid"+ },"walletShown": {"anyOf": [{ "type": "boolean" }, { "type": "null" }],"title": "Walletshown"