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): raise your own expert v1 (#14041)
Abhimanyu Yadavf794951a3d87
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.pyindex 78b32db3d1..f534755535 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py@@ -1,5 +1,6 @@import asyncioimport logging+from typing import Literalimport prisma.errorsimport prisma.models@@ -14,20 +15,34 @@ from backend.api.features.experts.models import (ExpertSoulUpdate,ExpertWorkflowRef,HireResult,+ RaiseResult,decode_voice_preferences,)from backend.api.features.library import db as library_dbfrom backend.data.db import prisma as db_client-from backend.data.db import query_raw_with_schema+from backend.data.db import query_raw_with_schema, transactionfrom backend.data.expert_attribution import (resolve_attributable_expert as resolve_attributable_expert_row,)from backend.data.expert_spend import get_weekly_spendfrom backend.data.user import get_user_by_id+from backend.util.exceptions import NotFoundErrorfrom backend.util.timezone_utils import get_user_timezone_or_utclogger = logging.getLogger(__name__)++def _raised_identity(name: str) -> str:+ # f-string, not str.format on a template: user names may contain { or },+ # which str.format would choke on.+ return f"I'm {name}, raised by you. I learn how you work and grow with you."+++# The active cap bounds team-list fan-out. The lifetime raised-expert cap also+# bounds durable rows when users repeatedly raise and archive experts.+ACTIVE_EXPERT_LIMIT = 20+LIFETIME_RAISED_EXPERT_LIMIT = 100+_WORKFLOW_ROW_INCLUDE = {"LibraryAgent": True, "StoreListingVersion": True}_WORKFLOW_INCLUDE = {"Workflows": {"include": _WORKFLOW_ROW_INCLUDE}}@@ -44,6 +59,27 @@ class ExpertNotFoundError(Exception):self.expert_id = expert_id+class ExpertLimitExceededError(Exception):+ def __init__(self, limit: int):+ super().__init__(f"Active expert limit of {limit} reached")+ self.limit = limit+++class RaisedExpertLifetimeLimitExceededError(Exception):+ def __init__(self, limit: int):+ super().__init__(f"Raised expert lifetime limit of {limit} reached")+ self.limit = limit+++class FirstJobUnavailableError(Exception):+ def __init__(self, store_listing_version_id: str):+ super().__init__(+ f"Store listing version {store_listing_version_id} "+ "not found or unavailable"+ )+ self.store_listing_version_id = store_listing_version_id++def _to_workflow_ref(row: prisma.models.ExpertWorkflow) -> ExpertWorkflowRef:listing = row.StoreListingVersionlibrary_agent = row.LibraryAgent@@ -258,18 +294,11 @@ async def hire_expert(user_id: str, template_id: str, name: str | None) -> HireRif template is None:raise ExpertTemplateNotFoundError(template_id)- existing = await prisma.models.Expert.prisma().find_first(- where={"ownerUserId": user_id, "sourceTemplateId": template_id},- include=_WORKFLOW_INCLUDE,- )- if existing is not None:- return await _existing_hire_result(existing)-# Copy the plain description, never the template's sample envelope: a hire# that skips the voice pick must not leave raw JSON in the prompt, and the# pick (when made) overwrites this via the soul PATCH anyway.template_voice, _ = decode_voice_preferences(template.voicePreferences)- create_data: dict = {+ create_data: prisma.types.ExpertCreateInput = {"ownerUserId": user_id,"name": name or template.name,"avatarUrl": template.avatarUrl,@@ -284,17 +313,20 @@ async def hire_expert(user_id: str, template_id: str, name: str | None) -> HireR}if template.toolProfile is not None:create_data["toolProfile"] = template.toolProfile+try:- expert = await prisma.models.Expert.prisma().create(data=create_data)+ expert, state = await _reserve_hired_expert(user_id, template_id, create_data)except prisma.errors.UniqueViolationError:- # Lost a concurrent hire race; the winner's row satisfies idempotency.- raced = await prisma.models.Expert.prisma().find_first(- where={"ownerUserId": user_id, "sourceTemplateId": template_id},- include=_WORKFLOW_INCLUDE,- )- if raced is None:- raise- return await _existing_hire_result(raced)+ # A caller running older code may not participate in the advisory lock.+ # Retry after the failed transaction so its winning row is handled by+ # the same capacity-aware path.+ expert, state = await _reserve_hired_expert(user_id, template_id, create_data)++ if state == "existing":+ return HireResult(expert=_to_model(expert), failed_preloads=[])+ if state == "revived":+ expert = await _resume_revived_hire(expert)+ return HireResult(expert=_to_model(expert), failed_preloads=[])failed = await _install_preloads(expert.id, user_id, template.Workflows or [])@@ -306,38 +338,219 @@ async def hire_expert(user_id: str, template_id: str, name: str | None) -> HireRreturn HireResult(expert=_to_model(hydrated), failed_preloads=failed)-async def _existing_hire_result(row: prisma.models.Expert) -> HireResult:- """Idempotent-hire result for an already-existing hired copy.+async def _reserve_hired_expert(+ user_id: str,+ template_id: str,+ create_data: prisma.types.ExpertCreateInput,+) -> tuple[prisma.models.Expert, Literal["existing", "revived", "created"]]:+ """Atomically get, revive, or create one hired expert.++ Hires share the same per-user lock and active-team capacity check as+ raised experts. An idempotent retry of an already-active hire does not+ consume capacity, while reviving an archived hire does.+ """+ async with transaction() as tx:+ await _lock_expert_creation(tx, user_id)+ existing = await tx.expert.find_first(+ where={"ownerUserId": user_id, "sourceTemplateId": template_id},+ include=_WORKFLOW_INCLUDE,+ )+ if existing is not None:+ if not existing.isArchived:+ return existing, "existing"+ await _ensure_active_expert_capacity(tx, user_id)+ revived = await tx.expert.update(+ where={"id": existing.id},+ data={"isArchived": False},+ include=_WORKFLOW_INCLUDE,+ )+ if revived is None:+ raise ExpertNotFoundError(existing.id)+ return revived, "revived"++ await _ensure_active_expert_capacity(tx, user_id)+ created = await tx.expert.create(+ data=create_data,+ include=_WORKFLOW_INCLUDE,+ )+ return created, "created"+++async def _resume_revived_hire(row: prisma.models.Expert) -> prisma.models.Expert:+ if row.ownerUserId is None:+ return row++ await scheduling.resume_expert_schedules(row.ownerUserId, row.id)+ try:+ await scheduling.reattach_expert_triggers(row.ownerUserId, row.id)+ except Exception:+ logger.exception(f"Failed to reattach triggers while reviving expert #{row.id}")++ # Resume/reattach mutated pause state and workflow scheduleIds after `row`+ # was read — reload so the result isn't stale.+ refreshed = await prisma.models.Expert.prisma().find_unique(+ where={"id": row.id}, include=_WORKFLOW_INCLUDE+ )+ return refreshed or row+- Re-hiring an archived expert revives it — the unique- (ownerUserId, sourceTemplateId) constraint means a fresh row cannot be- created, and returning the archived row as-is would hand back a- "successful" hire that stays invisible to list_experts/get_expert.+async def _lock_expert_creation(tx: prisma.Prisma, user_id: str) -> None:+ # execute_raw, not query_raw: pg_advisory_xact_lock returns void,+ # which Prisma cannot deserialize as a result column.+ await tx.execute_raw(+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", user_id+ )+++async def _ensure_active_expert_capacity(tx: prisma.Prisma, user_id: str) -> None:+ active_count = await tx.expert.count(+ where={+ "ownerUserId": user_id,+ "isTemplate": False,+ "isArchived": False,+ }+ )+ if active_count >= ACTIVE_EXPERT_LIMIT:+ raise ExpertLimitExceededError(ACTIVE_EXPERT_LIMIT)+++async def create_raised_expert(+ user_id: str,+ name: str,+ role: str | None,+ voice_preferences: str | None,+ first_job_store_listing_version_id: str | None,+) -> RaiseResult:+ """Raise a blank expert owned by *user_id*.++ A raised expert has no source template, so ``sourceTemplateId`` stays+ NULL. Capacity checks and creation share a per-user advisory lock. A+ requested first job is validated before creation, then its exact listing+ rows are locked and revalidated through workflow association. Installation+ failure remains non-fatal and is reported in the result."""- if row.isArchived:- revived = await prisma.models.Expert.prisma().update(- where={"id": row.id},- data={"isArchived": False},+ if first_job_store_listing_version_id is not None:+ await _validate_first_job_listing(first_job_store_listing_version_id)++ expert = await _create_raised_expert_row(user_id, name, role, voice_preferences)+ first_job_installed = False+ failure_reason: Literal["unavailable", "installation_failed"] | None = None+ if first_job_store_listing_version_id is not None:+ try:+ await _install_first_job(+ user_id, expert.id, first_job_store_listing_version_id+ )+ first_job_installed = True+ except (FirstJobUnavailableError, NotFoundError):+ # NotFoundError covers the listing version or its graph disappearing+ # between the locked availability check and graph resolution, which+ # is the same "no longer available" outcome for the client.+ failure_reason = "unavailable"+ logger.warning(+ f"First job {first_job_store_listing_version_id} became "+ f"unavailable while raising expert #{expert.id} for user #{user_id}"+ )+ except Exception:+ failure_reason = "installation_failed"+ logger.exception(+ f"Failed to install first job "+ f"{first_job_store_listing_version_id} on raised "+ f"expert #{expert.id} for user #{user_id}"+ )++ if first_job_installed:+ hydrated = await get_expert(user_id, expert.id)+ if hydrated is None:+ raise ExpertNotFoundError(expert.id)+ else:+ hydrated = _to_model(expert)+ return RaiseResult(+ expert=hydrated,+ first_job_installed=first_job_installed,+ first_job_failure_reason=failure_reason,+ )+++async def _create_raised_expert_row(+ user_id: str,+ name: str,+ role: str | None,+ voice_preferences: str | None,+) -> prisma.models.Expert:+ async with transaction() as tx:+ await _lock_expert_creation(tx, user_id)+ await _ensure_active_expert_capacity(tx, user_id)+ lifetime_raised_count = await tx.expert.count(+ where={+ "ownerUserId": user_id,+ "isTemplate": False,+ "sourceTemplateId": None,+ }+ )+ if lifetime_raised_count >= LIFETIME_RAISED_EXPERT_LIMIT:+ raise RaisedExpertLifetimeLimitExceededError(LIFETIME_RAISED_EXPERT_LIMIT)+ return await tx.expert.create(+ data={+ "ownerUserId": user_id,+ "name": name,+ "role": role or "",+ "identity": _raised_identity(name),+ "voicePreferences": voice_preferences or "",+ },include=_WORKFLOW_INCLUDE,)- if revived is not None:- row = revived- if row.ownerUserId:- await scheduling.resume_expert_schedules(row.ownerUserId, row.id)- try:- await scheduling.reattach_expert_triggers(row.ownerUserId, row.id)- except Exception:- logger.exception(- f"Failed to reattach triggers while reviving expert #{row.id}"- )- # Resume/reattach mutated pause state and workflow scheduleIds- # after `row` was read — reload so the result isn't stale.- refreshed = await prisma.models.Expert.prisma().find_unique(- where={"id": row.id}, include=_WORKFLOW_INCLUDE+++async def _install_first_job(+ user_id: str,+ expert_id: str,+ store_listing_version_id: str,+) -> None:+ async with transaction() as tx:+ is_installable = (+ await library_db.is_store_listing_version_available_for_install(+ store_listing_version_id,+ tx=tx,+ lock_rows=True,)- if refreshed is not None:- row = refreshed- return HireResult(expert=_to_model(row), failed_preloads=[])+ )+ if not is_installable:+ raise FirstJobUnavailableError(store_listing_version_id)++ expert = await tx.expert.find_first(+ where={+ "id": expert_id,+ "ownerUserId": user_id,+ "isTemplate": False,+ "isArchived": False,+ }+ )+ if expert is None:+ raise ExpertNotFoundError(expert_id)++ library_agent = await library_db.add_store_agent_to_library_in_transaction(+ store_listing_version_id, user_id, tx+ )+ await tx.expertworkflow.create(+ data={+ "expertId": expert_id,+ "storeListingVersionId": store_listing_version_id,+ "libraryAgentId": library_agent.id,+ }+ )+++async def _validate_first_job_listing(store_listing_version_id: str) -> None:+ """Require the submitted listing-version row itself to be live.++ The shared library install path authorizes by graph, which would let a+ pending or deleted version UUID pointing at an approved graph slip+ through and link the expert to an unapproved row."""+ is_installable = await library_db.is_store_listing_version_available_for_install(+ store_listing_version_id+ )+ if not is_installable:+ raise FirstJobUnavailableError(store_listing_version_id)async def update_soul(user_id: str, expert_id: str, soul: ExpertSoulUpdate) -> Expert:diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.pyindex 2d8f8f2e8d..b991b0ddbf 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py@@ -30,7 +30,6 @@ from backend.data.db import prisma as db_clientfrom backend.data.graph import Graph, GraphSettings, Nodefrom backend.data.model import Userfrom backend.data.user import get_or_create_user-from backend.usecases.sample import create_test_userfrom backend.util.exceptions import ExpertRunPausedError, NotFoundErrorfrom backend.util.json import SafeJsonfrom backend.util.test import SpinTestServer@@ -67,12 +66,12 @@ def mock_embedding_functions():@pytest.fixtureasync def test_user():- return await create_test_user()+ return await _create_seed_user()@pytest.fixtureasync def other_user():- return await create_test_user(alt_user=True)+ return await _create_seed_user()async def _create_seed_user():@@ -86,11 +85,12 @@ async def _create_seed_user():)-async def _seed_store_listing(server: SpinTestServer) -> str:- """Create a graph plus an APPROVED store listing on top of it.+async def _seed_store_listing(server: SpinTestServer, approved: bool = True) -> str:+ """Create a graph plus a store listing on top of it.Returns the StoreListingVersion ID, ready for- ``add_store_agent_to_library``. Mirrors the seeding pattern from+ ``add_store_agent_to_library``. With ``approved=False`` the version is+ left in its submitted PENDING state. Mirrors the seeding pattern from``backend/data/graph_test.py::test_access_store_listing_graph``."""owner = await _create_seed_user()@@ -130,14 +130,15 @@ async def _seed_store_listing(server: SpinTestServer) -> str:slv_id = listing.listing_version_idassert slv_id is not None, "Failed to create store listing"- await server.agent_server.test_review_store_listing(- store_model.ReviewSubmissionRequest(- store_listing_version_id=slv_id,- is_approved=True,- comments="seed",- ),- user_id=admin.id,- )+ if approved:+ await server.agent_server.test_review_store_listing(+ store_model.ReviewSubmissionRequest(+ store_listing_version_id=slv_id,+ is_approved=True,+ comments="seed",+ ),+ user_id=admin.id,+ )return slv_id@@ -250,6 +251,521 @@ async def test_hire_expert_is_idempotent(server: SpinTestServer, test_user):assert first.expert.source_template_id == template.id[email protected](loop_scope="session")+async def test_hire_expert_is_idempotent_at_active_cap(server: SpinTestServer):+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ first = await experts_db.hire_expert(owner.id, template.id, None)+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Filler {i}",+ "role": "",+ "identity": f"I'm Filler {i}.",+ }+ for i in range(experts_db.ACTIVE_EXPERT_LIMIT - 1)+ ]+ )++ second = await experts_db.hire_expert(owner.id, template.id, None)++ assert second.expert.id == first.expert.id++[email protected](loop_scope="session")+async def test_hire_expert_enforces_active_expert_cap(server: SpinTestServer):+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Filler {i}",+ "role": "",+ "identity": f"I'm Filler {i}.",+ }+ for i in range(experts_db.ACTIVE_EXPERT_LIMIT)+ ]+ )++ with pytest.raises(experts_db.ExpertLimitExceededError):+ await experts_db.hire_expert(owner.id, template.id, None)++ assert (+ await prisma.models.Expert.prisma().count(+ where={"ownerUserId": owner.id, "sourceTemplateId": template.id}+ )+ == 0+ )++[email protected](loop_scope="session")+async def test_hire_and_raise_share_active_expert_cap(server: SpinTestServer):+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Filler {i}",+ "role": "",+ "identity": f"I'm Filler {i}.",+ }+ for i in range(experts_db.ACTIVE_EXPERT_LIMIT - 1)+ ]+ )++ results = await asyncio.gather(+ experts_db.hire_expert(owner.id, template.id, None),+ experts_db.create_raised_expert(owner.id, "Nova", None, None, None),+ return_exceptions=True,+ )++ assert sum(not isinstance(result, BaseException) for result in results) == 1+ assert (+ sum(+ isinstance(result, experts_db.ExpertLimitExceededError)+ for result in results+ )+ == 1+ )+ assert (+ await prisma.models.Expert.prisma().count(+ where={+ "ownerUserId": owner.id,+ "isTemplate": False,+ "isArchived": False,+ }+ )+ == experts_db.ACTIVE_EXPERT_LIMIT+ )++[email protected](loop_scope="session")+async def test_raise_expert_creates_blank_owned_expert(server: SpinTestServer):+ owner = await _create_seed_user()+ raised = await experts_db.create_raised_expert(+ owner.id,+ name="Otto",+ role=None,+ voice_preferences=None,+ first_job_store_listing_version_id=None,+ )+ assert not raised.expert.is_template+ assert raised.expert.source_template_id is None+ assert raised.expert.name == "Otto"+ assert "Otto" in raised.expert.identity+ assert raised.expert.workflows == []+ assert raised.first_job_installed is False+ assert raised.first_job_failure_reason is None+ assert raised.expert.id in {e.id for e in await experts_db.list_experts(owner.id)}++[email protected](loop_scope="session")+async def test_raise_expert_allows_multiple_per_owner(server: SpinTestServer):+ owner = await _create_seed_user()+ first = await experts_db.create_raised_expert(owner.id, "Otto", None, None, None)+ second = await experts_db.create_raised_expert(owner.id, "Nova", None, None, None)+ assert first.expert.id != second.expert.id+ owned = {e.id for e in await experts_db.list_experts(owner.id)}+ assert {first.expert.id, second.expert.id} <= owned++[email protected](loop_scope="session")+async def test_raise_expert_is_scoped_to_owner(server: SpinTestServer, other_user):+ owner = await _create_seed_user()+ raised = await experts_db.create_raised_expert(owner.id, "Otto", None, None, None)+ assert await experts_db.get_expert(other_user.id, raised.expert.id) is None+ assert await experts_db.get_expert(owner.id, raised.expert.id) is not None++[email protected](loop_scope="session")+async def test_raise_expert_installs_first_job(server: SpinTestServer):+ owner = await _create_seed_user()+ slv_id = await _seed_store_listing(server)+ raised = await experts_db.create_raised_expert(+ owner.id,+ name="Nova",+ role="Research Assistant",+ voice_preferences="Warm and detailed.",+ first_job_store_listing_version_id=slv_id,+ )+ assert raised.expert.role == "Research Assistant"+ assert raised.expert.voice_preferences == "Warm and detailed."+ assert raised.first_job_installed is True+ assert raised.first_job_failure_reason is None+ assert len(raised.expert.workflows) == 1+ assert raised.expert.workflows[0].store_listing_version_id == slv_id++[email protected](loop_scope="session")+async def test_raise_expert_restores_existing_first_job_library_agent(+ server: SpinTestServer,+):+ owner = await _create_seed_user()+ slv_id = await _seed_store_listing(server)+ existing = await library_db.add_store_agent_to_library(slv_id, owner.id)+ existing_row = await prisma.models.LibraryAgent.prisma().find_unique(+ where={"id": existing.id}+ )+ assert existing_row is not None+ original_tenancy = (existing_row.organizationId, existing_row.teamId)+ await prisma.models.LibraryAgent.prisma().update(+ where={"id": existing.id},+ data={"isDeleted": True, "isArchived": True},+ )++ raised = await experts_db.create_raised_expert(owner.id, "Nova", None, None, slv_id)++ restored = await prisma.models.LibraryAgent.prisma().find_unique(+ where={"id": existing.id}+ )+ assert restored is not None+ assert restored.isDeleted is False+ assert restored.isArchived is False+ assert (restored.organizationId, restored.teamId) == original_tenancy+ assert raised.expert.workflows[0].library_agent_id == existing.id++[email protected](loop_scope="session")+async def test_first_job_install_rolls_back_library_agent_on_link_failure(+ server: SpinTestServer,+):+ owner = await _create_seed_user()+ slv_id = await _seed_store_listing(server)+ expert = await prisma.models.Expert.prisma().create(+ data={+ "ownerUserId": owner.id,+ "name": "Nova",+ "role": "",+ "identity": experts_db._raised_identity("Nova"),+ }+ )+ await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": expert.id,+ "storeListingVersionId": slv_id,+ }+ )++ with pytest.raises(prisma.errors.UniqueViolationError):+ await experts_db._install_first_job(owner.id, expert.id, slv_id)++ listing = await prisma.models.StoreListingVersion.prisma().find_unique(+ where={"id": slv_id}, include={"AgentGraph": True}+ )+ assert listing is not None+ assert listing.AgentGraph is not None+ assert (+ await prisma.models.LibraryAgent.prisma().count(+ where={+ "userId": owner.id,+ "agentGraphId": listing.AgentGraph.id,+ "agentGraphVersion": listing.AgentGraph.version,+ }+ )+ == 0+ )++[email protected](loop_scope="session")+async def test_raise_expert_reports_failed_first_job(server: SpinTestServer):+ owner = await _create_seed_user()+ slv_id = await _seed_store_listing(server)+ with patch.object(+ experts_db.library_db,+ "add_store_agent_to_library_in_transaction",+ new_callable=AsyncMock,+ side_effect=RuntimeError("install exploded"),+ ):+ raised = await experts_db.create_raised_expert(+ owner.id, "Otto", None, None, slv_id+ )+ assert not raised.expert.is_template+ assert raised.expert.workflows == []+ assert raised.first_job_installed is False+ assert raised.first_job_failure_reason == "installation_failed"++[email protected](loop_scope="session")+async def test_raise_expert_reports_vanished_graph_as_unavailable(+ server: SpinTestServer,+):+ """A graph that disappears during install is 'unavailable', not a failure."""+ owner = await _create_seed_user()+ slv_id = await _seed_store_listing(server)+ with patch.object(+ experts_db.library_db,+ "add_store_agent_to_library_in_transaction",+ new_callable=AsyncMock,+ side_effect=NotFoundError("Graph #x v1 not found or accessible"),+ ):+ raised = await experts_db.create_raised_expert(+ owner.id, "Otto", None, None, slv_id+ )+ assert raised.expert.workflows == []+ assert raised.first_job_installed is False+ assert raised.first_job_failure_reason == "unavailable"++[email protected](loop_scope="session")+async def test_raise_expert_handles_braces_in_name(server: SpinTestServer):+ owner = await _create_seed_user()+ raised = await experts_db.create_raised_expert(owner.id, "a{b", None, None, None)+ assert raised.expert.name == "a{b"+ assert "a{b" in raised.expert.identity++[email protected](loop_scope="session")+async def test_raise_expert_degrades_when_first_job_vanishes_mid_flight(+ server: SpinTestServer,+):+ """A real withdrawal between precheck and locked install is rejected."""+ owner = await _create_seed_user()+ slv_id = await _seed_store_listing(server)+ create_row = experts_db._create_raised_expert_row++ async def create_then_withdraw(+ user_id: str,+ name: str,+ role: str | None,+ voice_preferences: str | None,+ ) -> prisma.models.Expert:+ expert = await create_row(user_id, name, role, voice_preferences)+ await prisma.models.StoreListingVersion.prisma().update(+ where={"id": slv_id}, data={"isAvailable": False}+ )+ return expert++ with patch.object(+ experts_db,+ "_create_raised_expert_row",+ new=create_then_withdraw,+ ):+ raised = await experts_db.create_raised_expert(+ owner.id, "Otto", None, None, slv_id+ )+ assert raised.expert.workflows == []+ assert raised.first_job_installed is False+ assert raised.first_job_failure_reason == "unavailable"+ assert (+ await prisma.models.ExpertWorkflow.prisma().count(+ where={"expertId": raised.expert.id}+ )+ == 0+ )++[email protected](loop_scope="session")+async def test_raise_expert_rejects_unapproved_first_job(server: SpinTestServer):+ owner = await _create_seed_user()+ pending_slv_id = await _seed_store_listing(server, approved=False)++ with pytest.raises(experts_db.FirstJobUnavailableError):+ await experts_db.create_raised_expert(+ owner.id, "Otto", None, None, pending_slv_id+ )++ assert await experts_db.list_experts(owner.id) == []++[email protected](loop_scope="session")+async def test_raise_expert_rejects_withdrawn_first_job(server: SpinTestServer):+ owner = await _create_seed_user()+ withdrawn_slv_id = await _seed_store_listing(server)+ await prisma.models.StoreListingVersion.prisma().update(+ where={"id": withdrawn_slv_id}, data={"isAvailable": False}+ )++ with pytest.raises(experts_db.FirstJobUnavailableError):+ await experts_db.create_raised_expert(+ owner.id, "Otto", None, None, withdrawn_slv_id+ )++ assert await experts_db.list_experts(owner.id) == []++[email protected](loop_scope="session")+async def test_raise_expert_rejects_pending_version_of_approved_graph(+ server: SpinTestServer,+):+ owner = await _create_seed_user()+ approved_slv_id = await _seed_store_listing(server)+ approved = await prisma.models.StoreListingVersion.prisma().find_unique(+ where={"id": approved_slv_id}+ )+ assert approved is not None+ pending = await prisma.models.StoreListingVersion.prisma().create(+ data={+ "version": approved.version + 1,+ "agentGraphId": approved.agentGraphId,+ "agentGraphVersion": approved.agentGraphVersion,+ "name": approved.name,+ "subHeading": approved.subHeading,+ "videoUrl": approved.videoUrl,+ "agentOutputDemoUrl": approved.agentOutputDemoUrl,+ "imageUrls": approved.imageUrls,+ "description": approved.description,+ "instructions": approved.instructions,+ "categories": approved.categories,+ "submissionStatus": prisma.enums.SubmissionStatus.PENDING,+ "storeListingId": approved.storeListingId,+ }+ )++ with pytest.raises(experts_db.FirstJobUnavailableError):+ await experts_db.create_raised_expert(owner.id, "Otto", None, None, pending.id)++ assert await experts_db.list_experts(owner.id) == []++[email protected](loop_scope="session")+async def test_raise_expert_enforces_active_expert_cap(server: SpinTestServer):+ owner = await _create_seed_user()+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Filler {i}",+ "role": "",+ "identity": f"I'm Filler {i}.",+ }+ for i in range(experts_db.ACTIVE_EXPERT_LIMIT)+ ]+ )++ with pytest.raises(experts_db.ExpertLimitExceededError):+ await experts_db.create_raised_expert(+ owner.id, "One Too Many", None, None, None+ )++ filler = await prisma.models.Expert.prisma().find_first(+ where={"ownerUserId": owner.id}+ )+ assert filler is not None+ await experts_db.archive_expert(owner.id, filler.id)++ raised = await experts_db.create_raised_expert(+ owner.id, "Fits Now", None, None, None+ )+ assert raised.expert.name == "Fits Now"++[email protected](loop_scope="session")+async def test_raise_expert_serializes_concurrent_cap_checks(server: SpinTestServer):+ owner = await _create_seed_user()+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Filler {i}",+ "role": "",+ "identity": f"I'm Filler {i}.",+ }+ for i in range(experts_db.ACTIVE_EXPERT_LIMIT - 1)+ ]+ )++ results = await asyncio.gather(+ experts_db.create_raised_expert(owner.id, "Alpha", None, None, None),+ experts_db.create_raised_expert(owner.id, "Beta", None, None, None),+ return_exceptions=True,+ )++ assert sum(not isinstance(result, BaseException) for result in results) == 1+ assert (+ sum(+ isinstance(result, experts_db.ExpertLimitExceededError)+ for result in results+ )+ == 1+ )+ assert (+ await prisma.models.Expert.prisma().count(+ where={+ "ownerUserId": owner.id,+ "isTemplate": False,+ "isArchived": False,+ }+ )+ == experts_db.ACTIVE_EXPERT_LIMIT+ )++[email protected](loop_scope="session")+async def test_raise_expert_locks_are_independent_per_owner(server: SpinTestServer):+ first_owner = await _create_seed_user()+ second_owner = await _create_seed_user()+ first_lock_acquired = asyncio.Event()+ second_lock_acquired = asyncio.Event()+ release_first = asyncio.Event()+ lock_creation = experts_db._lock_expert_creation++ async def lock_and_hold_first(tx: prisma.Prisma, user_id: str) -> None:+ await lock_creation(tx, user_id)+ if user_id == first_owner.id:+ first_lock_acquired.set()+ await release_first.wait()+ elif user_id == second_owner.id:+ second_lock_acquired.set()++ with patch.object(experts_db, "_lock_expert_creation", new=lock_and_hold_first):+ first = asyncio.create_task(+ experts_db.create_raised_expert(first_owner.id, "Alpha", None, None, None)+ )+ await asyncio.wait_for(first_lock_acquired.wait(), timeout=5)+ second = asyncio.create_task(+ experts_db.create_raised_expert(second_owner.id, "Beta", None, None, None)+ )+ try:+ await asyncio.wait_for(second_lock_acquired.wait(), timeout=5)+ finally:+ release_first.set()+ first_result, second_result = await asyncio.gather(first, second)++ assert first_result.expert.name == "Alpha"+ assert second_result.expert.name == "Beta"++[email protected](loop_scope="session")+async def test_raise_expert_enforces_lifetime_cap(server: SpinTestServer):+ owner = await _create_seed_user()+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Archived {i}",+ "role": "",+ "identity": f"I'm Archived {i}.",+ "isArchived": True,+ }+ for i in range(experts_db.LIFETIME_RAISED_EXPERT_LIMIT)+ ]+ )++ with pytest.raises(experts_db.RaisedExpertLifetimeLimitExceededError):+ await experts_db.create_raised_expert(+ owner.id, "One Too Many", None, None, None+ )++[email protected](loop_scope="session")+async def test_hired_experts_do_not_consume_raised_lifetime_cap(+ server: SpinTestServer,+):+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ await experts_db.hire_expert(owner.id, template.id, None)++ with patch.object(experts_db, "LIFETIME_RAISED_EXPERT_LIMIT", 1):+ raised = await experts_db.create_raised_expert(+ owner.id, "Nova", None, None, None+ )++ assert raised.expert.source_template_id is None++@pytest.mark.asyncio(loop_scope="session")async def test_rehire_after_archive_revives_expert(server: SpinTestServer, test_user):template = await _seed_template(name="Maria", preload_listings=[])@@ -265,6 +781,34 @@ async def test_rehire_after_archive_revives_expert(server: SpinTestServer, test_}[email protected](loop_scope="session")+async def test_rehire_archived_expert_respects_active_cap(server: SpinTestServer):+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(owner.id, template.id, None)+ await experts_db.archive_expert(owner.id, hired.expert.id)+ await prisma.models.Expert.prisma().create_many(+ data=[+ {+ "ownerUserId": owner.id,+ "name": f"Filler {i}",+ "role": "",+ "identity": f"I'm Filler {i}.",+ }+ for i in range(experts_db.ACTIVE_EXPERT_LIMIT)+ ]+ )++ with pytest.raises(experts_db.ExpertLimitExceededError):+ await experts_db.hire_expert(owner.id, template.id, None)++ archived = await prisma.models.Expert.prisma().find_unique(+ where={"id": hired.expert.id}+ )+ assert archived is not None+ assert archived.isArchived++@pytest.mark.asyncio(loop_scope="session")async def test_list_expert_identities_is_lightweight_and_includes_archived(server: SpinTestServer, test_user, other_userdiff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.pyindex d000e39e59..aebbfe8e8c 100644--- a/autogpt_platform/backend/backend/api/features/experts/models.py+++ b/autogpt_platform/backend/backend/api/features/experts/models.py@@ -1,5 +1,6 @@import jsonfrom datetime import datetime+from typing import Literalfrom pydantic import BaseModel, Field, ValidationError, field_validator@@ -25,7 +26,8 @@ def _strip_optional_soul_field(value: str) -> str:class VoiceSample(BaseModel):"""A short writing sample in a persona's own voice, offered as a pick in- the hire flow. The first sample is choice "a", the second choice "b"."""+ the hire or raise flow. The first sample is choice "a", the second choice+ "b"."""label: strtext: str@@ -96,6 +98,18 @@ class HireResult(BaseModel):failed_preloads: list[str]+class RaiseResult(BaseModel):+ """Result of raising a blank expert. ``first_job_installed`` is only+ True when a first job was requested and its install succeeded, so the+ client can surface partial success instead of a silent no-op. The stable+ failure reason distinguishes a listing withdrawn mid-flow from an install+ failure."""++ expert: Expert+ first_job_installed: bool+ first_job_failure_reason: Literal["unavailable", "installation_failed"] | None++class ExpertSoulUpdate(BaseModel):name: str = Field(min_length=1, max_length=_EXPERT_NAME_MAX_LENGTH)identity: str = Field(min_length=1, max_length=_EXPERT_IDENTITY_MAX_LENGTH)diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.pyindex ac7c24e771..f5bcb46018 100644--- a/autogpt_platform/backend/backend/api/features/experts/routes.py+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py@@ -1,7 +1,7 @@import autogpt_libs.auth as autogpt_auth_libimport fastapifrom fastapi import APIRouter, Security-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, field_validatorfrom backend.api.features.experts import experts_db, schedulingfrom backend.api.features.experts.models import (@@ -11,6 +11,7 @@ from backend.api.features.experts.models import (ExpertSoulUpdate,ExpertWorkflowRef,HireResult,+ RaiseResult,)router = APIRouter(@@ -29,6 +30,21 @@ class InstallWorkflowRequest(BaseModel):store_listing_version_id: str+class CreateRaisedExpertRequest(BaseModel):+ name: str = Field(min_length=1, max_length=100)+ role: str | None = Field(default=None, max_length=100)+ voice_preferences: str | None = Field(default=None, max_length=4_000)+ first_job_store_listing_version_id: str | None = Field(default=None, max_length=100)++ @field_validator("name")+ @classmethod+ def strip_name(cls, value: str) -> str:+ stripped = value.strip()+ if not stripped:+ raise ValueError("Name must not be blank")+ return stripped++@router.get("/templates", operation_id="list_expert_templates")async def list_expert_templates() -> list[Expert]:return await experts_db.list_templates()@@ -37,7 +53,10 @@ async def list_expert_templates() -> list[Expert]:@router.post("",operation_id="hire_expert",- responses={404: {"description": "Expert template not found"}},+ responses={+ 404: {"description": "Expert template not found"},+ 409: {"description": "Active expert limit reached"},+ },)async def hire_expert(request: HireRequest,@@ -47,6 +66,51 @@ async def hire_expert(return await experts_db.hire_expert(user_id, request.template_id, request.name)except experts_db.ExpertTemplateNotFoundError as e:raise fastapi.HTTPException(status_code=404, detail=str(e))+ except experts_db.ExpertLimitExceededError as e:+ raise fastapi.HTTPException(+ status_code=409,+ detail={"code": "active_expert_limit", "limit": e.limit},+ )+++ "/raise",+ operation_id="create_raised_expert",+ responses={+ 404: {"description": "First job listing not found or unavailable"},+ 409: {"description": "Active expert limit reached"},+ },+)+async def create_raised_expert(+ request: CreateRaisedExpertRequest,+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> RaiseResult:+ try:+ return await experts_db.create_raised_expert(+ user_id,+ request.name,+ request.role,+ request.voice_preferences,+ request.first_job_store_listing_version_id,+ )+ except experts_db.FirstJobUnavailableError as e:+ raise fastapi.HTTPException(+ status_code=404,+ detail={+ "code": "first_job_unavailable",+ "store_listing_version_id": e.store_listing_version_id,+ },+ )+ except experts_db.ExpertLimitExceededError as e:+ raise fastapi.HTTPException(+ status_code=409,+ detail={"code": "active_expert_limit", "limit": e.limit},+ )+ except experts_db.RaisedExpertLifetimeLimitExceededError as e:+ raise fastapi.HTTPException(+ status_code=409,+ detail={"code": "raised_expert_lifetime_limit", "limit": e.limit},+ )@router.get("", operation_id="list_experts")diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.pyindex 179f8e3ed0..8211fe971d 100644--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py@@ -24,6 +24,7 @@ from backend.api.features.experts.models import (ExpertSoulUpdate,ExpertWorkflowRef,HireResult,+ RaiseResult,)from backend.api.features.experts.routes import router@@ -77,6 +78,27 @@ def _make_workflow_ref(**overrides) -> ExpertWorkflowRef:return ExpertWorkflowRef(**values)+def _make_raised_expert(+ *,+ name: str,+ role: str = "",+ voice_preferences: str = "",+ workflows: list[ExpertWorkflowRef] | None = None,+ **overrides,+) -> Expert:+ return _make_expert(+ name=name,+ role=role,+ tagline=None,+ identity=experts_db._raised_identity(name),+ voice_preferences=voice_preferences,+ boundaries="",+ source_template_id=None,+ workflows=workflows or [],+ **overrides,+ )++# ─── List templates ────────────────────────────────────────────────────@@ -167,6 +189,281 @@ def test_hire_expert_unknown_template_returns_404(assert response.status_code == 404+def test_hire_expert_at_cap_returns_409(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.hire_expert",+ new_callable=AsyncMock,+ side_effect=experts_db.ExpertLimitExceededError(20),+ )++ response = client.post("/experts", json={"template_id": "template-1"})++ assert response.status_code == 409+ assert response.json()["detail"] == {+ "code": "active_expert_limit",+ "limit": 20,+ }+ configured_snapshot.assert_match(+ json.dumps(response.json(), indent=2, sort_keys=True),+ "expert_hire_active_cap",+ )+++# ─── Raise ─────────────────────────────────────────────────────────────+++def test_create_raised_expert_returns_expert(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+ configured_snapshot: Snapshot,+) -> None:+ raised = _make_raised_expert(id="raised-1", name="Otto")+ mock_create = mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ return_value=RaiseResult(+ expert=raised,+ first_job_installed=False,+ first_job_failure_reason=None,+ ),+ )++ response = client.post("/experts/raise", json={"name": "Otto"})++ assert response.status_code == 200+ data = response.json()+ assert data["expert"]["id"] == "raised-1"+ assert data["expert"]["source_template_id"] is None+ assert data["first_job_installed"] is False+ assert data["first_job_failure_reason"] is None+ mock_create.assert_awaited_once_with(test_user_id, "Otto", None, None, None)+ configured_snapshot.assert_match(+ json.dumps(data, indent=2, sort_keys=True), "expert_raise_default"+ )+++def test_create_raised_expert_passes_role_voice_and_first_job(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+ configured_snapshot: Snapshot,+) -> None:+ mock_create = mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ return_value=RaiseResult(+ expert=_make_raised_expert(+ id="raised-2",+ name="Nova",+ role="Research Assistant",+ voice_preferences="Warm and detailed.",+ workflows=[_make_workflow_ref()],+ ),+ first_job_installed=True,+ first_job_failure_reason=None,+ ),+ )++ response = client.post(+ "/experts/raise",+ json={+ "name": "Nova",+ "role": "Research Assistant",+ "voice_preferences": "Warm and detailed.",+ "first_job_store_listing_version_id": "listing-version-1",+ },+ )++ assert response.status_code == 200+ data = response.json()+ assert data["first_job_installed"] is True+ mock_create.assert_awaited_once_with(+ test_user_id,+ "Nova",+ "Research Assistant",+ "Warm and detailed.",+ "listing-version-1",+ )+ configured_snapshot.assert_match(+ json.dumps(data, indent=2, sort_keys=True), "expert_raise_first_job"+ )+++def test_create_raised_expert_reports_first_job_installation_failure(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+ configured_snapshot: Snapshot,+) -> None:+ mock_create = mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ return_value=RaiseResult(+ expert=_make_raised_expert(id="raised-3", name="Nova"),+ first_job_installed=False,+ first_job_failure_reason="installation_failed",+ ),+ )++ response = client.post(+ "/experts/raise",+ json={+ "name": "Nova",+ "first_job_store_listing_version_id": "listing-version-1",+ },+ )++ assert response.status_code == 200+ data = response.json()+ assert data["first_job_installed"] is False+ assert data["first_job_failure_reason"] == "installation_failed"+ mock_create.assert_awaited_once_with(+ test_user_id,+ "Nova",+ None,+ None,+ "listing-version-1",+ )+ configured_snapshot.assert_match(+ json.dumps(data, indent=2, sort_keys=True),+ "expert_raise_first_job_installation_failure",+ )+++def test_create_raised_expert_requires_name(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+) -> None:+ mock_create = mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ )++ response = client.post("/experts/raise", json={"name": " "})++ assert response.status_code == 422+ mock_create.assert_not_awaited()+ configured_snapshot.assert_match(+ json.dumps(response.json(), indent=2, sort_keys=True),+ "expert_raise_blank_name",+ )+++ ("field", "value", "snapshot_name"),+ [+ ("name", "n" * 101, "expert_raise_name_too_long"),+ ("role", "r" * 101, "expert_raise_role_too_long"),+ (+ "voice_preferences",+ "v" * 4_001,+ "expert_raise_voice_preferences_too_long",+ ),+ (+ "first_job_store_listing_version_id",+ "l" * 101,+ "expert_raise_first_job_id_too_long",+ ),+ ],+)+def test_create_raised_expert_rejects_overlong_fields(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+ field: str,+ value: str,+ snapshot_name: str,+) -> None:+ mock_create = mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ )+ payload = {"name": "Otto", field: value}++ response = client.post("/experts/raise", json=payload)++ assert response.status_code == 422+ mock_create.assert_not_awaited()+ configured_snapshot.assert_match(+ json.dumps(response.json(), indent=2, sort_keys=True), snapshot_name+ )+++def test_create_raised_expert_at_cap_returns_409(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ side_effect=experts_db.ExpertLimitExceededError(20),+ )++ response = client.post("/experts/raise", json={"name": "Otto"})++ assert response.status_code == 409+ assert response.json()["detail"] == {+ "code": "active_expert_limit",+ "limit": 20,+ }+ configured_snapshot.assert_match(+ json.dumps(response.json(), indent=2, sort_keys=True),+ "expert_raise_active_cap",+ )+++def test_create_raised_expert_at_lifetime_cap_returns_409(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ side_effect=experts_db.RaisedExpertLifetimeLimitExceededError(100),+ )++ response = client.post("/experts/raise", json={"name": "Otto"})++ assert response.status_code == 409+ assert response.json()["detail"] == {+ "code": "raised_expert_lifetime_limit",+ "limit": 100,+ }+ configured_snapshot.assert_match(+ json.dumps(response.json(), indent=2, sort_keys=True),+ "expert_raise_lifetime_cap",+ )+++def test_create_raised_expert_unavailable_first_job_returns_404(+ mocker: pytest_mock.MockerFixture,+ configured_snapshot: Snapshot,+) -> None:+ mocker.patch(+ "backend.api.features.experts.routes.experts_db.create_raised_expert",+ new_callable=AsyncMock,+ side_effect=experts_db.FirstJobUnavailableError("listing-version-9"),+ )++ response = client.post(+ "/experts/raise",+ json={+ "name": "Otto",+ "first_job_store_listing_version_id": "listing-version-9",+ },+ )++ assert response.status_code == 404+ assert response.json()["detail"] == {+ "code": "first_job_unavailable",+ "store_listing_version_id": "listing-version-9",+ }+ configured_snapshot.assert_match(+ json.dumps(response.json(), indent=2, sort_keys=True),+ "expert_raise_first_job_unavailable",+ )++# ─── Get ───────────────────────────────────────────────────────────────diff --git a/autogpt_platform/backend/backend/api/features/library/_add_to_library.py b/autogpt_platform/backend/backend/api/features/library/_add_to_library.pyindex 10b1ceab55..38ef62d888 100644--- a/autogpt_platform/backend/backend/api/features/library/_add_to_library.py+++ b/autogpt_platform/backend/backend/api/features/library/_add_to_library.py@@ -41,14 +41,20 @@ async def resolve_store_version_for_library(store_listing_version_id: str,*,admin: bool,+ tx: prisma.Prisma | None = None,) -> prisma.models.StoreListingVersion:"""Look up an installable StoreListingVersion and its graph reference."""+ delegate = (+ prisma.models.StoreListingVersion.prisma(tx)+ if tx is not None+ else prisma.models.StoreListingVersion.prisma()+ )if admin:- slv = await prisma.models.StoreListingVersion.prisma().find_unique(+ slv = await delegate.find_unique(where={"id": store_listing_version_id}, include={"AgentGraph": True})else:- slv = await prisma.models.StoreListingVersion.prisma().find_first(+ slv = await delegate.find_first(where={"id": store_listing_version_id,**installable_store_version_where(),@@ -91,6 +97,7 @@ async def resolve_graph_for_library(user_id: str,*,admin: bool,+ tx: prisma.Prisma | None = None,) -> tuple[GraphModel, prisma.models.StoreListingVersion]:"""Look up a StoreListingVersion and resolve its graph.@@ -100,7 +107,9 @@ async def resolve_graph_for_library(Returns the resolved graph together with the StoreListingVersion, so callerscan snapshot marketplace metadata without re-querying it."""- slv = await resolve_store_version_for_library(store_listing_version_id, admin=admin)+ slv = await resolve_store_version_for_library(+ store_listing_version_id, admin=admin, tx=tx+ )graph_model = await resolve_graph_model_for_library(slv, user_id, admin=admin)return graph_model, slv@@ -170,79 +179,33 @@ async def add_graph_to_library(graph_model: GraphModel,user_id: str,store_listing_version: prisma.models.StoreListingVersion,+ *,+ tx: prisma.Prisma | None = None,) -> library_model.LibraryAgent:"""Check existing / restore soft-deleted / create new LibraryAgent.- Uses a create-then-catch-UniqueViolationError-then-update pattern on- the (userId, agentGraphId, agentGraphVersion) composite unique constraint.- This is more robust than ``upsert`` because Prisma's upsert atomicity- guarantees are not well-documented for all versions.+ The standalone path preserves the established create-then-update behavior.+ When a transaction client is supplied, an upsert keeps the library write+ atomic with the caller's other writes; catching a uniqueness error inside+ PostgreSQL's transaction would leave that transaction aborted."""settings_json = SafeJson(GraphSettings.from_graph(graph_model).model_dump())_include = library_agent_include(user_id, include_nodes=False, include_executions=False)marketplace = _marketplace_metadata(store_listing_version)+ create_data, update_data = await _library_agent_payloads(+ graph_model, user_id, settings_json, marketplace+ )- # A library entry is the adding user's bookmark, so tag it with their- # default org/team at creation (mirrors create_library_agent).- # resolve_default_tenancy is best-effort — an unresolvable org or a raised- # lookup yields (None, None) and the row is left untagged; never block a- # library add on tenancy resolution.- organization_id, team_id = await resolve_default_tenancy(user_id)-- try:- added_agent = await prisma.models.LibraryAgent.prisma().create(- data={- "User": {"connect": {"id": user_id}},- "AgentGraph": {- "connect": {- "graphVersionId": {- "id": graph_model.id,- "version": graph_model.version,- }- }- },- "isCreatedByUser": False,- "useGraphIsActiveVersion": False,- "settings": settings_json,- "name": marketplace["name"],- "description": marketplace["description"],- "imageUrl": marketplace["imageUrl"],- **({"organizationId": organization_id} if organization_id else {}),- **({"Team": {"connect": {"id": team_id}}} if team_id else {}),- },- include=_include,+ if tx is not None:+ added_agent = await _upsert_library_agent(+ tx, graph_model, user_id, create_data, update_data, _include)- except prisma.errors.UniqueViolationError:- # Already exists — update to restore if previously soft-deleted/archived- # and refresh the marketplace snapshot in case the listing changed.- added_agent = await prisma.models.LibraryAgent.prisma().update(- where={- "userId_agentGraphId_agentGraphVersion": {- "userId": user_id,- "agentGraphId": graph_model.id,- "agentGraphVersion": graph_model.version,- }- },- data={- "isDeleted": False,- "isArchived": False,- "name": marketplace["name"],- "description": marketplace["description"],- "imageUrl": marketplace["imageUrl"],- # Deliberately leave organizationId/Team untouched on re-add:- # an existing bookmark already carries its tenancy. Only the- # create branch tenants; re-tagging here risked disconnecting- # an existing team when a default team couldn't be resolved.- },- include=_include,+ else:+ added_agent = await _create_or_restore_library_agent(+ graph_model, user_id, create_data, update_data, _include)- if added_agent is None:- raise NotFoundError(- f"LibraryAgent for graph #{graph_model.id} "- f"v{graph_model.version} not found after UniqueViolationError"- )logger.debug(f"Added graph #{graph_model.id} v{graph_model.version} "@@ -255,3 +218,92 @@ async def add_graph_to_library(schedule_info=schedule_info,store_listing_version_id=store_listing_version.id,)+++async def _library_agent_payloads(+ graph_model: GraphModel,+ user_id: str,+ settings_json: SafeJson,+ marketplace: dict[str, str | None],+) -> tuple[dict, dict]:+ organization_id, team_id = await resolve_default_tenancy(user_id)+ create_data = {+ "User": {"connect": {"id": user_id}},+ "AgentGraph": {+ "connect": {+ "graphVersionId": {+ "id": graph_model.id,+ "version": graph_model.version,+ }+ }+ },+ "isCreatedByUser": False,+ "useGraphIsActiveVersion": False,+ "settings": settings_json,+ "name": marketplace["name"],+ "description": marketplace["description"],+ "imageUrl": marketplace["imageUrl"],+ **({"organizationId": organization_id} if organization_id else {}),+ **({"Team": {"connect": {"id": team_id}}} if team_id else {}),+ }+ # Deliberately leave settings and organizationId/Team untouched on re-add:+ # an existing entry already carries its safety/tenancy configuration.+ update_data = {+ "isDeleted": False,+ "isArchived": False,+ "name": marketplace["name"],+ "description": marketplace["description"],+ "imageUrl": marketplace["imageUrl"],+ }+ return create_data, update_data+++def _library_agent_where(graph_model: GraphModel, user_id: str) -> dict:+ return {+ "userId_agentGraphId_agentGraphVersion": {+ "userId": user_id,+ "agentGraphId": graph_model.id,+ "agentGraphVersion": graph_model.version,+ }+ }+++async def _upsert_library_agent(+ tx: prisma.Prisma,+ graph_model: GraphModel,+ user_id: str,+ create_data: dict,+ update_data: dict,+ include: dict,+) -> prisma.models.LibraryAgent:+ return await prisma.models.LibraryAgent.prisma(tx).upsert(+ where=_library_agent_where(graph_model, user_id),+ data={"create": create_data, "update": update_data},+ include=include,+ )+++async def _create_or_restore_library_agent(+ graph_model: GraphModel,+ user_id: str,+ create_data: dict,+ update_data: dict,+ include: dict,+) -> prisma.models.LibraryAgent:+ try:+ return await prisma.models.LibraryAgent.prisma().create(+ data=create_data,+ include=include,+ )+ except prisma.errors.UniqueViolationError:+ added_agent = await prisma.models.LibraryAgent.prisma().update(+ where=_library_agent_where(graph_model, user_id),+ data=update_data,+ include=include,+ )+ if added_agent is None:+ raise NotFoundError(+ f"LibraryAgent for graph #{graph_model.id} "+ f"v{graph_model.version} not found after UniqueViolationError"+ )+ return added_agentdiff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex 45174148ad..6fd4d55b11 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -1,7 +1,7 @@import asyncioimport itertoolsimport logging-from typing import Literal, Optional, cast+from typing import Literal, LiteralString, Optional, castimport fastapiimport prisma.errors@@ -19,7 +19,7 @@ from backend.api.features.library.exceptions import (from backend.api.features.store.store_listing_versions import (installable_store_version_where,)-from backend.data.db import transaction+from backend.data.db import get_database_schema, transactionfrom backend.data.execution import get_graph_executionfrom backend.data.expert_attribution import resolve_attributable_expertfrom backend.data.graph import GraphSettings@@ -1219,29 +1219,93 @@ async def delete_library_agent_by_graph_id(graph_id: str, user_id: str) -> None:)+async def is_store_listing_version_available_for_install(+ store_listing_version_id: str,+ *,+ tx: prisma.Prisma | None = None,+ lock_rows: bool = False,+) -> bool:+ """Validate one exact marketplace version for a library install.++ Both the preflight and transactional revalidation use this query. The+ shared row lock blocks withdrawal while permitting concurrent installs of+ the same popular listing.+ """+ if lock_rows and tx is None:+ raise ValueError("lock_rows requires a transaction client")++ schema = get_database_schema()+ schema_prefix = f'"{schema}".' if schema != "public" else ""+ lock_clause = "FOR SHARE OF slv, sl" if lock_rows else ""+ query = cast(+ LiteralString,+ """+ SELECT slv.id+ FROM {schema_prefix}"StoreListingVersion" AS slv+ JOIN {schema_prefix}"StoreListing" AS sl+ ON sl.id = slv."storeListingId"+ WHERE slv.id = $1+ AND slv."isDeleted" = false+ AND slv."isAvailable" = true+ AND slv."submissionStatus" = 'APPROVED'+ AND sl."isDeleted" = false+ {lock_clause}+ """.format(+ schema_prefix=schema_prefix, lock_clause=lock_clause+ ),+ )+ client = tx if tx is not None else prisma.get_client()+ rows = await client.query_raw(query, store_listing_version_id)+ return bool(rows)++async def add_store_agent_to_library(- store_listing_version_id: str, user_id: str+ store_listing_version_id: str,+ user_id: str,) -> library_model.LibraryAgent:"""Adds a marketplace agent to the user’s library.See also: `add_store_agent_to_library_as_admin()` which uses`get_graph_as_admin` to bypass marketplace status checks for admin review."""+ return await _add_store_agent_to_library(store_listing_version_id, user_id, tx=None)+++async def add_store_agent_to_library_in_transaction(+ store_listing_version_id: str,+ user_id: str,+ tx: prisma.Prisma,+) -> library_model.LibraryAgent:+ """Add a marketplace agent using the caller's transaction."""+ return await _add_store_agent_to_library(store_listing_version_id, user_id, tx=tx)+++async def _add_store_agent_to_library(+ store_listing_version_id: str,+ user_id: str,+ *,+ tx: prisma.Prisma | None,+) -> library_model.LibraryAgent:logger.debug("Adding agent from store listing version #%s to library for user #%s",store_listing_version_id,user_id,)store_listing_version = await resolve_store_version_for_library(- store_listing_version_id, admin=False- )- existing = await restore_existing_library_agent(store_listing_version, user_id)- if existing is not None:- return existing+ store_listing_version_id, admin=False, tx=tx+ )+ if tx is None:+ # The transactional path upserts instead, so an existing entry is+ # restored atomically with the caller's other writes.+ existing = await restore_existing_library_agent(store_listing_version, user_id)+ if existing is not None:+ return existinggraph_model = await resolve_graph_model_for_library(store_listing_version, user_id, admin=False)- return await add_graph_to_library(graph_model, user_id, store_listing_version)+ return await add_graph_to_library(+ graph_model, user_id, store_listing_version, tx=tx+ )async def add_store_agent_to_library_as_admin(diff --git a/autogpt_platform/backend/backend/data/db_manager_test.py b/autogpt_platform/backend/backend/data/db_manager_test.pyindex e622acc09a..71c7429cd1 100644--- a/autogpt_platform/backend/backend/data/db_manager_test.py+++ b/autogpt_platform/backend/backend/data/db_manager_test.py@@ -15,3 +15,8 @@ def test_bot_analytics_methods_registered() -> None:):assert hasattr(DatabaseManager, method)assert hasattr(DatabaseManagerAsyncClient, method)+++def test_add_store_agent_rpc_request_schema_is_constructible() -> None:+ manager = DatabaseManager()+ manager._create_fastapi_endpoint(manager.add_store_agent_to_library)diff --git a/autogpt_platform/backend/snapshots/expert_hire_active_cap b/autogpt_platform/backend/snapshots/expert_hire_active_capnew file mode 100644index 0000000000..fd58e31a67--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_hire_active_cap@@ -0,0 +1,6 @@+{+ "detail": {+ "code": "active_expert_limit",+ "limit": 20+ }+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_active_cap b/autogpt_platform/backend/snapshots/expert_raise_active_capnew file mode 100644index 0000000000..fd58e31a67--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_active_cap@@ -0,0 +1,6 @@+{+ "detail": {+ "code": "active_expert_limit",+ "limit": 20+ }+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_blank_name b/autogpt_platform/backend/snapshots/expert_raise_blank_namenew file mode 100644index 0000000000..3f6cd85b30--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_blank_name@@ -0,0 +1,16 @@+{+ "detail": [+ {+ "ctx": {+ "error": {}+ },+ "input": " ",+ "loc": [+ "body",+ "name"+ ],+ "msg": "Value error, Name must not be blank",+ "type": "value_error"+ }+ ]+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_default b/autogpt_platform/backend/snapshots/expert_raise_defaultnew file mode 100644index 0000000000..72161f196f--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_default@@ -0,0 +1,30 @@+{+ "expert": {+ "avatar_url": null,+ "bio": null,+ "boundaries": "",+ "id": "raised-1",+ "identity": "I'm Otto, raised by you. I learn how you work and grow with you.",+ "is_archived": false,+ "is_template": false,+ "last_run_at": null,+ "last_run_status": null,+ "name": "Otto",+ "protected_soul_rules": [+ "The expert discloses that it is AI when acting externally.",+ "External actions require approval."+ ],+ "role": "",+ "schedules_paused_at": null,+ "skills": [],+ "source_template_id": null,+ "tagline": null,+ "voice_preferences": "",+ "voice_samples": [],+ "weekly_budget": null,+ "weekly_spend": 0,+ "workflows": []+ },+ "first_job_failure_reason": null,+ "first_job_installed": false+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_first_job b/autogpt_platform/backend/snapshots/expert_raise_first_jobnew file mode 100644index 0000000000..4c210830c9--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_first_job@@ -0,0 +1,41 @@+{+ "expert": {+ "avatar_url": null,+ "bio": null,+ "boundaries": "",+ "id": "raised-2",+ "identity": "I'm Nova, raised by you. I learn how you work and grow with you.",+ "is_archived": false,+ "is_template": false,+ "last_run_at": null,+ "last_run_status": null,+ "name": "Nova",+ "protected_soul_rules": [+ "The expert discloses that it is AI when acting externally.",+ "External actions require approval."+ ],+ "role": "Research Assistant",+ "schedules_paused_at": null,+ "skills": [],+ "source_template_id": null,+ "tagline": null,+ "voice_preferences": "Warm and detailed.",+ "voice_samples": [],+ "weekly_budget": null,+ "weekly_spend": 0,+ "workflows": [+ {+ "description": "Writes SEO-optimized blog posts",+ "graph_id": "graph-1",+ "id": "workflow-ref-1",+ "library_agent_id": "library-agent-1",+ "name": "SEO Blog Writer",+ "schedule_cron": null,+ "schedule_id": null,+ "store_listing_version_id": "listing-version-1"+ }+ ]+ },+ "first_job_failure_reason": null,+ "first_job_installed": true+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_first_job_id_too_long b/autogpt_platform/backend/snapshots/expert_raise_first_job_id_too_longnew file mode 100644index 0000000000..65e98a0db1--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_first_job_id_too_long@@ -0,0 +1,16 @@+{+ "detail": [+ {+ "ctx": {+ "max_length": 100+ },+ "input": "lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll",+ "loc": [+ "body",+ "first_job_store_listing_version_id"+ ],+ "msg": "String should have at most 100 characters",+ "type": "string_too_long"+ }+ ]+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_first_job_installation_failure b/autogpt_platform/backend/snapshots/expert_raise_first_job_installation_failurenew file mode 100644index 0000000000..dff6d632fa--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_first_job_installation_failure@@ -0,0 +1,30 @@+{+ "expert": {+ "avatar_url": null,+ "bio": null,+ "boundaries": "",+ "id": "raised-3",+ "identity": "I'm Nova, raised by you. I learn how you work and grow with you.",+ "is_archived": false,+ "is_template": false,+ "last_run_at": null,+ "last_run_status": null,+ "name": "Nova",+ "protected_soul_rules": [+ "The expert discloses that it is AI when acting externally.",+ "External actions require approval."+ ],+ "role": "",+ "schedules_paused_at": null,+ "skills": [],+ "source_template_id": null,+ "tagline": null,+ "voice_preferences": "",+ "voice_samples": [],+ "weekly_budget": null,+ "weekly_spend": 0,+ "workflows": []+ },+ "first_job_failure_reason": "installation_failed",+ "first_job_installed": false+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_first_job_unavailable b/autogpt_platform/backend/snapshots/expert_raise_first_job_unavailablenew file mode 100644index 0000000000..ad0648774f--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_first_job_unavailable@@ -0,0 +1,6 @@+{+ "detail": {+ "code": "first_job_unavailable",+ "store_listing_version_id": "listing-version-9"+ }+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_lifetime_cap b/autogpt_platform/backend/snapshots/expert_raise_lifetime_capnew file mode 100644index 0000000000..4d26cb5520--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_lifetime_cap@@ -0,0 +1,6 @@+{+ "detail": {+ "code": "raised_expert_lifetime_limit",+ "limit": 100+ }+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_name_too_long b/autogpt_platform/backend/snapshots/expert_raise_name_too_longnew file mode 100644index 0000000000..a4093d42b1--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_name_too_long@@ -0,0 +1,16 @@+{+ "detail": [+ {+ "ctx": {+ "max_length": 100+ },+ "input": "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn",+ "loc": [+ "body",+ "name"+ ],+ "msg": "String should have at most 100 characters",+ "type": "string_too_long"+ }+ ]+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_role_too_long b/autogpt_platform/backend/snapshots/expert_raise_role_too_longnew file mode 100644index 0000000000..65274a13a6--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_role_too_long@@ -0,0 +1,16 @@+{+ "detail": [+ {+ "ctx": {+ "max_length": 100+ },+ "input": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr",+ "loc": [+ "body",+ "role"+ ],+ "msg": "String should have at most 100 characters",+ "type": "string_too_long"+ }+ ]+}\ No newline at end of filediff --git a/autogpt_platform/backend/snapshots/expert_raise_voice_preferences_too_long b/autogpt_platform/backend/snapshots/expert_raise_voice_preferences_too_longnew file mode 100644index 0000000000..3586cbe6da--- /dev/null+++ b/autogpt_platform/backend/snapshots/expert_raise_voice_preferences_too_long@@ -0,0 +1,16 @@+{+ "detail": [+ {+ "ctx": {+ "max_length": 4000+ },+ "input": "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv",+ "loc": [+ "body",+ "voice_preferences"+ ],+ "msg": "String should have at most 4000 characters",+ "type": "string_too_long"+ }+ ]+}\ No newline at end of filediff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsxindex 6d018939e1..148c8b9de0 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx@@ -113,6 +113,11 @@ describe("Marketplace ExpertsSection", () => {renderMarketplace();expect(await screen.findByText("Meet the AI Experts")).toBeDefined();+ expect(+ screen+ .getByRole("link", { name: /raise your own expert from scratch/i })+ .getAttribute("href"),+ ).toBe("/raise");await userEvent.click(await screen.findByText("Maria"));await userEvent.click(await screen.findByRole("button", { name: "Hire Maria" }),@@ -141,9 +146,48 @@ describe("Marketplace ExpertsSection", () => {expect(await screen.findByText("All AI Workflows")).toBeDefined();expect(screen.queryByText("Meet the AI Experts")).toBeNull();+ expect(screen.queryByText(/raise your own expert/)).toBeNull();expect(templatesRequested).toBe(false);});+ test("keeps the raise-your-own door open when no templates exist", async () => {+ server.use(+ getListExpertTemplatesMockHandler([]),+ getListExpertsMockHandler([]),+ );++ renderMarketplace();++ await waitFor(+ () => {+ const raiseLink = screen.getByRole("link", {+ name: "Raise your own expert from scratch",+ });+ expect(raiseLink.getAttribute("href")).toBe("/raise");+ expect(raiseLink.textContent).not.toContain("…or");+ expect(screen.queryByText("Meet the AI Experts")).toBeNull();+ },+ { timeout: 5_000 },+ );+ });++ test("uses standalone raise copy when templates fail to load", async () => {+ server.use(+ http.get("/api/proxy/api/experts/templates", () =>+ HttpResponse.json({ detail: "Unavailable" }, { status: 500 }),+ ),+ getListExpertsMockHandler([]),+ );++ renderMarketplace();++ const raiseLink = await screen.findByRole("link", {+ name: "Raise your own expert from scratch",+ });+ expect(raiseLink.getAttribute("href")).toBe("/raise");+ expect(raiseLink.textContent).not.toContain("…or");+ });+test("captures a voice pick as a plain-text soul PATCH after hire", async () => {let savedVoice = "";server.use(diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsxindex 00bdfaea17..aa10ffcd27 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/ExpertsSection.tsx@@ -2,6 +2,7 @@import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";import { AITeamIcon } from "@/components/atoms/AITeamIcon/AITeamIcon";+import Link from "next/link";import { SectionHeader } from "../SectionHeader";import { ExpertCard } from "./components/ExpertCard";import { ExpertProfileSheet } from "./components/ExpertProfileSheet/ExpertProfileSheet";@@ -9,6 +10,7 @@ import { useExpertsSection } from "./useExpertsSection";export function ExpertsSection() {const {+ isLoggedIn,templates,hiredTemplateIds,isLoading,@@ -18,10 +20,20 @@ export function ExpertsSection() {closeSheet,} = useExpertsSection();- if (isError || (!isLoading && templates.length === 0)) {+ if (!isLoggedIn) {return null;}+ if (isError || (!isLoading && templates.length === 0)) {+ // Raising an expert needs no roster templates, so the second door+ // stays open even when the template list is empty or failed to load.+ return (+ <section id="experts" className="mb-20 scroll-mt-24">+ <RaiseLink standalone />+ </section>+ );+ }+return (<section id="experts" className="mb-20 scroll-mt-24"><SectionHeader@@ -30,6 +42,9 @@ export function ExpertsSection() {subtitle="Hire a ready-made specialist — competent on day one, working for you in minutes."action={{ label: "View your team", href: "/team" }}/>+ <div className="-mt-3 mb-6">+ <RaiseLink />+ </div>{isLoading ? (<div className="grid grid-cols-1 gap-5 md:grid-cols-2 lg:grid-cols-3">{[0, 1, 2].map((i) => (@@ -55,3 +70,20 @@ export function ExpertsSection() {</section>);}++type RaiseLinkProps = {+ standalone?: boolean;+};++function RaiseLink({ standalone = false }: RaiseLinkProps) {+ return (+ <Link+ href="/raise"+ className="text-sm font-medium text-accent transition-colors hover:text-accent/80"+ >+ {standalone+ ? "Raise your own expert from scratch"+ : "…or raise your own expert from scratch"}+ </Link>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.tsindex ae9ffa4738..5b78867711 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/useExpertsSection.ts@@ -27,6 +27,7 @@ export function useExpertsSection() {}return {+ isLoggedIn,templates: templatesQuery.data ?? [],hiredTemplateIds,isLoading: isLoggedIn && templatesQuery.isLoading,diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsxnew file mode 100644index 0000000000..ec54047b4b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/__tests__/main.test.tsx@@ -0,0 +1,568 @@+import { getCreateRaisedExpertMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";+import {+ getGetV2GetSpecificAgentMockHandler,+ getGetV2ListStoreAgentsMockHandler,+} from "@/app/api/__generated__/endpoints/store/store.msw";+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { RaiseResult } from "@/app/api/__generated__/models/raiseResult";+import type { StoreAgent } from "@/app/api/__generated__/models/storeAgent";+import type { StoreAgentDetails } from "@/app/api/__generated__/models/storeAgentDetails";+import type { StoreAgentsResponse } from "@/app/api/__generated__/models/storeAgentsResponse";+import { Toaster } from "@/components/molecules/Toast/toaster";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { HttpResponse, http } from "msw";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import RaisePage from "../page";++const { setFlagStatusMock } = vi.hoisted(() => ({+ setFlagStatusMock: vi.fn(() => ({ enabled: true, ready: true })),+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {+ const actual =+ await importActual<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useFlagStatus: (flag: string) =>+ flag === "hire-experts"+ ? setFlagStatusMock()+ : actual.useFlagStatus(flag as never),+ };+});++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({ isLoggedIn: true, user: { id: "user-1" } }),+}));++const { pushMock, notFoundMock } = vi.hoisted(() => ({+ pushMock: vi.fn(),+ notFoundMock: vi.fn(),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: pushMock }),+ usePathname: () => "/raise",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({}),+ notFound: () => {+ notFoundMock();+ throw new Error("NEXT_NOT_FOUND");+ },+}));++const raisedExpert = {+ id: "raised-1",+ name: "Otto",+ avatar_url: null,+ role: "",+ tagline: null,+ bio: null,+ skills: [],+ identity: "I'm Otto, raised by you. I learn how you work and grow with you.",+ voice_preferences: "",+ boundaries: "",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: null,+ is_archived: false,+ workflows: [],+} as Expert;++const installedWorkflow = {+ id: "workflow-1",+ store_listing_version_id: "listing-version-42",+ library_agent_id: "library-agent-1",+ graph_id: "graph-1",+ name: "SEO Blog Writer",+ description: null,+};++const storeAgent = {+ slug: "seo-writer",+ agent_name: "SEO Blog Writer",+ agent_image: "",+ creator: "acme",+ creator_avatar: "",+ sub_heading: "Writes optimized blog posts",+ description: "",+ runs: 1200,+ rating: 4.8,+ agent_graph_id: "graph-1",+} as StoreAgent;++const storeAgentsResponse: StoreAgentsResponse = {+ agents: [storeAgent],+ pagination: {+ total_items: 1,+ total_pages: 1,+ current_page: 1,+ page_size: 3,+ },+};++const agentDetails = {+ store_listing_version_id: "listing-version-42",+ slug: "seo-writer",+ agent_name: "SEO Blog Writer",+ creator: "acme",+} as StoreAgentDetails;++function useStoreHandlers() {+ server.use(+ getGetV2ListStoreAgentsMockHandler(storeAgentsResponse),+ getGetV2GetSpecificAgentMockHandler(agentDetails),+ );+}++function renderRaise() {+ return render(+ <>+ <RaisePage />+ <Toaster />+ </>,+ );+}++async function walkToReviewWithJob() {+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));++ await userEvent.click(await screen.findByText("Concise and direct"));+ await userEvent.click(screen.getByRole("button", { name: "Use this voice" }));++ await userEvent.click(await screen.findByText("SEO Blog Writer"));+ const confirmJob = (await screen.findByRole("button", {+ name: "Give me this job",+ })) as HTMLButtonElement;+ await waitFor(() => expect(confirmJob.disabled).toBe(false));+ await userEvent.click(confirmJob);+}++beforeEach(() => {+ window.sessionStorage.clear();+ setFlagStatusMock.mockReturnValue({ enabled: true, ready: true });+ pushMock.mockClear();+ notFoundMock.mockClear();+});++afterEach(() => {+ vi.clearAllMocks();+});++test("calls notFound when the experts feature is disabled", () => {+ setFlagStatusMock.mockReturnValue({ enabled: false, ready: true });++ try {+ renderRaise();+ } catch {}++ expect(notFoundMock).toHaveBeenCalled();+});++test("walks name → voice → first job, posts the payload, and kicks off", async () => {+ let captured: unknown = null;+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler(async (info) => {+ captured = await info.request.json();+ return {+ expert: { ...raisedExpert, workflows: [installedWorkflow] },+ first_job_installed: true,+ first_job_failure_reason: null,+ } as RaiseResult;+ }),+ );++ renderRaise();+ expect(+ await screen.findByRole("log", { name: "Raise expert conversation" }),+ ).toBeDefined();+ await walkToReviewWithJob();++ await userEvent.click(+ await screen.findByRole("button", { name: /Bring Otto to life/ }),+ );++ await waitFor(() => expect(captured).not.toBeNull());+ expect(captured).toMatchObject({+ name: "Otto",+ first_job_store_listing_version_id: "listing-version-42",+ });+ expect(+ (captured as { voice_preferences: string }).voice_preferences,+ ).toContain("Concise and direct");+ expect(captured as Record<string, unknown>).not.toHaveProperty("role");++ await waitFor(() =>+ expect(pushMock).toHaveBeenCalledWith(+ "/copilot?expertId=raised-1&kickoff=1",+ ),+ );+});++test("posts a custom writing sample as voice preferences", async () => {+ let captured: unknown = null;+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler(async (info) => {+ captured = await info.request.json();+ return {+ expert: raisedExpert,+ first_job_installed: false,+ first_job_failure_reason: null,+ } as RaiseResult;+ }),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.type(+ await screen.findByRole("textbox", { name: "Custom voice sample" }),+ "Keep every answer short, practical, and warm.",+ );+ await userEvent.click(screen.getByRole("button", { name: "Use this voice" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(await screen.findByRole("button", { name: /life/ }));++ await waitFor(() => expect(captured).not.toBeNull());+ const payload = captured as Record<string, unknown>;+ expect(payload.voice_preferences).toContain(+ "Keep every answer short, practical, and warm.",+ );+ expect(payload).not.toHaveProperty("role");+});++test("skips voice and first job, posts a minimal payload without kickoff", async () => {+ let captured: unknown = null;+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler(async (info) => {+ captured = await info.request.json();+ return {+ expert: raisedExpert,+ first_job_installed: false,+ first_job_failure_reason: null,+ } as RaiseResult;+ }),+ );++ renderRaise();++ const nameInput = await screen.findByPlaceholderText("Type a name…");+ await userEvent.type(nameInput, "Juno");+ await userEvent.click(screen.getByRole("button", { name: "Name me" }));++ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );++ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );++ await userEvent.click(await screen.findByRole("button", { name: /life/ }));++ await waitFor(() => expect(captured).not.toBeNull());+ expect(+ (captured as Record<string, unknown>).first_job_store_listing_version_id,+ ).toBeNull();+ await waitFor(() =>+ expect(pushMock).toHaveBeenCalledWith("/copilot?expertId=raised-1"),+ );+});++test("surfaces a failed first-job install and skips kickoff", async () => {+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler({+ expert: raisedExpert,+ first_job_installed: false,+ first_job_failure_reason: "installation_failed",+ } as RaiseResult),+ );++ renderRaise();+ await walkToReviewWithJob();++ await userEvent.click(+ await screen.findByRole("button", { name: /Bring Otto to life/ }),+ );++ expect(+ await screen.findByText("Couldn't set up Otto's first job"),+ ).toBeDefined();+ expect(screen.getByText(/from their page anytime/)).toBeDefined();+ await waitFor(() =>+ expect(pushMock).toHaveBeenCalledWith("/copilot?expertId=raised-1"),+ );+});++test("a rapid double-click on finish sends a single POST", async () => {+ let postCount = 0;+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler(() => {+ postCount += 1;+ return {+ expert: raisedExpert,+ first_job_installed: false,+ first_job_failure_reason: null,+ } as RaiseResult;+ }),+ );++ renderRaise();++ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );++ const finishButton = await screen.findByRole("button", { name: /life/ });+ await Promise.all([+ userEvent.click(finishButton),+ userEvent.click(finishButton),+ ]);++ await waitFor(() => expect(pushMock).toHaveBeenCalled());+ expect(postCount).toBe(1);+});++test("unlocks finish after a raise POST fails so the user can retry", async () => {+ let postCount = 0;+ useStoreHandlers();+ server.use(+ http.post("/api/proxy/api/experts/raise", () => {+ postCount += 1;+ return HttpResponse.json({ detail: "Raise failed" }, { status: 500 });+ }),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );++ await userEvent.click(await screen.findByRole("button", { name: /life/ }));+ expect(await screen.findByText("Couldn't raise Otto")).toBeDefined();+ await waitFor(() => expect(postCount).toBe(1));++ const retry = screen.getByRole("button", { name: /Bring Otto to life/ });+ expect((retry as HTMLButtonElement).disabled).toBe(false);+ await userEvent.click(retry);+ await waitFor(() => expect(postCount).toBe(2));+});++test("keeps navigation locked after success until the route unmounts", async () => {+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler({+ expert: raisedExpert,+ first_job_installed: false,+ first_job_failure_reason: null,+ } as RaiseResult),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(await screen.findByRole("button", { name: /life/ }));++ await waitFor(() => expect(pushMock).toHaveBeenCalled());+ expect(+ (screen.getByRole("button", { name: "Back" }) as HTMLButtonElement)+ .disabled,+ ).toBe(true);+});++test("shows a friendly limit message on 409", async () => {+ useStoreHandlers();+ server.use(+ http.post("/api/proxy/api/experts/raise", () =>+ HttpResponse.json(+ { detail: { code: "active_expert_limit", limit: 20 } },+ { status: 409 },+ ),+ ),+ );++ renderRaise();++ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(await screen.findByRole("button", { name: /life/ }));++ expect(await screen.findByText("Your team is full")).toBeDefined();+ expect(pushMock).not.toHaveBeenCalled();+});++test("distinguishes the lifetime raised-expert limit", async () => {+ useStoreHandlers();+ server.use(+ http.post("/api/proxy/api/experts/raise", () =>+ HttpResponse.json(+ {+ detail: { code: "raised_expert_lifetime_limit", limit: 100 },+ },+ { status: 409 },+ ),+ ),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(await screen.findByRole("button", { name: /life/ }));++ expect(+ await screen.findByText("Expert creation limit reached"),+ ).toBeDefined();+ expect(screen.getByText(/Contact support/)).toBeDefined();+ expect(pushMock).not.toHaveBeenCalled();+});++test("back returns to the previous step and the draft survives", async () => {+ useStoreHandlers();+ renderRaise();++ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ expect(await screen.findByText("How should Otto write?")).toBeDefined();+ await waitFor(() =>+ expect(document.activeElement).toBe(+ screen.getByRole("region", { name: "Voice step" }),+ ),+ );++ await userEvent.click(screen.getByRole("button", { name: "Back" }));++ expect(await screen.findByPlaceholderText("Type a name…")).toBeDefined();+ expect(screen.getByText("Otto's Soul")).toBeDefined();+ await waitFor(() =>+ expect(document.activeElement).toBe(+ screen.getByRole("region", { name: "Name step" }),+ ),+ );+});++test("a refresh resumes the draft from session storage", async () => {+ useStoreHandlers();+ const first = renderRaise();++ await userEvent.click(await screen.findByRole("button", { name: "Nova" }));+ expect(await screen.findByText("How should Nova write?")).toBeDefined();++ first.unmount();+ renderRaise();++ expect(await screen.findByText("How should Nova write?")).toBeDefined();+ expect(screen.getByText("Nova's Soul")).toBeDefined();+});++test("explains when the selected first job becomes unavailable", async () => {+ useStoreHandlers();+ server.use(+ getCreateRaisedExpertMockHandler({+ expert: raisedExpert,+ first_job_installed: false,+ first_job_failure_reason: "unavailable",+ } as RaiseResult),+ );++ renderRaise();+ await walkToReviewWithJob();+ await userEvent.click(+ await screen.findByRole("button", { name: /Bring Otto to life/ }),+ );++ expect(+ await screen.findByText("SEO Blog Writer is no longer available"),+ ).toBeDefined();+ expect(screen.getByText(/choose another first job/)).toBeDefined();+});++test("keeps skip available when starter-job suggestions fail", async () => {+ server.use(+ http.get("/api/proxy/api/store/agents", () =>+ HttpResponse.json({ detail: "Store unavailable" }, { status: 500 }),+ ),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );++ expect(await screen.findByText("Something went wrong")).toBeDefined();+ expect(screen.getByRole("button", { name: "Skip for now" })).toBeDefined();+});++test("explains when there are no starter jobs", async () => {+ server.use(+ getGetV2ListStoreAgentsMockHandler({+ ...storeAgentsResponse,+ agents: [],+ pagination: { ...storeAgentsResponse.pagination, total_items: 0 },+ }),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );++ expect(+ await screen.findByText(/No starter jobs are available right now/),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: "Skip for now" })).toBeDefined();+});++test("surfaces a selected job detail failure", async () => {+ server.use(+ getGetV2ListStoreAgentsMockHandler(storeAgentsResponse),+ http.get("/api/proxy/api/store/agents/:username/:agentName", () =>+ HttpResponse.json({ detail: "Details unavailable" }, { status: 500 }),+ ),+ );++ renderRaise();+ await userEvent.click(await screen.findByRole("button", { name: "Otto" }));+ await userEvent.click(+ await screen.findByRole("button", { name: "Skip for now" }),+ );+ await userEvent.click(await screen.findByText("SEO Blog Writer"));++ expect(await screen.findByText("Something went wrong")).toBeDefined();+ expect(screen.getByText("SEO Blog Writer")).toBeDefined();+ const confirm = screen.getByRole("button", { name: "Give me this job" });+ expect((confirm as HTMLButtonElement).disabled).toBe(true);+ expect(screen.getByRole("button", { name: "Skip for now" })).toBeDefined();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/AssistantBubble/AssistantBubble.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/components/AssistantBubble/AssistantBubble.tsxnew file mode 100644index 0000000000..608a180892--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/AssistantBubble/AssistantBubble.tsx@@ -0,0 +1,32 @@+"use client";++import { useEffect, useState } from "react";++type Props = {+ text: string;+ typingDelayMs?: number;+};++export function AssistantBubble({ text, typingDelayMs = 350 }: Props) {+ const [revealed, setRevealed] = useState(typingDelayMs === 0);++ useEffect(() => {+ if (typingDelayMs === 0) return;+ const timer = setTimeout(() => setRevealed(true), typingDelayMs);+ return () => clearTimeout(timer);+ }, [typingDelayMs]);++ return (+ <div className="max-w-[80%] self-start rounded-3xl rounded-bl-lg bg-background px-5 py-3.5 text-[15px] leading-relaxed text-foreground shadow-sm">+ {revealed ? (+ text+ ) : (+ <span className="flex gap-1" aria-label="Typing">+ <span className="h-2 w-2 animate-bounce rounded-full bg-muted-foreground/40 [animation-delay:-0.3s]" />+ <span className="h-2 w-2 animate-bounce rounded-full bg-muted-foreground/40 [animation-delay:-0.15s]" />+ <span className="h-2 w-2 animate-bounce rounded-full bg-muted-foreground/40" />+ </span>+ )}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/FirstJobStep/FirstJobStep.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/components/FirstJobStep/FirstJobStep.tsxnew file mode 100644index 0000000000..35caf66673--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/FirstJobStep/FirstJobStep.tsx@@ -0,0 +1,124 @@+"use client";++import type { StoreAgent } from "@/app/api/__generated__/models/storeAgent";+import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { selectableCardClassName } from "@/components/organisms/VoicePicker/styles";+import { cn } from "@/lib/utils";+import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";+import { useFirstJobStep } from "./useFirstJobStep";++type Props = {+ onPick: (job: { id: string; name: string }) => void;+ onSkip: () => void;+};++export function FirstJobStep({ onPick, onSkip }: Props) {+ const {+ suggestions,+ isLoading,+ suggestionsHaveError,+ selectedJobHasError,+ selected,+ select,+ isResolving,+ canConfirm,+ confirm,+ retrySuggestions,+ retrySelectedJob,+ } = useFirstJobStep({ onPick });++ return (+ <div className="flex flex-col gap-3">+ {suggestionsHaveError ? (+ <ErrorCard+ context="starter jobs"+ hint="We couldn't load the available jobs. You can retry or skip for now."+ onRetry={retrySuggestions}+ />+ ) : isLoading ? (+ <div className="flex flex-col gap-3">+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-20 w-full rounded-2xl" />+ ))}+ </div>+ ) : suggestions.length > 0 ? (+ suggestions.map((agent) => (+ <JobCard+ key={agent.slug}+ agent={agent}+ isSelected={selected?.slug === agent.slug}+ onSelect={() => select(agent)}+ />+ ))+ ) : (+ <p className="rounded-2xl border border-border bg-background p-5 text-sm text-muted-foreground">+ No starter jobs are available right now. You can skip for now.+ </p>+ )}++ {selectedJobHasError && !suggestionsHaveError ? (+ <ErrorCard+ context="that starter job"+ hint="We couldn't load that job. Pick another, retry, or skip for now."+ onRetry={retrySelectedJob}+ />+ ) : null}++ <footer className="flex items-center justify-between gap-3">+ <Button variant="ghost" onClick={onSkip}>+ Skip for now+ </Button>+ <Button+ variant="primary"+ onClick={confirm}+ disabled={!canConfirm}+ loading={isResolving}+ className="rounded-full"+ >+ Give me this job+ </Button>+ </footer>+ </div>+ );+}++type JobCardProps = {+ agent: StoreAgent;+ isSelected: boolean;+ onSelect: () => void;+};++function JobCard({ agent, isSelected, onSelect }: JobCardProps) {+ return (+ <button+ type="button"+ onClick={onSelect}+ aria-pressed={isSelected}+ className={cn(+ selectableCardClassName(isSelected, true),+ "w-full p-4 text-left",+ )}+ >+ <div className="flex items-center justify-between gap-3">+ <span className="text-[15px] font-medium text-foreground">+ {agent.agent_name}+ </span>+ {isSelected ? (+ <Icon+ icon={CheckmarkCircle02Icon}+ size={18}+ className="shrink-0 text-accent"+ />+ ) : null}+ </div>+ {agent.sub_heading ? (+ <p className="mt-1 line-clamp-2 text-sm text-muted-foreground">+ {agent.sub_heading}+ </p>+ ) : null}+ </button>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/FirstJobStep/useFirstJobStep.ts b/autogpt_platform/frontend/src/app/(platform)/raise/components/FirstJobStep/useFirstJobStep.tsnew file mode 100644index 0000000000..47406fbdff--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/FirstJobStep/useFirstJobStep.ts@@ -0,0 +1,70 @@+import {+ useGetV2GetSpecificAgent,+ useGetV2ListStoreAgents,+} from "@/app/api/__generated__/endpoints/store/store";+import type { StoreAgent } from "@/app/api/__generated__/models/storeAgent";+import type { StoreAgentDetails } from "@/app/api/__generated__/models/storeAgentDetails";+import type { StoreAgentsResponse } from "@/app/api/__generated__/models/storeAgentsResponse";+import { useAuth } from "@/lib/auth/hooks/useAuth";+import { useState } from "react";++interface Args {+ onPick: (job: { id: string; name: string }) => void;+}++export function useFirstJobStep({ onPick }: Args) {+ const { isLoggedIn } = useAuth();+ const [selected, setSelected] = useState<StoreAgent | null>(null);++ const agentsQuery = useGetV2ListStoreAgents(+ { sorted_by: "runs", page_size: 3 },+ {+ query: {+ select: (response) => response.data as StoreAgentsResponse,+ enabled: isLoggedIn,+ },+ },+ );++ const detailQuery = useGetV2GetSpecificAgent(+ selected?.creator ?? "",+ selected?.slug ?? "",+ undefined,+ {+ query: {+ select: (response) => response.data as StoreAgentDetails,+ enabled: Boolean(selected),+ },+ },+ );++ const versionId = detailQuery.data?.store_listing_version_id ?? null;++ function confirm() {+ if (selected && versionId) {+ onPick({ id: versionId, name: selected.agent_name });+ }+ }++ function retrySuggestions() {+ void agentsQuery.refetch();+ }++ function retrySelectedJob() {+ void detailQuery.refetch();+ }++ return {+ suggestions: agentsQuery.data?.agents ?? [],+ isLoading: isLoggedIn && agentsQuery.isLoading,+ suggestionsHaveError: agentsQuery.isError,+ selectedJobHasError: detailQuery.isError,+ selected,+ select: setSelected,+ isResolving: Boolean(selected) && detailQuery.isFetching,+ canConfirm: Boolean(selected) && Boolean(versionId),+ confirm,+ retrySuggestions,+ retrySelectedJob,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/NameStep/NameStep.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/components/NameStep/NameStep.tsxnew file mode 100644index 0000000000..dead9ea91b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/NameStep/NameStep.tsx@@ -0,0 +1,57 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Input } from "@/components/atoms/Input/Input";+import { NAME_CHIPS } from "../../helpers";+import { useNameStep } from "./useNameStep";++interface Props {+ onSubmit: (name: string) => void;+}++export function NameStep({ onSubmit }: Props) {+ const { custom, setCustom, trimmed, submitCustom } = useNameStep({+ onSubmit,+ });++ return (+ <div className="flex flex-col gap-4">+ <div+ role="group"+ aria-label="Suggested names"+ className="flex flex-wrap gap-2.5"+ >+ {NAME_CHIPS.map((chip) => (+ <button+ key={chip}+ type="button"+ onClick={() => onSubmit(chip)}+ className="rounded-full border border-border bg-background px-5 py-2.5 text-sm font-medium text-foreground transition-colors hover:border-accent hover:bg-accent/5"+ >+ {chip}+ </button>+ ))}+ </div>+ <form onSubmit={submitCustom} className="flex items-end gap-2">+ <Input+ id="raise-name"+ label="Or type your own"+ hideLabel+ value={custom}+ onChange={(event) => setCustom(event.target.value)}+ placeholder="Type a name…"+ maxLength={100}+ wrapperClassName="flex-1"+ />+ <Button+ type="submit"+ variant="primary"+ disabled={!trimmed}+ className="rounded-full"+ >+ Name me+ </Button>+ </form>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/NameStep/useNameStep.ts b/autogpt_platform/frontend/src/app/(platform)/raise/components/NameStep/useNameStep.tsnew file mode 100644index 0000000000..359fc13831--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/NameStep/useNameStep.ts@@ -0,0 +1,18 @@+import type { FormEvent } from "react";+import { useState } from "react";++interface Args {+ onSubmit: (name: string) => void;+}++export function useNameStep({ onSubmit }: Args) {+ const [custom, setCustom] = useState("");+ const trimmed = custom.trim();++ function submitCustom(event: FormEvent) {+ event.preventDefault();+ if (trimmed) onSubmit(trimmed);+ }++ return { custom, setCustom, trimmed, submitCustom };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/RaiseFlow/RaiseFlow.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/components/RaiseFlow/RaiseFlow.tsxnew file mode 100644index 0000000000..56be138cad--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/RaiseFlow/RaiseFlow.tsx@@ -0,0 +1,125 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Icon } from "@/components/atoms/Icon/Icon";+import { VoicePicker } from "@/components/organisms/VoicePicker/VoicePicker";+import { ArrowLeft02Icon } from "@hugeicons/core-free-icons";+import { useEffect, useRef } from "react";+import { VOICE_SAMPLES } from "../../helpers";+import { useRaisePage } from "../../useRaisePage";+import { AssistantBubble } from "../AssistantBubble/AssistantBubble";+import { FirstJobStep } from "../FirstJobStep/FirstJobStep";+import { NameStep } from "../NameStep/NameStep";+import { SoulPreviewPanel } from "../SoulPreviewPanel/SoulPreviewPanel";++export function RaiseFlow() {+ const {+ step,+ messages,+ name,+ voiceLabel,+ firstJob,+ isSubmitting,+ submitName,+ pickVoice,+ skipVoice,+ pickFirstJob,+ skipFirstJob,+ goBack,+ finish,+ } = useRaisePage();+ const stepPanelRef = useRef<HTMLDivElement>(null);+ const previousStepRef = useRef(step);+ const stepLabel =+ step === "firstJob"+ ? "First job"+ : `${step[0].toUpperCase()}${step.slice(1)}`;++ useEffect(() => {+ if (previousStepRef.current !== step) {+ stepPanelRef.current?.focus();+ previousStepRef.current = step;+ }+ }, [step]);++ return (+ <main className="min-h-screen bg-muted/30 px-4 pb-16 pt-6 sm:px-6 lg:px-8">+ <div className="mx-auto grid w-full max-w-[1000px] gap-6 lg:grid-cols-[1fr_minmax(300px,360px)]">+ <div className="order-2 flex flex-col gap-4 lg:order-1">+ <div+ role="log"+ aria-live="polite"+ aria-relevant="additions text"+ aria-label="Raise expert conversation"+ className="flex flex-col gap-3"+ >+ {messages.map((message) =>+ message.role === "assistant" ? (+ <AssistantBubble key={message.id} text={message.text} />+ ) : (+ <div+ key={message.id}+ className="max-w-[80%] self-end rounded-3xl rounded-br-lg bg-accent px-5 py-3.5 text-[15px] leading-relaxed text-accent-foreground"+ >+ {message.text}+ </div>+ ),+ )}+ </div>++ <div+ ref={stepPanelRef}+ role="region"+ aria-label={`${stepLabel} step`}+ tabIndex={-1}+ className="mt-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ {step !== "name" ? (+ <button+ type="button"+ onClick={goBack}+ disabled={isSubmitting}+ className="mb-3 flex items-center gap-1 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"+ >+ <Icon icon={ArrowLeft02Icon} size={14} />+ Back+ </button>+ ) : null}+ {step === "name" ? <NameStep onSubmit={submitName} /> : null}+ {step === "voice" ? (+ <VoicePicker+ name={name}+ samples={VOICE_SAMPLES}+ onPick={pickVoice}+ onSkip={skipVoice}+ />+ ) : null}+ {step === "firstJob" ? (+ <FirstJobStep onPick={pickFirstJob} onSkip={skipFirstJob} />+ ) : null}+ {step === "review" ? (+ <div className="flex justify-end">+ <Button+ variant="primary"+ onClick={finish}+ loading={isSubmitting}+ className="rounded-full"+ >+ {`Bring ${name} to life`}+ </Button>+ </div>+ ) : null}+ </div>+ </div>++ <div className="order-1 lg:order-2">+ <SoulPreviewPanel+ name={name}+ voiceLabel={voiceLabel}+ firstJobName={firstJob?.name ?? null}+ />+ </div>+ </div>+ </main>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/SoulPreviewPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/SoulPreviewPanel.tsxnew file mode 100644index 0000000000..af44839546--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/SoulPreviewPanel.tsx@@ -0,0 +1,79 @@+"use client";++import { Avatar, AvatarFallback } from "@/components/atoms/Avatar/Avatar";+import { raisedIdentity } from "../../helpers";+import { expertInitials } from "./helpers";++type Props = {+ name: string;+ voiceLabel: string | null;+ firstJobName: string | null;+};++export function SoulPreviewPanel({ name, voiceLabel, firstJobName }: Props) {+ return (+ <aside className="flex flex-col overflow-hidden rounded-3xl border border-border bg-background shadow-sm">+ <div className="flex items-center gap-3 border-b border-border px-6 py-5">+ <Avatar className="h-11 w-11">+ <AvatarFallback>{expertInitials(name)}</AvatarFallback>+ </Avatar>+ <div>+ <h2 className="text-lg font-semibold tracking-[-0.01em] text-foreground">+ {name ? `${name}'s Soul` : "A new Soul"}+ </h2>+ <p className="text-sm text-muted-foreground">+ Edit any line, anytime.+ </p>+ </div>+ </div>++ <dl className="flex flex-col gap-5 px-6 py-6">+ <SoulLine+ label="Name"+ value={name || null}+ placeholder="Waiting for a name…"+ />+ <SoulLine+ label="Identity"+ value={name ? raisedIdentity(name) : null}+ placeholder="Takes shape once you name me."+ />+ <SoulLine+ label="Voice"+ value={voiceLabel}+ placeholder="However you'd like me to sound."+ />+ <SoulLine+ label="First job"+ value={firstJobName}+ placeholder="Something to get started on."+ />+ </dl>+ </aside>+ );+}++type SoulLineProps = {+ label: string;+ value: string | null;+ placeholder: string;+};++function SoulLine({ label, value, placeholder }: SoulLineProps) {+ return (+ <div className="flex flex-col gap-1">+ <dt className="text-xs font-medium uppercase tracking-[0.12em] text-accent">+ {label}+ </dt>+ <dd+ className={+ value+ ? "text-[15px] text-foreground"+ : "text-[15px] italic text-muted-foreground"+ }+ >+ {value ?? placeholder}+ </dd>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/helpers.test.tsnew file mode 100644index 0000000000..93bace0a4c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/helpers.test.ts@@ -0,0 +1,13 @@+import { describe, expect, test } from "vitest";+import { expertInitials } from "./helpers";++describe("expertInitials", () => {+ test.each([+ ["", "?"],+ ["Otto", "O"],+ ["Nova Ray", "NR"],+ [" juno star extra ", "JS"],+ ])("converts %j to %s", (name, expected) => {+ expect(expertInitials(name)).toBe(expected);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/helpers.tsnew file mode 100644index 0000000000..1a26bf8c25--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/components/SoulPreviewPanel/helpers.ts@@ -0,0 +1,8 @@+export function expertInitials(name: string): string {+ const words = name.trim().split(/\s+/).filter(Boolean);+ if (words.length === 0) return "?";+ return words+ .slice(0, 2)+ .map((word) => word.charAt(0).toUpperCase())+ .join("");+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/raise/helpers.test.tsnew file mode 100644index 0000000000..5d7c6d42dd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/helpers.test.ts@@ -0,0 +1,51 @@+import type { VoiceSample } from "@/app/api/__generated__/models/voiceSample";+import { describe, expect, test } from "vitest";+import {+ getExpertLimitCode,+ raisedIdentity,+ resolveVoicePreferences,+ voiceSummaryLabel,+} from "./helpers";++const samples: VoiceSample[] = [+ { label: "Direct", text: "Do this next." },+ { label: "Warm", text: "Let's work through this together." },+];++describe("raise helpers", () => {+ test("labels preset and custom voice choices", () => {+ expect(voiceSummaryLabel({ choice: "a" }, samples)).toBe("Direct");+ expect(voiceSummaryLabel({ choice: "b" }, samples)).toBe("Warm");+ expect(+ voiceSummaryLabel(+ { choice: "custom", customText: "My own sample" },+ samples,+ ),+ ).toBe("My own writing sample");+ });++ test("resolves a preset and rejects a blank custom voice", () => {+ expect(resolveVoicePreferences({ choice: "a" }, samples)).toContain(+ "Preferred writing style: Direct.",+ );+ expect(+ resolveVoicePreferences({ choice: "custom", customText: " " }, samples),+ ).toBeNull();+ });++ test("builds the same complete raised identity shown by the backend", () => {+ expect(raisedIdentity("Otto")).toBe(+ "I'm Otto, raised by you. I learn how you work and grow with you.",+ );+ });++ test("extracts a structured expert-limit code safely", () => {+ expect(+ getExpertLimitCode({+ detail: { code: "raised_expert_lifetime_limit", limit: 100 },+ }),+ ).toBe("raised_expert_lifetime_limit");+ expect(getExpertLimitCode({ detail: "legacy error" })).toBeNull();+ expect(getExpertLimitCode(null)).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/raise/helpers.tsnew file mode 100644index 0000000000..9c9a67d52f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/helpers.ts@@ -0,0 +1,172 @@+import type { VoiceSample } from "@/app/api/__generated__/models/voiceSample";+import {+ buildVoicePreferences,+ type VoicePickResult,+} from "@/components/organisms/VoicePicker/helpers";++export type RaiseStep = "name" | "voice" | "firstJob" | "review";++export const NAME_CHIPS = ["Otto", "Nova", "Juno"];++export const VOICE_SAMPLES: VoiceSample[] = [+ {+ label: "Concise and direct",+ text: "Here's what I found and what I'd do next. No fluff — just the decision and the reason behind it.",+ },+ {+ label: "Warm and detailed",+ text: "I dug into this for you and want to walk you through what stood out, why it matters, and where I think we should head together.",+ },+];++export const RAISE_PROMPTS = {+ name: "Hi. I don't have a name yet — that's where you come in.",+ voice: (name: string) =>+ `Nice to meet you, ${name}. How should I sound when I write?`,+ firstJob:+ "What should I take on first? Pick a starter job, or skip and we'll figure it out together.",+ review: "That's me so far. Ready when you are — I'll open our first chat.",+};++export const VOICE_SKIPPED_LABEL = "I'll decide the voice later";+export const FIRST_JOB_SKIPPED_LABEL = "Skip for now";++export interface RaiseDraft {+ step: RaiseStep;+ name: string;+ voicePreferences: string;+ voiceLabel: string | null;+ firstJob: { id: string; name: string } | null;+}++export const EMPTY_DRAFT: RaiseDraft = {+ step: "name",+ name: "",+ voicePreferences: "",+ voiceLabel: null,+ firstJob: null,+};++const DRAFT_STORAGE_KEY = "raise-expert-draft";++export function loadDraft(): RaiseDraft {+ if (typeof window === "undefined") return EMPTY_DRAFT;+ try {+ const raw = window.sessionStorage.getItem(DRAFT_STORAGE_KEY);+ if (!raw) return EMPTY_DRAFT;+ const parsed = JSON.parse(raw) as Partial<RaiseDraft>;+ return { ...EMPTY_DRAFT, ...parsed };+ } catch {+ return EMPTY_DRAFT;+ }+}++export function saveDraft(draft: RaiseDraft) {+ try {+ window.sessionStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft));+ } catch {+ // Draft persistence is best-effort when storage is blocked or full.+ }+}++export function clearDraft() {+ try {+ window.sessionStorage.removeItem(DRAFT_STORAGE_KEY);+ } catch {+ // Clearing is best-effort under the same storage restrictions.+ }+}++interface RaiseMessage {+ id: string;+ role: "assistant" | "user";+ text: string;+}++const STEP_ORDER: RaiseStep[] = ["name", "voice", "firstJob", "review"];++export function previousStep(step: RaiseStep): RaiseStep {+ const index = STEP_ORDER.indexOf(step);+ return STEP_ORDER[Math.max(index - 1, 0)];+}++// The transcript is derived from the draft rather than accumulated, so+// back transitions and refresh restores always rebuild it consistently.+export function buildTranscript(draft: RaiseDraft): RaiseMessage[] {+ const messages: RaiseMessage[] = [+ { id: "assistant-name", role: "assistant", text: RAISE_PROMPTS.name },+ ];+ const stepIndex = STEP_ORDER.indexOf(draft.step);++ if (stepIndex >= 1) {+ messages.push(+ { id: "user-name", role: "user", text: draft.name },+ {+ id: "assistant-voice",+ role: "assistant",+ text: RAISE_PROMPTS.voice(draft.name),+ },+ );+ }+ if (stepIndex >= 2) {+ messages.push(+ {+ id: "user-voice",+ role: "user",+ text: draft.voiceLabel ?? VOICE_SKIPPED_LABEL,+ },+ {+ id: "assistant-first-job",+ role: "assistant",+ text: RAISE_PROMPTS.firstJob,+ },+ );+ }+ if (stepIndex >= 3) {+ messages.push(+ {+ id: "user-first-job",+ role: "user",+ text: draft.firstJob?.name ?? FIRST_JOB_SKIPPED_LABEL,+ },+ {+ id: "assistant-review",+ role: "assistant",+ text: RAISE_PROMPTS.review,+ },+ );+ }+ return messages;+}++export function voiceSummaryLabel(+ result: VoicePickResult,+ samples: VoiceSample[],+): string {+ if (result.choice === "custom") return "My own writing sample";+ const sample = result.choice === "a" ? samples[0] : samples[1];+ return sample?.label ?? "A voice";+}++export function resolveVoicePreferences(+ result: VoicePickResult,+ samples: VoiceSample[],+): string | null {+ return buildVoicePreferences(result, samples);+}++export function raisedIdentity(name: string): string {+ // Keep this preview copy aligned with backend experts_db._raised_identity.+ return `I'm ${name}, raised by you. I learn how you work and grow with you.`;+}++export function getExpertLimitCode(response: unknown): string | null {+ if (!response || typeof response !== "object" || !("detail" in response)) {+ return null;+ }+ const detail = response.detail;+ if (!detail || typeof detail !== "object" || !("code" in detail)) {+ return null;+ }+ return typeof detail.code === "string" ? detail.code : null;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/page.tsx b/autogpt_platform/frontend/src/app/(platform)/raise/page.tsxnew file mode 100644index 0000000000..873cb617d6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/page.tsx@@ -0,0 +1,46 @@+"use client";++import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";+import dynamic from "next/dynamic";+import { notFound } from "next/navigation";++const RaiseFlow = dynamic(+ () =>+ import("./components/RaiseFlow/RaiseFlow").then(+ (module) => module.RaiseFlow,+ ),+ { ssr: false, loading: RaiseSkeleton },+);++export default function RaisePage() {+ const { enabled, ready } = useFlagStatus(Flag.HIRE_EXPERTS);++ if (!ready) {+ return <RaiseSkeleton />;+ }+ if (!enabled) {+ notFound();+ }++ return <RaiseFlow />;+}++function RaiseSkeleton() {+ return (+ <main+ className="min-h-screen bg-muted/30 px-4 pb-16 pt-6 sm:px-6 lg:px-8"+ aria-label="Loading…"+ >+ <div className="mx-auto grid w-full max-w-[1000px] gap-6 lg:grid-cols-[1fr_minmax(300px,360px)]">+ <div className="order-2 flex flex-col gap-4 lg:order-1">+ <Skeleton className="h-16 w-3/4 rounded-3xl" />+ <Skeleton className="h-40 w-full rounded-2xl" />+ </div>+ <div className="order-1 lg:order-2">+ <Skeleton className="h-80 w-full rounded-3xl" />+ </div>+ </div>+ </main>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/raise/useRaisePage.ts b/autogpt_platform/frontend/src/app/(platform)/raise/useRaisePage.tsnew file mode 100644index 0000000000..53b6f80f80--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/raise/useRaisePage.ts@@ -0,0 +1,155 @@+import { useCreateRaisedExpert } from "@/app/api/__generated__/endpoints/experts/experts";+import type { RaiseResult } from "@/app/api/__generated__/models/raiseResult";+import { toast } from "@/components/molecules/Toast/use-toast";+import type { VoicePickResult } from "@/components/organisms/VoicePicker/helpers";+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import { useRouter } from "next/navigation";+import { useRef, useState } from "react";+import {+ buildTranscript,+ clearDraft,+ getExpertLimitCode,+ loadDraft,+ previousStep,+ resolveVoicePreferences,+ saveDraft,+ voiceSummaryLabel,+ VOICE_SAMPLES,+ type RaiseDraft,+} from "./helpers";++export function useRaisePage() {+ const router = useRouter();+ const { mutateAsync: createRaisedExpert, isPending } =+ useCreateRaisedExpert();+ const [draft, setDraft] = useState<RaiseDraft>(loadDraft);+ const [isSubmissionLocked, setIsSubmissionLocked] = useState(false);+ // Synchronous latch: isPending only flips after a rerender, so a rapid+ // double-click could dispatch two POSTs without it. Stays latched after+ // success (we are navigating away); resets only on error so the user+ // can retry.+ const submitLatch = useRef(false);++ function update(changes: Partial<RaiseDraft>) {+ const next = { ...draft, ...changes };+ saveDraft(next);+ setDraft(next);+ }++ function submitName(value: string) {+ const trimmed = value.trim();+ if (!trimmed) return;+ update({ name: trimmed, step: "voice" });+ }++ function pickVoice(result: VoicePickResult) {+ const preferences = resolveVoicePreferences(result, VOICE_SAMPLES);+ if (preferences === null) {+ skipVoice();+ return;+ }+ update({+ voicePreferences: preferences,+ voiceLabel: voiceSummaryLabel(result, VOICE_SAMPLES),+ step: "firstJob",+ });+ }++ function skipVoice() {+ update({+ voicePreferences: "",+ voiceLabel: null,+ step: "firstJob",+ });+ }++ function pickFirstJob(job: { id: string; name: string }) {+ update({ firstJob: job, step: "review" });+ }++ function skipFirstJob() {+ update({ firstJob: null, step: "review" });+ }++ function goBack() {+ update({ step: previousStep(draft.step) });+ }++ async function finish() {+ if (submitLatch.current) return;+ submitLatch.current = true;+ setIsSubmissionLocked(true);+ try {+ const response = await createRaisedExpert({+ data: {+ name: draft.name,+ voice_preferences: draft.voicePreferences || null,+ first_job_store_listing_version_id: draft.firstJob?.id ?? null,+ },+ });+ const result = response.data as RaiseResult;+ clearDraft();+ if (draft.firstJob && !result.first_job_installed) {+ if (result.first_job_failure_reason === "unavailable") {+ toast({+ title: `${draft.firstJob.name} is no longer available`,+ description: `${result.expert.name} is ready. You can choose another first job from their page.`,+ variant: "default",+ });+ } else {+ toast({+ title: `Couldn't set up ${result.expert.name}'s first job`,+ description: `You can install "${draft.firstJob.name}" from their page anytime.`,+ variant: "default",+ });+ }+ }+ const kickoff = result.expert.workflows.length > 0 ? "&kickoff=1" : "";+ router.push(`/copilot?expertId=${result.expert.id}${kickoff}`);+ } catch (error) {+ submitLatch.current = false;+ setIsSubmissionLocked(false);+ if (error instanceof ApiError && error.status === 409) {+ if (+ getExpertLimitCode(error.response) === "raised_expert_lifetime_limit"+ ) {+ toast({+ title: "Expert creation limit reached",+ description:+ "This account has reached its lifetime raised-expert limit. Contact support if you need more capacity.",+ variant: "destructive",+ });+ return;+ }+ toast({+ title: "Your team is full",+ description:+ "You've reached the limit of active experts. Archive one from your team page to raise another.",+ variant: "destructive",+ });+ return;+ }+ toast({+ title: `Couldn't raise ${draft.name || "your expert"}`,+ description: "Something went wrong. Please try again.",+ variant: "destructive",+ });+ }+ }++ return {+ step: draft.step,+ messages: buildTranscript(draft),+ name: draft.name,+ voiceLabel: draft.voiceLabel,+ firstJob: draft.firstJob,+ isSubmitting: isPending || isSubmissionLocked,+ submitName,+ pickVoice,+ skipVoice,+ pickFirstJob,+ skipFirstJob,+ goBack,+ finish,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsxindex 96fdc2005e..dc0b2ec3d5 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx@@ -830,6 +830,9 @@ describe("TeamPage", () => {name: "Browse the marketplace",});expect(link.getAttribute("href")).toBe("/marketplace");+ expect(+ screen.getByRole("link", { name: "Raise your own" }).getAttribute("href"),+ ).toBe("/raise");});test("shows an error card when loading experts fails", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/EmptyTeamState.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/EmptyTeamState.tsxindex 939bc64b9c..b4e40a0ed6 100644--- a/autogpt_platform/frontend/src/app/(platform)/team/components/EmptyTeamState.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/EmptyTeamState.tsx@@ -12,9 +12,19 @@ export function EmptyTeamState() {Hire an expert from the marketplace and they will show up here, ready towork alongside Autopilot.</Text>- <Button as="NextLink" href="/marketplace" variant="primary" size="small">- Browse the marketplace- </Button>+ <div className="flex flex-wrap items-center justify-center gap-2">+ <Button+ as="NextLink"+ href="/marketplace"+ variant="primary"+ size="small"+ >+ Browse the marketplace+ </Button>+ <Button as="NextLink" href="/raise" variant="secondary" size="small">+ Raise your own+ </Button>+ </div></div>);}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex a59aa9cdff..07f9007848 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -5901,6 +5901,7 @@"$ref": "#/components/responses/HTTP401NotAuthenticatedError"},"404": { "description": "Expert template not found" },+ "409": { "description": "Active expert limit reached" },"422": {"description": "Validation Error","content": {@@ -5939,6 +5940,49 @@"security": [{ "HTTPBearerJWT": [] }]}},+ "/api/experts/raise": {+ "post": {+ "tags": ["v2", "experts", "experts", "private"],+ "summary": "Create Raised Expert",+ "operationId": "create_raised_expert",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateRaisedExpertRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/RaiseResult" }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": {+ "description": "First job listing not found or unavailable"+ },+ "409": { "description": "Active expert limit reached" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },"/api/experts/templates": {"get": {"tags": ["v2", "experts", "experts", "private"],@@ -16859,6 +16903,40 @@"required": ["name", "slug"],"title": "CreateOrgRequest"},+ "CreateRaisedExpertRequest": {+ "properties": {+ "name": {+ "type": "string",+ "maxLength": 100,+ "minLength": 1,+ "title": "Name"+ },+ "role": {+ "anyOf": [+ { "type": "string", "maxLength": 100 },+ { "type": "null" }+ ],+ "title": "Role"+ },+ "voice_preferences": {+ "anyOf": [+ { "type": "string", "maxLength": 4000 },+ { "type": "null" }+ ],+ "title": "Voice Preferences"+ },+ "first_job_store_listing_version_id": {+ "anyOf": [+ { "type": "string", "maxLength": 100 },+ { "type": "null" }+ ],+ "title": "First Job Store Listing Version Id"+ }+ },+ "type": "object",+ "required": ["name"],+ "title": "CreateRaisedExpertRequest"+ },"CreateSessionRequest": {"properties": {"dry_run": {@@ -23057,6 +23135,33 @@"title": "QueuePendingMessageResponse","description": "Response returned when a message is queued because the session already\nhas a turn in flight.\n\n- ``buffer_length``: how many messages are now in the session's\n pending buffer (after this push)\n- ``max_buffer_length``: the per-session cap (server-side constant)\n- ``turn_in_flight``: ``True`` if a copilot turn was running when\n we checked — purely informational for UX feedback."},+ "RaiseResult": {+ "properties": {+ "expert": { "$ref": "#/components/schemas/Expert" },+ "first_job_installed": {+ "type": "boolean",+ "title": "First Job Installed"+ },+ "first_job_failure_reason": {+ "anyOf": [+ {+ "type": "string",+ "enum": ["unavailable", "installation_failed"]+ },+ { "type": "null" }+ ],+ "title": "First Job Failure Reason"+ }+ },+ "type": "object",+ "required": [+ "expert",+ "first_job_installed",+ "first_job_failure_reason"+ ],+ "title": "RaiseResult",+ "description": "Result of raising a blank expert. ``first_job_installed`` is only\nTrue when a first job was requested and its install succeeded, so the\nclient can surface partial success instead of a silent no-op. The stable\nfailure reason distinguishes a listing withdrawn mid-flow from an install\nfailure."+ },"RateLimitResetResponse": {"properties": {"success": { "type": "boolean", "title": "Success" },@@ -27734,7 +27839,7 @@"type": "object","required": ["label", "text"],"title": "VoiceSample",- "description": "A short writing sample in a persona's own voice, offered as a pick in\nthe hire flow. The first sample is choice \"a\", the second choice \"b\"."+ "description": "A short writing sample in a persona's own voice, offered as a pick in\nthe hire or raise flow. The first sample is choice \"a\", the second choice\n\"b\"."},"Webhook": {"properties": {diff --git a/autogpt_platform/frontend/src/components/organisms/VoicePicker/VoicePicker.tsx b/autogpt_platform/frontend/src/components/organisms/VoicePicker/VoicePicker.tsxindex 04ea9c2517..9fb0330873 100644--- a/autogpt_platform/frontend/src/components/organisms/VoicePicker/VoicePicker.tsx+++ b/autogpt_platform/frontend/src/components/organisms/VoicePicker/VoicePicker.tsx@@ -2,18 +2,12 @@import type { VoiceSample } from "@/app/api/__generated__/models/voiceSample";import { Button } from "@/components/atoms/Button/Button";-import { Icon } from "@/components/atoms/Icon/Icon";-import { cn } from "@/lib/utils";-import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";import { useId } from "react";+import { CustomVoiceOption } from "./components/CustomVoiceOption";+import { SampleCard } from "./components/SampleCard";import type { VoicePickResult } from "./helpers";import { useVoicePicker } from "./useVoicePicker";-const MAX_CUSTOM_VOICE_SAMPLE_CHARACTERS = 2_000;-const CUSTOM_VOICE_TEXTAREA_ROWS = 3;-const SELECTABLE_CARD_CLASS_NAME =- "rounded-2xl border border-border bg-background p-5 transition-colors focus-within:ring-2 focus-within:ring-ring";-type Props = {name?: string;samples: VoiceSample[];@@ -31,7 +25,6 @@ export function VoicePicker({}: Props) {const choiceGroupName = useId();const customTextareaId = useId();- const customCharacterCountId = `${customTextareaId}-character-count`;const {selected,customText,@@ -70,41 +63,14 @@ export function VoicePicker({);})}- <div className={selectableCardClassName(selected === "custom")}>- <label- htmlFor={`${customTextareaId}-choice`}- className="mb-2 block cursor-pointer text-xs font-medium uppercase tracking-[0.12em] text-accent"- >- <input- id={`${customTextareaId}-choice`}- type="radio"- name={choiceGroupName}- value="custom"- checked={selected === "custom"}- onChange={focusCustom}- className="sr-only"- />- Paste your own- </label>- <textarea- id={customTextareaId}- value={customText}- onFocus={focusCustom}- onChange={(event) => changeCustom(event.target.value)}- rows={CUSTOM_VOICE_TEXTAREA_ROWS}- maxLength={MAX_CUSTOM_VOICE_SAMPLE_CHARACTERS}- aria-describedby={customCharacterCountId}- placeholder="Paste a few sentences written the way you'd like this expert to sound."- className="w-full resize-none rounded-xl border border-input bg-background px-4 py-2.5 text-sm leading-relaxed text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-1 focus:ring-ring"- />- <p- id={customCharacterCountId}- className="mt-1.5 text-right text-xs text-muted-foreground"- >- {customText.length.toLocaleString()} /{" "}- {MAX_CUSTOM_VOICE_SAMPLE_CHARACTERS.toLocaleString()} characters- </p>- </div>+ <CustomVoiceOption+ choiceGroupName={choiceGroupName}+ textareaId={customTextareaId}+ customText={customText}+ isSelected={selected === "custom"}+ onFocus={focusCustom}+ onChange={changeCustom}+ /></fieldset><footer className="flex items-center justify-between gap-3">@@ -124,62 +90,3 @@ export function VoicePicker({</div>);}--type SampleCardProps = {- sample: VoiceSample;- choice: "a" | "b";- choiceGroupName: string;- isSelected: boolean;- onSelect: () => void;-};--function selectableCardClassName(isSelected: boolean, interactive = false) {- return cn(- SELECTABLE_CARD_CLASS_NAME,- isSelected- ? "border-accent bg-accent/5 ring-2 ring-accent/20"- : interactive && "cursor-pointer hover:border-foreground/30",- );-}--function SampleCard({- sample,- choice,- choiceGroupName,- isSelected,- onSelect,-}: SampleCardProps) {- return (- <label- className={cn(- "block w-full text-left",- selectableCardClassName(isSelected, true),- )}- >- <input- type="radio"- name={choiceGroupName}- value={choice}- checked={isSelected}- onChange={onSelect}- aria-label={sample.label}- className="sr-only"- />- <div className="mb-2 flex items-center justify-between gap-3">- <span className="text-xs font-medium uppercase tracking-[0.12em] text-accent">- {sample.label}- </span>- {isSelected ? (- <Icon- icon={CheckmarkCircle02Icon}- size={18}- className="shrink-0 text-accent"- />- ) : null}- </div>- <p className="whitespace-pre-line text-[15px] leading-relaxed text-muted-foreground">- {sample.text}- </p>- </label>- );-}diff --git a/autogpt_platform/frontend/src/components/organisms/VoicePicker/__tests__/VoicePicker.test.tsx b/autogpt_platform/frontend/src/components/organisms/VoicePicker/__tests__/VoicePicker.test.tsxindex dfbea14da5..58e51a8d09 100644--- a/autogpt_platform/frontend/src/components/organisms/VoicePicker/__tests__/VoicePicker.test.tsx+++ b/autogpt_platform/frontend/src/components/organisms/VoicePicker/__tests__/VoicePicker.test.tsx@@ -72,10 +72,10 @@ describe("VoicePicker", () => {test("picks the user's own pasted sample", async () => {const { onPick } = setup();- await userEvent.type(- screen.getByPlaceholderText(/Paste a few sentences/),- "Keep it breezy.",- );+ const customSample = screen.getByRole("textbox", {+ name: "Custom voice sample",+ });+ await userEvent.type(customSample, "Keep it breezy.");await userEvent.click(screen.getByRole("button", { name: "Use this voice" }),);diff --git a/autogpt_platform/frontend/src/components/organisms/VoicePicker/components/CustomVoiceOption.tsx b/autogpt_platform/frontend/src/components/organisms/VoicePicker/components/CustomVoiceOption.tsxnew file mode 100644index 0000000000..0a27089249--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/VoicePicker/components/CustomVoiceOption.tsx@@ -0,0 +1,65 @@+import { selectableCardClassName } from "../styles";++const MAX_CUSTOM_VOICE_SAMPLE_CHARACTERS = 2_000;+const CUSTOM_VOICE_TEXTAREA_ROWS = 3;++type Props = {+ choiceGroupName: string;+ textareaId: string;+ customText: string;+ isSelected: boolean;+ onFocus: () => void;+ onChange: (value: string) => void;+};++export function CustomVoiceOption({+ choiceGroupName,+ textareaId,+ customText,+ isSelected,+ onFocus,+ onChange,+}: Props) {+ const characterCountId = `${textareaId}-character-count`;++ return (+ <div className={selectableCardClassName(isSelected)}>+ <label+ htmlFor={`${textareaId}-choice`}+ className="mb-2 block cursor-pointer text-xs font-medium uppercase tracking-[0.12em] text-accent"+ >+ <input+ id={`${textareaId}-choice`}+ type="radio"+ name={choiceGroupName}+ value="custom"+ checked={isSelected}+ onChange={onFocus}+ className="sr-only"+ />+ Paste your own+ </label>+ <label htmlFor={textareaId} className="sr-only">+ Custom voice sample+ </label>+ <textarea+ id={textareaId}+ value={customText}+ onFocus={onFocus}+ onChange={(event) => onChange(event.target.value)}+ rows={CUSTOM_VOICE_TEXTAREA_ROWS}+ maxLength={MAX_CUSTOM_VOICE_SAMPLE_CHARACTERS}+ aria-describedby={characterCountId}+ placeholder="Paste a few sentences written the way you'd like this expert to sound."+ className="w-full resize-none rounded-xl border border-input bg-background px-4 py-2.5 text-sm leading-relaxed text-foreground placeholder:text-muted-foreground focus:border-ring focus:outline-none focus:ring-1 focus:ring-ring"+ />+ <p+ id={characterCountId}+ className="mt-1.5 text-right text-xs text-muted-foreground"+ >+ {customText.length.toLocaleString()} /{" "}+ {MAX_CUSTOM_VOICE_SAMPLE_CHARACTERS.toLocaleString()} characters+ </p>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/VoicePicker/components/SampleCard.tsx b/autogpt_platform/frontend/src/components/organisms/VoicePicker/components/SampleCard.tsxnew file mode 100644index 0000000000..e6afd52e86--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/VoicePicker/components/SampleCard.tsx@@ -0,0 +1,55 @@+import type { VoiceSample } from "@/app/api/__generated__/models/voiceSample";+import { Icon } from "@/components/atoms/Icon/Icon";+import { cn } from "@/lib/utils";+import { CheckmarkCircle02Icon } from "@hugeicons/core-free-icons";+import { selectableCardClassName } from "../styles";++type Props = {+ sample: VoiceSample;+ choice: "a" | "b";+ choiceGroupName: string;+ isSelected: boolean;+ onSelect: () => void;+};++export function SampleCard({+ sample,+ choice,+ choiceGroupName,+ isSelected,+ onSelect,+}: Props) {+ return (+ <label+ className={cn(+ "block w-full text-left",+ selectableCardClassName(isSelected, true),+ )}+ >+ <input+ type="radio"+ name={choiceGroupName}+ value={choice}+ checked={isSelected}+ onChange={onSelect}+ aria-label={sample.label}+ className="sr-only"+ />+ <div className="mb-2 flex items-center justify-between gap-3">+ <span className="text-xs font-medium uppercase tracking-[0.12em] text-accent">+ {sample.label}+ </span>+ {isSelected ? (+ <Icon+ icon={CheckmarkCircle02Icon}+ size={18}+ className="shrink-0 text-accent"+ />+ ) : null}+ </div>+ <p className="whitespace-pre-line text-[15px] leading-relaxed text-muted-foreground">+ {sample.text}+ </p>+ </label>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/VoicePicker/styles.ts b/autogpt_platform/frontend/src/components/organisms/VoicePicker/styles.tsnew file mode 100644index 0000000000..c2a1fbebe3--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/VoicePicker/styles.ts@@ -0,0 +1,16 @@+import { cn } from "@/lib/utils";++const SELECTABLE_CARD_CLASS_NAME =+ "rounded-2xl border border-border bg-background p-5 transition-colors focus-within:ring-2 focus-within:ring-ring";++export function selectableCardClassName(+ isSelected: boolean,+ interactive = false,+) {+ return cn(+ SELECTABLE_CARD_CLASS_NAME,+ isSelected+ ? "border-accent bg-accent/5 ring-2 ring-accent/20"+ : interactive && "cursor-pointer hover:border-foreground/30",+ );+}