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.
refactor(platform): OnboardingStep from Prisma enum to String[] (#13119)
Krzysztof Czerwinskia6ee6df941bd
diff --git a/.claude/skills/pr-test/SKILL.md b/.claude/skills/pr-test/SKILL.mdindex 66bcc7bc7e..c17ebd19fc 100644--- a/.claude/skills/pr-test/SKILL.md+++ b/.claude/skills/pr-test/SKILL.md@@ -539,12 +539,12 @@ curl -H "Authorization: Bearer $TOKEN" http://localhost:8006/api/...### 3i. Disable onboarding for test user-The frontend redirects to `/onboarding` when the `VISIT_COPILOT` step is not in `completedSteps`.+The frontend redirects to `/onboarding` when the `ONBOARDING_COMPLETE` step is not in `completedSteps`.Mark it complete via the backend API so every browser test lands on the real feature UI:```bashONBOARDING_RESULT=$(curl -s --max-time 30 -X POST \- "http://localhost:8006/api/onboarding/step?step=VISIT_COPILOT" \+ "http://localhost:8006/api/onboarding/step?step=ONBOARDING_COMPLETE" \-H "Authorization: Bearer $TOKEN")echo "Onboarding bypass: $ONBOARDING_RESULT"diff --git a/autogpt_platform/analytics/queries/user_onboarding_funnel.sql b/autogpt_platform/analytics/queries/user_onboarding_funnel.sqlindex cd5da2d307..5d4f275e17 100644--- a/autogpt_platform/analytics/queries/user_onboarding_funnel.sql+++ b/autogpt_platform/analytics/queries/user_onboarding_funnel.sql@@ -21,11 +21,11 @@-- STEP ORDER-- 1 WELCOME 9 MARKETPLACE_VISIT 17 SCHEDULE_AGENT-- 2 USAGE_REASON 10 MARKETPLACE_ADD_AGENT 18 RUN_AGENTS--- 3 INTEGRATIONS 11 MARKETPLACE_RUN_AGENT 19 RUN_3_DAYS+-- 3 INTEGRATIONS 11 LIBRARY_RUN_AGENT 19 RUN_3_DAYS-- 4 AGENT_CHOICE 12 BUILDER_OPEN 20 TRIGGER_WEBHOOK-- 5 AGENT_NEW_RUN 13 BUILDER_SAVE_AGENT 21 RUN_14_DAYS-- 6 AGENT_INPUT 14 BUILDER_RUN_AGENT 22 RUN_AGENTS_100--- 7 CONGRATS 15 VISIT_COPILOT+-- 7 CONGRATS 15 ONBOARDING_COMPLETE-- 8 GET_RESULTS 16 RE_RUN_AGENT---- WINDOW@@ -55,11 +55,11 @@ WITH all_steps AS (('GET_RESULTS', 8),('MARKETPLACE_VISIT', 9),('MARKETPLACE_ADD_AGENT', 10),- ('MARKETPLACE_RUN_AGENT', 11),+ ('LIBRARY_RUN_AGENT', 11),('BUILDER_OPEN', 12),('BUILDER_SAVE_AGENT', 13),('BUILDER_RUN_AGENT', 14),- ('VISIT_COPILOT', 15),+ ('ONBOARDING_COMPLETE', 15),('RE_RUN_AGENT', 16),('SCHEDULE_AGENT', 17),('RUN_AGENTS', 18),diff --git a/autogpt_platform/backend/backend/api/features/library/routes/agents.py b/autogpt_platform/backend/backend/api/features/library/routes/agents.pyindex 6cb4a687ea..199635231a 100644--- a/autogpt_platform/backend/backend/api/features/library/routes/agents.py+++ b/autogpt_platform/backend/backend/api/features/library/routes/agents.py@@ -3,9 +3,8 @@ from typing import Literal, Optionalimport autogpt_libs.auth as autogpt_auth_libfrom fastapi import APIRouter, Body, HTTPException, Query, Security, statusfrom fastapi.responses import Response-from prisma.enums import OnboardingStep-from backend.data.onboarding import complete_onboarding_step+from backend.data.onboarding import OnboardingStep, complete_onboarding_stepfrom .. import db as library_dbfrom .. import model as library_modeldiff --git a/autogpt_platform/backend/backend/api/features/onboarding_step_test.py b/autogpt_platform/backend/backend/api/features/onboarding_step_test.pynew file mode 100644index 0000000000..6397fef022--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/onboarding_step_test.py@@ -0,0 +1,153 @@+from unittest.mock import AsyncMock++import fastapi+import fastapi.testclient+import pytest++from backend.api.features.v1 import v1_router+from backend.data.onboarding import OnboardingStep++app = fastapi.FastAPI()+app.include_router(v1_router)+client = fastapi.testclient.TestClient(app)++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user):+ from autogpt_libs.auth.jwt_utils import get_jwt_payload++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()++[email protected]("invalid_step", ["VISIT_COPILOT", "BOGUS", "welcome", ""])+def test_complete_step_rejects_invalid_step(invalid_step):+ # Boundary validation is what replaces the dropped Prisma enum: any value+ # outside FrontendOnboardingStep must be rejected before any DB write. This+ # also locks in that the retired VISIT_COPILOT value is no longer accepted.+ response = client.post("/onboarding/step", params={"step": invalid_step})+ assert response.status_code == 422+++def test_complete_step_accepts_renamed_complete_value(mocker):+ mock_complete = mocker.patch(+ "backend.api.features.v1.complete_onboarding_step",+ new_callable=AsyncMock,+ return_value=None,+ )++ response = client.post(+ "/onboarding/step",+ params={"step": OnboardingStep.ONBOARDING_COMPLETE.value},+ )++ assert response.status_code == 200+ mock_complete.assert_awaited_once()+ assert mock_complete.await_args.args[1] == OnboardingStep.ONBOARDING_COMPLETE+++def test_is_onboarding_completed_true_when_complete_step_present(mocker):+ from backend.data.model import UserOnboarding++ mock_get = mocker.patch(+ "backend.api.features.v1.get_user_onboarding",+ new_callable=AsyncMock,+ )+ mock_get.return_value = UserOnboarding.model_construct(+ completedSteps=[OnboardingStep.WELCOME, OnboardingStep.ONBOARDING_COMPLETE],+ )++ response = client.get("/onboarding/completed")++ assert response.status_code == 200+ assert response.json()["is_completed"] is True+++def test_is_onboarding_completed_false_without_complete_step(mocker):+ from backend.data.model import UserOnboarding++ mock_get = mocker.patch(+ "backend.api.features.v1.get_user_onboarding",+ new_callable=AsyncMock,+ )+ mock_get.return_value = UserOnboarding.model_construct(+ completedSteps=[OnboardingStep.WELCOME],+ )++ response = client.get("/onboarding/completed")++ assert response.status_code == 200+ assert response.json()["is_completed"] is False+++def test_user_onboarding_response_model_accepts_deprecated_stored_values():+ from backend.data.model import UserOnboarding++ # Deprecated steps stay in OnboardingStep forever: existing rows still+ # contain them and the strict ``list[OnboardingStep]`` response model would+ # 500 reads otherwise. This validates (no ``model_construct``) so it fails+ # if a member is ever deleted from the enum.+ onboarding = UserOnboarding.model_validate(+ {+ "userId": "test-user-id",+ "completedSteps": ["MARKETPLACE_VISIT", "RE_RUN_AGENT", "RUN_AGENTS"],+ "walletShown": False,+ "notified": ["BUILDER_SAVE_AGENT"],+ "rewardedFor": ["MARKETPLACE_VISIT"],+ "usageReason": None,+ "integrations": [],+ "otherIntegrations": None,+ "selectedStoreListingVersionId": None,+ "agentInput": None,+ "onboardingAgentExecutionId": None,+ "agentRuns": 0,+ "lastRunAt": None,+ "consecutiveRunDays": 0,+ }+ )++ assert onboarding.completedSteps == [+ OnboardingStep.MARKETPLACE_VISIT,+ OnboardingStep.RE_RUN_AGENT,+ OnboardingStep.RUN_AGENTS,+ ]+++def test_update_onboarding_rejects_invalid_notified_step(mocker):+ mock_update = mocker.patch(+ "backend.api.features.v1.update_user_onboarding",+ new_callable=AsyncMock,+ )++ response = client.patch("/onboarding", json={"notified": ["VISIT_COPILOT"]})++ assert response.status_code == 422+ mock_update.assert_not_awaited()+++async def test_update_user_onboarding_merges_notified_as_plain_strings(mocker):+ from backend.data import onboarding as onboarding_module+ from backend.data.model import UserOnboarding++ mocker.patch.object(+ onboarding_module,+ "get_user_onboarding",+ new_callable=AsyncMock,+ return_value=UserOnboarding.model_construct(notified=["WELCOME"]),+ )+ mock_prisma_model = mocker.patch.object(onboarding_module, "UserOnboarding")+ mock_upsert = AsyncMock()+ mock_prisma_model.prisma.return_value.upsert = mock_upsert++ await onboarding_module.update_user_onboarding(+ "test-user-id",+ onboarding_module.UserOnboardingUpdate(+ notified=[OnboardingStep.AGENT_INPUT, OnboardingStep.WELCOME]+ ),+ )++ notified = mock_upsert.await_args.kwargs["data"]["update"]["notified"]+ assert sorted(notified) == ["AGENT_INPUT", "WELCOME"]+ assert all(type(value) is str for value in notified)diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex f295d552be..ab09eb18a4 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -381,7 +381,8 @@ async def is_onboarding_completed() -> OnboardingStatusResponse:user_onboarding = await get_user_onboarding(user_id)return OnboardingStatusResponse(- is_completed=OnboardingStep.VISIT_COPILOT in user_onboarding.completedSteps,+ is_completed=OnboardingStep.ONBOARDING_COMPLETE+ in user_onboarding.completedSteps,)@@ -1998,9 +1999,7 @@ async def execute_graph(record_graph_execution(graph_id=graph_id, status="success", user_id=user_id)record_graph_operation(operation="execute", status="success")if source == "library":- await complete_onboarding_step(- user_id, OnboardingStep.MARKETPLACE_RUN_AGENT- )+ await complete_onboarding_step(user_id, OnboardingStep.LIBRARY_RUN_AGENT)elif source == "builder":await complete_onboarding_step(user_id, OnboardingStep.BUILDER_RUN_AGENT)return resultdiff --git a/autogpt_platform/backend/backend/api/model.py b/autogpt_platform/backend/backend/api/model.pyindex c1642fb258..5a357a4e39 100644--- a/autogpt_platform/backend/backend/api/model.py+++ b/autogpt_platform/backend/backend/api/model.py@@ -2,10 +2,10 @@ import enumfrom typing import Any, Literal, Optionalimport pydantic-from prisma.enums import OnboardingStepfrom backend.data.auth.api_key import APIKeyInfo, APIKeyPermissionfrom backend.data.graph import Graph+from backend.data.onboarding_steps import OnboardingStepfrom backend.util.timezone_name import TimeZoneName@@ -93,6 +93,9 @@ class NotificationPayload(pydantic.BaseModel):class OnboardingNotificationPayload(NotificationPayload):+ # Typed enum: notifications only fire on fresh completions, where ``step`` is+ # always a current ``OnboardingStep`` (or ``None`` for ``increment_runs``).+ # Legacy step names live only in stored rows, never in emitted notifications.step: OnboardingStep | Nonediff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex f8c4a972c2..98533fbb43 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -13,7 +13,6 @@ from prisma.enums import (CreditRefundRequestStatus,CreditTransactionType,NotificationType,- OnboardingStep,SubscriptionTier,)from prisma.errors import PrismaError, UniqueViolationError@@ -52,6 +51,7 @@ from backend.util.settings import Settingsif TYPE_CHECKING:from backend.blocks._base import Block, BlockCost+ from backend.data.onboarding import OnboardingStepsettings = Settings()stripe.api_key = settings.secrets.stripe_api_key@@ -266,7 +266,7 @@ class UserCreditBase(ABC):@abstractmethodasync def onboarding_reward(- self, user_id: str, credits: int, step: OnboardingStep+ self, user_id: str, credits: int, step: "OnboardingStep") -> bool:"""Reward the user with credits for completing an onboarding step.@@ -275,7 +275,9 @@ class UserCreditBase(ABC):Args:user_id (str): The user ID.credits (int): The amount to reward.- step (OnboardingStep): The onboarding step.+ step (OnboardingStep): The onboarding step identifier. Imported under+ ``TYPE_CHECKING`` only, to avoid a circular import with+ ``backend.data.onboarding``.Returns:bool: True if rewarded, False if already rewarded.@@ -812,15 +814,17 @@ class UserCredit(UserCreditBase):balance, _ = await self._get_credits(user_id)return balance- async def onboarding_reward(self, user_id: str, credits: int, step: OnboardingStep):+ async def onboarding_reward(+ self, user_id: str, credits: int, step: "OnboardingStep"+ ):try:await self._add_transaction(user_id=user_id,amount=credits,transaction_type=CreditTransactionType.GRANT,- transaction_key=f"REWARD-{user_id}-{step.value}",+ transaction_key=f"REWARD-{user_id}-{step}",metadata=SafeJson(- {"reason": f"Reward for completing {step.value} onboarding step."}+ {"reason": f"Reward for completing {step} onboarding step."}),)return Truediff --git a/autogpt_platform/backend/backend/data/credit_concurrency_test.py b/autogpt_platform/backend/backend/data/credit_concurrency_test.pyindex 6a7be947a1..bf62714dbc 100644--- a/autogpt_platform/backend/backend/data/credit_concurrency_test.py+++ b/autogpt_platform/backend/backend/data/credit_concurrency_test.py@@ -16,6 +16,7 @@ from prisma.errors import UniqueViolationErrorfrom prisma.models import CreditTransaction, User, UserBalancefrom backend.data.credit import POSTGRES_INT_MAX, UsageTransactionMetadata, UserCredit+from backend.data.onboarding import OnboardingStepfrom backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.json import SafeJsonfrom backend.util.test import SpinTestServer@@ -290,7 +291,7 @@ async def test_onboarding_reward_idempotency(server: SpinTestServer):async def claim_reward():try:result = await credit_system.onboarding_reward(- user_id, 500, prisma.enums.OnboardingStep.WELCOME+ user_id, 500, OnboardingStep.WELCOME)return "SUCCESS" if result else "DUPLICATE"except Exception as e:diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.pyindex 04d9365741..a566a7b32b 100644--- a/autogpt_platform/backend/backend/data/model.py+++ b/autogpt_platform/backend/backend/data/model.py@@ -21,7 +21,7 @@ from typing import ()from uuid import uuid4-from prisma.enums import CreditTransactionType, OnboardingStep, SubscriptionTier+from prisma.enums import CreditTransactionType, SubscriptionTierfrom pydantic import (BaseModel,ConfigDict,@@ -41,6 +41,7 @@ from pydantic_core import ()from typing_extensions import TypedDict+from backend.data.onboarding_steps import OnboardingStepfrom backend.integrations.providers import ProviderNamefrom backend.util.json import loads as json_loadsfrom backend.util.request import parse_url@@ -985,6 +986,10 @@ class UserExecutionSummaryStats(BaseModel):class UserOnboarding(BaseModel):userId: str+ # 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 completion+ # endpoint via the ``FrontendOnboardingStep`` Literal.completedSteps: list[OnboardingStep]walletShown: boolnotified: list[OnboardingStep]diff --git a/autogpt_platform/backend/backend/data/onboarding.py b/autogpt_platform/backend/backend/data/onboarding.pyindex d770b1e818..9ebbfd105a 100644--- a/autogpt_platform/backend/backend/data/onboarding.py+++ b/autogpt_platform/backend/backend/data/onboarding.py@@ -1,11 +1,10 @@import refrom datetime import datetime, timedelta, timezone-from typing import Any, Literal, Optional+from typing import Any, Optionalfrom zoneinfo import ZoneInfoimport prismaimport pydantic-from prisma.enums import OnboardingStepfrom prisma.models import UserOnboardingfrom prisma.types import UserOnboardingCreateInput, UserOnboardingUpdateInput@@ -16,6 +15,10 @@ from backend.data.notification_bus import (AsyncRedisNotificationEventBus,NotificationEvent,)+from backend.data.onboarding_steps import (+ FrontendOnboardingStep as FrontendOnboardingStep,+)+from backend.data.onboarding_steps import OnboardingStepfrom backend.data.user import get_user_by_idfrom backend.util.cache import cachedfrom backend.util.json import SafeJson@@ -32,22 +35,17 @@ REASON_MAPPING: dict[str, list[str]] = {POINTS_AGENT_COUNT = 50 # Number of agents to calculate points forMIN_AGENT_COUNT = 2 # Minimum number of marketplace agents to enable onboarding-FrontendOnboardingStep = Literal[- OnboardingStep.WELCOME,- OnboardingStep.USAGE_REASON,- OnboardingStep.INTEGRATIONS,- OnboardingStep.AGENT_CHOICE,- OnboardingStep.AGENT_NEW_RUN,- OnboardingStep.AGENT_INPUT,- OnboardingStep.CONGRATS,- OnboardingStep.VISIT_COPILOT,- OnboardingStep.BUILDER_OPEN,- OnboardingStep.CAPABILITY_CARDS,-]+# OnboardingStep and FrontendOnboardingStep are imported from+# backend.data.onboarding_steps and remain importable from this module for+# backwards compatibility (`from backend.data.onboarding import OnboardingStep`).class UserOnboardingUpdate(pydantic.BaseModel):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,+ # which type `notified` as list[OnboardingStep]). The API merges this with+ # the existing column rather than treating it as authoritative.notified: Optional[list[OnboardingStep]] = NoneusageReason: Optional[str] = Noneintegrations: Optional[list[str]] = None@@ -96,7 +94,12 @@ async def update_user_onboarding(user_id: str, data: UserOnboardingUpdate):if data.walletShown:update["walletShown"] = data.walletShownif data.notified is not None:- update["notified"] = list(set(data.notified + onboarding.notified))+ # str(step): persist plain str so the merge with the stored str[] column+ # stays list[str]. str() works whether the value is an OnboardingStep+ # (StrEnum) or already a plain str, so it can't AttributeError.+ update["notified"] = list(+ set(onboarding.notified + [str(step) for step in data.notified])+ )if data.usageReason is not None:update["usageReason"] = data.usageReasonif data.integrations is not None:@@ -122,15 +125,15 @@ async def update_user_onboarding(user_id: str, data: UserOnboardingUpdate):async def _reward_user(user_id: str, onboarding: UserOnboarding, step: OnboardingStep):reward = 0match step:- # The wizard fires VISIT_COPILOT on completion; this is the grant+ # The wizard fires ONBOARDING_COMPLETE on completion; this is the grant# backing the wallet's "Complete onboarding" task ($3).- case OnboardingStep.VISIT_COPILOT:+ case OnboardingStep.ONBOARDING_COMPLETE:reward = 300case OnboardingStep.AGENT_NEW_RUN:reward = 300case OnboardingStep.MARKETPLACE_ADD_AGENT:reward = 100- case OnboardingStep.MARKETPLACE_RUN_AGENT:+ case OnboardingStep.LIBRARY_RUN_AGENT:reward = 100case OnboardingStep.SCHEDULE_AGENT:reward = 100@@ -155,7 +158,9 @@ async def _reward_user(user_id: str, onboarding: UserOnboarding, step: Onboardinawait UserOnboarding.prisma().update(where={"userId": user_id},data={- "rewardedFor": list(set(onboarding.rewardedFor + [step])),+ # str(step): persist a plain str (consistent with+ # update_user_onboarding); robust whether step is a StrEnum or a str.+ "rewardedFor": list(set(onboarding.rewardedFor + [str(step)])),},)@@ -169,7 +174,9 @@ async def complete_onboarding_step(user_id: str, step: OnboardingStep):await UserOnboarding.prisma().update(where={"userId": user_id},data={- "completedSteps": list(set(onboarding.completedSteps + [step])),+ # str(step): persist a plain str (see update_user_onboarding);+ # robust whether step is a StrEnum or a str.+ "completedSteps": list(set(onboarding.completedSteps + [str(step)])),},)await _reward_user(user_id, onboarding, step)diff --git a/autogpt_platform/backend/backend/data/onboarding_steps.py b/autogpt_platform/backend/backend/data/onboarding_steps.pynew file mode 100644index 0000000000..782cf78025--- /dev/null+++ b/autogpt_platform/backend/backend/data/onboarding_steps.py@@ -0,0 +1,74 @@+from enum import StrEnum+from typing import Literal+++# Stored as plain strings in UserOnboarding.{completedSteps,notified,rewardedFor}+# so adds/renames/retires are code-only. Writes are validated on the completion+# endpoint via FrontendOnboardingStep (a Pydantic Literal); reads are validated+# against this enum, which is why retired members are kept below.+#+# Lives in its own module (rather than onboarding.py) so the response model in+# backend.data.model can type its fields with this enum without importing the+# onboarding logic layer, which would create an import cycle.+#+# The class docstring ships into openapi.json (and the generated frontend+# client) as the schema description - keep it short and user-facing.+class OnboardingStep(StrEnum):+ """Application-level onboarding step identifiers."""++ # Retired steps are kept, never deleted: existing rows may still contain+ # them and the strict ``list[OnboardingStep]`` response model would 500 on+ # read otherwise, and the analytics funnel reports on them. Steps marked+ # ``# deprecated`` below are no longer set by any code path (no writer, not+ # accepted by the completion endpoint) - keep them; don't use in new code.++ # Introductory onboarding (Library)+ WELCOME = "WELCOME"+ USAGE_REASON = "USAGE_REASON"+ INTEGRATIONS = "INTEGRATIONS"+ AGENT_CHOICE = "AGENT_CHOICE"+ AGENT_NEW_RUN = "AGENT_NEW_RUN"+ AGENT_INPUT = "AGENT_INPUT"+ CONGRATS = "CONGRATS"+ # First Wins+ # ONBOARDING_COMPLETE is the wizard-completion signal that backs the+ # wallet's "Complete onboarding $3" tile. Renamed from VISIT_COPILOT in+ # SECRT-2355; existing rows are migrated in-place.+ ONBOARDING_COMPLETE = "ONBOARDING_COMPLETE"+ GET_RESULTS = "GET_RESULTS"+ MARKETPLACE_VISIT = "MARKETPLACE_VISIT" # deprecated: never set+ MARKETPLACE_ADD_AGENT = "MARKETPLACE_ADD_AGENT"+ # Fires on Library runs (source == "library") and is shown to users as a+ # Library action. Renamed from MARKETPLACE_RUN_AGENT in SECRT-2355 (the+ # MARKETPLACE_ prefix was a misnomer); existing rows are migrated in-place.+ LIBRARY_RUN_AGENT = "LIBRARY_RUN_AGENT"+ BUILDER_SAVE_AGENT = "BUILDER_SAVE_AGENT" # deprecated: never set+ # Consistency Challenge+ RE_RUN_AGENT = "RE_RUN_AGENT" # deprecated: never set+ SCHEDULE_AGENT = "SCHEDULE_AGENT"+ RUN_AGENTS = "RUN_AGENTS" # deprecated: never set+ RUN_3_DAYS = "RUN_3_DAYS"+ # The Pro Playground+ TRIGGER_WEBHOOK = "TRIGGER_WEBHOOK"+ RUN_14_DAYS = "RUN_14_DAYS"+ RUN_AGENTS_100 = "RUN_AGENTS_100"+ # No longer rewarded but exist for analytical purposes+ BUILDER_OPEN = "BUILDER_OPEN"+ BUILDER_RUN_AGENT = "BUILDER_RUN_AGENT"+ # Copilot home first-run: the capability-cards modal was completed or+ # skipped. Unrewarded; recorded so it shows only once per user.+ CAPABILITY_CARDS = "CAPABILITY_CARDS"+++FrontendOnboardingStep = Literal[+ OnboardingStep.WELCOME,+ OnboardingStep.USAGE_REASON,+ OnboardingStep.INTEGRATIONS,+ OnboardingStep.AGENT_CHOICE,+ OnboardingStep.AGENT_NEW_RUN,+ OnboardingStep.AGENT_INPUT,+ OnboardingStep.CONGRATS,+ OnboardingStep.ONBOARDING_COMPLETE,+ OnboardingStep.BUILDER_OPEN,+ OnboardingStep.CAPABILITY_CARDS,+]diff --git a/autogpt_platform/backend/backend/data/onboarding_test.py b/autogpt_platform/backend/backend/data/onboarding_test.pyindex 40b0507a91..814e860d58 100644--- a/autogpt_platform/backend/backend/data/onboarding_test.py+++ b/autogpt_platform/backend/backend/data/onboarding_test.py@@ -1,10 +1,14 @@+from typing import castfrom unittest.mock import AsyncMock, Mockimport pytestimport pytest_mock-from prisma.enums import OnboardingStep-from backend.data.onboarding import _reward_user, format_onboarding_for_extraction+from backend.data.onboarding import (+ OnboardingStep,+ _reward_user,+ format_onboarding_for_extraction,+)def test_format_onboarding_for_extraction_basic():@@ -37,10 +41,10 @@ def test_format_onboarding_for_extraction_with_other():@pytest.mark.parametrize("step,expected_reward",[- (OnboardingStep.VISIT_COPILOT, 300),+ (OnboardingStep.ONBOARDING_COMPLETE, 300),(OnboardingStep.AGENT_NEW_RUN, 300),(OnboardingStep.MARKETPLACE_ADD_AGENT, 100),- (OnboardingStep.MARKETPLACE_RUN_AGENT, 100),+ (OnboardingStep.LIBRARY_RUN_AGENT, 100),(OnboardingStep.SCHEDULE_AGENT, 100),(OnboardingStep.RUN_3_DAYS, 100),(OnboardingStep.TRIGGER_WEBHOOK, 100),@@ -89,3 +93,64 @@ async def test_reward_user_skips_if_already_rewarded(await _reward_user("user-1", onboarding, OnboardingStep.RUN_14_DAYS)credit_model.onboarding_reward.assert_not_called()++[email protected](loop_scope="function")+async def test_reward_user_noop_for_zero_reward_step(+ mocker: pytest_mock.MockFixture,+):+ # Steps without a configured reward (e.g. WELCOME) must never touch the+ # credit model — they are pure progress markers.+ onboarding = Mock()+ onboarding.rewardedFor = []++ credit_model = Mock()+ credit_model.onboarding_reward = AsyncMock()+ mocker.patch(+ "backend.data.onboarding.get_user_credit_model",+ AsyncMock(return_value=credit_model),+ )++ await _reward_user("user-1", onboarding, OnboardingStep.WELCOME)++ credit_model.onboarding_reward.assert_not_called()++[email protected](loop_scope="function")+async def test_reward_user_accepts_plain_string_step(+ mocker: pytest_mock.MockFixture,+):+ # The completion endpoint validates against ``FrontendOnboardingStep``+ # (a ``Literal[OnboardingStep, ...]``), which can hand the data layer a+ # plain ``str`` rather than an enum instance. The persist path must coerce+ # with ``str()``, not ``.value`` (which would AttributeError on a str).+ onboarding = Mock()+ onboarding.rewardedFor = []++ credit_model = Mock()+ credit_model.onboarding_reward = AsyncMock()+ mocker.patch(+ "backend.data.onboarding.get_user_credit_model",+ AsyncMock(return_value=credit_model),+ )+ mock_prisma = mocker.patch("backend.data.onboarding.UserOnboarding.prisma")+ mock_prisma.return_value.update = AsyncMock()++ # Pass a raw string typed as OnboardingStep to mimic the endpoint boundary.+ await _reward_user(+ "user-1", onboarding, cast(OnboardingStep, "ONBOARDING_COMPLETE")+ )++ credit_model.onboarding_reward.assert_called_once()+ persisted = mock_prisma.return_value.update.call_args.kwargs["data"]["rewardedFor"]+ assert persisted == ["ONBOARDING_COMPLETE"]+++def test_onboarding_step_values_are_plain_strings():+ # StrEnum members must round-trip through ``str`` unchanged so they can be+ # written directly into the ``String[]`` columns on UserOnboarding.+ assert str(OnboardingStep.ONBOARDING_COMPLETE) == "ONBOARDING_COMPLETE"+ assert OnboardingStep.ONBOARDING_COMPLETE == "ONBOARDING_COMPLETE"+ # Legacy values that have been retired (e.g. VISIT_COPILOT) must not appear+ # in the active set — existing rows containing them remain inert strings.+ assert "VISIT_COPILOT" not in {step.value for step in OnboardingStep}diff --git a/autogpt_platform/backend/backend/data/org_credit.py b/autogpt_platform/backend/backend/data/org_credit.pyindex 4f1999373d..2056dcf874 100644--- a/autogpt_platform/backend/backend/data/org_credit.py+++ b/autogpt_platform/backend/backend/data/org_credit.py@@ -10,7 +10,7 @@ import loggingfrom datetime import datetime, timezoneimport stripe-from prisma.enums import CreditTransactionType, OnboardingStep+from prisma.enums import CreditTransactionTypefrom pydantic import BaseModelfrom backend.data.credit import (@@ -21,6 +21,7 @@ from backend.data.credit import ()from backend.data.db import prismafrom backend.data.model import RefundRequest, TransactionHistory+from backend.data.onboarding_steps import OnboardingStepfrom backend.util.cache import cachedfrom backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.json import SafeJsondiff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.pyindex 19bf5f9841..96ee90ca19 100644--- a/autogpt_platform/backend/backend/executor/utils_test.py+++ b/autogpt_platform/backend/backend/executor/utils_test.py@@ -609,6 +609,7 @@ async def test_add_graph_execution_born_tenanted_via_rpc_when_prisma_disconnectemock_graph_exec = mocker.MagicMock(spec=GraphExecutionWithNodes)mock_graph_exec.organization_id = "org-rpc"mock_graph_exec.team_id = "team-rpc"+ mock_graph_exec.expert_id = Nonemock_graph_exec.id = "exec-id-rpc"mock_graph_exec.node_executions = []mock_graph_exec.status = ExecutionStatus.QUEUED@@ -1997,6 +1998,7 @@ def _mock_add_graph_execution_create_path(mock_graph_exec = mocker.MagicMock(spec=GraphExecutionWithNodes)mock_graph_exec.organization_id = org_idmock_graph_exec.team_id = team_id+ mock_graph_exec.expert_id = Nonemock_graph_exec.id = "exec-id"mock_graph_exec.node_executions = []mock_graph_exec.status = ExecutionStatus.QUEUEDdiff --git a/autogpt_platform/backend/migrations/20260805120000_onboarding_step_to_string/migration.sql b/autogpt_platform/backend/migrations/20260805120000_onboarding_step_to_string/migration.sqlnew file mode 100644index 0000000000..0719e90ca5--- /dev/null+++ b/autogpt_platform/backend/migrations/20260805120000_onboarding_step_to_string/migration.sql@@ -0,0 +1,44 @@+-- Convert UserOnboarding step columns from `OnboardingStep[]` to `String[]` so+-- that step renames/adds/retires become code-only changes. Boundary validation+-- moves to the API layer (Pydantic Literal on backend, OpenAPI-generated union+-- on frontend). See SECRT-2355.+--+-- Also renames two steps in existing rows so users keep their progress/rewards:+-- * `VISIT_COPILOT` -> `ONBOARDING_COMPLETE` (wizard-completion signal+-- backing the wallet's "Complete onboarding $3" tile; avoids re-routing+-- already-onboarded users through the wizard).+-- * `MARKETPLACE_RUN_AGENT` -> `LIBRARY_RUN_AGENT` (the step fires on Library+-- runs and is shown to users as a Library action, so the MARKETPLACE_ prefix+-- was a misnomer).++-- Drop defaults so the column type cast doesn't trip on the default's enum type.+ALTER TABLE "UserOnboarding" ALTER COLUMN "completedSteps" DROP DEFAULT;+ALTER TABLE "UserOnboarding" ALTER COLUMN "notified" DROP DEFAULT;+ALTER TABLE "UserOnboarding" ALTER COLUMN "rewardedFor" DROP DEFAULT;++-- Retype the columns. Data is preserved verbatim (enum -> text is lossless).+ALTER TABLE "UserOnboarding"+ ALTER COLUMN "completedSteps" TYPE TEXT[] USING "completedSteps"::TEXT[],+ ALTER COLUMN "notified" TYPE TEXT[] USING "notified"::TEXT[],+ ALTER COLUMN "rewardedFor" TYPE TEXT[] USING "rewardedFor"::TEXT[];++-- Restore defaults on the new column type.+ALTER TABLE "UserOnboarding" ALTER COLUMN "completedSteps" SET DEFAULT '{}';+ALTER TABLE "UserOnboarding" ALTER COLUMN "notified" SET DEFAULT '{}';+ALTER TABLE "UserOnboarding" ALTER COLUMN "rewardedFor" SET DEFAULT '{}';++-- Rename retired step names in existing rows so users keep their progress:+-- VISIT_COPILOT -> ONBOARDING_COMPLETE and MARKETPLACE_RUN_AGENT ->+-- LIBRARY_RUN_AGENT. Both renames are chained into a single pass so the table+-- is rewritten once. array_replace is a no-op when the value isn't present, so+-- applying both to every matched row is safe.+UPDATE "UserOnboarding"+SET "completedSteps" = array_replace(array_replace("completedSteps", 'VISIT_COPILOT', 'ONBOARDING_COMPLETE'), 'MARKETPLACE_RUN_AGENT', 'LIBRARY_RUN_AGENT'),+ "notified" = array_replace(array_replace("notified", 'VISIT_COPILOT', 'ONBOARDING_COMPLETE'), 'MARKETPLACE_RUN_AGENT', 'LIBRARY_RUN_AGENT'),+ "rewardedFor" = array_replace(array_replace("rewardedFor", 'VISIT_COPILOT', 'ONBOARDING_COMPLETE'), 'MARKETPLACE_RUN_AGENT', 'LIBRARY_RUN_AGENT')+WHERE "completedSteps" && ARRAY['VISIT_COPILOT', 'MARKETPLACE_RUN_AGENT']+ OR "notified" && ARRAY['VISIT_COPILOT', 'MARKETPLACE_RUN_AGENT']+ OR "rewardedFor" && ARRAY['VISIT_COPILOT', 'MARKETPLACE_RUN_AGENT'];++-- Drop the now-unused enum type.+DROP TYPE "OnboardingStep";diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex c7e71aa46f..d59a1909f8 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -187,48 +187,19 @@ enum SubscriptionTier {ENTERPRISE}-enum OnboardingStep {- // Introductory onboarding (Library)- WELCOME- USAGE_REASON- INTEGRATIONS- AGENT_CHOICE- AGENT_NEW_RUN- AGENT_INPUT- CONGRATS- // First Wins- VISIT_COPILOT- GET_RESULTS- MARKETPLACE_VISIT- MARKETPLACE_ADD_AGENT- MARKETPLACE_RUN_AGENT- BUILDER_SAVE_AGENT- // Consistency Challenge- RE_RUN_AGENT- SCHEDULE_AGENT- RUN_AGENTS- RUN_3_DAYS- // The Pro Playground- TRIGGER_WEBHOOK- RUN_14_DAYS- RUN_AGENTS_100- // No longer rewarded but exist for analytical purposes- BUILDER_OPEN- BUILDER_RUN_AGENT- // Copilot home first-run: the capability-cards modal was completed or- // skipped. Unrewarded; recorded so it shows only once per user.- CAPABILITY_CARDS-}-model UserOnboarding {id String @id @default(uuid())createdAt DateTime @default(now())updatedAt DateTime? @updatedAt- completedSteps OnboardingStep[] @default([])+ // Step names are validated at the API boundary (Pydantic Literal on the+ // backend, OpenAPI-generated union on the frontend). Storing as String[]+ // means renames/adds/retires are code-only — legacy values become inert+ // strings instead of stuck enum members. See SECRT-2355.+ completedSteps String[] @default([])walletShown Boolean @default(false)- notified OnboardingStep[] @default([])- rewardedFor OnboardingStep[] @default([])+ notified String[] @default([])+ rewardedFor String[] @default([])usageReason String?integrations String[] @default([])otherIntegrations String?diff --git a/autogpt_platform/backend/test/test_data_creator.py b/autogpt_platform/backend/test/test_data_creator.pyindex 75d45a0c1a..b1538261e1 100644--- a/autogpt_platform/backend/test/test_data_creator.py+++ b/autogpt_platform/backend/test/test_data_creator.py@@ -35,6 +35,8 @@ from prisma.types import (UserCreateInput,)+from backend.data.onboarding import OnboardingStep+faker = Faker()# Constants for data generation limits@@ -706,7 +708,7 @@ async def main():users, k=int(NUM_USERS * 0.7)): # 70% of users have onboarding datacompleted_steps = []- possible_steps = list(prisma.enums.OnboardingStep)+ possible_steps = [step.value for step in OnboardingStep]# Randomly complete some stepsif random.random() < 0.8:num_steps = random.randint(1, len(possible_steps))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 d60f766341..e1b3268b75 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@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {cleanup,+ fireEvent,render,screen,waitFor,@@ -23,8 +24,8 @@ vi.mock("../steps/SubscriptionStep/SubscriptionStep", () => ({SubscriptionStep: () => <div data-testid="step-subscription" />,}));vi.mock("../steps/PreparingStep", () => ({- PreparingStep: ({ onComplete: _onComplete }: { onComplete: () => void }) => (- <div data-testid="step-preparing" />+ PreparingStep: ({ onComplete }: { onComplete: () => void }) => (+ <button data-testid="step-preparing" onClick={onComplete} />),}));@@ -63,13 +64,20 @@ function mockAuthUserRoute() {);}+let mockCompletedSteps: string[] = [];+const completeOnboardingStep = vi.hoisted(() =>+ vi.fn(() => Promise.resolve({ status: 200 })),+);vi.mock("@/app/api/__generated__/endpoints/onboarding/onboarding", () => ({getV1OnboardingState: () =>- Promise.resolve({ status: 200, data: { completedSteps: [] } }),+ Promise.resolve({+ status: 200,+ data: { completedSteps: mockCompletedSteps },+ }),getV1CheckIfOnboardingIsCompleted: () =>Promise.resolve({ status: 200, data: false }),patchV1UpdateOnboardingState: () => Promise.resolve({ status: 200 }),- postV1CompleteOnboardingStep: () => Promise.resolve({ status: 200 }),+ postV1CompleteOnboardingStep: completeOnboardingStep,postV1SubmitOnboardingProfile: () => Promise.resolve({ status: 200 }),}));@@ -120,7 +128,9 @@ beforeEach(() => {authUserPutBodies.length = 0;mockAuthUserRoute();mockRefreshSession.mockClear();+ mockCompletedSteps = [];routerReplace.mockClear();+ completeOnboardingStep.mockClear();useOnboardingWizardStore.getState().reset();window.sessionStorage.removeItem(STEP_STORAGE_KEY);});@@ -240,7 +250,7 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {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 VISIT_COPILOT) being kicked through onboarding and asked to+ // pre-date ONBOARDING_COMPLETE) being kicked through onboarding and asked to// pay again to escape. With ENABLE_PLATFORM_PAYMENT on and tier=PRO,// step 4 must render Preparing — not SubscriptionStep.mockFlagValue = true;@@ -327,6 +337,33 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {expect(authUserPutBodies).toEqual([]);});+ it("redirects straight to /copilot when onboarding is already complete", async () => {+ mockCompletedSteps = ["ONBOARDING_COMPLETE"];+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "3");+ render(<OnboardingPage />);+ await waitFor(() => {+ expect(routerReplace).toHaveBeenCalledWith("/copilot");+ });+ // The wizard never renders and the resume ceiling is cleared.+ expect(screen.queryByTestId("step-welcome")).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, "4");+ currentSearchParams = new URLSearchParams("step=4");+ render(<OnboardingPage />);+ fireEvent.click(await screen.findByTestId("step-preparing"));+ await waitFor(() => {+ expect(routerReplace).toHaveBeenCalledWith("/copilot");+ });+ expect(completeOnboardingStep).toHaveBeenCalledWith({+ step: "ONBOARDING_COMPLETE",+ });+ expect(window.sessionStorage.getItem(STEP_STORAGE_KEY)).toBeNull();+ });+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// name/role on every mount. With zustand persist, refreshing mid-wizarddiff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.tsindex f1ec2f13f7..30f0d95a48 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts@@ -23,9 +23,10 @@ import {const LD_INIT_TIMEOUT_SECONDS = 5;// SessionStorage ceiling for the wizard. The backend's `completedSteps`-// only records VISIT_COPILOT 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.+// 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 {@@ -103,7 +104,7 @@ export function useOnboardingPage() {const isBrainDumpEnabled = brainDumpEnabledSnapshot.current ?? false;// Skip the paywall for users already on a paid tier (admin grants or- // pre-VISIT_COPILOT accounts) so they aren't asked to pay again to escape.+ // pre-ONBOARDING_COMPLETE accounts) so they aren't asked to pay again to escape.const { data: tier, isLoading: isTierLoading } = useGetSubscriptionStatus({query: {enabled: isLoggedIn,@@ -177,7 +178,7 @@ export function useOnboardingPage() {async function checkCompletion() {try {const onboarding = await resolveResponse(getV1OnboardingState());- if (onboarding.completedSteps.includes("VISIT_COPILOT")) {+ 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@@ -240,7 +241,7 @@ export function useOnboardingPage() {async function handlePreparingComplete() {for (let attempt = 0; attempt < 3; attempt++) {try {- await postV1CompleteOnboardingStep({ step: "VISIT_COPILOT" });+ await postV1CompleteOnboardingStep({ step: "ONBOARDING_COMPLETE" });clearHighestStep();useOnboardingWizardStore.persist.clearStorage();router.replace("/copilot");diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex c8b5930f19..2bb2c34fec 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -9338,7 +9338,7 @@"AGENT_NEW_RUN","AGENT_INPUT","CONGRATS",- "VISIT_COPILOT",+ "ONBOARDING_COMPLETE","BUILDER_OPEN","CAPABILITY_CARDS"],@@ -20249,11 +20249,11 @@"AGENT_NEW_RUN","AGENT_INPUT","CONGRATS",- "VISIT_COPILOT",+ "ONBOARDING_COMPLETE","GET_RESULTS","MARKETPLACE_VISIT","MARKETPLACE_ADD_AGENT",- "MARKETPLACE_RUN_AGENT",+ "LIBRARY_RUN_AGENT","BUILDER_SAVE_AGENT","RE_RUN_AGENT","SCHEDULE_AGENT",@@ -20266,7 +20266,8 @@"BUILDER_RUN_AGENT","CAPABILITY_CARDS"],- "title": "OnboardingStep"+ "title": "OnboardingStep",+ "description": "Application-level onboarding step identifiers."},"OrgAliasResponse": {"properties": {diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsxindex 3dc0dc028e..ffa3b42e1c 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/Wallet.test.tsx@@ -76,7 +76,7 @@ function buildOnboarding(overrides: Partial<UserOnboarding> = {},): UserOnboarding {return {- completedSteps: ["VISIT_COPILOT"],+ completedSteps: ["ONBOARDING_COMPLETE"],walletShown: false,notified: [],rewardedFor: [],@@ -210,7 +210,7 @@ describe("Wallet onboarding notifications", () => {expect(connectWebSocketMock).toHaveBeenCalledTimes(1);onboardingState.state = buildOnboarding({- completedSteps: ["VISIT_COPILOT", "SCHEDULE_AGENT"],+ completedSteps: ["ONBOARDING_COMPLETE", "SCHEDULE_AGENT"],});rerender(<Wallet />);diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsxindex 3e3c76aa96..295defc293 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/__tests__/WalletCompactPanel.test.tsx@@ -20,7 +20,7 @@ const groups: TaskGroup[] = [details: "",tasks: [{- id: "VISIT_COPILOT",+ id: "ONBOARDING_COMPLETE",name: "Complete onboarding",amount: 3,details: "",@@ -54,7 +54,7 @@ const groups: TaskGroup[] = [];const completedSteps: OnboardingStep[] = [- "VISIT_COPILOT",+ "ONBOARDING_COMPLETE","MARKETPLACE_ADD_AGENT",];@@ -88,7 +88,7 @@ describe("getEarnRows", () => {const rows = getEarnRows(groups, ["SCHEDULE_AGENT"]);expect(rows.map((row) => row.key)).toEqual([- "VISIT_COPILOT",+ "ONBOARDING_COMPLETE","MARKETPLACE_ADD_AGENT","SCHEDULE_AGENT","RUN_3_DAYS",@@ -100,7 +100,7 @@ describe("getEarnRows", () => {const rows = getEarnRows(groups, undefined);expect(rows.map((row) => row.key)).toEqual([- "VISIT_COPILOT",+ "ONBOARDING_COMPLETE","MARKETPLACE_ADD_AGENT","SCHEDULE_AGENT","RUN_3_DAYS",diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsxindex cb613aff1d..be5769470f 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/components/WalletCompactPanel.tsx@@ -2,7 +2,6 @@import { Text } from "@/components/atoms/Text/Text";import { Collapsible } from "@/components/molecules/Collapsible/Collapsible";-import { OnboardingStep } from "@/lib/autogpt-server-api";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { getEarnRows, TaskGroup } from "../helpers";import {@@ -14,7 +13,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";interface Props {groups: TaskGroup[];- completedSteps: OnboardingStep[] | undefined;+ completedSteps: string[] | undefined;formattedCredits: string;onAddCredits: () => void;}diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.ts b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.tsindex b18353addd..2452eea64f 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.ts+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/Wallet/helpers.ts@@ -25,7 +25,7 @@ export function getTaskGroups(state: UserOnboarding | null): TaskGroup[] {details: "Kickstart your journey with quick wins.",tasks: [{- id: "VISIT_COPILOT",+ id: "ONBOARDING_COMPLETE",name: "Complete onboarding",amount: 3,details: "",@@ -39,7 +39,7 @@ export function getTaskGroups(state: UserOnboarding | null): TaskGroup[] {video: "/onboarding/marketplace-add.mp4",},{- id: "MARKETPLACE_RUN_AGENT",+ id: "LIBRARY_RUN_AGENT",name: "Open the Library page and run an agent",amount: 1,details: "Go to the Library, open an agent you want, and run it",@@ -125,8 +125,9 @@ export function getEarnRows(// The onboarding payload is typed as always carrying `completedSteps`, but// the rest of the wallet already guards against it being absent — do the same// here so a thin backend response degrades to "nothing claimed" and not a- // TypeError.- completedSteps: OnboardingStep[] | undefined,+ // TypeError. Plain string[] (not OnboardingStep[]): stored rows may contain+ // legacy step names; the typed task ids still get typo protection.+ completedSteps: string[] | undefined,): EarnRow[] {const claimed = completedSteps ?? [];diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.tsindex f5290b166d..c040cb0dac 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts@@ -879,17 +879,16 @@ export type OnboardingStep =| "AGENT_INPUT"| "CONGRATS"// First Wins- | "VISIT_COPILOT"- | "CAPABILITY_CARDS"+ | "ONBOARDING_COMPLETE"| "GET_RESULTS"- | "MARKETPLACE_VISIT"+ | "MARKETPLACE_VISIT" // deprecated: never set| "MARKETPLACE_ADD_AGENT"- | "MARKETPLACE_RUN_AGENT"- | "BUILDER_SAVE_AGENT"+ | "LIBRARY_RUN_AGENT"+ | "BUILDER_SAVE_AGENT" // deprecated: never set// Consistency Challenge- | "RE_RUN_AGENT"+ | "RE_RUN_AGENT" // deprecated: never set| "SCHEDULE_AGENT"- | "RUN_AGENTS"+ | "RUN_AGENTS" // deprecated: never set| "RUN_3_DAYS"// The Pro Playground| "TRIGGER_WEBHOOK"@@ -897,13 +896,20 @@ export type OnboardingStep =| "RUN_AGENTS_100"// No longer used but tracked| "BUILDER_OPEN"- | "BUILDER_RUN_AGENT";+ | "BUILDER_RUN_AGENT"+ // Copilot home first-run: capability-cards modal completed or skipped+ | "CAPABILITY_CARDS";export interface UserOnboarding {- completedSteps: OnboardingStep[];+ // Plain string[] so legacy step names from existing rows pass through.+ // Validation against the active set lives on the completion endpoint via+ // `PostV1CompleteOnboardingStepStep` (the generated literal union).+ completedSteps: string[];walletShown: boolean;+ // Typed enum: `notified` is written back via PATCH /onboarding, which now+ // validates step names against OnboardingStep at the boundary.notified: OnboardingStep[];- rewardedFor: OnboardingStep[];+ rewardedFor: string[];usageReason: string | null;integrations: string[];otherIntegrations: string | null;@@ -918,6 +924,9 @@ export interface UserOnboarding {export interface OnboardingNotificationPayload {type: "onboarding";event: "step_completed" | "increment_runs";+ // Typed enum: notifications only fire on fresh completions, so `step` is+ // always a current OnboardingStep (or null for `increment_runs`). Legacy step+ // names live only in stored rows, never in emitted notifications.step: OnboardingStep | null;}diff --git a/autogpt_platform/frontend/src/playwright/utils/onboarding.ts b/autogpt_platform/frontend/src/playwright/utils/onboarding.tsindex 85fdd04b56..d5402a8665 100644--- a/autogpt_platform/frontend/src/playwright/utils/onboarding.ts+++ b/autogpt_platform/frontend/src/playwright/utils/onboarding.ts@@ -22,7 +22,7 @@ export async function completeOnboardingViaAPI(page: Page) {resolveAppUrl(page, "/api/proxy/api/onboarding/step"),{headers: { "Content-Type": "application/json" },- params: { step: "VISIT_COPILOT" },+ params: { step: "ONBOARDING_COMPLETE" },},);}diff --git a/autogpt_platform/frontend/src/providers/onboarding/helpers.test.ts b/autogpt_platform/frontend/src/providers/onboarding/helpers.test.tsindex e4e3f36cdd..b1db9aa580 100644--- a/autogpt_platform/frontend/src/providers/onboarding/helpers.test.ts+++ b/autogpt_platform/frontend/src/providers/onboarding/helpers.test.ts@@ -5,19 +5,22 @@ import {} from "./helpers";describe("shouldRedirectFromOnboarding", () => {- test("returns true once VISIT_COPILOT is completed", () => {- expect(shouldRedirectFromOnboarding(["VISIT_COPILOT"], "/onboarding")).toBe(- true,- );+ test("returns true once ONBOARDING_COMPLETE is completed", () => {+ expect(+ shouldRedirectFromOnboarding(["ONBOARDING_COMPLETE"], "/onboarding"),+ ).toBe(true);});- test("returns false when VISIT_COPILOT is missing", () => {+ test("returns false when ONBOARDING_COMPLETE is missing", () => {expect(shouldRedirectFromOnboarding([], "/onboarding")).toBe(false);});test("does not redirect away from /onboarding/reset", () => {expect(- shouldRedirectFromOnboarding(["VISIT_COPILOT"], "/onboarding/reset"),+ shouldRedirectFromOnboarding(+ ["ONBOARDING_COMPLETE"],+ "/onboarding/reset",+ ),).toBe(false);});});diff --git a/autogpt_platform/frontend/src/providers/onboarding/helpers.ts b/autogpt_platform/frontend/src/providers/onboarding/helpers.tsindex 6ddd71676a..894ce3fc2a 100644--- a/autogpt_platform/frontend/src/providers/onboarding/helpers.ts+++ b/autogpt_platform/frontend/src/providers/onboarding/helpers.ts@@ -31,12 +31,18 @@ export function fromBackendUserOnboarding(};}+// `completedSteps` stays string[] so legacy stored values pass through, but the+// step we gate the redirect on is checked against the union: a rename that+// misses this call site must fail the build, not silently route every+// onboarded user back into the wizard.+const ONBOARDING_COMPLETE = "ONBOARDING_COMPLETE" satisfies OnboardingStep;+export function shouldRedirectFromOnboarding(- completedSteps: OnboardingStep[],+ completedSteps: string[],pathname: string,): boolean {return (- completedSteps.includes("VISIT_COPILOT") &&+ completedSteps.includes(ONBOARDING_COMPLETE) &&!pathname.startsWith("/onboarding/reset"));}