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): add Team What runs zone and adopt action (#14045)

Abhimanyu Yadav3413db7eec46
diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py
index 0d741cc08a..8b3e057298 100644
--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py
@@ -287,7 +287,7 @@ async def test_resolve_graph_regular_uses_get_graph() -> None:
return_value=mock_graph_model,
) as mock_regular,
):
- mock_prisma.return_value.find_unique = AsyncMock(return_value=mock_slv)
+ mock_prisma.return_value.find_first = AsyncMock(return_value=mock_slv)
result, resolved_slv = await resolve_graph_for_library(
SLV_ID, "regular-user-id", admin=False
@@ -299,6 +299,7 @@ async def test_resolve_graph_regular_uses_get_graph() -> None:
graph_id=GRAPH_ID, version=GRAPH_VERSION, user_id="regular-user-id"
)
mock_admin.assert_not_awaited()
+ mock_prisma.return_value.find_first.assert_awaited_once()
# ---- Library membership grants graph access (product decision) ---- #
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 8905afaa57..2d8f8f2e8d 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
@@ -7,6 +7,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import prisma.enums
+import prisma.errors
import prisma.models
import pydantic
import pytest
@@ -26,11 +27,12 @@ from backend.api.model import CreateGraph
from backend.blocks.io import AgentInputBlock
from backend.copilot.model import create_chat_session
from backend.data.db import prisma as db_client
-from backend.data.graph import Graph, Node
+from backend.data.graph import Graph, GraphSettings, Node
from backend.data.model import User
from backend.data.user import get_or_create_user
from backend.usecases.sample import create_test_user
-from backend.util.exceptions import ExpertRunPausedError
+from backend.util.exceptions import ExpertRunPausedError, NotFoundError
+from backend.util.json import SafeJson
from backend.util.test import SpinTestServer
EXPECTED_ROSTER_PRELOAD_SLUGS = {
@@ -628,6 +630,152 @@ async def test_install_workflow_duplicate_returns_existing(
assert a.store_listing_version_id == slv_id
[email protected](loop_scope="session")
+async def test_install_workflow_returns_concurrent_winner(
+ server: SpinTestServer, test_user
+):
+ 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)
+ library_agent = await experts_db.library_db.add_store_agent_to_library(
+ slv_id, test_user.id
+ )
+ winner = await prisma.models.ExpertWorkflow.prisma().create(
+ data={
+ "expertId": hired.expert.id,
+ "storeListingVersionId": slv_id,
+ "libraryAgentId": library_agent.id,
+ },
+ include={"LibraryAgent": True, "StoreListingVersion": True},
+ )
+ workflow_client = SimpleNamespace(
+ find_first=AsyncMock(side_effect=[None, winner]),
+ create=AsyncMock(side_effect=prisma.errors.UniqueViolationError({})),
+ )
+
+ with patch.object(
+ prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client
+ ):
+ installed = await experts_db.install_workflow(
+ test_user.id, hired.expert.id, slv_id
+ )
+
+ assert installed.id == winner.id
+ assert workflow_client.find_first.await_count == 2
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_reraises_race_without_winner(
+ server: SpinTestServer, test_user
+):
+ 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)
+ workflow_client = SimpleNamespace(
+ find_first=AsyncMock(side_effect=[None, None]),
+ create=AsyncMock(side_effect=prisma.errors.UniqueViolationError({})),
+ )
+
+ with (
+ patch.object(
+ prisma.models.ExpertWorkflow, "prisma", return_value=workflow_client
+ ),
+ pytest.raises(prisma.errors.UniqueViolationError),
+ ):
+ await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+
+ assert workflow_client.find_first.await_count == 2
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_reuses_library_agent_without_resetting_settings(
+ server: SpinTestServer, test_user
+):
+ 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)
+ library_agent = await experts_db.library_db.add_store_agent_to_library(
+ slv_id, test_user.id
+ )
+ expected_settings = GraphSettings(
+ human_in_the_loop_safe_mode=False,
+ sensitive_action_safe_mode=True,
+ builder_chat_session_id="builder-session",
+ )
+ await prisma.models.LibraryAgent.prisma().update(
+ where={"id": library_agent.id},
+ data={"settings": SafeJson(expected_settings.model_dump())},
+ )
+ before_count = await prisma.models.LibraryAgent.prisma().count(
+ where={"userId": test_user.id}
+ )
+
+ installed = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+
+ persisted = await prisma.models.LibraryAgent.prisma().find_unique(
+ where={"id": library_agent.id}
+ )
+ after_count = await prisma.models.LibraryAgent.prisma().count(
+ where={"userId": test_user.id}
+ )
+ assert persisted is not None
+ assert installed.library_agent_id == library_agent.id
+ assert after_count == before_count
+ assert GraphSettings.model_validate(persisted.settings) == expected_settings
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_restores_archived_deleted_library_agent(
+ server: SpinTestServer, test_user
+):
+ 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)
+ library_agent = await experts_db.library_db.add_store_agent_to_library(
+ slv_id, test_user.id
+ )
+ expected_settings = GraphSettings(
+ human_in_the_loop_safe_mode=False,
+ sensitive_action_safe_mode=False,
+ builder_chat_session_id="restored-builder-session",
+ )
+ await prisma.models.LibraryAgent.prisma().update(
+ where={"id": library_agent.id},
+ data={
+ "isArchived": True,
+ "isDeleted": True,
+ "settings": SafeJson(expected_settings.model_dump()),
+ },
+ )
+
+ installed = await experts_db.install_workflow(test_user.id, hired.expert.id, slv_id)
+
+ restored = await prisma.models.LibraryAgent.prisma().find_unique(
+ where={"id": library_agent.id}
+ )
+ assert restored is not None
+ assert installed.library_agent_id == library_agent.id
+ assert not restored.isArchived
+ assert not restored.isDeleted
+ assert GraphSettings.model_validate(restored.settings) == expected_settings
+
+
[email protected](loop_scope="session")
+async def test_install_workflow_rejects_unapproved_store_version(
+ server: SpinTestServer, test_user
+):
+ slv_id = await _seed_store_listing(server)
+ await prisma.models.StoreListingVersion.prisma().update(
+ where={"id": slv_id},
+ data={"submissionStatus": prisma.enums.SubmissionStatus.DRAFT},
+ )
+ 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, slv_id)
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_resolve_expert_for_graph_unique_match(
server: SpinTestServer, test_user, other_user
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 c11cd3011f..10b1ceab55 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
@@ -12,16 +12,80 @@ import prisma.models
import backend.api.features.library.model as library_model
import backend.data.graph as graph_db
-from backend.api.features.library.db import _fetch_schedule_info
from backend.api.features.orgs.db import resolve_default_tenancy
+from backend.api.features.store.store_listing_versions import (
+ installable_store_version_where,
+)
from backend.data.graph import GraphModel, GraphSettings
from backend.data.includes import library_agent_include
from backend.util.exceptions import NotFoundError
from backend.util.json import SafeJson
+from ._schedule_info import _fetch_schedule_info
+
logger = logging.getLogger(__name__)
+def _require_graph(
+ store_listing_version: prisma.models.StoreListingVersion,
+) -> prisma.models.AgentGraph:
+ graph = store_listing_version.AgentGraph
+ if not graph:
+ raise NotFoundError(
+ f"Store listing version {store_listing_version.id} has no graph"
+ )
+ return graph
+
+
+async def resolve_store_version_for_library(
+ store_listing_version_id: str,
+ *,
+ admin: bool,
+) -> prisma.models.StoreListingVersion:
+ """Look up an installable StoreListingVersion and its graph reference."""
+ if admin:
+ slv = await prisma.models.StoreListingVersion.prisma().find_unique(
+ where={"id": store_listing_version_id}, include={"AgentGraph": True}
+ )
+ else:
+ slv = await prisma.models.StoreListingVersion.prisma().find_first(
+ where={
+ "id": store_listing_version_id,
+ **installable_store_version_where(),
+ },
+ include={"AgentGraph": True},
+ )
+ if not slv:
+ raise NotFoundError(
+ f"Store listing version {store_listing_version_id} not found or invalid"
+ )
+ _require_graph(slv)
+ return slv
+
+
+async def resolve_graph_model_for_library(
+ store_listing_version: prisma.models.StoreListingVersion,
+ user_id: str,
+ *,
+ admin: bool,
+) -> GraphModel:
+ """Resolve the graph for an already-validated marketplace version."""
+ ag = _require_graph(store_listing_version)
+
+ graph_model = (
+ await graph_db.get_graph_as_admin(
+ graph_id=ag.id, version=ag.version, user_id=user_id
+ )
+ if admin
+ else await graph_db.get_graph(
+ graph_id=ag.id, version=ag.version, user_id=user_id
+ )
+ )
+ if not graph_model:
+ raise NotFoundError(f"Graph #{ag.id} v{ag.version} not found or accessible")
+ return graph_model
+
+
async def resolve_graph_for_library(
store_listing_version_id: str,
user_id: str,
@@ -36,26 +100,8 @@ async def resolve_graph_for_library(
Returns the resolved graph together with the StoreListingVersion, so callers
can snapshot marketplace metadata without re-querying it.
"""
- slv = await prisma.models.StoreListingVersion.prisma().find_unique(
- where={"id": store_listing_version_id}, include={"AgentGraph": True}
- )
- if not slv or not slv.AgentGraph:
- raise NotFoundError(
- f"Store listing version {store_listing_version_id} not found or invalid"
- )
-
- ag = slv.AgentGraph
- if admin:
- graph_model = await graph_db.get_graph_as_admin(
- graph_id=ag.id, version=ag.version, user_id=user_id
- )
- else:
- graph_model = await graph_db.get_graph(
- graph_id=ag.id, version=ag.version, user_id=user_id
- )
-
- if not graph_model:
- raise NotFoundError(f"Graph #{ag.id} v{ag.version} not found or accessible")
+ slv = await resolve_store_version_for_library(store_listing_version_id, admin=admin)
+ graph_model = await resolve_graph_model_for_library(slv, user_id, admin=admin)
return graph_model, slv
@@ -79,6 +125,47 @@ def _marketplace_metadata(
}
+async def restore_existing_library_agent(
+ store_listing_version: prisma.models.StoreListingVersion,
+ user_id: str,
+) -> library_model.LibraryAgent | None:
+ """Restore and return an existing library entry without loading its graph."""
+ ag = _require_graph(store_listing_version)
+
+ client = prisma.models.LibraryAgent.prisma()
+ where = {
+ "userId_agentGraphId_agentGraphVersion": {
+ "userId": user_id,
+ "agentGraphId": ag.id,
+ "agentGraphVersion": ag.version,
+ }
+ }
+ existing = await client.find_unique(where=where)
+ if existing is None:
+ return None
+
+ restored = await client.update(
+ where=where,
+ data={
+ "isDeleted": False,
+ "isArchived": False,
+ **_marketplace_metadata(store_listing_version),
+ },
+ include=library_agent_include(
+ user_id, include_nodes=False, include_executions=False
+ ),
+ )
+ if restored is None:
+ return None
+
+ schedule_info = await _fetch_schedule_info(user_id, graph_id=ag.id)
+ return library_model.LibraryAgent.from_db(
+ restored,
+ schedule_info=schedule_info,
+ store_listing_version_id=store_listing_version.id,
+ )
+
+
async def add_graph_to_library(
graph_model: GraphModel,
user_id: str,
@@ -141,7 +228,6 @@ async def add_graph_to_library(
data={
"isDeleted": False,
"isArchived": False,
- "settings": settings_json,
"name": marketplace["name"],
"description": marketplace["description"],
"imageUrl": marketplace["imageUrl"],
@@ -164,4 +250,8 @@ async def add_graph_to_library(
f"to library for user #{user_id}"
)
schedule_info = await _fetch_schedule_info(user_id, graph_id=graph_model.id)
- return library_model.LibraryAgent.from_db(added_agent, schedule_info=schedule_info)
+ 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 9b97d2ade8..72aa9e4e0e 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
@@ -53,7 +53,11 @@ async def test_add_graph_to_library_create_new_agent() -> None:
result = await add_graph_to_library(graph_model, "user-id", _make_slv())
assert result is converted_agent
- mock_from_db.assert_called_once_with(created_agent, schedule_info={})
+ 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
create_data = create_call.kwargs["data"]
@@ -178,7 +182,11 @@ async def test_add_graph_to_library_unique_violation_updates_existing() -> None:
result = await add_graph_to_library(graph_model, "user-id", _make_slv())
assert result is converted_agent
- mock_from_db.assert_called_once_with(updated_agent, schedule_info={})
+ 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
assert update_call.kwargs["where"] == {
@@ -191,6 +199,7 @@ async def test_add_graph_to_library_unique_violation_updates_existing() -> None:
update_data = update_call.kwargs["data"]
assert update_data["isDeleted"] is False
assert update_data["isArchived"] is False
+ assert "settings" not in update_data
# Restoring a soft-deleted agent refreshes the marketplace snapshot too
assert update_data["name"] == "Marketplace Title"
assert update_data["description"] == "Marketplace description"
diff --git a/autogpt_platform/backend/backend/api/features/library/_schedule_info.py b/autogpt_platform/backend/backend/api/features/library/_schedule_info.py
new file mode 100644
index 0000000000..0c41e43965
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/library/_schedule_info.py
@@ -0,0 +1,46 @@
+import logging
+from datetime import datetime, timezone
+from typing import Optional
+
+from backend.util.clients import get_scheduler_client
+
+logger = logging.getLogger(__name__)
+
+
+async def _fetch_schedule_info(
+ user_id: str, graph_id: Optional[str] = None
+) -> dict[str, str]:
+ """Fetch a map of graph ID to earliest next-run time.
+
+ When ``graph_id`` is provided, narrow the scheduler query to that graph.
+ """
+ try:
+ scheduler_client = get_scheduler_client()
+ schedules = await scheduler_client.get_graph_execution_schedules(
+ graph_id=graph_id,
+ user_id=user_id,
+ )
+ earliest: dict[str, tuple[datetime, str]] = {}
+ for schedule in schedules:
+ parsed = _parse_iso_datetime(schedule.next_run_time)
+ if parsed is None:
+ continue
+ current = earliest.get(schedule.graph_id)
+ if current is None or parsed < current[0]:
+ earliest[schedule.graph_id] = (parsed, schedule.next_run_time)
+ return {graph_id: iso for graph_id, (_, iso) in earliest.items()}
+ except Exception:
+ logger.warning("Failed to fetch schedules for library agents", exc_info=True)
+ return {}
+
+
+def _parse_iso_datetime(value: str) -> Optional[datetime]:
+ """Parse an ISO 8601 datetime, tolerating Z and naive UTC forms."""
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ logger.warning("Failed to parse schedule next_run_time: %s", value)
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index 70bd6ae221..45174148ad 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -1,7 +1,6 @@
import asyncio
import itertools
import logging
-from datetime import datetime, timezone
from typing import Literal, Optional, cast
import fastapi
@@ -17,6 +16,9 @@ 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 transaction
from backend.data.execution import get_graph_execution
from backend.data.expert_attribution import resolve_attributable_expert
@@ -39,6 +41,13 @@ from backend.util.models import Pagination
from backend.util.settings import Config
from . import model as library_model
+from ._add_to_library import (
+ add_graph_to_library,
+ resolve_graph_model_for_library,
+ resolve_store_version_for_library,
+ restore_existing_library_agent,
+)
+from ._schedule_info import _fetch_schedule_info
from .embeddings import schedule_library_agent_embedding
logger = logging.getLogger(__name__)
@@ -65,44 +74,68 @@ async def _fetch_execution_counts(user_id: str, graph_ids: list[str]) -> dict[st
}
-async def _fetch_schedule_info(
- user_id: str, graph_id: Optional[str] = None
-) -> dict[str, str]:
- """Fetch a map of graph_id → earliest next_run_time ISO string.
+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.
- When `graph_id` is provided, the scheduler query is narrowed to that graph,
- which is cheaper for single-agent lookups (detail page, post-update, etc.).
+ 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:
- scheduler_client = get_scheduler_client()
- schedules = await scheduler_client.get_graph_execution_schedules(
- graph_id=graph_id,
- user_id=user_id,
+ 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"},
+ ],
)
- earliest: dict[str, tuple[datetime, str]] = {}
- for s in schedules:
- parsed = _parse_iso_datetime(s.next_run_time)
- if parsed is None:
- continue
- current = earliest.get(s.graph_id)
- if current is None or parsed < current[0]:
- earliest[s.graph_id] = (parsed, s.next_run_time)
- return {graph_id: iso for graph_id, (_, iso) in earliest.items()}
except Exception:
- logger.warning("Failed to fetch schedules for library agents", exc_info=True)
+ 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
-def _parse_iso_datetime(value: str) -> Optional[datetime]:
- """Parse an ISO 8601 datetime, tolerating `Z` and naive forms (assumed UTC)."""
- try:
- parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
- except ValueError:
- logger.warning("Failed to parse schedule next_run_time: %s", value)
- return None
- if parsed.tzinfo is None:
- parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed
+async def _fetch_marketplace_details(
+ graph_id: str,
+) -> tuple[prisma.models.StoreListing | None, prisma.models.Profile | None]:
+ store_listing = await prisma.models.StoreListing.prisma().find_first(
+ where={
+ "agentGraphId": graph_id,
+ "isDeleted": False,
+ "hasApprovedVersion": True,
+ },
+ include={"ActiveVersion": True},
+ )
+ profile = None
+ if store_listing and store_listing.ActiveVersion and store_listing.owningUserId:
+ profile = await prisma.models.Profile.prisma().find_first(
+ where={"userId": store_listing.owningUserId}
+ )
+ return store_listing, profile
async def list_library_agents(
@@ -248,9 +281,10 @@ 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 = await asyncio.gather(
+ execution_counts, schedule_info, store_version_ids = 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
@@ -262,6 +296,9 @@ 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:
@@ -335,9 +372,10 @@ async def list_favorite_library_agents(
)
graph_ids = [a.agentGraphId for a in library_agents if a.agentGraphId]
- execution_counts, schedule_info = await asyncio.gather(
+ execution_counts, schedule_info, store_version_ids = 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
@@ -349,6 +387,9 @@ 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:
@@ -380,7 +421,7 @@ async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent
The requested LibraryAgent.
Raises:
- NotFoundError: If the specified agent does not exist.
+ NotFoundError: If the specified agent or its graph relation does not exist.
DatabaseError: If there's an error during retrieval.
"""
library_agent = await prisma.models.LibraryAgent.prisma().find_first(
@@ -395,42 +436,31 @@ async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent
if not library_agent:
raise NotFoundError(f"Library agent #{id} not found")
- # Fetch marketplace listing if the agent has been published
- store_listing = None
- profile = None
- if library_agent.AgentGraph:
- store_listing = await prisma.models.StoreListing.prisma().find_first(
- where={
- "agentGraphId": library_agent.AgentGraph.id,
- "isDeleted": False,
- "hasApprovedVersion": True,
- },
- include={
- "ActiveVersion": True,
- },
- )
- if store_listing and store_listing.ActiveVersion and store_listing.owningUserId:
- # Fetch Profile separately since User doesn't have a direct Profile relation
- profile = await prisma.models.Profile.prisma().find_first(
- where={"userId": store_listing.owningUserId}
- )
+ if not library_agent.AgentGraph:
+ raise NotFoundError(f"Agent graph for library agent #{id} not found")
- schedule_info = (
- await _fetch_schedule_info(user_id, graph_id=library_agent.AgentGraph.id)
- if library_agent.AgentGraph
- else {}
+ (
+ 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
return library_model.LibraryAgent.from_db(
library_agent,
- sub_graphs=(
- await graph_db.get_sub_graphs(library_agent.AgentGraph)
- if library_agent.AgentGraph
- else None
- ),
+ sub_graphs=sub_graphs,
store_listing=store_listing,
profile=profile,
schedule_info=schedule_info,
+ store_listing_version_id=store_version_ids.get(
+ (library_agent.agentGraphId, library_agent.agentGraphVersion)
+ ),
)
@@ -1197,14 +1227,19 @@ async def add_store_agent_to_library(
See also: `add_store_agent_to_library_as_admin()` which uses
`get_graph_as_admin` to bypass marketplace status checks for admin review.
"""
- from ._add_to_library import add_graph_to_library, resolve_graph_for_library
-
logger.debug(
- f"Adding agent from store listing version #{store_listing_version_id} "
- f"to library for user #{user_id}"
+ "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
)
- graph_model, store_listing_version = await resolve_graph_for_library(
- store_listing_version_id, user_id, admin=False
+ existing = await restore_existing_library_agent(store_listing_version, user_id)
+ if existing is not None:
+ return existing
+ graph_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)
@@ -1214,14 +1249,18 @@ async def add_store_agent_to_library_as_admin(
) -> library_model.LibraryAgent:
"""Admin variant that uses `get_graph_as_admin` to bypass marketplace
APPROVED-only checks, allowing admins to add pending agents for review."""
- from ._add_to_library import add_graph_to_library, resolve_graph_for_library
-
logger.warning(
f"ADMIN adding agent from store listing version "
f"#{store_listing_version_id} to library for user #{user_id}"
)
- graph_model, store_listing_version = await resolve_graph_for_library(
- store_listing_version_id, user_id, admin=True
+ store_listing_version = await resolve_store_version_for_library(
+ store_listing_version_id, admin=True
+ )
+ existing = await restore_existing_library_agent(store_listing_version, user_id)
+ if existing is not None:
+ return existing
+ graph_model = await resolve_graph_model_for_library(
+ store_listing_version, user_id, admin=True
)
return await add_graph_to_library(graph_model, user_id, store_listing_version)
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 6424af59aa..3e3fb1e87a 100644
--- a/autogpt_platform/backend/backend/api/features/library/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py
@@ -74,6 +74,12 @@ async def test_get_library_agents(mocker):
)
mock_library_agent.return_value.count = mocker.AsyncMock(return_value=1)
+ # Function-scoped-loop tests must never run real prisma queries: a pooled
+ # connection created here would outlive this test's event loop and break
+ # later session-loop tests with "Event loop is closed".
+ mock_slv = mocker.patch("prisma.models.StoreListingVersion.prisma")
+ mock_slv.return_value.find_many = mocker.AsyncMock(return_value=[])
+
mocker.patch(
"backend.api.features.library.db._fetch_execution_counts",
new=mocker.AsyncMock(return_value={}),
@@ -173,6 +179,142 @@ 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(
@@ -233,11 +375,12 @@ async def test_add_agent_to_library(mocker):
mock_store_listing_version = mocker.patch(
"prisma.models.StoreListingVersion.prisma"
)
- mock_store_listing_version.return_value.find_unique = mocker.AsyncMock(
+ mock_store_listing_version.return_value.find_first = mocker.AsyncMock(
return_value=mock_store_listing_data
)
mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_library_agent.return_value.find_unique = mocker.AsyncMock(return_value=None)
mock_library_agent.return_value.create = mocker.AsyncMock(
return_value=mock_library_agent_data
)
@@ -265,9 +408,15 @@ async def test_add_agent_to_library(mocker):
await db.add_store_agent_to_library("version123", "test-user")
# Verify mocks called correctly
- mock_store_listing_version.return_value.find_unique.assert_called_once_with(
- where={"id": "version123"}, include={"AgentGraph": True}
- )
+ resolve_call = mock_store_listing_version.return_value.find_first.call_args
+ assert resolve_call.kwargs["where"] == {
+ "id": "version123",
+ "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
+ "isDeleted": False,
+ "isAvailable": True,
+ "StoreListing": {"is": {"isDeleted": False}},
+ }
+ assert resolve_call.kwargs["include"] == {"AgentGraph": True}
# Check that create was called with the expected data including settings
create_call_args = mock_library_agent.return_value.create.call_args
assert create_call_args is not None
@@ -291,6 +440,95 @@ 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"
+
+
+async def test_add_agent_to_library_reuses_existing_without_loading_graph(mocker):
+ agent_graph = MagicMock(id="agent1", version=1)
+ store_version = MagicMock(
+ id="version123",
+ agentGraphId="agent1",
+ agentGraphVersion=1,
+ AgentGraph=agent_graph,
+ description="Marketplace description",
+ imageUrls=["https://example.com/agent.png"],
+ )
+ store_version.name = "Marketplace agent"
+ existing = MagicMock(id="library-agent")
+ restored = MagicMock(id="library-agent")
+ converted = MagicMock(id="library-agent")
+
+ store_client = mocker.patch("prisma.models.StoreListingVersion.prisma")
+ store_client.return_value.find_first = mocker.AsyncMock(return_value=store_version)
+ library_client = mocker.patch("prisma.models.LibraryAgent.prisma")
+ library_client.return_value.find_unique = mocker.AsyncMock(return_value=existing)
+ library_client.return_value.update = mocker.AsyncMock(return_value=restored)
+ library_client.return_value.create = mocker.AsyncMock()
+ get_graph = mocker.patch(
+ "backend.api.features.library._add_to_library.graph_db.get_graph",
+ new=mocker.AsyncMock(),
+ )
+ mocker.patch(
+ "backend.api.features.library._add_to_library._fetch_schedule_info",
+ new=mocker.AsyncMock(return_value={}),
+ )
+ from_db = mocker.patch(
+ "backend.api.features.library.model.LibraryAgent.from_db",
+ return_value=converted,
+ )
+
+ result = await db.add_store_agent_to_library("version123", "test-user")
+
+ assert result is converted
+ get_graph.assert_not_awaited()
+ library_client.return_value.create.assert_not_awaited()
+ update_call = library_client.return_value.update.call_args
+ assert update_call.kwargs["where"] == {
+ "userId_agentGraphId_agentGraphVersion": {
+ "userId": "test-user",
+ "agentGraphId": "agent1",
+ "agentGraphVersion": 1,
+ }
+ }
+ assert update_call.kwargs["data"] == {
+ "isDeleted": False,
+ "isArchived": False,
+ "name": "Marketplace agent",
+ "description": "Marketplace description",
+ "imageUrl": "https://example.com/agent.png",
+ }
+ from_db.assert_called_once_with(
+ restored,
+ schedule_info={},
+ store_listing_version_id="version123",
+ )
+
+
+async def test_restore_existing_library_agent_handles_deleted_update(mocker):
+ from backend.api.features.library._add_to_library import (
+ restore_existing_library_agent,
+ )
+
+ agent_graph = MagicMock(id="agent1", version=1)
+ store_version = MagicMock(id="version123", AgentGraph=agent_graph)
+ library_client = mocker.patch("prisma.models.LibraryAgent.prisma")
+ library_client.return_value.find_unique = mocker.AsyncMock(
+ return_value=MagicMock(id="library-agent")
+ )
+ library_client.return_value.update = mocker.AsyncMock(return_value=None)
+ fetch_schedule_info = mocker.patch(
+ "backend.api.features.library._add_to_library._fetch_schedule_info",
+ new=mocker.AsyncMock(),
+ )
+ from_db = mocker.patch("backend.api.features.library.model.LibraryAgent.from_db")
+
+ result = await restore_existing_library_agent(store_version, "test-user")
+
+ assert result is None
+ fetch_schedule_info.assert_not_awaited()
+ from_db.assert_not_called()
@pytest.mark.asyncio(loop_scope="session")
@@ -304,7 +542,7 @@ async def test_add_agent_to_library_not_found(mocker):
mock_store_listing_version = mocker.patch(
"prisma.models.StoreListingVersion.prisma"
)
- mock_store_listing_version.return_value.find_unique = mocker.AsyncMock(
+ mock_store_listing_version.return_value.find_first = mocker.AsyncMock(
return_value=None
)
@@ -313,9 +551,7 @@ async def test_add_agent_to_library_not_found(mocker):
await db.add_store_agent_to_library("version123", "test-user")
# Verify mock called correctly
- mock_store_listing_version.return_value.find_unique.assert_called_once_with(
- where={"id": "version123"}, include={"AgentGraph": True}
- )
+ mock_store_listing_version.return_value.find_first.assert_awaited_once()
@pytest.mark.asyncio
@@ -543,6 +779,12 @@ 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}),
@@ -554,12 +796,69 @@ 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"
+
+
+async def test_get_library_agent_rejects_missing_graph(mocker):
+ library_agent = MagicMock(id="library-id", AgentGraph=None)
+ mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_library_agent.return_value.find_first = mocker.AsyncMock(
+ return_value=library_agent
+ )
+ mock_from_db = mocker.patch.object(library_model.LibraryAgent, "from_db")
+
+ with pytest.raises(
+ NotFoundError, match="Agent graph for library agent #library-id not found"
+ ):
+ await db.get_library_agent("library-id", "test-user")
+
+ mock_from_db.assert_not_called()
+
+
@pytest.mark.asyncio
async def test_list_library_agents_skips_failed_agent(mocker):
"""Agents that fail parsing should be skipped — covers the except branch."""
@@ -598,6 +897,9 @@ async def test_list_library_agents_skips_failed_agent(mocker):
)
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(return_value=[])
+
mocker.patch(
"backend.api.features.library.db._fetch_execution_counts",
new=mocker.AsyncMock(return_value={}),
diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.py
index 6a7c8e91a6..eabb0ed721 100644
--- a/autogpt_platform/backend/backend/api/features/library/model.py
+++ b/autogpt_platform/backend/backend/api/features/library/model.py
@@ -240,6 +240,14 @@ 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(
@@ -249,6 +257,7 @@ 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
@@ -400,6 +409,7 @@ 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/backend/api/features/store/store_listing_versions.py b/autogpt_platform/backend/backend/api/features/store/store_listing_versions.py
new file mode 100644
index 0000000000..58dcea794c
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/store_listing_versions.py
@@ -0,0 +1,11 @@
+import prisma.enums
+import prisma.types
+
+
+def installable_store_version_where() -> prisma.types.StoreListingVersionWhereInput:
+ return {
+ "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,
+ "isDeleted": False,
+ "isAvailable": True,
+ "StoreListing": {"is": {"isDeleted": False}},
+ }
diff --git a/autogpt_platform/backend/snapshots/lib_agts_search b/autogpt_platform/backend/snapshots/lib_agts_search
index 04fc2e30af..f8f809fe54 100644
--- a/autogpt_platform/backend/snapshots/lib_agts_search
+++ b/autogpt_platform/backend/snapshots/lib_agts_search
@@ -49,7 +49,8 @@
"sensitive_action_safe_mode": false,
"builder_chat_session_id": null
},
- "marketplace_listing": null
+ "marketplace_listing": null,
+ "store_listing_version_id": null
},
{
"id": "test-agent-2",
@@ -100,7 +101,8 @@
"sensitive_action_safe_mode": false,
"builder_chat_session_id": null
},
- "marketplace_listing": null
+ "marketplace_listing": null,
+ "store_listing_version_id": null
}
],
"pagination": {
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowsSection.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowsSection.tsx
index e589a29626..8c85ea15c9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowsSection.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowsSection.tsx
@@ -2,7 +2,7 @@
import { Expert } from "@/app/api/__generated__/models/expert";
import { Button } from "@/components/atoms/Button/Button";
-import { humanizeCronExpression } from "@/lib/cron-expression-utils";
+import { safeHumanizeCronExpression } from "@/lib/cron-expression-utils";
import { FlashIcon, PlusSignIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
import { workflowNeedsSetup } from "../../helpers";
@@ -66,7 +66,7 @@ export function ExpertWorkflowsSection({
</span>
) : workflow.schedule_cron ? (
<span className="shrink-0 rounded-full bg-zinc-100 px-2.5 py-1 text-xs text-zinc-600">
- {humanizeCronExpression(workflow.schedule_cron)}
+ {safeHumanizeCronExpression(workflow.schedule_cron)}
</span>
) : null}
</div>
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 9b585c0584..96fdc2005e 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
@@ -2,16 +2,24 @@ import {
getArchiveExpertMockHandler,
getArchiveExpertMockHandler401,
getGetExpertDetachPreviewMockHandler,
+ getInstallExpertWorkflowMockHandler,
+ getInstallExpertWorkflowMockHandler404,
+ getInstallExpertWorkflowMockHandler422,
getListExpertsMockHandler,
getListExpertsMockHandler401,
getResumeExpertSchedulesMockHandler,
getUpdateExpertSoulMockHandler,
getUpdateExpertSoulMockHandler422,
} from "@/app/api/__generated__/endpoints/experts/experts.msw";
-import { delay, http, HttpResponse } from "msw";
+import {
+ getGetV2ListLibraryAgentsMockHandler200,
+ getGetV2ListLibraryAgentsMockHandler401,
+ getGetV2ListLibraryAgentsResponseMock200,
+} from "@/app/api/__generated__/endpoints/library/library.msw";
import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
import { Expert } from "@/app/api/__generated__/models/expert";
import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import { server } from "@/mocks/mock-server";
import {
fireEvent,
@@ -21,6 +29,7 @@ import {
within,
} from "@/tests/integrations/test-utils";
import userEvent from "@testing-library/user-event";
+import { delay, http, HttpResponse } from "msw";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import TeamPage from "../page";
@@ -29,8 +38,90 @@ const { setFlagStatusMock } = vi.hoisted(() => ({
setFlagStatusMock: vi.fn(() => ({ enabled: true, ready: true })),
}));
+function libraryResponse(
+ agents: LibraryAgent[],
+ totalItems = agents.length,
+ currentPage = 1,
+) {
+ const base = getGetV2ListLibraryAgentsResponseMock200();
+ return {
+ ...base,
+ agents,
+ pagination: {
+ ...base.pagination,
+ total_items: totalItems,
+ current_page: currentPage,
+ page_size: 100,
+ total_pages: Math.ceil(totalItems / 100),
+ },
+ };
+}
+
+function makeLibraryAgent(over: Partial<LibraryAgent>): LibraryAgent {
+ return {
+ id: "lib-agent",
+ graph_id: "graph-agent",
+ graph_version: 1,
+ name: "Research Assistant",
+ description: "",
+ creator_name: "Acme Labs",
+ creator_image_url: "",
+ image_url: null,
+ status: "COMPLETED",
+ created_at: new Date(),
+ updated_at: new Date(),
+ input_schema: {},
+ output_schema: {},
+ credentials_input_schema: {},
+ has_external_trigger: false,
+ has_human_in_the_loop: false,
+ has_sensitive_action: false,
+ new_output: false,
+ can_access_graph: true,
+ is_latest_version: true,
+ is_favorite: false,
+ marketplace_listing: null,
+ store_listing_version_id: null,
+ ...over,
+ } as unknown as LibraryAgent;
+}
+
+const adoptableAgent = makeLibraryAgent({
+ id: "lib-research",
+ graph_id: "graph-research",
+ name: "Research Assistant",
+ store_listing_version_id: "slv-adopt",
+});
+
+const localOnlyAgent = makeLibraryAgent({
+ id: "lib-local",
+ graph_id: "graph-local",
+ name: "My Private Agent",
+ store_listing_version_id: null,
+});
+
+function makeSchedule(
+ over: Partial<GraphExecutionJobInfo> = {},
+): GraphExecutionJobInfo {
+ return {
+ id: "sched-1",
+ name: "Content Calendar",
+ user_id: "user-1",
+ graph_id: "graph-1",
+ graph_version: 1,
+ cron: "40 7 * * *",
+ input_data: {},
+ next_run_time: "2026-08-15T07:40:00Z",
+ expert_id: "expert-maria",
+ ...over,
+ };
+}
+
beforeEach(() => {
- server.use(getGetV1ListExecutionSchedulesForAUserMockHandler([]));
+ server.use(
+ getGetV1ListExecutionSchedulesForAUserMockHandler([]),
+ getGetV2ListLibraryAgentsMockHandler200(libraryResponse([])),
+ );
});
afterEach(() => {
@@ -178,8 +269,9 @@ describe("TeamPage", () => {
expect(await screen.findByText("Maria")).toBeDefined();
expect(screen.getByText("Marketing Strategist")).toBeDefined();
expect(screen.getByText("2 workflows")).toBeDefined();
- expect(screen.queryByText("Content Calendar")).toBeNull();
- expect(screen.queryByText("SEO Audit")).toBeNull();
+ const card = screen.getByRole("link", { name: "View Maria" });
+ expect(within(card).queryByText("Content Calendar")).toBeNull();
+ expect(within(card).queryByText("SEO Audit")).toBeNull();
});
test("links the card content to the expert page", async () => {
@@ -210,17 +302,9 @@ describe("TeamPage", () => {
test("shows a schedule count with the next run on the expert card", async () => {
const inTwoDays = new Date(Date.now() + 2 * 24 * 60 * 60 * 1000);
- const mariaSchedule: GraphExecutionJobInfo = {
- id: "sched-1",
- name: "Content Calendar",
- user_id: "user-1",
- graph_id: "graph-1",
- graph_version: 1,
- cron: "40 7 * * *",
- input_data: {},
+ const mariaSchedule = makeSchedule({
next_run_time: inTwoDays.toISOString(),
- expert_id: "expert-maria",
- };
+ });
server.use(
getListExpertsMockHandler([scheduledMaria]),
getGetV1ListExecutionSchedulesForAUserMockHandler([mariaSchedule]),
@@ -778,4 +862,632 @@ describe("TeamPage", () => {
expect(listRequests).toBe(0);
expect(screen.queryByRole("button", { name: "Edit Soul" })).toBeNull();
});
+
+ test("groups installed workflows under each expert in the What runs zone", async () => {
+ const john: Expert = {
+ ...hiredMaria,
+ id: "expert-john",
+ name: "John",
+ workflows: [
+ {
+ id: "wf-j",
+ store_listing_version_id: "slv-j",
+ library_agent_id: "lib-j",
+ graph_id: "graph-j",
+ name: "Lead Scraper",
+ description: null,
+ },
+ ],
+ };
+ server.use(getListExpertsMockHandler([scheduledMaria, john]));
+
+ render(<TeamPage />);
+
+ const zone = await screen.findByRole("region", { name: "What runs" });
+ const mariaGroup = within(zone).getByRole("region", {
+ name: "Maria runs",
+ });
+ expect(within(mariaGroup).getByText("Content Calendar")).toBeDefined();
+ expect(within(mariaGroup).getByText("SEO Audit")).toBeDefined();
+ expect(within(mariaGroup).queryByText("Lead Scraper")).toBeNull();
+
+ const johnGroup = within(zone).getByRole("region", { name: "John runs" });
+ expect(within(johnGroup).getByText("Lead Scraper")).toBeDefined();
+ expect(within(johnGroup).queryByText("Content Calendar")).toBeNull();
+ });
+
+ test("shows a quiet empty message for an expert with nothing installed", async () => {
+ const emptyMaria: Expert = { ...hiredMaria, workflows: [] };
+ server.use(getListExpertsMockHandler([emptyMaria]));
+
+ render(<TeamPage />);
+
+ const group = await screen.findByRole("region", { name: "Maria runs" });
+ expect(within(group).getByText(/nothing installed yet/i)).toBeDefined();
+ });
+
+ test("lists adoptable and local-only agents under Your agents", async () => {
+ const user = userEvent.setup();
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent, localOnlyAgent]),
+ ),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ 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.",
+ );
+ });
+
+ test("hides already-installed agents from Your agents", async () => {
+ const installedAgent = makeLibraryAgent({
+ id: "lib-installed",
+ graph_id: "graph-1",
+ name: "Content Calendar",
+ store_listing_version_id: "slv-1",
+ });
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([installedAgent, adoptableAgent]),
+ ),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ expect(within(agents).getByText("Research Assistant")).toBeDefined();
+ expect(within(agents).queryByText("My Private Agent")).toBeNull();
+ expect(
+ within(agents).getAllByRole("button", { name: "Adopt" }),
+ ).toHaveLength(1);
+ });
+
+ test("adopts an agent onto the selected expert via the install endpoint", async () => {
+ const user = userEvent.setup();
+ let installExpertId: string | undefined;
+ let installBody: unknown;
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler(async (info) => {
+ installExpertId = info.params.expertId as string;
+ installBody = await info.request.json();
+ return {
+ id: "wf-adopted",
+ store_listing_version_id: "slv-adopt",
+ library_agent_id: "lib-research",
+ graph_id: "graph-research",
+ name: "Research Assistant",
+ description: null,
+ };
+ }),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+
+ await waitFor(() => expect(installExpertId).toBe("expert-maria"));
+ expect(installBody).toEqual({ store_listing_version_id: "slv-adopt" });
+ expect(within(agents).queryByText("Research Assistant")).toBeNull();
+ });
+
+ test("asks which expert to adopt into when more than one is hired", async () => {
+ const user = userEvent.setup();
+ const john: Expert = {
+ ...hiredMaria,
+ id: "expert-john",
+ name: "John",
+ workflows: [],
+ };
+ let installExpertId: string | undefined;
+ server.use(
+ getListExpertsMockHandler([hiredMaria, john]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler((info) => {
+ installExpertId = info.params.expertId as string;
+ return {
+ id: "wf-adopted",
+ store_listing_version_id: "slv-adopt",
+ library_agent_id: "lib-research",
+ graph_id: "graph-research",
+ name: "Research Assistant",
+ description: null,
+ };
+ }),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+ expect(screen.queryByText(/undo anytime/i)).toBeNull();
+ await user.click(
+ await screen.findByRole("button", {
+ name: /Adds this agent to John's workflows/i,
+ }),
+ );
+
+ await waitFor(() => expect(installExpertId).toBe("expert-john"));
+ });
+
+ test("offers an exact version only to experts that have not adopted it", async () => {
+ const user = userEvent.setup();
+ const mariaWithAgent: Expert = {
+ ...hiredMaria,
+ workflows: [
+ ...hiredMaria.workflows,
+ {
+ id: "wf-adopted",
+ store_listing_version_id: "slv-adopt",
+ library_agent_id: "lib-research",
+ graph_id: "graph-research",
+ name: "Research Assistant",
+ description: null,
+ },
+ ],
+ };
+ const john: Expert = {
+ ...hiredMaria,
+ id: "expert-john",
+ name: "John",
+ workflows: [],
+ };
+ let installExpertId: string | undefined;
+ server.use(
+ getListExpertsMockHandler([mariaWithAgent, john]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler((info) => {
+ installExpertId = info.params.expertId as string;
+ return {
+ id: "wf-john",
+ store_listing_version_id: "slv-adopt",
+ library_agent_id: "lib-research",
+ graph_id: "graph-research",
+ name: "Research Assistant",
+ description: null,
+ };
+ }),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+
+ await waitFor(() => expect(installExpertId).toBe("expert-john"));
+ expect(screen.queryByText("Choose an expert")).toBeNull();
+ });
+
+ test("filter chips switch between members and agents in the zone", async () => {
+ const user = userEvent.setup();
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ );
+
+ render(<TeamPage />);
+
+ await screen.findByRole("region", { name: "Maria runs" });
+ await screen.findByRole("region", { name: "Your agents" });
+
+ await user.click(screen.getByRole("button", { name: "Agents" }));
+ expect(screen.queryByRole("region", { name: "Maria runs" })).toBeNull();
+ expect(screen.getByRole("region", { name: "Your agents" })).toBeDefined();
+
+ await user.click(screen.getByRole("button", { name: "Members" }));
+ expect(screen.getByRole("region", { name: "Maria runs" })).toBeDefined();
+ expect(screen.queryByRole("region", { name: "Your agents" })).toBeNull();
+ });
+
+ test("keeps only workflows with actual jobs when Scheduled is active", async () => {
+ const user = userEvent.setup();
+ const manuallyScheduledMaria: Expert = {
+ ...hiredMaria,
+ workflows: [
+ { ...hiredMaria.workflows[0], schedule_id: null, schedule_cron: null },
+ hiredMaria.workflows[1],
+ ],
+ };
+ server.use(
+ getListExpertsMockHandler([manuallyScheduledMaria]),
+ getGetV1ListExecutionSchedulesForAUserMockHandler([makeSchedule()]),
+ );
+
+ render(<TeamPage />);
+
+ const group = await screen.findByRole("region", { name: "Maria runs" });
+ expect(within(group).getByText("Content Calendar")).toBeDefined();
+ expect(within(group).getByText("SEO Audit")).toBeDefined();
+
+ await user.click(screen.getByRole("button", { name: "Scheduled" }));
+
+ const scheduledGroup = screen.getByRole("region", { name: "Maria runs" });
+ expect(within(scheduledGroup).getByText("Content Calendar")).toBeDefined();
+ expect(within(scheduledGroup).queryByText("SEO Audit")).toBeNull();
+ });
+
+ test("does not treat a deleted scheduler job as scheduled", async () => {
+ const user = userEvent.setup();
+ server.use(getListExpertsMockHandler([scheduledMaria]));
+
+ render(<TeamPage />);
+
+ await screen.findByRole("region", { name: "Maria runs" });
+ await user.click(screen.getByRole("button", { name: "Scheduled" }));
+
+ expect(screen.queryByRole("region", { name: "Maria runs" })).toBeNull();
+ expect(screen.getByText("No scheduled workflows yet.")).toBeDefined();
+ });
+
+ test("shows every actual schedule attached to a workflow", async () => {
+ server.use(
+ getListExpertsMockHandler([scheduledMaria]),
+ getGetV1ListExecutionSchedulesForAUserMockHandler([
+ makeSchedule(),
+ makeSchedule({ id: "sched-2", cron: "0 9 * * 1" }),
+ ]),
+ );
+
+ render(<TeamPage />);
+
+ const group = await screen.findByRole("region", { name: "Maria runs" });
+ expect(within(group).getByText("Every day at 07:40")).toBeDefined();
+ expect(within(group).getByText("Every Monday at 09:00")).toBeDefined();
+ });
+
+ test("shows paused instead of recurrence for a paused workflow", async () => {
+ const pausedMaria: Expert = {
+ ...scheduledMaria,
+ schedules_paused_at: new Date("2026-08-14T12:00:00Z"),
+ workflows: scheduledMaria.workflows.map((workflow) => ({
+ ...workflow,
+ schedule_id: null,
+ })),
+ };
+ server.use(
+ getListExpertsMockHandler([pausedMaria]),
+ getGetV1ListExecutionSchedulesForAUserMockHandler([makeSchedule()]),
+ );
+
+ render(<TeamPage />);
+
+ const group = await screen.findByRole("region", { name: "Maria runs" });
+ const workflow = within(group).getAllByTestId("what-runs-workflow-row")[0];
+ expect(within(group).getAllByText("Paused")).toHaveLength(1);
+ expect(within(workflow).queryByText("Paused")).toBeNull();
+ expect(within(workflow).queryByText("Every day at 07:40")).toBeNull();
+ expect(within(workflow).queryByText("Needs setup")).toBeNull();
+ });
+
+ test("links a workflow with a missing job to its setup page", async () => {
+ const staleMaria: Expert = {
+ ...hiredMaria,
+ workflows: [
+ {
+ ...hiredMaria.workflows[0],
+ schedule_cron: "40 7 * * *",
+ schedule_id: "deleted-schedule",
+ },
+ ],
+ };
+ server.use(getListExpertsMockHandler([staleMaria]));
+
+ render(<TeamPage />);
+
+ const group = await screen.findByRole("region", { name: "Maria runs" });
+ expect(within(group).getByText("Needs setup")).toBeDefined();
+ expect(
+ within(group).getByRole("link", { name: "Set up" }).getAttribute("href"),
+ ).toBe("/library/agents/lib-1");
+ });
+
+ test("does not mark the card as needing setup when a stale id has a live job", async () => {
+ const staleButLiveMaria: Expert = {
+ ...hiredMaria,
+ workflows: [
+ {
+ ...hiredMaria.workflows[0],
+ schedule_cron: "40 7 * * *",
+ schedule_id: "deleted-schedule",
+ },
+ ],
+ };
+ server.use(
+ getListExpertsMockHandler([staleButLiveMaria]),
+ getGetV1ListExecutionSchedulesForAUserMockHandler([makeSchedule()]),
+ );
+
+ render(<TeamPage />);
+
+ const card = await screen.findByRole("link", { name: "View Maria" });
+ expect(within(card).queryByText(/needs setup/i)).toBeNull();
+ });
+
+ test("shows feedback and re-enables Adopt when adoption fails", async () => {
+ const user = userEvent.setup();
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler422(),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Couldn't adopt Research Assistant",
+ variant: "destructive",
+ }),
+ ),
+ );
+ const adoptButton = within(agents).getByRole("button", { name: "Adopt" });
+ expect(adoptButton.hasAttribute("disabled")).toBe(false);
+ });
+
+ test("explains when an adopt version is no longer available", async () => {
+ const user = userEvent.setup();
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler404(),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ await user.click(within(agents).getByRole("button", { name: "Adopt" }));
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: "This Marketplace version is no longer available.",
+ }),
+ ),
+ );
+ });
+
+ test("tracks pending adoption by library agent id", async () => {
+ const user = userEvent.setup();
+ let installCalls = 0;
+ const sameGraphAgent = makeLibraryAgent({
+ ...adoptableAgent,
+ id: "lib-research-v2",
+ name: "Research Assistant v2",
+ });
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent, sameGraphAgent]),
+ ),
+ getInstallExpertWorkflowMockHandler(async () => {
+ installCalls += 1;
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ return {
+ id: "wf-adopted",
+ store_listing_version_id: "slv-adopt",
+ library_agent_id: "lib-research",
+ graph_id: "graph-research",
+ name: "Research Assistant",
+ description: null,
+ };
+ }),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ 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" });
+ await user.click(firstAdopt);
+ await waitFor(() => expect(firstAdopt.hasAttribute("disabled")).toBe(true));
+ expect(secondAdopt.hasAttribute("disabled")).toBe(false);
+ await user.click(firstAdopt);
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: "success" }),
+ ),
+ );
+ expect(installCalls).toBe(1);
+ });
+
+ test("shows a retry state when loading your agents fails", async () => {
+ const user = userEvent.setup();
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler401(),
+ );
+
+ render(<TeamPage />);
+
+ expect(
+ await screen.findByText(/could not load your agents/i),
+ ).toBeDefined();
+
+ server.use(
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([adoptableAgent]),
+ ),
+ );
+ await user.click(screen.getByRole("button", { name: "Retry" }));
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ expect(within(agents).getByText("Research Assistant")).toBeDefined();
+ });
+
+ test("shows filter-specific empty states for Workflows and Scheduled", async () => {
+ const user = userEvent.setup();
+ const emptyMaria: Expert = { ...hiredMaria, workflows: [] };
+ server.use(getListExpertsMockHandler([emptyMaria]));
+
+ render(<TeamPage />);
+
+ await screen.findByRole("region", { name: "What runs" });
+
+ await user.click(screen.getByRole("button", { name: "Workflows" }));
+ expect(screen.getByText("No workflows installed yet.")).toBeDefined();
+
+ await user.click(screen.getByRole("button", { name: "Scheduled" }));
+ expect(screen.getByText("No scheduled workflows yet.")).toBeDefined();
+ });
+
+ test("tells an empty library apart from a fully adopted one", async () => {
+ server.use(getListExpertsMockHandler([hiredMaria]));
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ expect(
+ await within(agents).findByText("No available agents to adopt."),
+ ).toBeDefined();
+ });
+
+ test("loads additional non-hidden library pages on demand", async () => {
+ const user = userEvent.setup();
+ const secondAgent = makeLibraryAgent({
+ id: "lib-second",
+ graph_id: "graph-second",
+ name: "Second-page Agent",
+ store_listing_version_id: "slv-second",
+ });
+ const requestedPages: string[] = [];
+ const hiddenFilters: string[] = [];
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(({ request }) => {
+ const params = new URL(request.url).searchParams;
+ const page = params.get("page") ?? "1";
+ requestedPages.push(page);
+ hiddenFilters.push(params.get("is_hidden") ?? "missing");
+ return page === "2"
+ ? libraryResponse([secondAgent], 101, 2)
+ : libraryResponse([adoptableAgent], 101, 1);
+ }),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ expect(within(agents).getByText("Research Assistant")).toBeDefined();
+ expect(within(agents).queryByText("Second-page Agent")).toBeNull();
+ expect(requestedPages).toEqual(["1"]);
+
+ await user.click(
+ within(agents).getByRole("button", { name: "Load more agents" }),
+ );
+
+ expect(await within(agents).findByText("Second-page Agent")).toBeDefined();
+ expect(requestedPages).toEqual(["1", "2"]);
+ expect(hiddenFilters).toEqual(["false", "false"]);
+ });
+
+ test("does not claim every agent is adopted while more pages remain", async () => {
+ const installedAgent = makeLibraryAgent({
+ id: "lib-installed",
+ graph_id: "graph-1",
+ name: "Content Calendar",
+ store_listing_version_id: "slv-1",
+ });
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ getGetV2ListLibraryAgentsMockHandler200(
+ libraryResponse([installedAgent], 101, 1),
+ ),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ expect(
+ within(agents).queryByText("Every agent is already on your team."),
+ ).toBeNull();
+ expect(
+ within(agents).getByRole("button", { name: "Load more agents" }),
+ ).toBeDefined();
+ });
+
+ test("keeps page one visible and retries when loading page two fails", async () => {
+ const user = userEvent.setup();
+ let pageTwoFails = true;
+ const secondAgent = makeLibraryAgent({
+ id: "lib-second",
+ graph_id: "graph-second",
+ name: "Recovered Agent",
+ store_listing_version_id: "slv-second",
+ });
+ server.use(
+ getListExpertsMockHandler([hiredMaria]),
+ http.get("/api/proxy/api/library/agents", ({ request }) => {
+ const page = new URL(request.url).searchParams.get("page") ?? "1";
+ if (page === "2" && pageTwoFails) {
+ return HttpResponse.json({ detail: "expired" }, { status: 401 });
+ }
+ return HttpResponse.json(
+ page === "2"
+ ? libraryResponse([secondAgent], 101, 2)
+ : libraryResponse([adoptableAgent], 101, 1),
+ );
+ }),
+ );
+
+ render(<TeamPage />);
+
+ const agents = await screen.findByRole("region", { name: "Your agents" });
+ expect(within(agents).getByText("Research Assistant")).toBeDefined();
+ await user.click(
+ within(agents).getByRole("button", { name: "Load more agents" }),
+ );
+
+ expect(
+ await within(agents).findByText("We could not load more agents."),
+ ).toBeDefined();
+ expect(within(agents).getByText("Research Assistant")).toBeDefined();
+
+ pageTwoFails = false;
+ await user.click(
+ within(agents).getByRole("button", { name: "Retry loading more" }),
+ );
+
+ expect(await within(agents).findByText("Recovered Agent")).toBeDefined();
+ });
+
+ test("shows last-run status as a chip beside the workflow count", async () => {
+ server.use(getListExpertsMockHandler([scheduledMaria]));
+
+ render(<TeamPage />);
+
+ const group = await screen.findByRole("region", { name: "Maria runs" });
+ expect(within(group).getByText("Maria · 2 workflows")).toBeDefined();
+ expect(within(group).getByText(/Last run succeeded/)).toBeDefined();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
index d116abb7be..f6d70c6e05 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
@@ -37,7 +37,7 @@ export function ExpertTeamCard({
onEditSoul,
}: Props) {
const workflowCount = expert.workflows.length;
- const needsSetupCount = getNeedsSetupCount(expert);
+ const needsSetupCount = getNeedsSetupCount(expert, schedules);
const scheduleLabel = getScheduleCountLabel(schedules);
const weeklySpend = getWeeklySpend(expert);
const { handleResume, isResuming, isFireOpen, openFire, closeFire } =
@@ -54,7 +54,7 @@ export function ExpertTeamCard({
}
return (
- <div className="relative flex flex-col gap-3 rounded-2xl border border-zinc-200 bg-white p-5 transition-[transform,border-color,box-shadow] duration-200 hover:-translate-y-0.5 hover:border-zinc-300 hover:shadow-[0_16px_40px_-16px_rgba(16,24,40,0.18)]">
+ <div className="relative flex flex-col gap-3 rounded-2xl border border-zinc-200 bg-white p-5 transition-[border-color,box-shadow] duration-200 hover:border-zinc-300 hover:shadow-[0_16px_40px_-16px_rgba(16,24,40,0.18)]">
<div className="absolute right-3 top-3 z-10">
<FireExpertMenu
expertName={expert.name}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/WhatRunsZone.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/WhatRunsZone.tsx
new file mode 100644
index 0000000000..571f6bf926
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/WhatRunsZone.tsx
@@ -0,0 +1,102 @@
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+import { Button } from "@/components/atoms/Button/Button";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
+import { Text } from "@/components/atoms/Text/Text";
+import { ExpertWorkflowGroup } from "./components/ExpertWorkflowGroup";
+import { WhatRunsFilters } from "./components/WhatRunsFilters";
+import { YourAgentsList } from "./components/YourAgentsList";
+import { WhatRunsFilter } from "./helpers";
+import { useWhatRunsZone } from "./useWhatRunsZone";
+
+type Props = {
+ experts: Expert[];
+ schedules: GraphExecutionJobInfo[];
+};
+
+const GROUP_EMPTY_MESSAGES: Partial<Record<WhatRunsFilter, string>> = {
+ workflows: "No workflows installed yet.",
+ scheduled: "No scheduled workflows yet.",
+};
+
+export function WhatRunsZone({ experts, schedules }: Props) {
+ const {
+ filter,
+ setFilter,
+ groups,
+ showAgents,
+ unadoptedAgents,
+ libraryAgentCount,
+ isLoadingAgents,
+ isErrorAgents,
+ hasMoreAgents,
+ isLoadingMoreAgents,
+ isErrorLoadingMoreAgents,
+ retryAgents,
+ loadMoreAgents,
+ adopt,
+ pendingLibraryAgentIDs,
+ adoptedTargetKeys,
+ } = useWhatRunsZone({
+ experts,
+ schedules,
+ enabled: experts.length > 0,
+ });
+
+ if (experts.length === 0) return null;
+
+ const groupEmptyMessage = GROUP_EMPTY_MESSAGES[filter];
+
+ return (
+ <section aria-label="What runs" className="flex flex-col gap-4">
+ <div className="flex flex-col gap-1">
+ <Text variant="h3">What runs</Text>
+ <Text variant="body" className="max-w-prose text-zinc-600">
+ Workflows installed on your experts, plus agents you can adopt.
+ </Text>
+ </div>
+
+ <WhatRunsFilters value={filter} onChange={setFilter} />
+
+ {groups.length > 0 ? (
+ <div className="flex flex-col gap-3">
+ {groups.map((group) => (
+ <ExpertWorkflowGroup key={group.expert.id} group={group} />
+ ))}
+ </div>
+ ) : groupEmptyMessage ? (
+ <Text variant="small" className="text-zinc-500">
+ {groupEmptyMessage}
+ </Text>
+ ) : null}
+
+ {showAgents ? (
+ isLoadingAgents ? (
+ <Skeleton className="h-24 w-full rounded-2xl" />
+ ) : isErrorAgents ? (
+ <div className="flex items-center justify-between gap-3 rounded-2xl border border-zinc-200 bg-white px-4 py-3">
+ <Text variant="small" className="text-zinc-500">
+ We could not load your agents.
+ </Text>
+ <Button variant="secondary" size="small" onClick={retryAgents}>
+ Retry
+ </Button>
+ </div>
+ ) : (
+ <YourAgentsList
+ agents={unadoptedAgents}
+ experts={experts}
+ libraryAgentCount={libraryAgentCount}
+ pendingLibraryAgentIDs={pendingLibraryAgentIDs}
+ adoptedTargetKeys={adoptedTargetKeys}
+ hasMoreAgents={hasMoreAgents}
+ isLoadingMoreAgents={isLoadingMoreAgents}
+ isErrorLoadingMoreAgents={isErrorLoadingMoreAgents}
+ onLoadMore={loadMoreAgents}
+ onAdopt={adopt}
+ />
+ )
+ ) : null}
+ </section>
+ );
+}
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
new file mode 100644
index 0000000000..38589b5d71
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/AdoptAgentButton.tsx
@@ -0,0 +1,89 @@
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/molecules/Popover/Popover";
+import { useState } from "react";
+
+type Props = {
+ agent: LibraryAgent;
+ experts: Expert[];
+ isPending: boolean;
+ onAdopt: (agent: LibraryAgent, expert: Expert) => void;
+};
+
+export function AdoptAgentButton({
+ agent,
+ experts,
+ isPending,
+ onAdopt,
+}: Props) {
+ const [open, setOpen] = useState(false);
+
+ function handleSelect(expert: Expert) {
+ setOpen(false);
+ onAdopt(agent, expert);
+ }
+
+ function handleSingleExpert() {
+ const expert = experts[0];
+ if (expert) onAdopt(agent, expert);
+ }
+
+ if (experts.length === 1) {
+ return (
+ <Button
+ variant="secondary"
+ size="small"
+ loading={isPending}
+ onClick={handleSingleExpert}
+ >
+ Adopt
+ </Button>
+ );
+ }
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button variant="secondary" size="small" loading={isPending}>
+ Adopt
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-72 p-2">
+ <Text variant="small-medium" className="px-2 pb-1 pt-1 text-zinc-500">
+ Choose an expert
+ </Text>
+ <div className="flex flex-col">
+ {experts.map((expert) => (
+ <button
+ key={expert.id}
+ type="button"
+ onClick={() => handleSelect(expert)}
+ className="flex items-start gap-2 rounded-lg px-2 py-2 text-left hover:bg-zinc-50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-900"
+ >
+ <ExpertAvatar
+ name={expert.name}
+ avatarUrl={expert.avatar_url ?? null}
+ size={28}
+ />
+ <div className="min-w-0 flex-1">
+ <Text variant="body" className="truncate">
+ {expert.name}
+ </Text>
+ <Text variant="small" className="text-zinc-500">
+ Adds this agent to {expert.name}&apos;s workflows.
+ </Text>
+ </div>
+ </button>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/ExpertWorkflowGroup.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/ExpertWorkflowGroup.tsx
new file mode 100644
index 0000000000..516c23bb68
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/ExpertWorkflowGroup.tsx
@@ -0,0 +1,125 @@
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import { safeHumanizeCronExpression } from "@/lib/cron-expression-utils";
+import { FlashIcon } from "@hugeicons/core-free-icons";
+import Link from "next/link";
+import { getLastRunLabel, workflowNeedsSetup } from "../../../helpers";
+import { STATUS_BADGE_CLASS } from "../constants";
+import { ExpertWorkflowGroupData } from "../helpers";
+
+type Props = {
+ group: ExpertWorkflowGroupData;
+};
+
+export function ExpertWorkflowGroup({ group }: Props) {
+ const { expert, workflows } = group;
+ const lastRun = getLastRunLabel(expert);
+ const countLabel = `${workflows.length} ${workflows.length === 1 ? "workflow" : "workflows"}`;
+ const isPaused = Boolean(expert.schedules_paused_at);
+ const lastRunVariant =
+ expert.last_run_status === "FAILED"
+ ? "error"
+ : expert.last_run_status === "COMPLETED"
+ ? "success"
+ : "info";
+
+ return (
+ <section
+ aria-label={`${expert.name} runs`}
+ className="rounded-2xl border border-zinc-200 bg-white"
+ >
+ <div className="flex flex-wrap items-center gap-3 border-b border-zinc-100 px-4 py-3">
+ <ExpertAvatar
+ name={expert.name}
+ avatarUrl={expert.avatar_url ?? null}
+ size={32}
+ />
+ <div className="min-w-0 flex-1">
+ <Text variant="large-medium" className="truncate">
+ {`${expert.name} · ${countLabel}`}
+ </Text>
+ </div>
+ {lastRun ? (
+ <Badge
+ variant={lastRunVariant}
+ className={`shrink-0 ${STATUS_BADGE_CLASS}`}
+ >
+ {lastRun}
+ </Badge>
+ ) : null}
+ {isPaused ? (
+ <Badge variant="info" className={`shrink-0 ${STATUS_BADGE_CLASS}`}>
+ Paused
+ </Badge>
+ ) : null}
+ </div>
+
+ {workflows.length === 0 ? (
+ <div className="px-4 py-3">
+ <Text variant="small" className="text-zinc-500">
+ Nothing installed yet —{" "}
+ <Link href="/marketplace" className="underline">
+ browse marketplace
+ </Link>
+ </Text>
+ </div>
+ ) : (
+ <div className="divide-y divide-zinc-100">
+ {workflows.map(({ workflow, schedules }) => {
+ const needsSetup = workflowNeedsSetup(workflow, schedules);
+ const setupHref = workflow.library_agent_id
+ ? `/library/agents/${workflow.library_agent_id}`
+ : "/marketplace";
+ return (
+ <div
+ key={workflow.id}
+ data-testid="what-runs-workflow-row"
+ className="flex flex-wrap items-center gap-3 px-4 py-3"
+ >
+ <Icon
+ icon={FlashIcon}
+ size={18}
+ aria-hidden="true"
+ className="shrink-0 text-zinc-400"
+ />
+ <div className="min-w-0 flex-1">
+ <Text variant="body" className="truncate">
+ {workflow.name ?? "Unnamed workflow"}
+ </Text>
+ </div>
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
+ {needsSetup && !isPaused ? (
+ <>
+ <Badge variant="info" className={STATUS_BADGE_CLASS}>
+ Needs setup
+ </Badge>
+ <Link
+ href={setupHref}
+ className="rounded-sm text-sm font-medium text-zinc-700 underline underline-offset-2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-900"
+ >
+ Set up
+ </Link>
+ </>
+ ) : null}
+ {!isPaused
+ ? schedules.map((schedule) => (
+ <Badge
+ key={schedule.id}
+ variant="info"
+ className={STATUS_BADGE_CLASS}
+ >
+ {safeHumanizeCronExpression(schedule.cron)}
+ </Badge>
+ ))
+ : null}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/WhatRunsFilters.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/WhatRunsFilters.tsx
new file mode 100644
index 0000000000..c31bb0931d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/WhatRunsFilters.tsx
@@ -0,0 +1,33 @@
+import { cn } from "@/lib/utils";
+import { WHAT_RUNS_FILTERS, WhatRunsFilter } from "../helpers";
+
+type Props = {
+ value: WhatRunsFilter;
+ onChange: (filter: WhatRunsFilter) => void;
+};
+
+export function WhatRunsFilters({ value, onChange }: Props) {
+ return (
+ <div className="flex flex-wrap gap-2" role="group" aria-label="Filter">
+ {WHAT_RUNS_FILTERS.map((chip) => {
+ const isActive = chip.id === value;
+ return (
+ <button
+ key={chip.id}
+ type="button"
+ aria-pressed={isActive}
+ onClick={() => onChange(chip.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",
+ isActive
+ ? "bg-zinc-800 text-white"
+ : "bg-zinc-100 text-zinc-600 hover:bg-zinc-200",
+ )}
+ >
+ {chip.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
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
new file mode 100644
index 0000000000..f6eeea0d7c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/components/YourAgentsList.tsx
@@ -0,0 +1,136 @@
+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 { AdoptAgentButton } from "./AdoptAgentButton";
+
+type Props = {
+ agents: LibraryAgent[];
+ experts: Expert[];
+ libraryAgentCount: number;
+ pendingLibraryAgentIDs: Set<string>;
+ adoptedTargetKeys: Set<string>;
+ hasMoreAgents: boolean;
+ isLoadingMoreAgents: boolean;
+ isErrorLoadingMoreAgents: boolean;
+ onLoadMore: () => void;
+ onAdopt: (agent: LibraryAgent, expert: Expert) => void;
+};
+
+export function YourAgentsList({
+ agents,
+ experts,
+ libraryAgentCount,
+ pendingLibraryAgentIDs,
+ adoptedTargetKeys,
+ hasMoreAgents,
+ isLoadingMoreAgents,
+ isErrorLoadingMoreAgents,
+ onLoadMore,
+ onAdopt,
+}: Props) {
+ return (
+ <section aria-label="Your agents" className="flex flex-col gap-2">
+ <Text variant="small-medium" className="text-zinc-500">
+ Your agents
+ </Text>
+ {agents.length === 0 ? (
+ !hasMoreAgents ? (
+ <Text variant="small" className="text-zinc-500">
+ {libraryAgentCount === 0
+ ? "No available agents to adopt."
+ : "Every agent 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,
+ adoptedTargetKeys,
+ );
+ return (
+ <div
+ key={agent.id}
+ data-testid="what-runs-agent-row"
+ className="flex items-center gap-3 px-4 py-3"
+ >
+ <ExpertAvatar
+ name={agent.name}
+ avatarUrl={agent.image_url ?? null}
+ size={32}
+ />
+ <div className="min-w-0 flex-1">
+ <Text variant="body" className="truncate">
+ {agent.name}
+ </Text>
+ <Text variant="small" className="text-zinc-500">
+ {agent.creator_name}
+ </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>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ {isErrorLoadingMoreAgents ? (
+ <div className="flex items-center justify-between gap-3 rounded-xl border border-zinc-200 px-3 py-2">
+ <Text variant="small" className="text-zinc-500">
+ We could not load more agents.
+ </Text>
+ <Button variant="secondary" size="small" onClick={onLoadMore}>
+ Retry loading more
+ </Button>
+ </div>
+ ) : hasMoreAgents ? (
+ <Button
+ variant="secondary"
+ size="small"
+ loading={isLoadingMoreAgents}
+ onClick={onLoadMore}
+ className="self-start"
+ >
+ Load more agents
+ </Button>
+ ) : null}
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/constants.ts b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/constants.ts
new file mode 100644
index 0000000000..7fd4cff27e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/constants.ts
@@ -0,0 +1 @@
+export const STATUS_BADGE_CLASS = "normal-case tracking-normal";
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
new file mode 100644
index 0000000000..e3bfce3afc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.test.ts
@@ -0,0 +1,351 @@
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { ExpertWorkflowRef } from "@/app/api/__generated__/models/expertWorkflowRef";
+import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { describe, expect, it } from "vitest";
+import {
+ getGraphWorkflowCounts,
+ getWorkflowSchedules,
+ workflowNeedsSetup,
+} from "../../helpers";
+import {
+ getAdoptableExperts,
+ getAdoptTargetKey,
+ getAdoptTargetVersionID,
+ getFilterView,
+ getUnadoptedAgents,
+ getVisibleGroups,
+ pruneAdoptedTargetKeys,
+} from "./helpers";
+
+function makeWorkflow(over: Partial<ExpertWorkflowRef>): ExpertWorkflowRef {
+ return {
+ id: "wf",
+ store_listing_version_id: "slv",
+ library_agent_id: "lib",
+ graph_id: "graph",
+ name: "Workflow",
+ description: null,
+ ...over,
+ };
+}
+
+function makeExpert(over: Partial<Expert>): Expert {
+ return { id: "expert", name: "Expert", workflows: [], ...over } as Expert;
+}
+
+function makeAgent(over: Partial<LibraryAgent>): LibraryAgent {
+ return {
+ id: "agent",
+ graph_id: "graph",
+ name: "Agent",
+ store_listing_version_id: null,
+ ...over,
+ } as unknown as LibraryAgent;
+}
+
+function makeSchedule(
+ over: Partial<GraphExecutionJobInfo>,
+): GraphExecutionJobInfo {
+ return {
+ id: "schedule",
+ name: "Schedule",
+ user_id: "user",
+ graph_id: "graph-scheduled",
+ graph_version: 1,
+ cron: "40 7 * * *",
+ input_data: {},
+ next_run_time: "2026-08-15T07:40:00Z",
+ expert_id: "a",
+ ...over,
+ };
+}
+
+describe("getFilterView", () => {
+ it("shows both groups and agents for all", () => {
+ expect(getFilterView("all")).toEqual({
+ showGroups: true,
+ showAgents: true,
+ includeEmptyGroups: true,
+ scheduledOnly: false,
+ });
+ });
+
+ it("hides agents but keeps empty groups for members", () => {
+ const view = getFilterView("members");
+ expect(view.showGroups).toBe(true);
+ expect(view.showAgents).toBe(false);
+ expect(view.includeEmptyGroups).toBe(true);
+ });
+
+ it("shows only agents for agents", () => {
+ expect(getFilterView("agents")).toMatchObject({
+ showGroups: false,
+ showAgents: true,
+ });
+ });
+
+ it("drops empty groups for workflows", () => {
+ expect(getFilterView("workflows").includeEmptyGroups).toBe(false);
+ });
+
+ it("keeps only scheduled rows for scheduled", () => {
+ expect(getFilterView("scheduled")).toMatchObject({
+ scheduledOnly: true,
+ includeEmptyGroups: false,
+ });
+ });
+});
+
+describe("getVisibleGroups", () => {
+ const withWorkflows = makeExpert({
+ id: "a",
+ workflows: [
+ makeWorkflow({
+ id: "s",
+ graph_id: "graph-scheduled",
+ schedule_id: "sched",
+ schedule_cron: "40 7 * * *",
+ }),
+ makeWorkflow({ id: "u", graph_id: "graph-unscheduled" }),
+ ],
+ });
+ const empty = makeExpert({ id: "b", workflows: [] });
+ const schedules = [makeSchedule({})];
+
+ it("keeps empty groups for all and members", () => {
+ expect(
+ getVisibleGroups([withWorkflows, empty], schedules, "all"),
+ ).toHaveLength(2);
+ expect(
+ getVisibleGroups([withWorkflows, empty], schedules, "members"),
+ ).toHaveLength(2);
+ });
+
+ it("drops empty groups for workflows", () => {
+ const groups = getVisibleGroups(
+ [withWorkflows, empty],
+ schedules,
+ "workflows",
+ );
+ expect(groups).toHaveLength(1);
+ expect(groups[0].expert.id).toBe("a");
+ });
+
+ it("keeps only workflows with scheduler jobs for scheduled", () => {
+ const groups = getVisibleGroups(
+ [withWorkflows, empty],
+ schedules,
+ "scheduled",
+ );
+ expect(groups).toHaveLength(1);
+ expect(groups[0].workflows.map((item) => item.workflow.id)).toEqual(["s"]);
+ });
+
+ it("returns no groups for agents", () => {
+ expect(
+ getVisibleGroups([withWorkflows, empty], schedules, "agents"),
+ ).toHaveLength(0);
+ });
+
+ it("ignores a stale workflow schedule id when no scheduler job exists", () => {
+ expect(getVisibleGroups([withWorkflows], [], "scheduled")).toEqual([]);
+ });
+
+ it("keeps every scheduler job for a workflow", () => {
+ const groups = getVisibleGroups(
+ [withWorkflows],
+ [makeSchedule({ id: "one" }), makeSchedule({ id: "two" })],
+ "scheduled",
+ );
+ expect(
+ groups[0].workflows[0].schedules.map((schedule) => schedule.id),
+ ).toEqual(["one", "two"]);
+ });
+
+ it("does not assign one graph schedule to multiple workflow snapshots", () => {
+ const first = makeWorkflow({
+ id: "first",
+ graph_id: "shared-graph",
+ schedule_id: "first-schedule",
+ });
+ const second = makeWorkflow({
+ id: "second",
+ graph_id: "shared-graph",
+ schedule_id: null,
+ });
+ const expert = makeExpert({
+ id: "a",
+ workflows: [first, second],
+ });
+ const groups = getVisibleGroups(
+ [expert],
+ [makeSchedule({ id: "first-schedule", graph_id: "shared-graph" })],
+ "all",
+ );
+
+ expect(groups[0].workflows[0].schedules).toHaveLength(1);
+ expect(groups[0].workflows[1].schedules).toHaveLength(0);
+ });
+
+ it("leaves a manual graph schedule unassigned when snapshots are ambiguous", () => {
+ const workflows = [
+ makeWorkflow({ id: "first", graph_id: "shared-graph" }),
+ makeWorkflow({ id: "second", graph_id: "shared-graph" }),
+ ];
+ const schedule = makeSchedule({ id: "manual", graph_id: "shared-graph" });
+
+ const graphWorkflowCounts = getGraphWorkflowCounts(workflows);
+ expect(
+ getWorkflowSchedules(workflows[0], [schedule], graphWorkflowCounts),
+ ).toEqual([]);
+ expect(
+ getWorkflowSchedules(workflows[1], [schedule], graphWorkflowCounts),
+ ).toEqual([]);
+ });
+});
+
+describe("getUnadoptedAgents", () => {
+ it("excludes an exact version when every expert already has it", () => {
+ const experts = [
+ makeExpert({
+ id: "a",
+ workflows: [
+ makeWorkflow({
+ graph_id: "graph-installed",
+ store_listing_version_id: "slv-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"]);
+ });
+
+ 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",
+ });
+
+ expect(getUnadoptedAgents([newer], [expert])).toEqual([newer]);
+ });
+
+ it("keeps an agent visible while another expert can adopt it", () => {
+ const installed = makeExpert({
+ id: "installed",
+ workflows: [makeWorkflow({ store_listing_version_id: "slv-shared" })],
+ });
+ const available = makeExpert({ id: "available", workflows: [] });
+ const agent = makeAgent({ store_listing_version_id: "slv-shared" });
+
+ expect(getUnadoptedAgents([agent], [installed, available])).toEqual([
+ agent,
+ ]);
+ expect(getAdoptableExperts(agent, [installed, available])).toEqual([
+ available,
+ ]);
+
+ const optimistic = new Set([getAdoptTargetKey(agent, available)]);
+ expect(
+ 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("returns null for a pure-local agent", () => {
+ expect(
+ getAdoptTargetVersionID(makeAgent({ store_listing_version_id: null })),
+ ).toBe(null);
+ });
+});
+
+describe("pruneAdoptedTargetKeys", () => {
+ it("removes confirmed and fired-expert targets before the set grows", () => {
+ const pending = makeExpert({ id: "pending", workflows: [] });
+ const confirmed = makeExpert({
+ id: "confirmed",
+ workflows: [makeWorkflow({ store_listing_version_id: "slv-exact" })],
+ });
+ const fired = makeExpert({ id: "fired", workflows: [] });
+ const agent = makeAgent({ store_listing_version_id: "slv-exact" });
+ const keys = new Set([
+ getAdoptTargetKey(agent, pending),
+ getAdoptTargetKey(agent, confirmed),
+ getAdoptTargetKey(agent, fired),
+ ]);
+
+ expect(pruneAdoptedTargetKeys(keys, [agent], [pending, confirmed])).toEqual(
+ new Set([getAdoptTargetKey(agent, pending)]),
+ );
+ });
+
+ 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 keys = new Set([getAdoptTargetKey(agent, expert)]);
+
+ expect(pruneAdoptedTargetKeys(keys, [agent], [expert])).toBe(keys);
+ });
+});
+
+describe("workflow schedule helpers", () => {
+ it("marks cron without a schedule id as needing setup", () => {
+ expect(
+ workflowNeedsSetup(makeWorkflow({ schedule_cron: "40 7 * * *" })),
+ ).toBe(true);
+ expect(
+ workflowNeedsSetup(
+ makeWorkflow({ schedule_cron: "40 7 * * *", schedule_id: "x" }),
+ ),
+ ).toBe(false);
+ });
+
+ it("uses scheduler jobs instead of a stale schedule id when supplied", () => {
+ const workflow = makeWorkflow({
+ graph_id: "graph-scheduled",
+ schedule_cron: "40 7 * * *",
+ schedule_id: "stale",
+ });
+ expect(workflowNeedsSetup(workflow, [])).toBe(true);
+ expect(
+ workflowNeedsSetup(
+ workflow,
+ getWorkflowSchedules(
+ workflow,
+ [makeSchedule({ id: "active" })],
+ getGraphWorkflowCounts([workflow]),
+ ),
+ ),
+ ).toBe(false);
+ });
+});
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
new file mode 100644
index 0000000000..2804aff495
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/helpers.ts
@@ -0,0 +1,187 @@
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { ExpertWorkflowRef } from "@/app/api/__generated__/models/expertWorkflowRef";
+import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import {
+ getExpertSchedules,
+ getGraphWorkflowCounts,
+ getWorkflowSchedules,
+} from "../../helpers";
+
+export type WhatRunsFilter =
+ | "all"
+ | "members"
+ | "agents"
+ | "workflows"
+ | "scheduled";
+
+export const WHAT_RUNS_FILTERS: { id: WhatRunsFilter; label: string }[] = [
+ { id: "all", label: "All" },
+ { id: "members", label: "Members" },
+ { id: "agents", label: "Agents" },
+ { id: "workflows", label: "Workflows" },
+ { id: "scheduled", label: "Scheduled" },
+];
+
+interface FilterView {
+ showGroups: boolean;
+ showAgents: boolean;
+ includeEmptyGroups: boolean;
+ scheduledOnly: boolean;
+}
+
+export function getFilterView(filter: WhatRunsFilter): FilterView {
+ switch (filter) {
+ case "members":
+ return {
+ showGroups: true,
+ showAgents: false,
+ includeEmptyGroups: true,
+ scheduledOnly: false,
+ };
+ case "agents":
+ return {
+ showGroups: false,
+ showAgents: true,
+ includeEmptyGroups: false,
+ scheduledOnly: false,
+ };
+ case "workflows":
+ return {
+ showGroups: true,
+ showAgents: false,
+ includeEmptyGroups: false,
+ scheduledOnly: false,
+ };
+ case "scheduled":
+ return {
+ showGroups: true,
+ showAgents: false,
+ includeEmptyGroups: false,
+ scheduledOnly: true,
+ };
+ case "all":
+ default:
+ return {
+ showGroups: true,
+ showAgents: true,
+ includeEmptyGroups: true,
+ scheduledOnly: false,
+ };
+ }
+}
+
+export interface ExpertWorkflowGroupData {
+ expert: Expert;
+ workflows: {
+ workflow: ExpertWorkflowRef;
+ schedules: GraphExecutionJobInfo[];
+ }[];
+}
+
+export function getVisibleGroups(
+ experts: Expert[],
+ schedules: GraphExecutionJobInfo[],
+ filter: WhatRunsFilter,
+): ExpertWorkflowGroupData[] {
+ const view = getFilterView(filter);
+ if (!view.showGroups) return [];
+ const groups: ExpertWorkflowGroupData[] = [];
+ for (const expert of experts) {
+ const expertSchedules = getExpertSchedules(expert, schedules);
+ const graphWorkflowCounts = getGraphWorkflowCounts(expert.workflows);
+ const workflows = expert.workflows.map((workflow) => ({
+ workflow,
+ schedules: getWorkflowSchedules(
+ workflow,
+ expertSchedules,
+ graphWorkflowCounts,
+ ),
+ }));
+ const visibleWorkflows = view.scheduledOnly
+ ? workflows.filter((item) => item.schedules.length > 0)
+ : workflows;
+ if (view.includeEmptyGroups || visibleWorkflows.length > 0) {
+ groups.push({ expert, workflows: visibleWorkflows });
+ }
+ }
+ 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. */
+export function getUnadoptedAgents(
+ agents: LibraryAgent[],
+ experts: Expert[],
+ adoptedTargetKeys?: ReadonlySet<string>,
+): LibraryAgent[] {
+ return agents.filter(
+ (agent) =>
+ !getAdoptTargetVersionID(agent) ||
+ getAdoptableExperts(agent, experts, adoptedTargetKeys).length > 0,
+ );
+}
+
+export function getAdoptableExperts(
+ agent: LibraryAgent,
+ 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)),
+ );
+}
+
+export function getAdoptTargetKey(agent: LibraryAgent, expert: Expert) {
+ return `${agent.id}:${expert.id}`;
+}
+
+function parseAdoptTargetKey(key: string) {
+ const separator = key.lastIndexOf(":");
+ if (separator < 1 || separator === key.length - 1) return null;
+ return {
+ agentID: key.slice(0, separator),
+ expertID: key.slice(separator + 1),
+ };
+}
+
+export function pruneAdoptedTargetKeys(
+ adoptedTargetKeys: Set<string>,
+ agents: LibraryAgent[],
+ experts: Expert[],
+) {
+ if (adoptedTargetKeys.size === 0) return adoptedTargetKeys;
+
+ const agentsByID = new Map(agents.map((agent) => [agent.id, agent]));
+ const expertsByID = new Map(experts.map((expert) => [expert.id, expert]));
+ const next = new Set<string>();
+ for (const key of adoptedTargetKeys) {
+ const target = parseAdoptTargetKey(key);
+ if (!target) continue;
+ 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);
+ }
+
+ 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;
+}
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
new file mode 100644
index 0000000000..100439a732
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/WhatRunsZone/useWhatRunsZone.ts
@@ -0,0 +1,132 @@
+import {
+ getListExpertsQueryKey,
+ useInstallExpertWorkflow,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { useGetV2ListLibraryAgentsInfinite } from "@/app/api/__generated__/endpoints/library/library";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { getPaginationNextPageNumber, unpaginate } from "@/app/api/helpers";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import { useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import {
+ getAdoptTargetKey,
+ getAdoptTargetVersionID,
+ getUnadoptedAgents,
+ getVisibleGroups,
+ pruneAdoptedTargetKeys,
+ WhatRunsFilter,
+} from "./helpers";
+
+const AGENTS_PAGE_SIZE = 100;
+
+function hasStatus(error: unknown, status: number) {
+ return (
+ typeof error === "object" &&
+ error !== null &&
+ "status" in error &&
+ error.status === status
+ );
+}
+
+interface Args {
+ experts: Expert[];
+ schedules: GraphExecutionJobInfo[];
+ enabled: boolean;
+}
+
+export function useWhatRunsZone({ experts, schedules, enabled }: Args) {
+ const queryClient = useQueryClient();
+ const [filter, setFilter] = useState<WhatRunsFilter>("all");
+ const [pendingLibraryAgentIDs, setPendingLibraryAgentIDs] = useState<
+ Set<string>
+ >(new Set());
+ const [adoptedTargetKeys, setAdoptedTargetKeys] = useState<Set<string>>(
+ new Set(),
+ );
+
+ const agentsQuery = useGetV2ListLibraryAgentsInfinite(
+ { page: 1, page_size: AGENTS_PAGE_SIZE, is_hidden: false },
+ {
+ query: {
+ enabled,
+ getNextPageParam: getPaginationNextPageNumber,
+ },
+ },
+ );
+
+ const { mutateAsync: installWorkflow } = useInstallExpertWorkflow();
+
+ const libraryAgents = agentsQuery.data
+ ? unpaginate(agentsQuery.data, "agents")
+ : [];
+ const unadoptedAgents = getUnadoptedAgents(
+ libraryAgents,
+ experts,
+ adoptedTargetKeys,
+ );
+ const groups = getVisibleGroups(experts, schedules, filter);
+ const showAgents = filter === "all" || filter === "agents";
+
+ async function adopt(agent: LibraryAgent, expert: Expert) {
+ const versionID = getAdoptTargetVersionID(agent);
+ if (!versionID || 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 },
+ });
+ setAdoptedTargetKeys((current) => {
+ const next = new Set(
+ pruneAdoptedTargetKeys(current, libraryAgents, experts),
+ );
+ next.add(targetKey);
+ return next;
+ });
+ await queryClient.invalidateQueries({
+ queryKey: getListExpertsQueryKey(),
+ });
+ toast({
+ title: `Added to ${expert.name}'s workflows`,
+ 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."
+ : "Something went wrong. Please try again.",
+ variant: "destructive",
+ });
+ } finally {
+ setPendingLibraryAgentIDs((current) => {
+ const next = new Set(current);
+ next.delete(agent.id);
+ return next;
+ });
+ }
+ }
+
+ return {
+ filter,
+ setFilter,
+ groups,
+ showAgents,
+ unadoptedAgents,
+ libraryAgentCount: libraryAgents.length,
+ isLoadingAgents: enabled && agentsQuery.isLoading,
+ isErrorAgents: agentsQuery.isError && !agentsQuery.data,
+ hasMoreAgents: agentsQuery.hasNextPage === true,
+ isLoadingMoreAgents: agentsQuery.isFetchingNextPage,
+ isErrorLoadingMoreAgents: agentsQuery.isFetchNextPageError,
+ retryAgents: () => void agentsQuery.refetch(),
+ loadMoreAgents: () => void agentsQuery.fetchNextPage(),
+ adopt,
+ pendingLibraryAgentIDs,
+ adoptedTargetKeys,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/team/helpers.ts
index 645290a2a2..a2e69c0e9a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/helpers.ts
@@ -19,12 +19,49 @@ export function getWeeklySpend(expert: Expert) {
return { spent: expert.weekly_spend ?? 0, budget: expert.weekly_budget };
}
-export function workflowNeedsSetup(workflow: ExpertWorkflowRef) {
- return Boolean(workflow.schedule_cron) && !workflow.schedule_id;
+export function getWorkflowSchedules(
+ workflow: ExpertWorkflowRef,
+ schedules: GraphExecutionJobInfo[],
+ graphWorkflowCounts: ReadonlyMap<ExpertWorkflowRef["graph_id"], number>,
+) {
+ const sameGraphWorkflowCount =
+ graphWorkflowCounts.get(workflow.graph_id) ?? 0;
+ return schedules.filter(
+ (schedule) =>
+ schedule.id === workflow.schedule_id ||
+ (sameGraphWorkflowCount === 1 && schedule.graph_id === workflow.graph_id),
+ );
+}
+
+export function getGraphWorkflowCounts(workflows: ExpertWorkflowRef[]) {
+ const counts = new Map<ExpertWorkflowRef["graph_id"], number>();
+ for (const workflow of workflows) {
+ counts.set(workflow.graph_id, (counts.get(workflow.graph_id) ?? 0) + 1);
+ }
+ return counts;
}
-export function getNeedsSetupCount(expert: Expert) {
- return expert.workflows.filter(workflowNeedsSetup).length;
+export function workflowNeedsSetup(
+ workflow: ExpertWorkflowRef,
+ schedules?: GraphExecutionJobInfo[],
+) {
+ const hasSchedule = schedules
+ ? schedules.length > 0
+ : Boolean(workflow.schedule_id);
+ return Boolean(workflow.schedule_cron) && !hasSchedule;
+}
+
+export function getNeedsSetupCount(
+ expert: Expert,
+ schedules?: GraphExecutionJobInfo[],
+) {
+ const graphWorkflowCounts = getGraphWorkflowCounts(expert.workflows);
+ return expert.workflows.filter((workflow) => {
+ const workflowSchedules = schedules
+ ? getWorkflowSchedules(workflow, schedules, graphWorkflowCounts)
+ : undefined;
+ return workflowNeedsSetup(workflow, workflowSchedules);
+ }).length;
}
/** Schedules belonging to an expert, soonest-firing first. Matches on the
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/page.tsx b/autogpt_platform/frontend/src/app/(platform)/team/page.tsx
index 937b969a8e..f7869292d6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/page.tsx
@@ -12,6 +12,7 @@ import { CreateMenu } from "./components/CreateMenu/CreateMenu";
import { EmptyTeamState } from "./components/EmptyTeamState";
import { ExpertTeamCard } from "./components/ExpertTeamCard/ExpertTeamCard";
import { SoulDrawer } from "./components/SoulDrawer/SoulDrawer";
+import { WhatRunsZone } from "./components/WhatRunsZone/WhatRunsZone";
import { useTeamPage } from "./useTeamPage";
const MAIN_CLASS =
@@ -22,6 +23,7 @@ export default function TeamPage() {
const { enabled, ready } = useFlagStatus(Flag.HIRE_EXPERTS);
const {
hiredExperts,
+ schedules,
schedulesForExpert,
isLoading,
isError,
@@ -56,7 +58,7 @@ export default function TeamPage() {
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2.5">
- <AITeamIcon size={36} className="shrink-0 text-black" />
+ <AITeamIcon size={36} className="shrink-0 text-zinc-950" />
<Text variant="h3">Your Team</Text>
</div>
<Text variant="body" className="max-w-prose text-zinc-600">
@@ -81,6 +83,9 @@ export default function TeamPage() {
/>
))}
</div>
+ {!isLoading && !isError && hiredExperts.length > 0 ? (
+ <WhatRunsZone experts={hiredExperts} schedules={schedules} />
+ ) : null}
{isError ? (
<ErrorCard
context="your team"
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/useTeamPage.ts b/autogpt_platform/frontend/src/app/(platform)/team/useTeamPage.ts
index 3d6d3d690f..5f91e43f06 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/useTeamPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/team/useTeamPage.ts
@@ -24,9 +24,10 @@ export function useTeamPage({ enabled }: Args) {
const hiredExperts = (expertsQuery.data ?? []).filter(
(expert) => !expert.is_template && !expert.is_archived,
);
+ const schedules = schedulesQuery.data ?? [];
function schedulesForExpert(expert: Expert) {
- return getExpertSchedules(expert, schedulesQuery.data ?? []);
+ return getExpertSchedules(expert, schedules);
}
function installWorkflow(expertId: string) {
@@ -52,6 +53,7 @@ export function useTeamPage({ enabled }: Args) {
return {
hiredExperts,
+ schedules,
schedulesForExpert,
isLoading: enabled && (expertsQuery.isLoading || schedulesQuery.isLoading),
isError: expertsQuery.isError || schedulesQuery.isError,
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 5a8027d9f3..a59aa9cdff 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -20305,6 +20305,11 @@
{ "$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/contextual/SchedulesPanel/components/FollowupListItem/useFollowupListItem.ts b/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/FollowupListItem/useFollowupListItem.ts
index ce0736a0aa..c11daf46d1 100644
--- a/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/FollowupListItem/useFollowupListItem.ts
+++ b/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/FollowupListItem/useFollowupListItem.ts
@@ -1,7 +1,7 @@
import { useDeleteV1DeleteExecutionSchedule } from "@/app/api/__generated__/endpoints/schedules/schedules";
import type { CopilotTurnJobInfo } from "@/app/api/__generated__/models/copilotTurnJobInfo";
import { useToast } from "@/components/molecules/Toast/use-toast";
-import { humanizeCronExpression } from "@/lib/cron-expression-utils";
+import { safeHumanizeCronExpression } from "@/lib/cron-expression-utils";
import { invalidateAllScheduleQueries } from "@/services/schedules/invalidate-schedules";
import { useQueryClient } from "@tanstack/react-query";
import { formatDistanceToNow } from "date-fns";
@@ -36,7 +36,7 @@ export function useFollowupListItem({ followup }: Args) {
);
const recurrenceLabel = followup.cron
- ? safeHumanizeCron(followup.cron)
+ ? safeHumanizeCronExpression(followup.cron)
: "Runs once";
function openDelete() {
@@ -90,11 +90,3 @@ export function useFollowupListItem({ followup }: Args) {
fullMessage: followup.message || "(no message)",
};
}
-
-function safeHumanizeCron(cron: string): string {
- try {
- return humanizeCronExpression(cron);
- } catch {
- return cron;
- }
-}
diff --git a/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/GraphScheduleListItem/useGraphScheduleListItem.ts b/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/GraphScheduleListItem/useGraphScheduleListItem.ts
index 3d2d5b493c..3540352a20 100644
--- a/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/GraphScheduleListItem/useGraphScheduleListItem.ts
+++ b/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/GraphScheduleListItem/useGraphScheduleListItem.ts
@@ -1,7 +1,7 @@
import { useDeleteV1DeleteExecutionSchedule } from "@/app/api/__generated__/endpoints/schedules/schedules";
import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
import { useToast } from "@/components/molecules/Toast/use-toast";
-import { humanizeCronExpression } from "@/lib/cron-expression-utils";
+import { safeHumanizeCronExpression } from "@/lib/cron-expression-utils";
import { invalidateAllScheduleQueries } from "@/services/schedules/invalidate-schedules";
import { useQueryClient } from "@tanstack/react-query";
import { formatDistanceToNow } from "date-fns";
@@ -31,7 +31,7 @@ export function useGraphScheduleListItem({ schedule }: Args) {
const nextRunTitle = nextRunDate ? nextRunDate.toString() : undefined;
const recurrenceLabel = schedule.cron
- ? safeHumanizeCron(schedule.cron)
+ ? safeHumanizeCronExpression(schedule.cron)
: "Runs once";
const agentLabel = schedule.agent_name || schedule.name || "Scheduled agent";
@@ -85,11 +85,3 @@ export function useGraphScheduleListItem({ schedule }: Args) {
closeView,
};
}
-
-function safeHumanizeCron(cron: string): string {
- try {
- return humanizeCronExpression(cron);
- } catch {
- return cron;
- }
-}
diff --git a/autogpt_platform/frontend/src/lib/cron-expression-utils.test.ts b/autogpt_platform/frontend/src/lib/cron-expression-utils.test.ts
index 66a8a4572b..e1ec088471 100644
--- a/autogpt_platform/frontend/src/lib/cron-expression-utils.test.ts
+++ b/autogpt_platform/frontend/src/lib/cron-expression-utils.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
-import { humanizeCronExpression } from "./cron-expression-utils";
+import {
+ humanizeCronExpression,
+ safeHumanizeCronExpression,
+} from "./cron-expression-utils";
describe("humanizeCronExpression", () => {
it("renders comma-separated weekdays", () => {
@@ -33,3 +36,9 @@ describe("humanizeCronExpression", () => {
);
});
});
+
+describe("safeHumanizeCronExpression", () => {
+ it("uses a generic label for malformed cron expressions", () => {
+ expect(safeHumanizeCronExpression("not-a-cron")).toBe("Scheduled");
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/cron-expression-utils.ts b/autogpt_platform/frontend/src/lib/cron-expression-utils.ts
index e5e4641747..1a277b5137 100644
--- a/autogpt_platform/frontend/src/lib/cron-expression-utils.ts
+++ b/autogpt_platform/frontend/src/lib/cron-expression-utils.ts
@@ -219,6 +219,14 @@ export function humanizeCronExpression(cronExpression: string): string {
return `Cron Expression: ${cronExpression}`;
}
+export function safeHumanizeCronExpression(cronExpression: string): string {
+ try {
+ return humanizeCronExpression(cronExpression);
+ } catch {
+ return "Scheduled";
+ }
+}
+
function formatTime(hour: string, minute: string): string {
// Cron expressions are now stored in the schedule's timezone (not UTC)
// So we just format the time as-is without conversion