Skip to content

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): install your own library agents as expert workflows (#14297)

Reinier van der Leerb72706df605e
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index b0670bfde7..3641ef9d31 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -65,6 +65,7 @@ from backend.util.exceptions import (
ExpertNotFoundError,
ExpertPrivateTenancyNotFoundError,
ExpertWriteNotReadableError,
+ NotFoundError,
)
from backend.util.timezone_utils import get_user_timezone_or_utc
@@ -77,7 +78,12 @@ def _raised_identity(name: str) -> str:
return f"I'm {name}, raised by you. I learn how you work and grow with you."
-_WORKFLOW_ROW_INCLUDE = {"LibraryAgent": True, "StoreListingVersion": True}
+_WORKFLOW_ROW_INCLUDE: prisma.types.ExpertWorkflowInclude = {
+ # AgentGraph carries the name/description of a user-created library agent;
+ # LibraryAgent.name is only populated from a marketplace snapshot.
+ "LibraryAgent": {"include": {"AgentGraph": True}},
+ "StoreListingVersion": True,
+}
_WORKFLOW_INCLUDE = {"Workflows": {"include": _WORKFLOW_ROW_INCLUDE}}
_MAX_EXPERT_RUNS = 20
@@ -93,7 +99,7 @@ def _to_workflow_ref(row: prisma.models.ExpertWorkflow) -> ExpertWorkflowRef:
if listing is not None:
name, description = listing.name, listing.description
elif library_agent is not None:
- name, description = library_agent.name, library_agent.description
+ name, description = _library_agent_labels(library_agent)
else:
name, description = None, None
return ExpertWorkflowRef(
@@ -108,6 +114,25 @@ def _to_workflow_ref(row: prisma.models.ExpertWorkflow) -> ExpertWorkflowRef:
)
+def _library_agent_labels(
+ row: prisma.models.LibraryAgent,
+) -> tuple[str | None, str | None]:
+ """Name/description of a library agent, mirroring ``LibraryAgent.from_db``.
+
+ The columns hold a marketplace snapshot and are NULL on a user's own agent,
+ whose real title lives on the graph.
+ """
+ graph = row.AgentGraph
+ return (
+ row.name if row.name is not None else (graph.name if graph else None),
+ (
+ row.description
+ if row.description is not None
+ else (graph.description if graph else None)
+ ),
+ )
+
+
def _to_model(
row: prisma.models.Expert,
latest_run: prisma.models.AgentGraphExecution | None = None,
@@ -463,11 +488,20 @@ def _to_expert_run(
needs_review: bool,
) -> ExpertRun:
listing = workflow.StoreListingVersion if workflow else None
+ library_agent = workflow.LibraryAgent if workflow else None
library_agent_id = workflow.libraryAgentId if workflow else None
+ # Library-only workflows carry no listing, so the name comes from the
+ # user's own library agent rather than falling through to the placeholder.
+ if listing is not None:
+ agent_name = listing.name
+ elif library_agent is not None:
+ agent_name = _library_agent_labels(library_agent)[0] or DEFAULT_AGENT_NAME
+ else:
+ agent_name = DEFAULT_AGENT_NAME
return ExpertRun(
execution_id=execution.id,
graph_id=execution.agentGraphId,
- agent_name=listing.name if listing else DEFAULT_AGENT_NAME,
+ agent_name=agent_name,
library_agent_id=library_agent_id,
status=cast(ExpertRunStatus, str(execution.executionStatus).lower()),
output_type=output_type,
@@ -1043,8 +1077,24 @@ async def _install_preloads(
async def install_workflow(
- user_id: str, expert_id: str, store_listing_version_id: str
+ user_id: str,
+ expert_id: str,
+ *,
+ store_listing_version_id: str | None = None,
+ library_agent_id: str | None = None,
) -> ExpertWorkflowRef:
+ """Attach a workflow to a hired expert.
+
+ Exactly one source: a marketplace listing version, or one of the caller's
+ own library agents. The library path records no listing version, so an
+ agent that was never published is installable.
+ """
+ if bool(store_listing_version_id) == bool(library_agent_id):
+ raise ValueError(
+ "install_workflow takes exactly one of store_listing_version_id, "
+ "library_agent_id"
+ )
+
expert = await prisma.models.Expert.prisma().find_first(
where={
"id": expert_id,
@@ -1057,6 +1107,42 @@ async def install_workflow(
if expert is None:
raise ExpertNotFoundError(expert_id)
+ if library_agent_id is not None:
+ return await _install_library_workflow(user_id, expert_id, library_agent_id)
+ assert store_listing_version_id is not None
+ return await _install_marketplace_workflow(
+ user_id, expert_id, store_listing_version_id
+ )
+
+
+async def _install_library_workflow(
+ user_id: str, expert_id: str, library_agent_id: str
+) -> ExpertWorkflowRef:
+ library_agent = await prisma.models.LibraryAgent.prisma().find_first(
+ where={"id": library_agent_id, "userId": user_id, "isDeleted": False}
+ )
+ if library_agent is None:
+ raise NotFoundError(f"Library agent #{library_agent_id} not found")
+
+ # No listing version means the (expertId, storeListingVersionId) unique
+ # index cannot dedupe these rows — Postgres treats each NULL as distinct.
+ existing = await prisma.models.ExpertWorkflow.prisma().find_first(
+ where={"expertId": expert_id, "libraryAgentId": library_agent_id},
+ include=_WORKFLOW_ROW_INCLUDE,
+ )
+ if existing is not None:
+ return _to_workflow_ref(existing)
+
+ row = await prisma.models.ExpertWorkflow.prisma().create(
+ data={"expertId": expert_id, "libraryAgentId": library_agent_id},
+ include=_WORKFLOW_ROW_INCLUDE,
+ )
+ return _to_workflow_ref(row)
+
+
+async def _install_marketplace_workflow(
+ user_id: str, expert_id: str, store_listing_version_id: str
+) -> ExpertWorkflowRef:
existing = await prisma.models.ExpertWorkflow.prisma().find_first(
where={
"expertId": expert_id,
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.py
index 463ec09dc2..7f872e5d84 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
@@ -161,6 +161,28 @@ async def _seed_store_listing(server: SpinTestServer, approved: bool = True) ->
return slv_id
+async def _seed_own_library_agent(
+ server: SpinTestServer, user_id: str
+) -> tuple[str, str]:
+ """Create an unpublished graph owned by *user_id*, returning its
+ LibraryAgent id and name — the private case that has no store listing."""
+ name = f"Private graph {uuid.uuid4().hex[:8]}"
+ graph = Graph(
+ name=name,
+ description="Never published to the marketplace",
+ nodes=[Node(block_id=AgentInputBlock().id, input_default={"name": "input_1"})],
+ links=[],
+ )
+ created_graph = await server.agent_server.test_create_graph(
+ CreateGraph(graph=graph), user_id
+ )
+ library_agent = await prisma.models.LibraryAgent.prisma().find_first(
+ where={"userId": user_id, "agentGraphId": created_graph.id}
+ )
+ assert library_agent is not None, "Graph creation did not make a LibraryAgent"
+ return library_agent.id, name
+
+
async def _load_roster_store_assets() -> dict[str, str]:
"""Load the checked-in production store assets (StoreAgent_rows.csv plus
the matching graph JSONs) for every ROSTER preload slug into the test DB,
@@ -1249,7 +1271,9 @@ async def test_install_workflow_on_archived_expert_raises(
await experts_db.archive_expert(test_user.id, hired.expert.id)
with pytest.raises(experts_db.ExpertNotFoundError):
- await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+ await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
@pytest.mark.asyncio(loop_scope="session")
@@ -1866,8 +1890,12 @@ async def test_install_workflow_duplicate_returns_existing(
slv_id = await _seed_store_listing(server)
template = await _seed_template(name="Maria", preload_listings=[])
hired = await experts_db.hire_expert(test_user.id, template.id, None)
- a = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
- b = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+ a = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
+ b = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
assert a.id == b.id
assert a.library_agent_id is not None
assert a.store_listing_version_id == slv_id
@@ -1900,7 +1928,7 @@ async def test_install_workflow_returns_concurrent_winner(
prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client
):
installed = await experts_db.install_workflow(
- test_user.id, hired.expert.id, slv_id
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
)
assert installed.id == winner.id
@@ -1925,7 +1953,9 @@ async def test_install_workflow_reraises_race_without_winner(
),
pytest.raises(prisma.errors.UniqueViolationError),
):
- await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+ await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
assert workflow_client.find_first.await_count == 2
@@ -1953,7 +1983,9 @@ async def test_install_workflow_reuses_library_agent_without_resetting_settings(
where={"userId": test_user.id}
)
- installed = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+ installed = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
persisted = await prisma.models.LibraryAgent.prisma().find_unique(
where={"id": library_agent.id}
@@ -1991,7 +2023,9 @@ async def test_install_workflow_restores_archived_deleted_library_agent(
},
)
- installed = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+ installed = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
restored = await prisma.models.LibraryAgent.prisma().find_unique(
where={"id": library_agent.id}
@@ -2016,7 +2050,131 @@ async def test_install_workflow_rejects_unapproved_store_version(
hired = await experts_db.hire_expert(test_user.id, template.id, None)
with pytest.raises(NotFoundError):
- await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+ await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_from_own_library_agent(
+ server: SpinTestServer, test_user
+):
+ """The unpublished-agent case: no listing version, and the row still
+ carries the agent's own name so the UI is not left with a placeholder."""
+ library_agent_id, agent_name = await _seed_own_library_agent(server, test_user.id)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ installed = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, library_agent_id=library_agent_id
+ )
+
+ assert installed.library_agent_id == library_agent_id
+ assert installed.store_listing_version_id is None
+ assert installed.name == agent_name
+ assert installed.graph_id is not None
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_from_library_agent_is_idempotent(
+ server: SpinTestServer, test_user
+):
+ library_agent_id, _ = await _seed_own_library_agent(server, test_user.id)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ a = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, library_agent_id=library_agent_id
+ )
+ b = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, library_agent_id=library_agent_id
+ )
+
+ assert a.id == b.id
+ assert (
+ await prisma.models.ExpertWorkflow.prisma().count(
+ where={"expertId": hired.expert.id, "libraryAgentId": library_agent_id}
+ )
+ == 1
+ )
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_rejects_other_users_library_agent(
+ server: SpinTestServer, test_user, other_user
+):
+ library_agent_id, _ = await _seed_own_library_agent(server, other_user.id)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(NotFoundError):
+ await experts_db.install_workflow(
+ test_user.id, hired.expert.id, library_agent_id=library_agent_id
+ )
+
+ assert (
+ await prisma.models.ExpertWorkflow.prisma().count(
+ where={"expertId": hired.expert.id}
+ )
+ == 0
+ )
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_rejects_deleted_library_agent(
+ server: SpinTestServer, test_user
+):
+ library_agent_id, _ = await _seed_own_library_agent(server, test_user.id)
+ await prisma.models.LibraryAgent.prisma().update(
+ where={"id": library_agent_id}, data={"isDeleted": True}
+ )
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(NotFoundError):
+ await experts_db.install_workflow(
+ test_user.id, hired.expert.id, library_agent_id=library_agent_id
+ )
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_library_path_dedupes_marketplace_row(
+ server: SpinTestServer, test_user
+):
+ """Installing a listing and then its resulting library agent is one
+ attachment, not two — the marketplace install already set libraryAgentId."""
+ slv_id = await _seed_store_listing(server)
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ from_listing = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, store_listing_version_id=slv_id
+ )
+ assert from_listing.library_agent_id is not None
+ from_library = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, library_agent_id=from_listing.library_agent_id
+ )
+
+ assert from_library.id == from_listing.id
+ assert from_library.store_listing_version_id == slv_id
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_requires_exactly_one_source(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(ValueError):
+ await experts_db.install_workflow(test_user.id, hired.expert.id)
+ with pytest.raises(ValueError):
+ await experts_db.install_workflow(
+ test_user.id,
+ hired.expert.id,
+ store_listing_version_id="slv-1",
+ library_agent_id="library-agent-1",
+ )
@pytest.mark.asyncio(loop_scope="session")
@@ -3198,10 +3356,25 @@ def _run_execution(**overrides) -> SimpleNamespace:
def _run_workflow(name: str = "SEO Blog Writer") -> SimpleNamespace:
return SimpleNamespace(
libraryAgentId="library-agent-1",
+ LibraryAgent=None,
StoreListingVersion=SimpleNamespace(name=name),
)
+def _library_run_workflow(name: str, graph_name: str | None) -> SimpleNamespace:
+ """A library-only workflow row: no listing, so the name comes from the
+ library agent — or from its graph when the agent was never published."""
+ return SimpleNamespace(
+ libraryAgentId="library-agent-1",
+ LibraryAgent=SimpleNamespace(
+ name=name,
+ description=None,
+ AgentGraph=SimpleNamespace(name=graph_name, description=None),
+ ),
+ StoreListingVersion=None,
+ )
+
+
def test_to_expert_run_uses_workflow_name_and_deep_link():
run = experts_db._to_expert_run(
_run_execution(), _run_workflow(), "table", "result", needs_review=True
@@ -3216,6 +3389,17 @@ def test_to_expert_run_uses_workflow_name_and_deep_link():
)
+def test_to_expert_run_names_a_library_only_workflow():
+ run = experts_db._to_expert_run(
+ _run_execution(),
+ _library_run_workflow(None, "My Private Agent"),
+ "table",
+ "result",
+ needs_review=False,
+ )
+ assert run.agent_name == "My Private Agent"
+
+
def test_to_expert_run_falls_back_when_workflow_unresolved():
run = experts_db._to_expert_run(
_run_execution(), None, "unknown", None, needs_review=False
diff --git a/autogpt_platform/backend/backend/api/features/experts/raise_attachments.py b/autogpt_platform/backend/backend/api/features/experts/raise_attachments.py
index 3dacc1a339..5f8e160b01 100644
--- a/autogpt_platform/backend/backend/api/features/experts/raise_attachments.py
+++ b/autogpt_platform/backend/backend/api/features/experts/raise_attachments.py
@@ -4,6 +4,7 @@ import logging
import prisma.errors
import prisma.models
+import prisma.types
from pydantic import BaseModel
from backend.api.features.experts.models import (
@@ -14,9 +15,6 @@ from backend.api.features.experts.models import (
RaiseAttachmentSource,
)
from backend.api.features.library import db as library_db
-from backend.api.features.store.store_listing_versions import (
- installable_store_version_where,
-)
from backend.copilot.tools.skills import (
get_default_skill_with_body,
read_user_skill_with_body,
@@ -26,7 +24,10 @@ from backend.util.exceptions import ExpertNotFoundError, NotFoundError
logger = logging.getLogger(__name__)
-_WORKFLOW_ROW_INCLUDE = {"LibraryAgent": True, "StoreListingVersion": True}
+_WORKFLOW_ROW_INCLUDE: prisma.types.ExpertWorkflowInclude = {
+ "LibraryAgent": True,
+ "StoreListingVersion": True,
+}
class RaiseAttachmentUnavailableError(Exception):
@@ -173,7 +174,7 @@ async def _resolve_workflow(
row = await _library_agent_row(user_id, attachment.id)
return ResolvedWorkflow(
attachment=attachment,
- store_listing_version_id=await _matching_store_listing_version_id(row),
+ store_listing_version_id=None,
library_agent_id=row.id,
)
@@ -212,42 +213,28 @@ async def _validate_marketplace_listing(
async def _install_resolved_workflow(
user_id: str, expert_id: str, resolved: ResolvedWorkflow
) -> None:
- if resolved.store_listing_version_id and resolved.library_agent_id is None:
- await install_marketplace_workflow(
- user_id, expert_id, resolved.store_listing_version_id
- )
+ if resolved.library_agent_id is not None:
+ await _link_library_workflow(expert_id, resolved.library_agent_id)
return
- if resolved.library_agent_id is None:
+ if resolved.store_listing_version_id is None:
raise RaiseAttachmentUnavailableError(
- "workflow", "library", resolved.attachment.id
+ "workflow", resolved.attachment.source, resolved.attachment.id
)
- await _link_library_workflow(
- expert_id, resolved.library_agent_id, resolved.store_listing_version_id
+ await install_marketplace_workflow(
+ user_id, expert_id, resolved.store_listing_version_id
)
-async def _link_library_workflow(
- expert_id: str,
- library_agent_id: str,
- store_listing_version_id: str | None,
-) -> None:
- existing = await _existing_workflow(
- expert_id, library_agent_id, store_listing_version_id
- )
+async def _link_library_workflow(expert_id: str, library_agent_id: str) -> None:
+ existing = await _existing_library_workflow(expert_id, library_agent_id)
if existing is not None:
return
try:
await prisma.models.ExpertWorkflow.prisma().create(
- data={
- "expertId": expert_id,
- "libraryAgentId": library_agent_id,
- "storeListingVersionId": store_listing_version_id,
- }
+ data={"expertId": expert_id, "libraryAgentId": library_agent_id}
)
except prisma.errors.UniqueViolationError:
- raced = await _existing_workflow(
- expert_id, library_agent_id, store_listing_version_id
- )
+ raced = await _existing_library_workflow(expert_id, library_agent_id)
if raced is None:
raise
@@ -267,30 +254,10 @@ async def _library_agent_row(
return row
-async def _matching_store_listing_version_id(
- row: prisma.models.LibraryAgent,
-) -> str | None:
- listing = await prisma.models.StoreListingVersion.prisma().find_first(
- where={
- "agentGraphId": row.agentGraphId,
- "agentGraphVersion": row.agentGraphVersion,
- **installable_store_version_where(),
- }
- )
- return listing.id if listing else None
-
-
-async def _existing_workflow(
+async def _existing_library_workflow(
expert_id: str,
library_agent_id: str,
- store_listing_version_id: str | None,
) -> prisma.models.ExpertWorkflow | None:
- if store_listing_version_id is not None:
- by_listing = await _existing_listing_workflow(
- expert_id, store_listing_version_id
- )
- if by_listing is not None:
- return by_listing
return await prisma.models.ExpertWorkflow.prisma().find_first(
where={"expertId": expert_id, "libraryAgentId": library_agent_id},
include=_WORKFLOW_ROW_INCLUDE,
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.py
index 31626a2d54..ea0adb4235 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_lib
import fastapi
from fastapi import APIRouter, Security
-from pydantic import BaseModel, Field, field_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
from backend.api.features.experts import credentials as expert_credentials
from backend.api.features.experts import experts_db, scheduling
@@ -24,6 +24,7 @@ from backend.api.features.experts.models import (
RaiseResult,
validate_avatar_url,
)
+from backend.util.exceptions import NotFoundError
router = APIRouter(
prefix="/experts",
@@ -38,7 +39,18 @@ class HireRequest(BaseModel):
class InstallWorkflowRequest(BaseModel):
- store_listing_version_id: str
+ """One workflow source: a marketplace listing, or the caller's own agent."""
+
+ store_listing_version_id: str | None = None
+ library_agent_id: str | None = None
+
+ @model_validator(mode="after")
+ def exactly_one_source(self) -> "InstallWorkflowRequest":
+ if bool(self.store_listing_version_id) == bool(self.library_agent_id):
+ raise ValueError(
+ "Provide exactly one of store_listing_version_id, library_agent_id"
+ )
+ return self
class CreatePodRequest(BaseModel):
@@ -366,7 +378,7 @@ async def update_expert_soul(
@router.post(
"/{expert_id}/workflows",
operation_id="install_expert_workflow",
- responses={404: {"description": "Expert not found"}},
+ responses={404: {"description": "Expert or workflow not found"}},
)
async def install_expert_workflow(
expert_id: str,
@@ -375,9 +387,12 @@ async def install_expert_workflow(
) -> ExpertWorkflowRef:
try:
return await experts_db.install_workflow(
- user_id, expert_id, request.store_listing_version_id
+ user_id,
+ expert_id,
+ store_listing_version_id=request.store_listing_version_id,
+ library_agent_id=request.library_agent_id,
)
- except experts_db.ExpertNotFoundError as e:
+ except NotFoundError as e:
raise fastapi.HTTPException(status_code=404, detail=str(e))
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
index d090926b92..85b309b66c 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
@@ -31,6 +31,7 @@ from backend.api.features.experts.models import (
RaiseResult,
)
from backend.api.features.experts.routes import router
+from backend.util.exceptions import NotFoundError
app = fastapi.FastAPI()
app.include_router(router)
@@ -946,10 +947,13 @@ def test_install_workflow_duplicate_returns_same_row_id(
assert first.status_code == 200
assert second.status_code == 200
assert first.json()["id"] == second.json()["id"] == "workflow-ref-1"
- assert mock_install.await_args_list == [
- mocker.call(test_user_id, "expert-1", "listing-version-1"),
- mocker.call(test_user_id, "expert-1", "listing-version-1"),
- ]
+ expected = mocker.call(
+ test_user_id,
+ "expert-1",
+ store_listing_version_id="listing-version-1",
+ library_agent_id=None,
+ )
+ assert mock_install.await_args_list == [expected, expected]
def test_install_workflow_unknown_expert_returns_404(
@@ -968,6 +972,67 @@ def test_install_workflow_unknown_expert_returns_404(
assert response.status_code == 404
+def test_install_workflow_accepts_library_agent_id(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ ref = _make_workflow_ref()
+ mock_install = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.install_workflow",
+ new_callable=AsyncMock,
+ return_value=ref,
+ )
+
+ response = client.post(
+ "/experts/expert-1/workflows", json={"library_agent_id": "library-agent-1"}
+ )
+
+ assert response.status_code == 200
+ assert mock_install.await_args == mocker.call(
+ test_user_id,
+ "expert-1",
+ store_listing_version_id=None,
+ library_agent_id="library-agent-1",
+ )
+
+
+def test_install_workflow_unknown_library_agent_returns_404(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mocker.patch(
+ "backend.api.features.experts.routes.experts_db.install_workflow",
+ new_callable=AsyncMock,
+ side_effect=NotFoundError("Library agent #nope not found"),
+ )
+
+ response = client.post(
+ "/experts/expert-1/workflows", json={"library_agent_id": "nope"}
+ )
+
+ assert response.status_code == 404
+
+
+ "body",
+ [
+ {},
+ {"store_listing_version_id": "listing-1", "library_agent_id": "agent-1"},
+ ],
+)
+def test_install_workflow_requires_exactly_one_source(
+ mocker: pytest_mock.MockerFixture, body: dict[str, str]
+) -> None:
+ mock_install = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.install_workflow",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post("/experts/expert-1/workflows", json=body)
+
+ assert response.status_code == 422
+ mock_install.assert_not_awaited()
+
+
# ─── Archive + list ────────────────────────────────────────────────────
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.py
index 38ef62d888..437285b351 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
@@ -171,7 +171,6 @@ async def restore_existing_library_agent(
return library_model.LibraryAgent.from_db(
restored,
schedule_info=schedule_info,
- store_listing_version_id=store_listing_version.id,
)
@@ -216,7 +215,6 @@ async def add_graph_to_library(
return library_model.LibraryAgent.from_db(
added_agent,
schedule_info=schedule_info,
- store_listing_version_id=store_listing_version.id,
)
diff --git a/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py b/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py
index 72aa9e4e0e..e9bda94ee2 100644
--- a/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/_add_to_library_test.py
@@ -56,7 +56,6 @@ async def test_add_graph_to_library_create_new_agent() -> None:
mock_from_db.assert_called_once_with(
created_agent,
schedule_info={},
- store_listing_version_id="slv-id",
)
# Verify create was called with correct data
create_call = mock_prisma.return_value.create.call_args
@@ -185,7 +184,6 @@ async def test_add_graph_to_library_unique_violation_updates_existing() -> None:
mock_from_db.assert_called_once_with(
updated_agent,
schedule_info={},
- store_listing_version_id="slv-id",
)
# Verify update was called with correct where and data
update_call = mock_prisma.return_value.update.call_args
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index 00e21292c4..ea51bd43b9 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -16,9 +16,6 @@ from backend.api.features.library.exceptions import (
FolderAlreadyExistsError,
FolderValidationError,
)
-from backend.api.features.store.store_listing_versions import (
- installable_store_version_where,
-)
from backend.data.db import get_database_schema, transaction
from backend.data.execution import get_graph_execution
from backend.data.expert_attribution import resolve_attributable_expert
@@ -74,51 +71,6 @@ async def _fetch_execution_counts(user_id: str, graph_ids: list[str]) -> dict[st
}
-async def _fetch_matching_store_version_ids(
- agents: list[prisma.models.LibraryAgent],
-) -> dict[tuple[str, int], str]:
- """Map (graph_id, graph_version) → approved StoreListingVersion id.
-
- Only approved, non-deleted versions are returned so the ids are always
- valid install targets. Matching on the exact graph version keeps installs
- version-stable: the id refers to the snapshot the library agent holds,
- not the listing's current active version.
- """
- pairs = {(a.agentGraphId, a.agentGraphVersion) for a in agents}
- if not pairs:
- return {}
- pair_filters = [
- {"agentGraphId": graph_id, "agentGraphVersion": graph_version}
- for graph_id, graph_version in sorted(pairs)
- ]
- try:
- versions = await prisma.models.StoreListingVersion.prisma().find_many(
- where={
- "OR": pair_filters,
- **installable_store_version_where(),
- },
- distinct=["agentGraphId", "agentGraphVersion"],
- order=[
- {"agentGraphId": "asc"},
- {"agentGraphVersion": "asc"},
- {"createdAt": "desc"},
- {"id": "desc"},
- ],
- )
- except Exception:
- logger.warning(
- "Failed to fetch store listing versions for library agents",
- exc_info=True,
- )
- return {}
- matches: dict[tuple[str, int], str] = {}
- for version in versions:
- pair = (version.agentGraphId, version.agentGraphVersion)
- if pair in pairs and pair not in matches:
- matches[pair] = version.id
- return matches
-
-
async def _fetch_marketplace_details(
graph_id: str,
) -> tuple[prisma.models.StoreListing | None, prisma.models.Profile | None]:
@@ -281,10 +233,9 @@ async def list_library_agents(
logger.debug(f"Retrieved {len(library_agents)} library agents for user #{user_id}")
graph_ids = [a.agentGraphId for a in library_agents if a.agentGraphId]
- execution_counts, schedule_info, store_version_ids = await asyncio.gather(
+ execution_counts, schedule_info = await asyncio.gather(
_fetch_execution_counts(user_id, graph_ids),
_fetch_schedule_info(user_id),
- _fetch_matching_store_version_ids(library_agents),
)
# Only pass valid agents to the response
@@ -296,9 +247,6 @@ async def list_library_agents(
agent,
execution_count_override=execution_counts.get(agent.agentGraphId),
schedule_info=schedule_info,
- store_listing_version_id=store_version_ids.get(
- (agent.agentGraphId, agent.agentGraphVersion)
- ),
)
valid_library_agents.append(library_agent)
except Exception as e:
@@ -372,10 +320,9 @@ async def list_favorite_library_agents(
)
graph_ids = [a.agentGraphId for a in library_agents if a.agentGraphId]
- execution_counts, schedule_info, store_version_ids = await asyncio.gather(
+ execution_counts, schedule_info = await asyncio.gather(
_fetch_execution_counts(user_id, graph_ids),
_fetch_schedule_info(user_id),
- _fetch_matching_store_version_ids(library_agents),
)
# Only pass valid agents to the response
@@ -387,9 +334,6 @@ async def list_favorite_library_agents(
agent,
execution_count_override=execution_counts.get(agent.agentGraphId),
schedule_info=schedule_info,
- store_listing_version_id=store_version_ids.get(
- (agent.agentGraphId, agent.agentGraphVersion)
- ),
)
valid_library_agents.append(library_agent)
except Exception as e:
@@ -442,12 +386,10 @@ async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent
(
marketplace_details,
schedule_info,
- store_version_ids,
sub_graphs,
) = await asyncio.gather(
_fetch_marketplace_details(library_agent.AgentGraph.id),
_fetch_schedule_info(user_id, graph_id=library_agent.AgentGraph.id),
- _fetch_matching_store_version_ids([library_agent]),
graph_db.get_sub_graphs(library_agent.AgentGraph),
)
store_listing, profile = marketplace_details
@@ -458,9 +400,6 @@ async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent
store_listing=store_listing,
profile=profile,
schedule_info=schedule_info,
- store_listing_version_id=store_version_ids.get(
- (library_agent.agentGraphId, library_agent.agentGraphVersion)
- ),
)
diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.py
index 61addacd85..b110a2ca2f 100644
--- a/autogpt_platform/backend/backend/api/features/library/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py
@@ -211,142 +211,6 @@ async def test_list_library_agents_search_matches_snapshot_and_graph(mocker):
} in where["OR"]
-async def test_list_library_agents_exposes_matching_store_version_id(mocker):
- """The list response carries the approved StoreListingVersion id matching
- the agent's exact graph_id + graph_version, so install flows stay
- version-stable instead of resolving the listing's current active version."""
- mock_library_agents = [
- prisma.models.LibraryAgent(
- id="ua1",
- userId="test-user",
- agentGraphId="agent2",
- settings=cast(prisma.fields.Json, "{}"),
- agentGraphVersion=3,
- isCreatedByUser=False,
- isDeleted=False,
- isArchived=False,
- isHidden=False,
- createdAt=datetime.now(),
- updatedAt=datetime.now(),
- isFavorite=False,
- useGraphIsActiveVersion=True,
- visibility=prisma.enums.ResourceVisibility.PRIVATE,
- AgentGraph=prisma.models.AgentGraph(
- id="agent2",
- version=3,
- name="Test Agent 2",
- description="Test Description 2",
- userId="other-user",
- isActive=True,
- createdAt=datetime.now(),
- visibility=prisma.enums.ResourceVisibility.PRIVATE,
- ),
- )
- ]
-
- mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")
- mock_library_agent.return_value.find_many = mocker.AsyncMock(
- return_value=mock_library_agents
- )
- mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)
-
- matching_version = MagicMock(
- id="slv-exact", agentGraphId="agent2", agentGraphVersion=3
- )
- older_matching_version = MagicMock(
- id="slv-older", agentGraphId="agent2", agentGraphVersion=3
- )
- wrong_version = MagicMock(
- id="slv-other-version", agentGraphId="agent2", agentGraphVersion=4
- )
- mock_slv = mocker.patch("prisma.models.StoreListingVersion.prisma")
- mock_slv_find_many = mocker.AsyncMock(
- return_value=[wrong_version, matching_version, older_matching_version]
- )
- mock_slv.return_value.find_many = mock_slv_find_many
-
- mocker.patch(
- "backend.api.features.library.db._fetch_execution_counts",
- new=mocker.AsyncMock(return_value={}),
- )
-
- result = await db.list_library_agents("test-user")
-
- assert result.agents[0].store_listing_version_id == "slv-exact"
- where = mock_slv_find_many.call_args.kwargs["where"]
- assert where["OR"] == [{"agentGraphId": "agent2", "agentGraphVersion": 3}]
- assert where["submissionStatus"] == prisma.enums.SubmissionStatus.APPROVED
- assert where["isDeleted"] is False
- assert where["isAvailable"] is True
- assert where["StoreListing"] == {"is": {"isDeleted": False}}
- assert mock_slv_find_many.call_args.kwargs["distinct"] == [
- "agentGraphId",
- "agentGraphVersion",
- ]
- assert mock_slv_find_many.call_args.kwargs["order"] == [
- {"agentGraphId": "asc"},
- {"agentGraphVersion": "asc"},
- {"createdAt": "desc"},
- {"id": "desc"},
- ]
-
-
-async def test_list_library_agents_store_version_lookup_fails_soft(mocker):
- """A failing StoreListingVersion lookup must not break the library list;
- agents just come back without a store_listing_version_id."""
- mock_library_agents = [
- prisma.models.LibraryAgent(
- id="ua1",
- userId="test-user",
- agentGraphId="agent2",
- settings=cast(prisma.fields.Json, "{}"),
- agentGraphVersion=1,
- isCreatedByUser=False,
- isDeleted=False,
- isArchived=False,
- isHidden=False,
- createdAt=datetime.now(),
- updatedAt=datetime.now(),
- isFavorite=False,
- useGraphIsActiveVersion=True,
- visibility=prisma.enums.ResourceVisibility.PRIVATE,
- AgentGraph=prisma.models.AgentGraph(
- id="agent2",
- version=1,
- name="Test Agent 2",
- description="Test Description 2",
- userId="other-user",
- isActive=True,
- createdAt=datetime.now(),
- visibility=prisma.enums.ResourceVisibility.PRIVATE,
- ),
- )
- ]
-
- mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")
- mock_library_agent.return_value.find_many = mocker.AsyncMock(
- return_value=mock_library_agents
- )
- mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)
-
- mock_slv = mocker.patch("prisma.models.StoreListingVersion.prisma")
- mock_slv.return_value.find_many = mocker.AsyncMock(
- side_effect=RuntimeError("db down")
- )
-
- mocker.patch(
- "backend.api.features.library.db._fetch_execution_counts",
- new=mocker.AsyncMock(return_value={}),
- )
-
- result = await db.list_library_agents("test-user")
-
- assert len(result.agents) == 1
- assert result.agents[0].store_listing_version_id is None
-
-
@pytest.mark.asyncio(loop_scope="session")
async def test_add_agent_to_library(mocker):
mocker.patch(
@@ -472,7 +336,6 @@ async def test_add_agent_to_library(mocker):
assert create_call_args.kwargs["include"] == library_agent_include(
"test-user", include_nodes=False, include_executions=False
)
- assert mock_from_db.call_args.kwargs["store_listing_version_id"] == "version123"
@pytest.mark.asyncio
@@ -533,7 +396,6 @@ async def test_add_agent_to_library_reuses_existing_without_loading_graph(mocker
from_db.assert_called_once_with(
restored,
schedule_info={},
- store_listing_version_id="version123",
)
@@ -811,12 +673,6 @@ async def test_list_favorite_library_agents(mocker):
)
mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)
- matching_version = MagicMock(
- id="slv-favorite", agentGraphId="agent-fav", agentGraphVersion=1
- )
- mock_slv = mocker.patch("prisma.models.StoreListingVersion.prisma")
- mock_slv.return_value.find_many = mocker.AsyncMock(return_value=[matching_version])
-
mocker.patch(
"backend.api.features.library.db._fetch_execution_counts",
new=mocker.AsyncMock(return_value={"agent-fav": 7}),
@@ -828,52 +684,12 @@ async def test_list_favorite_library_agents(mocker):
assert result.agents[0].id == "fav1"
assert result.agents[0].name == "Favorite Agent"
assert result.agents[0].graph_id == "agent-fav"
- assert result.agents[0].store_listing_version_id == "slv-favorite"
assert result.pagination.total_items == 1
assert result.pagination.total_pages == 1
assert result.pagination.current_page == 1
assert result.pagination.page_size == 50
-async def test_get_library_agent_exposes_matching_store_version_id(mocker):
- agent_graph = MagicMock(id="graph-id", version=7)
- library_agent = MagicMock(
- id="library-id",
- agentGraphId="graph-id",
- agentGraphVersion=7,
- AgentGraph=agent_graph,
- )
- mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")
- mock_library_agent.return_value.find_first = mocker.AsyncMock(
- return_value=library_agent
- )
- mocker.patch(
- "backend.api.features.library.db._fetch_marketplace_details",
- new=mocker.AsyncMock(return_value=(None, None)),
- )
- mocker.patch(
- "backend.api.features.library.db._fetch_schedule_info",
- new=mocker.AsyncMock(return_value={}),
- )
- mocker.patch(
- "backend.api.features.library.db._fetch_matching_store_version_ids",
- new=mocker.AsyncMock(return_value={("graph-id", 7): "slv-exact"}),
- )
- mocker.patch.object(
- db.graph_db, "get_sub_graphs", new=mocker.AsyncMock(return_value=[])
- )
- converted = MagicMock()
- mock_from_db = mocker.patch.object(
- library_model.LibraryAgent, "from_db", return_value=converted
- )
-
- result = await db.get_library_agent("library-id", "test-user")
-
- assert result is converted
- assert mock_from_db.call_args.kwargs["store_listing_version_id"] == "slv-exact"
-
-
@pytest.mark.asyncio
async def test_get_library_agent_rejects_missing_graph(mocker):
library_agent = MagicMock(id="library-id", AgentGraph=None)
diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.py
index eabb0ed721..6a7c8e91a6 100644
--- a/autogpt_platform/backend/backend/api/features/library/model.py
+++ b/autogpt_platform/backend/backend/api/features/library/model.py
@@ -240,14 +240,6 @@ class LibraryAgent(pydantic.BaseModel):
)
settings: GraphSettings = pydantic.Field(default_factory=GraphSettings)
marketplace_listing: Optional["MarketplaceListing"] = None
- store_listing_version_id: Optional[str] = pydantic.Field(
- default=None,
- description=(
- "ID of the approved marketplace listing version whose graph snapshot "
- "exactly matches this agent's graph_id and graph_version. Install "
- "flows can use it directly to install this exact version."
- ),
- )
@staticmethod
def from_db(
@@ -257,7 +249,6 @@ class LibraryAgent(pydantic.BaseModel):
profile: Optional[prisma.models.Profile] = None,
execution_count_override: Optional[int] = None,
schedule_info: Optional[dict[str, str]] = None,
- store_listing_version_id: Optional[str] = None,
) -> "LibraryAgent":
"""
Factory method that constructs a LibraryAgent from a Prisma LibraryAgent
@@ -409,7 +400,6 @@ class LibraryAgent(pydantic.BaseModel):
),
settings=_parse_settings(agent.settings),
marketplace_listing=marketplace_listing_data,
- store_listing_version_id=store_listing_version_id,
)
diff --git a/autogpt_platform/backend/snapshots/lib_agts_search b/autogpt_platform/backend/snapshots/lib_agts_search
index f8f809fe54..04fc2e30af 100644
--- a/autogpt_platform/backend/snapshots/lib_agts_search
+++ b/autogpt_platform/backend/snapshots/lib_agts_search
@@ -49,8 +49,7 @@
"sensitive_action_safe_mode": false,
"builder_chat_session_id": null
},
- "marketplace_listing": null,
- "store_listing_version_id": null
+ "marketplace_listing": null
},
{
"id": "test-agent-2",
@@ -101,8 +100,7 @@
"sensitive_action_safe_mode": false,
"builder_chat_session_id": null
},
- "marketplace_listing": null,
- "store_listing_version_id": null
+ "marketplace_listing": null
}
],
"pagination": {
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
index 607eac9b83..8ffe70bb23 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/main.test.tsx
@@ -4,9 +4,14 @@ import {
getArchiveExpertMockHandler,
getGetExpertDetachPreviewMockHandler,
getGetExpertMockHandler,
+ getInstallExpertWorkflowMockHandler,
getListExpertRunsMockHandler,
+ getListExpertsMockHandler,
getResumeExpertSchedulesMockHandler,
} from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { getGetV2ListLibraryAgentsMockHandler200 } from "@/app/api/__generated__/endpoints/library/library.msw";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { LibraryAgentResponse } from "@/app/api/__generated__/models/libraryAgentResponse";
import { ExpertRun } from "@/app/api/__generated__/models/expertRun";
import {
getDeleteV1DeleteExecutionScheduleMockHandler,
@@ -149,6 +154,29 @@ const mariaRuns: ExpertRun[] = [
},
];
+const ownLibraryAgent = {
+ id: "lib-private",
+ graph_id: "graph-private",
+ graph_version: 1,
+ name: "My Private Agent",
+ description: "Never published to the marketplace",
+ creator_name: "You",
+ image_url: null,
+ marketplace_listing: null,
+} as unknown as LibraryAgent;
+
+function libraryResponse(agents: LibraryAgent[]): LibraryAgentResponse {
+ return {
+ agents,
+ pagination: {
+ total_items: agents.length,
+ total_pages: 1,
+ current_page: 1,
+ page_size: 10,
+ },
+ } as LibraryAgentResponse;
+}
+
beforeEach(() => {
server.use(
getGetExpertMockHandler(maria),
@@ -323,4 +351,79 @@ describe("ExpertDetailPage", () => {
await waitFor(() => expect(archiveSpy).toHaveBeenCalled());
await waitFor(() => expect(pushMock).toHaveBeenCalledWith("/team"));
});
+
+ test("installs one of the user's own agents as a workflow", async () => {
+ const user = userEvent.setup();
+ let installBody: unknown;
+ server.use(
+ getListExpertsMockHandler([maria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([ownLibraryAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler(async (info) => {
+ installBody = await info.request.json();
+ return {
+ id: "wf-private",
+ store_listing_version_id: null,
+ library_agent_id: "lib-private",
+ graph_id: "graph-private",
+ name: "My Private Agent",
+ description: null,
+ };
+ }),
+ );
+
+ render(<ExpertDetailPage />);
+
+ await screen.findByRole("heading", { name: "Maria" });
+ await user.click(screen.getByRole("button", { name: "Install workflow" }));
+
+ const dialog = await screen.findByRole("dialog");
+ const row = await within(dialog).findByTestId("install-workflow-option");
+ expect(within(row).getByText("My Private Agent")).toBeDefined();
+ await user.click(within(row).getByRole("button", { name: "Install" }));
+
+ await waitFor(() =>
+ expect(installBody).toEqual({ library_agent_id: "lib-private" }),
+ );
+ });
+
+ test("marks an already-installed workflow instead of offering Install", async () => {
+ const user = userEvent.setup();
+ const installed = { ...ownLibraryAgent, id: "lib-1" } as LibraryAgent;
+ server.use(
+ getListExpertsMockHandler([maria]),
+ getGetV2ListLibraryAgentsMockHandler200(libraryResponse([installed])),
+ );
+
+ render(<ExpertDetailPage />);
+
+ await screen.findByRole("heading", { name: "Maria" });
+ await user.click(screen.getByRole("button", { name: "Install workflow" }));
+
+ const dialog = await screen.findByRole("dialog");
+ const row = await within(dialog).findByTestId("install-workflow-option");
+ expect(within(row).getByText("Installed")).toBeDefined();
+ expect(within(row).queryByRole("button", { name: "Install" })).toBeNull();
+ });
+
+ test("shows the workflow description rather than an unknown creator", async () => {
+ const user = userEvent.setup();
+ server.use(
+ getListExpertsMockHandler([maria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([{ ...ownLibraryAgent, description: "" }]),
+ ),
+ );
+
+ render(<ExpertDetailPage />);
+
+ await screen.findByRole("heading", { name: "Maria" });
+ await user.click(screen.getByRole("button", { name: "Install workflow" }));
+
+ const dialog = await screen.findByRole("dialog");
+ const row = await within(dialog).findByTestId("install-workflow-option");
+ expect(within(row).getByText("From your library")).toBeDefined();
+ expect(within(row).queryByText("Unknown")).toBeNull();
+ });
});
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.tsx
index 29cd5fc416..3ff2a50672 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
@@ -86,7 +86,6 @@ function makeLibraryAgent(over: Partial<LibraryAgent>): LibraryAgent {
is_latest_version: true,
is_favorite: false,
marketplace_listing: null,
- store_listing_version_id: null,
...over,
} as unknown as LibraryAgent;
}
@@ -95,14 +94,12 @@ const adoptableAgent = makeLibraryAgent({
id: "lib-research",
graph_id: "graph-research",
name: "Research Assistant",
- store_listing_version_id: "slv-adopt",
});
-const localOnlyAgent = makeLibraryAgent({
+const unpublishedAgent = makeLibraryAgent({
id: "lib-local",
graph_id: "graph-local",
name: "My Private Agent",
- store_listing_version_id: null,
});
function makeSchedule(
@@ -1217,12 +1214,11 @@ describe("TeamPage", () => {
expect(within(group).getByText(/nothing installed yet/i)).toBeDefined();
});
- test("lists adoptable and local-only agents under Your workflows", async () => {
- const user = userEvent.setup();
+ test("offers Adopt for unpublished agents too", async () => {
server.use(
getListExpertsMockHandler([hiredMaria]),
getGetV2ListLibraryAgentsMockHandler200(
- libraryResponse([adoptableAgent, localOnlyAgent]),
+ libraryResponse([adoptableAgent, unpublishedAgent]),
),
);
@@ -1233,21 +1229,16 @@ describe("TeamPage", () => {
});
expect(within(agents).getByText("Research Assistant")).toBeDefined();
expect(within(agents).getByText("My Private Agent")).toBeDefined();
- expect(within(agents).getByRole("button", { name: "Adopt" })).toBeDefined();
- const localOnly = within(agents).getByText("Local only");
- expect(localOnly).toBeDefined();
- await user.hover(localOnly);
- expect((await screen.findByRole("tooltip")).textContent).toBe(
- "Publish this agent to the Marketplace before adopting it.",
- );
+ expect(
+ within(agents).getAllByRole("button", { name: "Install" }),
+ ).toHaveLength(2);
});
test("hides already-installed agents from Your workflows", async () => {
const installedAgent = makeLibraryAgent({
- id: "lib-installed",
+ id: "lib-1",
graph_id: "graph-1",
name: "Content Calendar",
- store_listing_version_id: "slv-1",
});
server.use(
getListExpertsMockHandler([hiredMaria]),
@@ -1264,7 +1255,7 @@ describe("TeamPage", () => {
expect(within(agents).getByText("Research Assistant")).toBeDefined();
expect(within(agents).queryByText("My Private Agent")).toBeNull();
expect(
- within(agents).getAllByRole("button", { name: "Adopt" }),
+ within(agents).getAllByRole("button", { name: "Install" }),
).toHaveLength(1);
});
@@ -1296,14 +1287,14 @@ describe("TeamPage", () => {
const agents = await screen.findByRole("region", {
name: "Your workflows",
});
- await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+ await user.click(within(agents).getByRole("button", { name: "Install" }));
await waitFor(() => expect(installExpertId).toBe("expert-maria"));
- expect(installBody).toEqual({ store_listing_version_id: "slv-adopt" });
+ expect(installBody).toEqual({ library_agent_id: "lib-research" });
expect(within(agents).queryByText("Research Assistant")).toBeNull();
});
- test("asks which expert to adopt into when more than one is hired", async () => {
+ test("asks which expert to install onto when more than one is hired", async () => {
const user = userEvent.setup();
const john: Expert = {
...hiredMaria,
@@ -1335,18 +1326,18 @@ describe("TeamPage", () => {
const agents = await screen.findByRole("region", {
name: "Your workflows",
});
- await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+ await user.click(within(agents).getByRole("button", { name: "Install" }));
expect(screen.queryByText(/undo anytime/i)).toBeNull();
await user.click(
await screen.findByRole("button", {
- name: /Adds this agent to John's workflows/i,
+ name: /Installs on John/i,
}),
);
await waitFor(() => expect(installExpertId).toBe("expert-john"));
});
- test("offers an exact version only to experts that have not adopted it", async () => {
+ test("offers an agent only to experts that have not adopted it", async () => {
const user = userEvent.setup();
const mariaWithAgent: Expert = {
...hiredMaria,
@@ -1354,7 +1345,7 @@ describe("TeamPage", () => {
...hiredMaria.workflows,
{
id: "wf-adopted",
- store_listing_version_id: "slv-adopt",
+ store_listing_version_id: null,
library_agent_id: "lib-research",
graph_id: "graph-research",
name: "Research Assistant",
@@ -1392,7 +1383,7 @@ describe("TeamPage", () => {
const agents = await screen.findByRole("region", {
name: "Your workflows",
});
- await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+ await user.click(within(agents).getByRole("button", { name: "Install" }));
await waitFor(() => expect(installExpertId).toBe("expert-john"));
expect(screen.queryByText("Choose an expert")).toBeNull();
@@ -1412,7 +1403,7 @@ describe("TeamPage", () => {
await screen.findByRole("region", { name: "Maria runs" });
await screen.findByRole("region", { name: "Your workflows" });
- await user.click(screen.getByRole("button", { name: "Agents" }));
+ await user.click(screen.getByRole("button", { name: "Unassigned" }));
expect(screen.queryByRole("region", { name: "Maria runs" })).toBeNull();
expect(
screen.getByRole("region", { name: "Your workflows" }),
@@ -1562,21 +1553,21 @@ describe("TeamPage", () => {
const agents = await screen.findByRole("region", {
name: "Your workflows",
});
- await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+ await user.click(within(agents).getByRole("button", { name: "Install" }));
await waitFor(() =>
expect(toastMock).toHaveBeenCalledWith(
expect.objectContaining({
- title: "Couldn't adopt Research Assistant",
+ title: "Couldn't install on Maria",
variant: "destructive",
}),
),
);
- const adoptButton = within(agents).getByRole("button", { name: "Adopt" });
+ const adoptButton = within(agents).getByRole("button", { name: "Install" });
expect(adoptButton.hasAttribute("disabled")).toBe(false);
});
- test("explains when an adopt version is no longer available", async () => {
+ test("explains when an adopted agent is no longer available", async () => {
const user = userEvent.setup();
server.use(
getListExpertsMockHandler([hiredMaria]),
@@ -1591,12 +1582,12 @@ describe("TeamPage", () => {
const agents = await screen.findByRole("region", {
name: "Your workflows",
});
- await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+ await user.click(within(agents).getByRole("button", { name: "Install" }));
await waitFor(() =>
expect(toastMock).toHaveBeenCalledWith(
expect.objectContaining({
- description: "This Marketplace version is no longer available.",
+ description: "This workflow is no longer available.",
}),
),
);
@@ -1635,8 +1626,10 @@ describe("TeamPage", () => {
name: "Your workflows",
});
const rows = within(agents).getAllByTestId("what-runs-agent-row");
- const firstAdopt = within(rows[0]).getByRole("button", { name: "Adopt" });
- const secondAdopt = within(rows[1]).getByRole("button", { name: "Adopt" });
+ const firstAdopt = within(rows[0]).getByRole("button", { name: "Install" });
+ const secondAdopt = within(rows[1]).getByRole("button", {
+ name: "Install",
+ });
await user.click(firstAdopt);
await waitFor(() => expect(firstAdopt.hasAttribute("disabled")).toBe(true));
expect(secondAdopt.hasAttribute("disabled")).toBe(false);
@@ -1701,7 +1694,7 @@ describe("TeamPage", () => {
name: "Your workflows",
});
expect(
- await within(agents).findByText("No available workflows to adopt."),
+ await within(agents).findByText("No workflows available to install."),
).toBeDefined();
});
@@ -1711,7 +1704,6 @@ describe("TeamPage", () => {
id: "lib-second",
graph_id: "graph-second",
name: "Second-page Agent",
- store_listing_version_id: "slv-second",
});
const requestedPages: string[] = [];
const hiddenFilters: string[] = [];
@@ -1748,10 +1740,9 @@ describe("TeamPage", () => {
test("does not claim every agent is adopted while more pages remain", async () => {
const installedAgent = makeLibraryAgent({
- id: "lib-installed",
+ id: "lib-1",
graph_id: "graph-1",
name: "Content Calendar",
- store_listing_version_id: "slv-1",
});
server.use(
getListExpertsMockHandler([hiredMaria]),
@@ -1780,7 +1771,6 @@ describe("TeamPage", () => {
id: "lib-second",
graph_id: "graph-second",
name: "Recovered Agent",
- store_listing_version_id: "slv-second",
});
server.use(
getListExpertsMockHandler([hiredMaria]),
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/AdoptAgentButton.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/AdoptAgentButton.tsx
index 38589b5d71..9306692152 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/AdoptAgentButton.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/AdoptAgentButton.tsx
@@ -43,7 +43,7 @@ export function AdoptAgentButton({
loading={isPending}
onClick={handleSingleExpert}
>
- Adopt
+ Install
</Button>
);
}
@@ -52,7 +52,7 @@ export function AdoptAgentButton({
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="secondary" size="small" loading={isPending}>
- Adopt
+ Install
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-72 p-2">
@@ -77,7 +77,7 @@ export function AdoptAgentButton({
{expert.name}
</Text>
<Text variant="small" className="text-zinc-500">
- Adds this agent to {expert.name}&apos;s workflows.
+ Installs on {expert.name}.
</Text>
</div>
</button>
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/YourAgentsList.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/YourAgentsList.tsx
index 0d5e8b8ea6..cf4a4317cd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/YourAgentsList.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/YourAgentsList.tsx
@@ -1,16 +1,10 @@
import { Expert } from "@/app/api/__generated__/models/expert";
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
-import { Badge } from "@/components/atoms/Badge/Badge";
import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/components/atoms/Tooltip/BaseTooltip";
import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
-import { STATUS_BADGE_CLASS } from "../constants";
-import { getAdoptableExperts, getAdoptTargetVersionID } from "../helpers";
+import { workflowSubtitle } from "@/components/molecules/InstallWorkflowPicker/helpers";
+import { getAdoptableExperts } from "../helpers";
import { AdoptAgentButton } from "./AdoptAgentButton";
type Props = {
@@ -47,14 +41,13 @@ export function YourAgentsList({
!hasMoreAgents ? (
<Text variant="small" className="text-zinc-500">
{libraryAgentCount === 0
- ? "No available workflows to adopt."
+ ? "No workflows available to install."
: "Every workflow is already on your team."}
</Text>
) : null
) : (
<div className="divide-y divide-zinc-100 rounded-2xl border border-zinc-200 bg-white">
{agents.map((agent) => {
- const canAdopt = Boolean(getAdoptTargetVersionID(agent));
const adoptableExperts = getAdoptableExperts(
agent,
experts,
@@ -75,37 +68,16 @@ export function YourAgentsList({
<Text variant="body" className="truncate">
{agent.name}
</Text>
- <Text variant="small" className="text-zinc-500">
- {agent.creator_name}
+ <Text variant="small" className="truncate text-zinc-500">
+ {workflowSubtitle(agent.description)}
</Text>
</div>
- {canAdopt ? (
- <AdoptAgentButton
- agent={agent}
- experts={adoptableExperts}
- isPending={pendingLibraryAgentIDs.has(agent.id)}
- onAdopt={onAdopt}
- />
- ) : (
- <Tooltip>
- <TooltipTrigger asChild>
- <span
- tabIndex={0}
- className="shrink-0 rounded-full focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-900"
- >
- <Badge
- variant="info"
- className={`${STATUS_BADGE_CLASS} text-zinc-500`}
- >
- Local only
- </Badge>
- </span>
- </TooltipTrigger>
- <TooltipContent>
- Publish this agent to the Marketplace before adopting it.
- </TooltipContent>
- </Tooltip>
- )}
+ <AdoptAgentButton
+ agent={agent}
+ experts={adoptableExperts}
+ isPending={pendingLibraryAgentIDs.has(agent.id)}
+ onAdopt={onAdopt}
+ />
</div>
);
})}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.test.ts
index e3bfce3afc..63a9a686ae 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.test.ts
@@ -11,7 +11,6 @@ import {
import {
getAdoptableExperts,
getAdoptTargetKey,
- getAdoptTargetVersionID,
getFilterView,
getUnadoptedAgents,
getVisibleGroups,
@@ -39,7 +38,6 @@ function makeAgent(over: Partial<LibraryAgent>): LibraryAgent {
id: "agent",
graph_id: "graph",
name: "Agent",
- store_listing_version_id: null,
...over,
} as unknown as LibraryAgent;
}
@@ -206,58 +204,35 @@ describe("getVisibleGroups", () => {
});
describe("getUnadoptedAgents", () => {
- it("excludes an exact version when every expert already has it", () => {
+ it("excludes an agent every expert already installed", () => {
const experts = [
makeExpert({
id: "a",
- workflows: [
- makeWorkflow({
- graph_id: "graph-installed",
- store_listing_version_id: "slv-installed",
- }),
- ],
+ workflows: [makeWorkflow({ library_agent_id: "installed" })],
}),
];
- const agents = [
- makeAgent({
- id: "installed",
- graph_id: "graph-installed",
- store_listing_version_id: "slv-installed",
- }),
- makeAgent({
- id: "free",
- graph_id: "graph-free",
- store_listing_version_id: "slv-free",
- }),
- ];
- const result = getUnadoptedAgents(agents, experts);
- expect(result.map((a) => a.id)).toEqual(["free"]);
+ const agents = [makeAgent({ id: "installed" }), makeAgent({ id: "free" })];
+
+ expect(getUnadoptedAgents(agents, experts).map((a) => a.id)).toEqual([
+ "free",
+ ]);
});
- it("keeps a newer snapshot of an installed graph adoptable", () => {
- const expert = makeExpert({
- workflows: [
- makeWorkflow({
- graph_id: "shared-graph",
- store_listing_version_id: "slv-v1",
- }),
- ],
- });
- const newer = makeAgent({
- graph_id: "shared-graph",
- store_listing_version_id: "slv-v2",
- });
+ it("keeps an unpublished agent adoptable", () => {
+ const agent = makeAgent({ id: "never-published" });
- expect(getUnadoptedAgents([newer], [expert])).toEqual([newer]);
+ expect(
+ getUnadoptedAgents([agent], [makeExpert({ workflows: [] })]),
+ ).toEqual([agent]);
});
it("keeps an agent visible while another expert can adopt it", () => {
const installed = makeExpert({
id: "installed",
- workflows: [makeWorkflow({ store_listing_version_id: "slv-shared" })],
+ workflows: [makeWorkflow({ library_agent_id: "shared" })],
});
const available = makeExpert({ id: "available", workflows: [] });
- const agent = makeAgent({ store_listing_version_id: "slv-shared" });
+ const agent = makeAgent({ id: "shared" });
expect(getUnadoptedAgents([agent], [installed, available])).toEqual([
agent,
@@ -271,21 +246,20 @@ describe("getUnadoptedAgents", () => {
getUnadoptedAgents([agent], [installed, available], optimistic),
).toEqual([]);
});
-});
-describe("getAdoptTargetVersionID", () => {
- it("returns the exact-match version id when present", () => {
- expect(
- getAdoptTargetVersionID(
- makeAgent({ store_listing_version_id: "slv-exact" }),
- ),
- ).toBe("slv-exact");
- });
+ it("counts a marketplace install of the same agent as adopted", () => {
+ const expert = makeExpert({
+ workflows: [
+ makeWorkflow({
+ library_agent_id: "shared",
+ store_listing_version_id: "slv-1",
+ }),
+ ],
+ });
- it("returns null for a pure-local agent", () => {
- expect(
- getAdoptTargetVersionID(makeAgent({ store_listing_version_id: null })),
- ).toBe(null);
+ expect(getUnadoptedAgents([makeAgent({ id: "shared" })], [expert])).toEqual(
+ [],
+ );
});
});
@@ -294,10 +268,10 @@ describe("pruneAdoptedTargetKeys", () => {
const pending = makeExpert({ id: "pending", workflows: [] });
const confirmed = makeExpert({
id: "confirmed",
- workflows: [makeWorkflow({ store_listing_version_id: "slv-exact" })],
+ workflows: [makeWorkflow({ library_agent_id: "agent" })],
});
const fired = makeExpert({ id: "fired", workflows: [] });
- const agent = makeAgent({ store_listing_version_id: "slv-exact" });
+ const agent = makeAgent({ id: "agent" });
const keys = new Set([
getAdoptTargetKey(agent, pending),
getAdoptTargetKey(agent, confirmed),
@@ -311,7 +285,7 @@ describe("pruneAdoptedTargetKeys", () => {
it("preserves the set identity when no targets can be pruned", () => {
const expert = makeExpert({ workflows: [] });
- const agent = makeAgent({ store_listing_version_id: "slv-exact" });
+ const agent = makeAgent({ id: "agent" });
const keys = new Set([getAdoptTargetKey(agent, expert)]);
expect(pruneAdoptedTargetKeys(keys, [agent], [expert])).toBe(keys);
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.ts
index 2804aff495..1c4780996c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.ts
@@ -18,7 +18,7 @@ export type WhatRunsFilter =
export const WHAT_RUNS_FILTERS: { id: WhatRunsFilter; label: string }[] = [
{ id: "all", label: "All" },
{ id: "members", label: "Members" },
- { id: "agents", label: "Agents" },
+ { id: "agents", label: "Unassigned" },
{ id: "workflows", label: "Workflows" },
{ id: "scheduled", label: "Scheduled" },
];
@@ -108,9 +108,7 @@ export function getVisibleGroups(
return groups;
}
-/** Keep agents that still have at least one eligible expert target. Matching
- * the immutable listing-version id lets a newer snapshot remain adoptable
- * and lets one agent be installed on more than one expert. */
+/** Keep agents that still have at least one eligible expert target. */
export function getUnadoptedAgents(
agents: LibraryAgent[],
experts: Expert[],
@@ -118,7 +116,6 @@ export function getUnadoptedAgents(
): LibraryAgent[] {
return agents.filter(
(agent) =>
- !getAdoptTargetVersionID(agent) ||
getAdoptableExperts(agent, experts, adoptedTargetKeys).length > 0,
);
}
@@ -128,13 +125,10 @@ export function getAdoptableExperts(
experts: Expert[],
adoptedTargetKeys?: ReadonlySet<string>,
): Expert[] {
- const versionID = getAdoptTargetVersionID(agent);
- if (!versionID) return experts;
return experts.filter(
(expert) =>
- !expert.workflows.some(
- (workflow) => workflow.store_listing_version_id === versionID,
- ) && !adoptedTargetKeys?.has(getAdoptTargetKey(agent, expert)),
+ !isAdopted(agent, expert) &&
+ !adoptedTargetKeys?.has(getAdoptTargetKey(agent, expert)),
);
}
@@ -167,21 +161,17 @@ export function pruneAdoptedTargetKeys(
const agent = agentsByID.get(target.agentID);
const expert = expertsByID.get(target.expertID);
if (!agent || !expert) continue;
- const versionID = getAdoptTargetVersionID(agent);
- if (!versionID) continue;
- const isConfirmed = expert.workflows.some(
- (workflow) => workflow.store_listing_version_id === versionID,
- );
- if (!isConfirmed) next.add(key);
+ if (!isAdopted(agent, expert)) next.add(key);
}
return next.size === adoptedTargetKeys.size ? adoptedTargetKeys : next;
}
-/** The immutable marketplace version matching this agent's exact graph
- * snapshot, resolved server-side. Pure-local agents have none, so Adopt is
- * hidden for them — the install endpoint only accepts a
- * store_listing_version_id. */
-export function getAdoptTargetVersionID(agent: LibraryAgent) {
- return agent.store_listing_version_id;
+/** An expert installs a library agent by id, so the same agent stays
+ * adoptable on other experts and a marketplace install of it counts too —
+ * that path records the same library_agent_id. */
+function isAdopted(agent: LibraryAgent, expert: Expert) {
+ return expert.workflows.some(
+ (workflow) => workflow.library_agent_id === agent.id,
+ );
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/useWhatRunsZone.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/useWhatRunsZone.ts
index 100439a732..30c887d339 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/useWhatRunsZone.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/useWhatRunsZone.ts
@@ -12,7 +12,6 @@ import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import {
getAdoptTargetKey,
- getAdoptTargetVersionID,
getUnadoptedAgents,
getVisibleGroups,
pruneAdoptedTargetKeys,
@@ -70,14 +69,13 @@ export function useWhatRunsZone({ experts, schedules, enabled }: Args) {
const showAgents = filter === "all" || filter === "agents";
async function adopt(agent: LibraryAgent, expert: Expert) {
- const versionID = getAdoptTargetVersionID(agent);
- if (!versionID || pendingLibraryAgentIDs.has(agent.id)) return;
+ if (pendingLibraryAgentIDs.has(agent.id)) return;
const targetKey = getAdoptTargetKey(agent, expert);
setPendingLibraryAgentIDs((current) => new Set(current).add(agent.id));
try {
await installWorkflow({
expertId: expert.id,
- data: { store_listing_version_id: versionID },
+ data: { library_agent_id: agent.id },
});
setAdoptedTargetKeys((current) => {
const next = new Set(
@@ -89,16 +87,12 @@ export function useWhatRunsZone({ experts, schedules, enabled }: Args) {
await queryClient.invalidateQueries({
queryKey: getListExpertsQueryKey(),
});
- toast({
- title: `Added to ${expert.name}'s workflows`,
- variant: "success",
- });
+ toast({ title: `Installed on ${expert.name}`, variant: "success" });
} catch (error) {
- const versionUnavailable = hasStatus(error, 404);
toast({
- title: `Couldn't adopt ${agent.name}`,
- description: versionUnavailable
- ? "This Marketplace version is no longer available."
+ title: `Couldn't install on ${expert.name}`,
+ description: hasStatus(error, 404)
+ ? "This workflow is no longer available."
: "Something went wrong. Please try again.",
variant: "destructive",
});
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 607d4e1a77..1a8c9f3a2c 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -6724,7 +6724,7 @@
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
},
- "404": { "description": "Expert not found" },
+ "404": { "description": "Expert or workflow not found" },
"422": {
"description": "Validation Error",
"content": {
@@ -21497,13 +21497,17 @@
"InstallWorkflowRequest": {
"properties": {
"store_listing_version_id": {
- "type": "string",
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Store Listing Version Id"
+ },
+ "library_agent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Library Agent Id"
}
},
"type": "object",
- "required": ["store_listing_version_id"],
- "title": "InstallWorkflowRequest"
+ "title": "InstallWorkflowRequest",
+ "description": "One workflow source: a marketplace listing, or the caller's own agent."
},
"IntroCardResponse": {
"properties": {
@@ -21825,11 +21829,6 @@
{ "$ref": "#/components/schemas/MarketplaceListing" },
{ "type": "null" }
]
- },
- "store_listing_version_id": {
- "anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Store Listing Version Id",
- "description": "ID of the approved marketplace listing version whose graph snapshot exactly matches this agent's graph_id and graph_version. Install flows can use it directly to install this exact version."
}
},
"type": "object",
diff --git a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/InstallWorkflowPicker.tsx b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/InstallWorkflowPicker.tsx
index e6e2b216f8..9ca7db9f84 100644
--- a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/InstallWorkflowPicker.tsx
+++ b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/InstallWorkflowPicker.tsx
@@ -9,6 +9,8 @@ import { Button } from "@/components/atoms/Button/Button";
import { Input } from "@/components/atoms/Input/Input";
import { Text } from "@/components/atoms/Text/Text";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { cn } from "@/lib/utils";
+import { INSTALL_WORKFLOW_SOURCES, workflowSubtitle } from "./helpers";
import { useInstallWorkflowPicker } from "./useInstallWorkflowPicker";
interface Props {
@@ -29,12 +31,17 @@ export function InstallWorkflowPicker({
const {
title,
hiredExperts,
+ isLibraryAgentInstalled,
+ source,
+ setSource,
searchQuery,
setSearchQuery,
- searchResults,
+ libraryResults,
+ marketplaceResults,
isSearching,
pendingKey,
installOnExpert,
+ installLibraryAgent,
installFromListing,
} = useInstallWorkflowPicker({
mode,
@@ -44,6 +51,11 @@ export function InstallWorkflowPicker({
onClose,
});
+ const isEmpty =
+ source === "library"
+ ? libraryResults.length === 0
+ : marketplaceResults.length === 0;
+
return (
<Dialog
title={title}
@@ -96,11 +108,37 @@ export function InstallWorkflowPicker({
)
) : (
<div className="flex flex-col gap-3">
+ <div
+ className="flex gap-2"
+ role="group"
+ aria-label="Workflow source"
+ >
+ {INSTALL_WORKFLOW_SOURCES.map((option) => (
+ <button
+ key={option.id}
+ type="button"
+ aria-pressed={source === option.id}
+ onClick={() => setSource(option.id)}
+ className={cn(
+ "rounded-full px-3 py-1.5 text-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-900",
+ source === option.id
+ ? "bg-zinc-800 text-white"
+ : "bg-zinc-100 text-zinc-600 hover:bg-zinc-200",
+ )}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
<Input
id="install-workflow-search"
label="Search workflows"
hideLabel
- placeholder="Search the marketplace"
+ placeholder={
+ source === "library"
+ ? "Search your workflows"
+ : "Search the marketplace"
+ }
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
/>
@@ -108,49 +146,93 @@ export function InstallWorkflowPicker({
<Text variant="small" className="py-2 text-center !text-zinc-500">
Searching…
</Text>
- ) : searchResults.length === 0 ? (
- searchQuery ? (
- <Text
- variant="small"
- className="py-2 text-center !text-zinc-500"
- >
- No workflows found.
- </Text>
- ) : null
+ ) : isEmpty ? (
+ <Text variant="small" className="py-2 text-center !text-zinc-500">
+ {source === "library"
+ ? "No workflows in your library."
+ : "No workflows found."}
+ </Text>
) : (
<div className="divide-y divide-zinc-100 overflow-hidden rounded-xl border border-zinc-200/80">
- {searchResults.map((agent) => (
- <div
- key={agent.agent_graph_id}
- className="flex items-center gap-3 px-3.5 py-2.5 transition-colors hover:bg-zinc-50"
- >
- <Avatar className="h-9 w-9">
- {agent.agent_image ? (
- <AvatarImage
- src={agent.agent_image}
- alt={agent.agent_name}
- />
- ) : null}
- <AvatarFallback>{agent.agent_name}</AvatarFallback>
- </Avatar>
- <div className="min-w-0 flex-1">
- <Text variant="body-medium" className="truncate">
- {agent.agent_name}
- </Text>
- <Text variant="small" className="!text-zinc-500">
- by {agent.creator}
- </Text>
- </div>
- <Button
- variant="secondary"
- size="small"
- loading={pendingKey === agent.agent_graph_id}
- onClick={() => installFromListing(agent)}
- >
- Install
- </Button>
- </div>
- ))}
+ {source === "library"
+ ? libraryResults.map((agent) => (
+ <div
+ key={agent.id}
+ data-testid="install-workflow-option"
+ className="flex items-center gap-3 px-3.5 py-2.5 transition-colors hover:bg-zinc-50"
+ >
+ <Avatar className="h-9 w-9">
+ {agent.image_url ? (
+ <AvatarImage
+ src={agent.image_url}
+ alt={agent.name}
+ />
+ ) : null}
+ <AvatarFallback>{agent.name}</AvatarFallback>
+ </Avatar>
+ <div className="min-w-0 flex-1">
+ <Text variant="body-medium" className="truncate">
+ {agent.name}
+ </Text>
+ <Text
+ variant="small"
+ className="truncate !text-zinc-500"
+ >
+ {workflowSubtitle(agent.description)}
+ </Text>
+ </div>
+ {isLibraryAgentInstalled(agent) ? (
+ <Text
+ variant="small"
+ className="shrink-0 !text-zinc-400"
+ >
+ Installed
+ </Text>
+ ) : (
+ <Button
+ variant="secondary"
+ size="small"
+ loading={pendingKey === agent.id}
+ onClick={() => installLibraryAgent(agent)}
+ >
+ Install
+ </Button>
+ )}
+ </div>
+ ))
+ : marketplaceResults.map((agent) => (
+ <div
+ key={agent.agent_graph_id}
+ data-testid="install-workflow-option"
+ className="flex items-center gap-3 px-3.5 py-2.5 transition-colors hover:bg-zinc-50"
+ >
+ <Avatar className="h-9 w-9">
+ {agent.agent_image ? (
+ <AvatarImage
+ src={agent.agent_image}
+ alt={agent.agent_name}
+ />
+ ) : null}
+ <AvatarFallback>{agent.agent_name}</AvatarFallback>
+ </Avatar>
+ <div className="min-w-0 flex-1">
+ <Text variant="body-medium" className="truncate">
+ {agent.agent_name}
+ </Text>
+ <Text variant="small" className="!text-zinc-500">
+ by {agent.creator}
+ </Text>
+ </div>
+ <Button
+ variant="secondary"
+ size="small"
+ loading={pendingKey === agent.agent_graph_id}
+ onClick={() => installFromListing(agent)}
+ >
+ Install
+ </Button>
+ </div>
+ ))}
</div>
)}
</div>
diff --git a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/helpers.ts b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/helpers.ts
new file mode 100644
index 0000000000..4f6c5a221a
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/helpers.ts
@@ -0,0 +1,20 @@
+export type InstallWorkflowSource = "library" | "marketplace";
+
+export const INSTALL_WORKFLOW_SOURCES: {
+ id: InstallWorkflowSource;
+ label: string;
+}[] = [
+ { id: "library", label: "Your workflows" },
+ { id: "marketplace", label: "Marketplace" },
+];
+
+export type WorkflowInstallData =
+ | { library_agent_id: string }
+ | { store_listing_version_id: string };
+
+/** Row subtitle: the workflow's own description, or a neutral source label.
+ * A user's own agent has no marketplace creator, so `creator_name` reads
+ * "Unknown" there. */
+export function workflowSubtitle(description: string | null | undefined) {
+ return description?.trim() || "From your library";
+}
diff --git a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/useInstallWorkflowPicker.ts b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/useInstallWorkflowPicker.ts
index d63c422591..197a259478 100644
--- a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/useInstallWorkflowPicker.ts
+++ b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/useInstallWorkflowPicker.ts
@@ -1,21 +1,27 @@
import {
+ getGetExpertQueryKey,
getListExpertsQueryKey,
useInstallExpertWorkflow,
useListExperts,
} from "@/app/api/__generated__/endpoints/experts/experts";
+import { useGetV2ListLibraryAgents } from "@/app/api/__generated__/endpoints/library/library";
import {
getV2GetSpecificAgent,
useGetV2ListStoreAgents,
} from "@/app/api/__generated__/endpoints/store/store";
import { Expert } from "@/app/api/__generated__/models/expert";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { LibraryAgentResponse } from "@/app/api/__generated__/models/libraryAgentResponse";
import { StoreAgent } from "@/app/api/__generated__/models/storeAgent";
import { StoreAgentsResponse } from "@/app/api/__generated__/models/storeAgentsResponse";
import { toast } from "@/components/molecules/Toast/use-toast";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
+import { InstallWorkflowSource, WorkflowInstallData } from "./helpers";
const SEARCH_DEBOUNCE_MS = 300;
+const RESULTS_PAGE_SIZE = 10;
interface Args {
mode: "pick-expert" | "pick-workflow";
@@ -33,6 +39,7 @@ export function useInstallWorkflowPicker({
onClose,
}: Args) {
const queryClient = useQueryClient();
+ const [source, setSource] = useState<InstallWorkflowSource>("library");
const [searchQuery, setSearchQuery] = useState("");
const [pendingKey, setPendingKey] = useState<string | null>(null);
@@ -48,56 +55,54 @@ export function useInstallWorkflowPicker({
searchQuery,
SEARCH_DEBOUNCE_MS,
);
+ const isPickingWorkflow = open && mode === "pick-workflow";
- const searchResultsQuery = useGetV2ListStoreAgents(
- { search_query: debouncedSearchQuery || undefined, page_size: 10 },
+ const libraryResultsQuery = useGetV2ListLibraryAgents(
+ {
+ search_term: debouncedSearchQuery || undefined,
+ page_size: RESULTS_PAGE_SIZE,
+ is_hidden: false,
+ },
+ {
+ query: {
+ select: (x) => (x.data as LibraryAgentResponse).agents,
+ enabled: isPickingWorkflow && source === "library",
+ },
+ },
+ );
+
+ const marketplaceResultsQuery = useGetV2ListStoreAgents(
+ {
+ search_query: debouncedSearchQuery || undefined,
+ page_size: RESULTS_PAGE_SIZE,
+ },
{
query: {
select: (x) => (x.data as StoreAgentsResponse).agents,
- enabled: open && mode === "pick-workflow",
+ enabled: isPickingWorkflow && source === "marketplace",
},
},
);
const { mutateAsync: installWorkflow } = useInstallExpertWorkflow();
- async function install(expert: Expert, versionId: string) {
- if (
- expert.workflows.some(
- (workflow) => workflow.store_listing_version_id === versionId,
- )
- ) {
- toast({
- title: `Already installed on ${expert.name}`,
- variant: "success",
- });
- onClose();
- return;
- }
+ async function installOnExpert(expert: Expert) {
+ if (!storeListingVersionId) return;
+ setPendingKey(expert.id);
try {
- await installWorkflow({
- expertId: expert.id,
- data: { store_listing_version_id: versionId },
- });
- await queryClient.invalidateQueries({
- queryKey: getListExpertsQueryKey(),
- });
- toast({ title: `Installed on ${expert.name}`, variant: "success" });
- onClose();
- } catch {
- toast({
- title: `Couldn't install on ${expert.name}`,
- description: "Something went wrong. Please try again.",
- variant: "destructive",
+ await install(expert, {
+ store_listing_version_id: storeListingVersionId,
});
+ } finally {
+ setPendingKey(null);
}
}
- async function installOnExpert(expert: Expert) {
- if (!storeListingVersionId) return;
- setPendingKey(expert.id);
+ async function installLibraryAgent(agent: LibraryAgent) {
+ if (!targetExpert) return;
+ setPendingKey(agent.id);
try {
- await install(expert, storeListingVersionId);
+ await install(targetExpert, { library_agent_id: agent.id });
} finally {
setPendingKey(null);
}
@@ -114,7 +119,9 @@ export function useInstallWorkflowPicker({
if (details.status !== 200) {
throw new Error("Failed to fetch agent details");
}
- await install(targetExpert, details.data.store_listing_version_id);
+ await install(targetExpert, {
+ store_listing_version_id: details.data.store_listing_version_id,
+ });
} catch {
toast({
title: `Couldn't install on ${targetExpert.name}`,
@@ -126,20 +133,76 @@ export function useInstallWorkflowPicker({
}
}
+ async function install(expert: Expert, data: WorkflowInstallData) {
+ if (isAlreadyInstalled(expert, data)) {
+ toast({
+ title: `Already installed on ${expert.name}`,
+ variant: "success",
+ });
+ onClose();
+ return;
+ }
+ try {
+ await installWorkflow({ expertId: expert.id, data });
+ // Both: the picker is opened from the team list and from one expert's
+ // own page, whose workflow section reads the single-expert query.
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: getListExpertsQueryKey() }),
+ queryClient.invalidateQueries({
+ queryKey: getGetExpertQueryKey(expert.id),
+ }),
+ ]);
+ toast({ title: `Installed on ${expert.name}`, variant: "success" });
+ onClose();
+ } catch {
+ toast({
+ title: `Couldn't install on ${expert.name}`,
+ description: "Something went wrong. Please try again.",
+ variant: "destructive",
+ });
+ }
+ }
+
+ // Only the library source can tell: a marketplace row carries no listing
+ // version until its detail is fetched at click time.
+ function isLibraryAgentInstalled(agent: LibraryAgent) {
+ return (
+ targetExpert?.workflows.some(
+ (workflow) => workflow.library_agent_id === agent.id,
+ ) ?? false
+ );
+ }
+
const title =
mode === "pick-expert"
? "Install on an expert"
: `Install a workflow${targetExpert ? ` on ${targetExpert.name}` : ""}`;
+ const resultsQuery =
+ source === "library" ? libraryResultsQuery : marketplaceResultsQuery;
+
return {
title,
hiredExperts,
+ isLibraryAgentInstalled,
+ source,
+ setSource,
searchQuery,
setSearchQuery,
- searchResults: searchResultsQuery.data ?? [],
- isSearching: searchResultsQuery.isLoading,
+ libraryResults: libraryResultsQuery.data ?? [],
+ marketplaceResults: marketplaceResultsQuery.data ?? [],
+ isSearching: resultsQuery.isLoading,
pendingKey,
installOnExpert,
+ installLibraryAgent,
installFromListing,
};
}
+
+function isAlreadyInstalled(expert: Expert, data: WorkflowInstallData) {
+ return expert.workflows.some((workflow) =>
+ "library_agent_id" in data
+ ? workflow.library_agent_id === data.library_agent_id
+ : workflow.store_listing_version_id === data.store_listing_version_id,
+ );
+}