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(library): implement folder organization system for agents (#12101)

Abhimanyu Yadav2136defea870
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index e07ed9f7ad..db52ca89b0 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -1,4 +1,5 @@
import asyncio
+import itertools
import logging
from typing import Literal, Optional
@@ -12,10 +13,18 @@ import backend.api.features.store.image_gen as store_image_gen
import backend.api.features.store.media as store_media
import backend.data.graph as graph_db
import backend.data.integrations as integrations_db
+from backend.api.features.library.exceptions import (
+ FolderAlreadyExistsError,
+ FolderValidationError,
+)
from backend.data.db import transaction
from backend.data.execution import get_graph_execution
from backend.data.graph import GraphSettings
-from backend.data.includes import AGENT_PRESET_INCLUDE, library_agent_include
+from backend.data.includes import (
+ AGENT_PRESET_INCLUDE,
+ LIBRARY_FOLDER_INCLUDE,
+ library_agent_include,
+)
from backend.data.model import CredentialsMetaInput, GraphInput
from backend.integrations.creds_manager import IntegrationCredentialsManager
from backend.integrations.webhooks.graph_lifecycle_hooks import (
@@ -23,7 +32,7 @@ from backend.integrations.webhooks.graph_lifecycle_hooks import (
on_graph_deactivate,
)
from backend.util.clients import get_scheduler_client
-from backend.util.exceptions import DatabaseError, InvalidInputError, NotFoundError
+from backend.util.exceptions import InvalidInputError, NotFoundError
from backend.util.json import SafeJson
from backend.util.models import Pagination
from backend.util.settings import Config
@@ -42,6 +51,8 @@ async def list_library_agents(
page: int = 1,
page_size: int = 50,
include_executions: bool = False,
+ folder_id: Optional[str] = None,
+ include_root_only: bool = False,
) -> library_model.LibraryAgentResponse:
"""
Retrieves a paginated list of LibraryAgent records for a given user.
@@ -52,6 +63,8 @@ async def list_library_agents(
sort_by: Sorting field (createdAt, updatedAt, isFavorite, isCreatedByUser).
page: Current page (1-indexed).
page_size: Number of items per page.
+ folder_id: Filter by folder ID. If provided, only returns agents in this folder.
+ include_root_only: If True, only returns agents without a folder (root-level).
include_executions: Whether to include execution data for status calculation.
Defaults to False for performance (UI fetches status separately).
Set to True when accurate status/metrics are needed (e.g., agent generator).
@@ -82,6 +95,13 @@ async def list_library_agents(
"isArchived": False,
}
+ # Apply folder filter (skip when searching — search spans all folders)
+ if folder_id is not None and not search_term:
+ where_clause["folderId"] = folder_id
+ elif include_root_only and not search_term:
+ where_clause["folderId"] = None
+
+ # Build search filter if applicable
if search_term:
where_clause["OR"] = [
{
@@ -105,52 +125,41 @@ async def list_library_agents(
elif sort_by == library_model.LibraryAgentSort.UPDATED_AT:
order_by = {"updatedAt": "desc"}
- try:
- library_agents = await prisma.models.LibraryAgent.prisma().find_many(
- where=where_clause,
- include=library_agent_include(
- user_id, include_nodes=False, include_executions=include_executions
- ),
- order=order_by,
- skip=(page - 1) * page_size,
- take=page_size,
- )
- agent_count = await prisma.models.LibraryAgent.prisma().count(
- where=where_clause
- )
+ library_agents = await prisma.models.LibraryAgent.prisma().find_many(
+ where=where_clause,
+ include=library_agent_include(
+ user_id, include_nodes=False, include_executions=include_executions
+ ),
+ order=order_by,
+ skip=(page - 1) * page_size,
+ take=page_size,
+ )
+ agent_count = await prisma.models.LibraryAgent.prisma().count(where=where_clause)
- logger.debug(
- f"Retrieved {len(library_agents)} library agents for user #{user_id}"
- )
+ logger.debug(f"Retrieved {len(library_agents)} library agents for user #{user_id}")
- # Only pass valid agents to the response
- valid_library_agents: list[library_model.LibraryAgent] = []
-
- for agent in library_agents:
- try:
- library_agent = library_model.LibraryAgent.from_db(agent)
- valid_library_agents.append(library_agent)
- except Exception as e:
- # Skip this agent if there was an error
- logger.error(
- f"Error parsing LibraryAgent #{agent.id} from DB item: {e}"
- )
- continue
-
- # Return the response with only valid agents
- return library_model.LibraryAgentResponse(
- agents=valid_library_agents,
- pagination=Pagination(
- total_items=agent_count,
- total_pages=(agent_count + page_size - 1) // page_size,
- current_page=page,
- page_size=page_size,
- ),
- )
+ # Only pass valid agents to the response
+ valid_library_agents: list[library_model.LibraryAgent] = []
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error fetching library agents: {e}")
- raise DatabaseError("Failed to fetch library agents") from e
+ for agent in library_agents:
+ try:
+ library_agent = library_model.LibraryAgent.from_db(agent)
+ valid_library_agents.append(library_agent)
+ except Exception as e:
+ # Skip this agent if there was an error
+ logger.error(f"Error parsing LibraryAgent #{agent.id} from DB item: {e}")
+ continue
+
+ # Return the response with only valid agents
+ return library_model.LibraryAgentResponse(
+ agents=valid_library_agents,
+ pagination=Pagination(
+ total_items=agent_count,
+ total_pages=(agent_count + page_size - 1) // page_size,
+ current_page=page,
+ page_size=page_size,
+ ),
+ )
async def list_favorite_library_agents(
@@ -191,52 +200,43 @@ async def list_favorite_library_agents(
# Sort favorites by updated date descending
order_by: prisma.types.LibraryAgentOrderByInput = {"updatedAt": "desc"}
- try:
- library_agents = await prisma.models.LibraryAgent.prisma().find_many(
- where=where_clause,
- include=library_agent_include(
- user_id, include_nodes=False, include_executions=False
- ),
- order=order_by,
- skip=(page - 1) * page_size,
- take=page_size,
- )
- agent_count = await prisma.models.LibraryAgent.prisma().count(
- where=where_clause
- )
+ library_agents = await prisma.models.LibraryAgent.prisma().find_many(
+ where=where_clause,
+ include=library_agent_include(
+ user_id, include_nodes=False, include_executions=False
+ ),
+ order=order_by,
+ skip=(page - 1) * page_size,
+ take=page_size,
+ )
+ agent_count = await prisma.models.LibraryAgent.prisma().count(where=where_clause)
- logger.debug(
- f"Retrieved {len(library_agents)} favorite library agents for user #{user_id}"
- )
+ logger.debug(
+ f"Retrieved {len(library_agents)} favorite library agents for user #{user_id}"
+ )
- # Only pass valid agents to the response
- valid_library_agents: list[library_model.LibraryAgent] = []
-
- for agent in library_agents:
- try:
- library_agent = library_model.LibraryAgent.from_db(agent)
- valid_library_agents.append(library_agent)
- except Exception as e:
- # Skip this agent if there was an error
- logger.error(
- f"Error parsing LibraryAgent #{agent.id} from DB item: {e}"
- )
- continue
-
- # Return the response with only valid agents
- return library_model.LibraryAgentResponse(
- agents=valid_library_agents,
- pagination=Pagination(
- total_items=agent_count,
- total_pages=(agent_count + page_size - 1) // page_size,
- current_page=page,
- page_size=page_size,
- ),
- )
+ # Only pass valid agents to the response
+ valid_library_agents: list[library_model.LibraryAgent] = []
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error fetching favorite library agents: {e}")
- raise DatabaseError("Failed to fetch favorite library agents") from e
+ for agent in library_agents:
+ try:
+ library_agent = library_model.LibraryAgent.from_db(agent)
+ valid_library_agents.append(library_agent)
+ except Exception as e:
+ # Skip this agent if there was an error
+ logger.error(f"Error parsing LibraryAgent #{agent.id} from DB item: {e}")
+ continue
+
+ # Return the response with only valid agents
+ return library_model.LibraryAgentResponse(
+ agents=valid_library_agents,
+ pagination=Pagination(
+ total_items=agent_count,
+ total_pages=(agent_count + page_size - 1) // page_size,
+ current_page=page,
+ page_size=page_size,
+ ),
+ )
async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent:
@@ -254,57 +254,48 @@ async def get_library_agent(id: str, user_id: str) -> library_model.LibraryAgent
AgentNotFoundError: If the specified agent does not exist.
DatabaseError: If there's an error during retrieval.
"""
- try:
- library_agent = await prisma.models.LibraryAgent.prisma().find_first(
+ library_agent = await prisma.models.LibraryAgent.prisma().find_first(
+ where={
+ "id": id,
+ "userId": user_id,
+ "isDeleted": False,
+ },
+ include=library_agent_include(user_id),
+ )
+
+ 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={
- "id": id,
- "userId": user_id,
+ "agentGraphId": library_agent.AgentGraph.id,
"isDeleted": False,
+ "hasApprovedVersion": True,
+ },
+ include={
+ "ActiveVersion": True,
},
- include=library_agent_include(user_id),
)
-
- 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 (
- 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}
- )
-
- 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
- ),
- store_listing=store_listing,
- profile=profile,
- )
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error fetching library agent: {e}")
- raise DatabaseError("Failed to fetch library agent") from e
+ 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
+ ),
+ store_listing=store_listing,
+ profile=profile,
+ )
async def get_library_agent_by_store_version_id(
@@ -347,29 +338,25 @@ async def get_library_agent_by_graph_id(
graph_id: str,
graph_version: Optional[int] = None,
) -> library_model.LibraryAgent | None:
- try:
- filter: prisma.types.LibraryAgentWhereInput = {
- "agentGraphId": graph_id,
- "userId": user_id,
- "isDeleted": False,
- }
- if graph_version is not None:
- filter["agentGraphVersion"] = graph_version
+ filter: prisma.types.LibraryAgentWhereInput = {
+ "agentGraphId": graph_id,
+ "userId": user_id,
+ "isDeleted": False,
+ }
+ if graph_version is not None:
+ filter["agentGraphVersion"] = graph_version
- agent = await prisma.models.LibraryAgent.prisma().find_first(
- where=filter,
- include=library_agent_include(user_id),
- )
- if not agent:
- return None
+ agent = await prisma.models.LibraryAgent.prisma().find_first(
+ where=filter,
+ include=library_agent_include(user_id),
+ )
+ if not agent:
+ return None
- assert agent.AgentGraph # make type checker happy
- # Include sub-graphs so we can make a full credentials input schema
- sub_graphs = await graph_db.get_sub_graphs(agent.AgentGraph)
- return library_model.LibraryAgent.from_db(agent, sub_graphs=sub_graphs)
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error fetching library agent by graph ID: {e}")
- raise DatabaseError("Failed to fetch library agent") from e
+ assert agent.AgentGraph # make type checker happy
+ # Include sub-graphs so we can make a full credentials input schema
+ sub_graphs = await graph_db.get_sub_graphs(agent.AgentGraph)
+ return library_model.LibraryAgent.from_db(agent, sub_graphs=sub_graphs)
async def add_generated_agent_image(
@@ -634,6 +621,7 @@ async def update_library_agent(
is_archived: Optional[bool] = None,
is_deleted: Optional[Literal[False]] = None,
settings: Optional[GraphSettings] = None,
+ folder_id: Optional[str] = None,
) -> library_model.LibraryAgent:
"""
Updates the specified LibraryAgent record.
@@ -646,6 +634,7 @@ async def update_library_agent(
is_favorite: Whether this agent is marked as a favorite.
is_archived: Whether this agent is archived.
settings: User-specific settings for this library agent.
+ folder_id: Folder ID to move agent to (None to skip).
Returns:
The updated LibraryAgent.
@@ -680,37 +669,44 @@ async def update_library_agent(
new_settings = settings.model_dump(exclude_unset=True)
merged_settings = {**current_settings_dict, **new_settings}
update_fields["settings"] = SafeJson(merged_settings)
-
- try:
- # If graph_version is provided, update to that specific version
- if graph_version is not None:
- # Get the current agent to find its graph_id
- agent = await get_library_agent(id=library_agent_id, user_id=user_id)
- # Update to the specified version using existing function
- return await update_agent_version_in_library(
- user_id=user_id,
- agent_graph_id=agent.graph_id,
- agent_graph_version=graph_version,
+ if folder_id is not None:
+ # Authorization: FK only checks existence, not ownership.
+ # Verify the folder belongs to this user to prevent cross-user nesting.
+ await get_folder(folder_id, user_id)
+ update_fields["folderId"] = folder_id
+
+ # If graph_version is provided, update to that specific version
+ if graph_version is not None:
+ # Apply any other field updates first so they aren't lost
+ if update_fields:
+ await prisma.models.LibraryAgent.prisma().update_many(
+ where={"id": library_agent_id, "userId": user_id},
+ data=update_fields,
)
+ # Get the current agent to find its graph_id
+ agent = await get_library_agent(id=library_agent_id, user_id=user_id)
+ # Update to the specified version using existing function
+ return await update_agent_version_in_library(
+ user_id=user_id,
+ agent_graph_id=agent.graph_id,
+ agent_graph_version=graph_version,
+ )
- # Otherwise, just update the simple fields
- if not update_fields:
- raise ValueError("No values were passed to update")
+ # Otherwise, just update the simple fields
+ if not update_fields:
+ raise ValueError("No values were passed to update")
- n_updated = await prisma.models.LibraryAgent.prisma().update_many(
- where={"id": library_agent_id, "userId": user_id},
- data=update_fields,
- )
- if n_updated < 1:
- raise NotFoundError(f"Library agent {library_agent_id} not found")
+ n_updated = await prisma.models.LibraryAgent.prisma().update_many(
+ where={"id": library_agent_id, "userId": user_id},
+ data=update_fields,
+ )
+ if n_updated < 1:
+ raise NotFoundError(f"Library agent {library_agent_id} not found")
- return await get_library_agent(
- id=library_agent_id,
- user_id=user_id,
- )
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error updating library agent: {str(e)}")
- raise DatabaseError("Failed to update library agent") from e
+ return await get_library_agent(
+ id=library_agent_id,
+ user_id=user_id,
+ )
async def delete_library_agent(
@@ -802,13 +798,9 @@ async def delete_library_agent_by_graph_id(graph_id: str, user_id: str) -> None:
"""
Deletes a library agent for the given user
"""
- try:
- await prisma.models.LibraryAgent.prisma().delete_many(
- where={"agentGraphId": graph_id, "userId": user_id}
- )
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error deleting library agent: {e}")
- raise DatabaseError("Failed to delete library agent") from e
+ await prisma.models.LibraryAgent.prisma().delete_many(
+ where={"agentGraphId": graph_id, "userId": user_id}
+ )
async def add_store_agent_to_library(
@@ -833,89 +825,660 @@ async def add_store_agent_to_library(
f"to library for user #{user_id}"
)
- try:
- store_listing_version = (
- await prisma.models.StoreListingVersion.prisma().find_unique(
- where={"id": store_listing_version_id}, include={"AgentGraph": True}
- )
+ store_listing_version = (
+ await prisma.models.StoreListingVersion.prisma().find_unique(
+ where={"id": store_listing_version_id}, include={"AgentGraph": True}
+ )
+ )
+ if not store_listing_version or not store_listing_version.AgentGraph:
+ logger.warning(f"Store listing version not found: {store_listing_version_id}")
+ raise store_exceptions.AgentNotFoundError(
+ f"Store listing version {store_listing_version_id} not found or invalid"
)
- if not store_listing_version or not store_listing_version.AgentGraph:
- logger.warning(
- f"Store listing version not found: {store_listing_version_id}"
- )
- raise store_exceptions.AgentNotFoundError(
- f"Store listing version {store_listing_version_id} not found or invalid"
- )
- graph = store_listing_version.AgentGraph
+ graph = store_listing_version.AgentGraph
- # Convert to GraphModel to check for HITL blocks
- graph_model = await graph_db.get_graph(
- graph_id=graph.id,
- version=graph.version,
- user_id=user_id,
- include_subgraphs=False,
+ # Convert to GraphModel to check for HITL blocks
+ graph_model = await graph_db.get_graph(
+ graph_id=graph.id,
+ version=graph.version,
+ user_id=user_id,
+ include_subgraphs=False,
+ )
+ if not graph_model:
+ raise store_exceptions.AgentNotFoundError(
+ f"Graph #{graph.id} v{graph.version} not found or accessible"
)
- if not graph_model:
- raise store_exceptions.AgentNotFoundError(
- f"Graph #{graph.id} v{graph.version} not found or accessible"
- )
- # Check if user already has this agent
- existing_library_agent = await prisma.models.LibraryAgent.prisma().find_unique(
- where={
- "userId_agentGraphId_agentGraphVersion": {
- "userId": user_id,
- "agentGraphId": graph.id,
- "agentGraphVersion": graph.version,
+ # Check if user already has this agent (non-deleted)
+ if existing := await get_library_agent_by_graph_id(
+ user_id, graph.id, graph.version
+ ):
+ return existing
+
+ # Check for soft-deleted version and restore it
+ deleted_agent = await prisma.models.LibraryAgent.prisma().find_unique(
+ where={
+ "userId_agentGraphId_agentGraphVersion": {
+ "userId": user_id,
+ "agentGraphId": graph.id,
+ "agentGraphVersion": graph.version,
+ }
+ },
+ )
+ if deleted_agent and deleted_agent.isDeleted:
+ return await update_library_agent(deleted_agent.id, user_id, is_deleted=False)
+
+ # Create LibraryAgent entry
+ added_agent = await prisma.models.LibraryAgent.prisma().create(
+ data={
+ "User": {"connect": {"id": user_id}},
+ "AgentGraph": {
+ "connect": {
+ "graphVersionId": {"id": graph.id, "version": graph.version}
}
},
- include={"AgentGraph": True},
+ "isCreatedByUser": False,
+ "useGraphIsActiveVersion": False,
+ "settings": SafeJson(GraphSettings.from_graph(graph_model).model_dump()),
+ },
+ include=library_agent_include(
+ user_id, include_nodes=False, include_executions=False
+ ),
+ )
+ logger.debug(
+ f"Added graph #{graph.id} v{graph.version}"
+ f"for store listing version #{store_listing_version.id} "
+ f"to library for user #{user_id}"
+ )
+ return library_model.LibraryAgent.from_db(added_agent)
+
+
+##############################################
+############ Folder DB Functions #############
+##############################################
+
+
+async def _fetch_user_folders(
+ user_id: str,
+ extra_where: Optional[prisma.types.LibraryFolderWhereInput] = None,
+ include_relations: bool = True,
+) -> list[prisma.models.LibraryFolder]:
+ """
+ Shared helper to fetch folders for a user with consistent query params.
+
+ Args:
+ user_id: The ID of the user.
+ extra_where: Additional where-clause filters to merge in.
+ include_relations: Whether to include LibraryAgents and Children relations
+ (used to derive counts via len(); Prisma Python has no _count include).
+
+ Returns:
+ A list of raw Prisma LibraryFolder records.
+ """
+ where_clause: prisma.types.LibraryFolderWhereInput = {
+ "userId": user_id,
+ "isDeleted": False,
+ }
+ if extra_where:
+ where_clause.update(extra_where)
+
+ return await prisma.models.LibraryFolder.prisma().find_many(
+ where=where_clause,
+ order={"createdAt": "asc"},
+ include=LIBRARY_FOLDER_INCLUDE if include_relations else None,
+ )
+
+
+async def list_folders(
+ user_id: str,
+ parent_id: Optional[str] = None,
+ include_relations: bool = True,
+) -> list[library_model.LibraryFolder]:
+ """
+ Lists folders for a user, optionally filtered by parent.
+
+ Args:
+ user_id: The ID of the user.
+ parent_id: If provided, only returns folders with this parent.
+ If None, returns root-level folders.
+ include_relations: Whether to include agent and subfolder relations for counts.
+
+ Returns:
+ A list of LibraryFolder objects.
+ """
+ logger.debug(f"Listing folders for user #{user_id}, parent_id={parent_id}")
+
+ folders = await _fetch_user_folders(
+ user_id,
+ extra_where={"parentId": parent_id},
+ include_relations=include_relations,
+ )
+
+ return [
+ library_model.LibraryFolder.from_db(
+ folder,
+ agent_count=len(folder.LibraryAgents) if folder.LibraryAgents else 0,
+ subfolder_count=len(folder.Children) if folder.Children else 0,
+ )
+ for folder in folders
+ ]
+
+
+async def get_folder_tree(
+ user_id: str,
+) -> list[library_model.LibraryFolderTree]:
+ """
+ Gets the full folder tree for a user.
+
+ Args:
+ user_id: The ID of the user.
+
+ Returns:
+ A list of LibraryFolderTree objects (root folders with nested children).
+ """
+ logger.debug(f"Getting folder tree for user #{user_id}")
+
+ # Fetch all folders for the user
+ all_folders = await _fetch_user_folders(user_id)
+
+ # Build a map of folder ID to folder data
+ folder_map: dict[str, library_model.LibraryFolderTree] = {
+ folder.id: library_model.LibraryFolderTree(
+ **library_model.LibraryFolder.from_db(
+ folder,
+ agent_count=len(folder.LibraryAgents) if folder.LibraryAgents else 0,
+ subfolder_count=len(folder.Children) if folder.Children else 0,
+ ).model_dump(),
+ children=[],
+ )
+ for folder in all_folders
+ }
+
+ # Build the tree structure
+ root_folders: list[library_model.LibraryFolderTree] = []
+ for folder in all_folders:
+ tree_folder = folder_map[folder.id]
+ if folder.parentId and folder.parentId in folder_map:
+ folder_map[folder.parentId].children.append(tree_folder)
+ else:
+ root_folders.append(tree_folder)
+
+ return root_folders
+
+
+async def get_folder(
+ folder_id: str,
+ user_id: str,
+) -> library_model.LibraryFolder:
+ """
+ Gets a single folder by ID.
+
+ Args:
+ folder_id: The ID of the folder.
+ user_id: The ID of the user (for ownership verification).
+
+ Returns:
+ The LibraryFolder object.
+
+ Raises:
+ NotFoundError: If the folder doesn't exist or doesn't belong to the user.
+ """
+ folder = await prisma.models.LibraryFolder.prisma().find_first(
+ where={
+ "id": folder_id,
+ "userId": user_id,
+ "isDeleted": False,
+ },
+ include=LIBRARY_FOLDER_INCLUDE,
+ )
+
+ if not folder:
+ raise NotFoundError(f"Folder #{folder_id} not found")
+
+ return library_model.LibraryFolder.from_db(
+ folder,
+ agent_count=len(folder.LibraryAgents) if folder.LibraryAgents else 0,
+ subfolder_count=len(folder.Children) if folder.Children else 0,
+ )
+
+
+async def _is_descendant_of(
+ folder_id: str,
+ potential_ancestor_id: str,
+ user_id: str,
+) -> bool:
+ """
+ Check if folder_id is a descendant of (or equal to) potential_ancestor_id.
+
+ Fetches all user folders in a single query and walks the parent chain
+ in memory to avoid N database round-trips.
+
+ Args:
+ folder_id: The ID of the folder to check.
+ potential_ancestor_id: The ID of the potential ancestor.
+ user_id: The ID of the user.
+
+ Returns:
+ True if folder_id is a descendant of (or equal to) potential_ancestor_id.
+ """
+ all_folders = await prisma.models.LibraryFolder.prisma().find_many(
+ where={"userId": user_id, "isDeleted": False},
+ )
+ parent_map = {f.id: f.parentId for f in all_folders}
+
+ visited: set[str] = set()
+ current_id: str | None = folder_id
+ while current_id:
+ if current_id == potential_ancestor_id:
+ return True
+ if current_id in visited:
+ break # cycle detected
+ visited.add(current_id)
+ current_id = parent_map.get(current_id)
+
+ return False
+
+
+async def create_folder(
+ user_id: str,
+ name: str,
+ parent_id: Optional[str] = None,
+ icon: Optional[str] = None,
+ color: Optional[str] = None,
+) -> library_model.LibraryFolder:
+ """
+ Creates a new folder for the user.
+
+ Args:
+ user_id: The ID of the user.
+ name: The folder name.
+ parent_id: Optional parent folder ID.
+ icon: Optional icon identifier.
+ color: Optional hex color code.
+
+ Returns:
+ The created LibraryFolder.
+
+ Raises:
+ FolderAlreadyExistsError: If a folder with this name already exists.
+ NotFoundError: If the parent folder doesn't exist.
+ """
+ logger.debug(f"Creating folder '{name}' for user #{user_id}")
+
+ # Authorization: FK only checks existence, not ownership.
+ # Verify the parent belongs to this user to prevent cross-user nesting.
+ if parent_id:
+ await get_folder(parent_id, user_id)
+
+ # Build data dict conditionally - don't include Parent key if no parent_id
+ create_data: dict = {
+ "name": name,
+ "User": {"connect": {"id": user_id}},
+ }
+ if icon is not None:
+ create_data["icon"] = icon
+ if color is not None:
+ create_data["color"] = color
+ if parent_id:
+ create_data["Parent"] = {"connect": {"id": parent_id}}
+
+ try:
+ folder = await prisma.models.LibraryFolder.prisma().create(data=create_data)
+ except prisma.errors.UniqueViolationError:
+ raise FolderAlreadyExistsError(
+ "A folder with this name already exists in this location"
)
- if existing_library_agent:
- if existing_library_agent.isDeleted:
- # Even if agent exists it needs to be marked as not deleted
- await update_library_agent(
- existing_library_agent.id, user_id, is_deleted=False
- )
- else:
- logger.debug(
- f"User #{user_id} already has graph #{graph.id} "
- f"v{graph.version} in their library"
- )
- return library_model.LibraryAgent.from_db(existing_library_agent)
- # Create LibraryAgent entry
- added_agent = await prisma.models.LibraryAgent.prisma().create(
+ return library_model.LibraryFolder.from_db(folder)
+
+
+async def create_folder_with_unique_name(
+ user_id: str,
+ base_name: str,
+ parent_id: Optional[str] = None,
+ icon: Optional[str] = None,
+ color: Optional[str] = None,
+) -> library_model.LibraryFolder:
+ """
+ Creates a folder, appending (2), (3), etc. if name exists.
+
+ Args:
+ user_id: The ID of the user.
+ base_name: The base folder name.
+ parent_id: Optional parent folder ID.
+ icon: Optional icon identifier.
+ color: Optional hex color code.
+
+ Returns:
+ The created LibraryFolder.
+ """
+ for i in itertools.count():
+ name = base_name if i == 0 else f"{base_name} ({i + 1})"
+ try:
+ return await create_folder(
+ user_id=user_id,
+ name=name,
+ parent_id=parent_id,
+ icon=icon,
+ color=color,
+ )
+ except FolderAlreadyExistsError:
+ continue
+
+ raise RuntimeError("Unreachable")
+
+
+async def update_folder(
+ folder_id: str,
+ user_id: str,
+ name: Optional[str] = None,
+ icon: Optional[str] = None,
+ color: Optional[str] = None,
+) -> library_model.LibraryFolder:
+ """
+ Updates a folder's properties.
+
+ Args:
+ folder_id: The ID of the folder to update.
+ user_id: The ID of the user.
+ name: New folder name.
+ icon: New icon identifier.
+ color: New hex color code.
+
+ Returns:
+ The updated LibraryFolder.
+
+ Raises:
+ NotFoundError: If the folder doesn't exist.
+ DatabaseError: If there's a database error.
+ """
+ logger.debug(f"Updating folder #{folder_id} for user #{user_id}")
+
+ # Authorization: update uses where={"id": ...} without userId,
+ # so we must verify ownership first.
+ await get_folder(folder_id, user_id)
+
+ update_data: prisma.types.LibraryFolderUpdateInput = {}
+ if name is not None:
+ update_data["name"] = name
+ if icon is not None:
+ update_data["icon"] = icon
+ if color is not None:
+ update_data["color"] = color
+
+ if not update_data:
+ return await get_folder(folder_id, user_id)
+
+ try:
+ folder = await prisma.models.LibraryFolder.prisma().update(
+ where={"id": folder_id},
+ data=update_data,
+ include=LIBRARY_FOLDER_INCLUDE,
+ )
+ except prisma.errors.UniqueViolationError:
+ raise FolderAlreadyExistsError(
+ "A folder with this name already exists in this location"
+ )
+
+ if not folder:
+ raise NotFoundError(f"Folder #{folder_id} not found")
+
+ return library_model.LibraryFolder.from_db(
+ folder,
+ agent_count=len(folder.LibraryAgents) if folder.LibraryAgents else 0,
+ subfolder_count=len(folder.Children) if folder.Children else 0,
+ )
+
+
+async def move_folder(
+ folder_id: str,
+ user_id: str,
+ target_parent_id: Optional[str],
+) -> library_model.LibraryFolder:
+ """
+ Moves a folder to a new parent.
+
+ Args:
+ folder_id: The ID of the folder to move.
+ user_id: The ID of the user.
+ target_parent_id: The target parent ID (None for root).
+
+ Returns:
+ The moved LibraryFolder.
+
+ Raises:
+ FolderValidationError: If the move is invalid.
+ NotFoundError: If the folder doesn't exist.
+ DatabaseError: If there's a database error.
+ """
+ logger.debug(f"Moving folder #{folder_id} to parent #{target_parent_id}")
+
+ # Authorization: update uses where={"id": ...} without userId,
+ # so we must verify ownership first.
+ await get_folder(folder_id, user_id)
+
+ # Authorization: FK only checks existence, not ownership.
+ # Verify the target parent belongs to this user to prevent cross-user nesting.
+ if target_parent_id:
+ await get_folder(target_parent_id, user_id)
+
+ # Validate no circular reference
+ if target_parent_id:
+ if await _is_descendant_of(target_parent_id, folder_id, user_id):
+ raise FolderValidationError("Cannot move folder into its own descendant")
+
+ try:
+ folder = await prisma.models.LibraryFolder.prisma().update(
+ where={"id": folder_id},
data={
- "User": {"connect": {"id": user_id}},
- "AgentGraph": {
- "connect": {
- "graphVersionId": {"id": graph.id, "version": graph.version}
- }
- },
- "isCreatedByUser": False,
- "useGraphIsActiveVersion": False,
- "settings": SafeJson(
- GraphSettings.from_graph(graph_model).model_dump()
- ),
+ "parentId": target_parent_id,
},
- include=library_agent_include(
- user_id, include_nodes=False, include_executions=False
- ),
+ include=LIBRARY_FOLDER_INCLUDE,
)
- logger.debug(
- f"Added graph #{graph.id} v{graph.version}"
- f"for store listing version #{store_listing_version.id} "
- f"to library for user #{user_id}"
+ except prisma.errors.UniqueViolationError:
+ raise FolderAlreadyExistsError(
+ "A folder with this name already exists in this location"
)
- return library_model.LibraryAgent.from_db(added_agent)
- except store_exceptions.AgentNotFoundError:
- # Reraise for external handling.
- raise
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error adding agent to library: {e}")
- raise DatabaseError("Failed to add agent to library") from e
+
+ if not folder:
+ raise NotFoundError(f"Folder #{folder_id} not found")
+
+ return library_model.LibraryFolder.from_db(
+ folder,
+ agent_count=len(folder.LibraryAgents) if folder.LibraryAgents else 0,
+ subfolder_count=len(folder.Children) if folder.Children else 0,
+ )
+
+
+async def delete_folder(
+ folder_id: str,
+ user_id: str,
+ soft_delete: bool = True,
+) -> None:
+ """
+ Deletes a folder and all its contents (cascade).
+
+ Args:
+ folder_id: The ID of the folder to delete.
+ user_id: The ID of the user.
+ soft_delete: If True, soft-deletes; otherwise hard-deletes.
+
+ Raises:
+ NotFoundError: If the folder doesn't exist.
+ DatabaseError: If there's a database error.
+ """
+ logger.debug(f"Deleting folder #{folder_id} for user #{user_id}")
+
+ # Authorization: verify folder exists and belongs to user.
+ await get_folder(folder_id, user_id)
+
+ # Collect all folder IDs (target + descendants) — single query, in-memory walk
+ descendant_ids = await _get_descendant_folder_ids(folder_id, user_id)
+ all_folder_ids = [folder_id] + descendant_ids
+
+ async with transaction() as tx:
+ if soft_delete:
+ # Move agents to root so they aren't lost when the folder is deleted
+ await prisma.models.LibraryAgent.prisma(tx).update_many(
+ where={
+ "folderId": {"in": all_folder_ids},
+ "userId": user_id,
+ },
+ data={"folderId": None},
+ )
+
+ # Soft-delete all folders
+ await prisma.models.LibraryFolder.prisma(tx).update_many(
+ where={
+ "id": {"in": all_folder_ids},
+ "userId": user_id,
+ },
+ data={"isDeleted": True},
+ )
+ else:
+ # Move agents to root (or could hard-delete them)
+ await prisma.models.LibraryAgent.prisma(tx).update_many(
+ where={
+ "folderId": {"in": all_folder_ids},
+ "userId": user_id,
+ },
+ data={"folderId": None},
+ )
+
+ # Hard-delete folders (children first due to FK constraints)
+ for fid in reversed(all_folder_ids):
+ await prisma.models.LibraryFolder.prisma(tx).delete(where={"id": fid})
+
+
+async def _get_descendant_folder_ids(
+ folder_id: str,
+ user_id: str,
+) -> list[str]:
+ """
+ Get all descendant folder IDs in a single query + in-memory walk,
+ same approach as _is_descendant_of to avoid N recursive DB round-trips.
+
+ Args:
+ folder_id: The ID of the parent folder.
+ user_id: The ID of the user.
+
+ Returns:
+ A list of descendant folder IDs.
+ """
+ all_folders = await prisma.models.LibraryFolder.prisma().find_many(
+ where={"userId": user_id, "isDeleted": False},
+ )
+
+ # Build children map: parent_id -> [child_ids]
+ children_map: dict[str, list[str]] = {}
+ for f in all_folders:
+ if f.parentId:
+ children_map.setdefault(f.parentId, []).append(f.id)
+
+ # Walk the tree in memory
+ result: list[str] = []
+ visited: set[str] = set()
+ stack = list(children_map.get(folder_id, []))
+ while stack:
+ current = stack.pop()
+ if current in visited:
+ continue # cycle guard
+ visited.add(current)
+ result.append(current)
+ stack.extend(children_map.get(current, []))
+
+ return result
+
+
+async def move_agent_to_folder(
+ library_agent_id: str,
+ folder_id: Optional[str],
+ user_id: str,
+) -> library_model.LibraryAgent:
+ """
+ Moves a library agent to a folder.
+
+ Args:
+ library_agent_id: The ID of the library agent.
+ folder_id: The target folder ID (None for root).
+ user_id: The ID of the user.
+
+ Returns:
+ The updated LibraryAgent.
+
+ Raises:
+ NotFoundError: If the agent or folder doesn't exist.
+ DatabaseError: If there's a database error.
+ """
+ logger.debug(f"Moving agent #{library_agent_id} to folder #{folder_id}")
+
+ # Authorization: verify agent belongs to user before updating.
+ # update() uses where={"id": ...} without userId, so check ownership first.
+ await get_library_agent(library_agent_id, user_id)
+
+ # Authorization: folderId is set directly, FK only checks existence
+ # not ownership, so verify the folder belongs to the user.
+ if folder_id:
+ await get_folder(folder_id, user_id)
+
+ await prisma.models.LibraryAgent.prisma().update(
+ where={"id": library_agent_id},
+ data={"folderId": folder_id},
+ )
+
+ return await get_library_agent(library_agent_id, user_id)
+
+
+async def bulk_move_agents_to_folder(
+ agent_ids: list[str],
+ folder_id: Optional[str],
+ user_id: str,
+) -> list[library_model.LibraryAgent]:
+ """
+ Moves multiple library agents to a folder.
+
+ Args:
+ agent_ids: The IDs of the library agents.
+ folder_id: The target folder ID (None for root).
+ user_id: The ID of the user.
+
+ Returns:
+ The updated LibraryAgents.
+
+ Raises:
+ NotFoundError: If any agent or the folder doesn't exist.
+ DatabaseError: If there's a database error.
+ """
+ logger.debug(f"Bulk moving {len(agent_ids)} agents to folder #{folder_id}")
+
+ # Authorization: folderId is set directly, FK only checks existence
+ # not ownership, so verify the folder belongs to the user.
+ if folder_id:
+ await get_folder(folder_id, user_id)
+
+ # Update all agents
+ await prisma.models.LibraryAgent.prisma().update_many(
+ where={
+ "id": {"in": agent_ids},
+ "userId": user_id,
+ "isDeleted": False,
+ },
+ data={"folderId": folder_id},
+ )
+
+ # Fetch and return updated agents
+ agents = await prisma.models.LibraryAgent.prisma().find_many(
+ where={
+ "id": {"in": agent_ids},
+ "userId": user_id,
+ },
+ include=library_agent_include(
+ user_id, include_nodes=False, include_executions=False
+ ),
+ )
+
+ return [library_model.LibraryAgent.from_db(agent) for agent in agents]
##############################################
@@ -949,7 +1512,7 @@ async def list_presets(
logger.warning(
"Invalid pagination input: page=%d, page_size=%d", page, page_size
)
- raise DatabaseError("Invalid pagination parameters")
+ raise InvalidInputError("Invalid pagination parameters")
query_filter: prisma.types.AgentPresetWhereInput = {
"userId": user_id,
@@ -958,34 +1521,28 @@ async def list_presets(
if graph_id:
query_filter["agentGraphId"] = graph_id
- try:
- presets_records = await prisma.models.AgentPreset.prisma().find_many(
- where=query_filter,
- skip=(page - 1) * page_size,
- take=page_size,
- include=AGENT_PRESET_INCLUDE,
- )
- total_items = await prisma.models.AgentPreset.prisma().count(where=query_filter)
- total_pages = (total_items + page_size - 1) // page_size
-
- presets = [
- library_model.LibraryAgentPreset.from_db(preset)
- for preset in presets_records
- ]
-
- return library_model.LibraryAgentPresetResponse(
- presets=presets,
- pagination=Pagination(
- total_items=total_items,
- total_pages=total_pages,
- current_page=page,
- page_size=page_size,
- ),
- )
-
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error getting presets: {e}")
- raise DatabaseError("Failed to fetch presets") from e
+ presets_records = await prisma.models.AgentPreset.prisma().find_many(
+ where=query_filter,
+ skip=(page - 1) * page_size,
+ take=page_size,
+ include=AGENT_PRESET_INCLUDE,
+ )
+ total_items = await prisma.models.AgentPreset.prisma().count(where=query_filter)
+ total_pages = (total_items + page_size - 1) // page_size
+
+ presets = [
+ library_model.LibraryAgentPreset.from_db(preset) for preset in presets_records
+ ]
+
+ return library_model.LibraryAgentPresetResponse(
+ presets=presets,
+ pagination=Pagination(
+ total_items=total_items,
+ total_pages=total_pages,
+ current_page=page,
+ page_size=page_size,
+ ),
+ )
async def get_preset(
@@ -1005,17 +1562,13 @@ async def get_preset(
DatabaseError: If there's a database error during the fetch.
"""
logger.debug(f"Fetching preset #{preset_id} for user #{user_id}")
- try:
- preset = await prisma.models.AgentPreset.prisma().find_unique(
- where={"id": preset_id},
- include=AGENT_PRESET_INCLUDE,
- )
- if not preset or preset.userId != user_id or preset.isDeleted:
- return None
- return library_model.LibraryAgentPreset.from_db(preset)
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error getting preset: {e}")
- raise DatabaseError("Failed to fetch preset") from e
+ preset = await prisma.models.AgentPreset.prisma().find_unique(
+ where={"id": preset_id},
+ include=AGENT_PRESET_INCLUDE,
+ )
+ if not preset or preset.userId != user_id or preset.isDeleted:
+ return None
+ return library_model.LibraryAgentPreset.from_db(preset)
async def create_preset(
@@ -1038,34 +1591,30 @@ async def create_preset(
logger.debug(
f"Creating preset ({repr(preset.name)}) for user #{user_id}",
)
- try:
- new_preset = await prisma.models.AgentPreset.prisma().create(
- data=prisma.types.AgentPresetCreateInput(
- userId=user_id,
- name=preset.name,
- description=preset.description,
- agentGraphId=preset.graph_id,
- agentGraphVersion=preset.graph_version,
- isActive=preset.is_active,
- webhookId=preset.webhook_id,
- InputPresets={
- "create": [
- prisma.types.AgentNodeExecutionInputOutputCreateWithoutRelationsInput( # noqa
- name=name, data=SafeJson(data)
- )
- for name, data in {
- **preset.inputs,
- **preset.credentials,
- }.items()
- ]
- },
- ),
- include=AGENT_PRESET_INCLUDE,
- )
- return library_model.LibraryAgentPreset.from_db(new_preset)
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error creating preset: {e}")
- raise DatabaseError("Failed to create preset") from e
+ new_preset = await prisma.models.AgentPreset.prisma().create(
+ data=prisma.types.AgentPresetCreateInput(
+ userId=user_id,
+ name=preset.name,
+ description=preset.description,
+ agentGraphId=preset.graph_id,
+ agentGraphVersion=preset.graph_version,
+ isActive=preset.is_active,
+ webhookId=preset.webhook_id,
+ InputPresets={
+ "create": [
+ prisma.types.AgentNodeExecutionInputOutputCreateWithoutRelationsInput( # noqa
+ name=name, data=SafeJson(data)
+ )
+ for name, data in {
+ **preset.inputs,
+ **preset.credentials,
+ }.items()
+ ]
+ },
+ ),
+ include=AGENT_PRESET_INCLUDE,
+ )
+ return library_model.LibraryAgentPreset.from_db(new_preset)
async def create_preset_from_graph_execution(
@@ -1160,50 +1709,46 @@ async def update_preset(
logger.debug(
f"Updating preset #{preset_id} ({repr(current.name)}) for user #{user_id}",
)
- try:
- async with transaction() as tx:
- update_data: prisma.types.AgentPresetUpdateInput = {}
- if name:
- update_data["name"] = name
- if description:
- update_data["description"] = description
- if is_active is not None:
- update_data["isActive"] = is_active
- if inputs or credentials:
- if not (inputs and credentials):
- raise ValueError(
- "Preset inputs and credentials must be provided together"
+ async with transaction() as tx:
+ update_data: prisma.types.AgentPresetUpdateInput = {}
+ if name:
+ update_data["name"] = name
+ if description:
+ update_data["description"] = description
+ if is_active is not None:
+ update_data["isActive"] = is_active
+ if inputs or credentials:
+ if not (inputs and credentials):
+ raise ValueError(
+ "Preset inputs and credentials must be provided together"
+ )
+ update_data["InputPresets"] = {
+ "create": [
+ prisma.types.AgentNodeExecutionInputOutputCreateWithoutRelationsInput( # noqa
+ name=name, data=SafeJson(data)
)
- update_data["InputPresets"] = {
- "create": [
- prisma.types.AgentNodeExecutionInputOutputCreateWithoutRelationsInput( # noqa
- name=name, data=SafeJson(data)
- )
- for name, data in {
- **inputs,
- **{
- key: creds_meta.model_dump(exclude_none=True)
- for key, creds_meta in credentials.items()
- },
- }.items()
- ],
- }
- # Existing InputPresets must be deleted, in a separate query
- await prisma.models.AgentNodeExecutionInputOutput.prisma(
- tx
- ).delete_many(where={"agentPresetId": preset_id})
-
- updated = await prisma.models.AgentPreset.prisma(tx).update(
- where={"id": preset_id},
- data=update_data,
- include=AGENT_PRESET_INCLUDE,
+ for name, data in {
+ **inputs,
+ **{
+ key: creds_meta.model_dump(exclude_none=True)
+ for key, creds_meta in credentials.items()
+ },
+ }.items()
+ ],
+ }
+ # Existing InputPresets must be deleted, in a separate query
+ await prisma.models.AgentNodeExecutionInputOutput.prisma(tx).delete_many(
+ where={"agentPresetId": preset_id}
)
- if not updated:
- raise RuntimeError(f"AgentPreset #{preset_id} vanished while updating")
- return library_model.LibraryAgentPreset.from_db(updated)
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error updating preset: {e}")
- raise DatabaseError("Failed to update preset") from e
+
+ updated = await prisma.models.AgentPreset.prisma(tx).update(
+ where={"id": preset_id},
+ data=update_data,
+ include=AGENT_PRESET_INCLUDE,
+ )
+ if not updated:
+ raise RuntimeError(f"AgentPreset #{preset_id} vanished while updating")
+ return library_model.LibraryAgentPreset.from_db(updated)
async def set_preset_webhook(
@@ -1242,14 +1787,10 @@ async def delete_preset(user_id: str, preset_id: str) -> None:
DatabaseError: If there's a database error during deletion.
"""
logger.debug(f"Setting preset #{preset_id} for user #{user_id} to deleted")
- try:
- await prisma.models.AgentPreset.prisma().update_many(
- where={"id": preset_id, "userId": user_id},
- data={"isDeleted": True},
- )
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error deleting preset: {e}")
- raise DatabaseError("Failed to delete preset") from e
+ await prisma.models.AgentPreset.prisma().update_many(
+ where={"id": preset_id, "userId": user_id},
+ data={"isDeleted": True},
+ )
async def fork_library_agent(
@@ -1269,33 +1810,30 @@ async def fork_library_agent(
DatabaseError: If there's an error during the forking process.
"""
logger.debug(f"Forking library agent {library_agent_id} for user {user_id}")
- try:
- # Fetch the original agent
- original_agent = await get_library_agent(library_agent_id, user_id)
-
- # Check if user owns the library agent
- # TODO: once we have open/closed sourced agents this needs to be enabled ~kcze
- # + update library/agents/[id]/page.tsx agent actions
- # if not original_agent.can_access_graph:
- # raise DatabaseError(
- # f"User {user_id} cannot access library agent graph {library_agent_id}"
- # )
-
- # Fork the underlying graph and nodes
- new_graph = await graph_db.fork_graph(
- original_agent.graph_id, original_agent.graph_version, user_id
+
+ # Fetch the original agent
+ original_agent = await get_library_agent(library_agent_id, user_id)
+
+ # Check if user owns the library agent
+ # TODO: once we have open/closed sourced agents this needs to be enabled ~kcze
+ # + update library/agents/[id]/page.tsx agent actions
+ # if not original_agent.can_access_graph:
+ # raise DatabaseError(
+ # f"User {user_id} cannot access library agent graph {library_agent_id}"
+ # )
+
+ # Fork the underlying graph and nodes
+ new_graph = await graph_db.fork_graph(
+ original_agent.graph_id, original_agent.graph_version, user_id
+ )
+ new_graph = await on_graph_activate(new_graph, user_id=user_id)
+
+ # Create a library agent for the new graph, preserving safe mode settings
+ return (
+ await create_library_agent(
+ new_graph,
+ user_id,
+ hitl_safe_mode=original_agent.settings.human_in_the_loop_safe_mode,
+ sensitive_action_safe_mode=original_agent.settings.sensitive_action_safe_mode,
)
- new_graph = await on_graph_activate(new_graph, user_id=user_id)
-
- # Create a library agent for the new graph, preserving safe mode settings
- return (
- await create_library_agent(
- new_graph,
- user_id,
- hitl_safe_mode=original_agent.settings.human_in_the_loop_safe_mode,
- sensitive_action_safe_mode=original_agent.settings.sensitive_action_safe_mode,
- )
- )[0]
- except prisma.errors.PrismaError as e:
- logger.error(f"Database error cloning library agent: {e}")
- raise DatabaseError("Failed to fork library agent") from e
+ )[0]
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 6023177070..46db1672a9 100644
--- a/autogpt_platform/backend/backend/api/features/library/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py
@@ -144,6 +144,7 @@ async def test_add_agent_to_library(mocker):
)
mock_library_agent = mocker.patch("prisma.models.LibraryAgent.prisma")
+ mock_library_agent.return_value.find_first = mocker.AsyncMock(return_value=None)
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
@@ -178,7 +179,6 @@ async def test_add_agent_to_library(mocker):
"agentGraphVersion": 1,
}
},
- 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
diff --git a/autogpt_platform/backend/backend/api/features/library/exceptions.py b/autogpt_platform/backend/backend/api/features/library/exceptions.py
new file mode 100644
index 0000000000..b5c8cab63f
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/library/exceptions.py
@@ -0,0 +1,10 @@
+class FolderValidationError(Exception):
+ """Raised when folder operations fail validation."""
+
+ pass
+
+
+class FolderAlreadyExistsError(FolderValidationError):
+ """Raised when a folder with the same name already exists in the location."""
+
+ pass
diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.py
index 9ecbaecccb..2c2f9df061 100644
--- a/autogpt_platform/backend/backend/api/features/library/model.py
+++ b/autogpt_platform/backend/backend/api/features/library/model.py
@@ -26,6 +26,95 @@ class LibraryAgentStatus(str, Enum):
ERROR = "ERROR"
+# === Folder Models ===
+
+
+class LibraryFolder(pydantic.BaseModel):
+ """Represents a folder for organizing library agents."""
+
+ id: str
+ user_id: str
+ name: str
+ icon: str | None = None
+ color: str | None = None
+ parent_id: str | None = None
+ created_at: datetime.datetime
+ updated_at: datetime.datetime
+ agent_count: int = 0 # Direct agents in folder
+ subfolder_count: int = 0 # Direct child folders
+
+ @staticmethod
+ def from_db(
+ folder: prisma.models.LibraryFolder,
+ agent_count: int = 0,
+ subfolder_count: int = 0,
+ ) -> "LibraryFolder":
+ """Factory method that constructs a LibraryFolder from a Prisma model."""
+ return LibraryFolder(
+ id=folder.id,
+ user_id=folder.userId,
+ name=folder.name,
+ icon=folder.icon,
+ color=folder.color,
+ parent_id=folder.parentId,
+ created_at=folder.createdAt,
+ updated_at=folder.updatedAt,
+ agent_count=agent_count,
+ subfolder_count=subfolder_count,
+ )
+
+
+class LibraryFolderTree(LibraryFolder):
+ """Folder with nested children for tree view."""
+
+ children: list["LibraryFolderTree"] = []
+
+
+class FolderCreateRequest(pydantic.BaseModel):
+ """Request model for creating a folder."""
+
+ name: str = pydantic.Field(..., min_length=1, max_length=100)
+ icon: str | None = None
+ color: str | None = pydantic.Field(
+ None, pattern=r"^#[0-9A-Fa-f]{6}$", description="Hex color code (#RRGGBB)"
+ )
+ parent_id: str | None = None
+
+
+class FolderUpdateRequest(pydantic.BaseModel):
+ """Request model for updating a folder."""
+
+ name: str | None = pydantic.Field(None, min_length=1, max_length=100)
+ icon: str | None = None
+ color: str | None = None
+
+
+class FolderMoveRequest(pydantic.BaseModel):
+ """Request model for moving a folder to a new parent."""
+
+ target_parent_id: str | None = None # None = move to root
+
+
+class BulkMoveAgentsRequest(pydantic.BaseModel):
+ """Request model for moving multiple agents to a folder."""
+
+ agent_ids: list[str]
+ folder_id: str | None = None # None = move to root
+
+
+class FolderListResponse(pydantic.BaseModel):
+ """Response schema for a list of folders."""
+
+ folders: list[LibraryFolder]
+ pagination: Pagination
+
+
+class FolderTreeResponse(pydantic.BaseModel):
+ """Response schema for folder tree structure."""
+
+ tree: list[LibraryFolderTree]
+
+
class MarketplaceListingCreator(pydantic.BaseModel):
"""Creator information for a marketplace listing."""
@@ -120,6 +209,9 @@ class LibraryAgent(pydantic.BaseModel):
can_access_graph: bool
is_latest_version: bool
is_favorite: bool
+ folder_id: str | None = None
+ folder_name: str | None = None # Denormalized for display
+
recommended_schedule_cron: str | None = None
settings: GraphSettings = pydantic.Field(default_factory=GraphSettings)
marketplace_listing: Optional["MarketplaceListing"] = None
@@ -259,6 +351,8 @@ class LibraryAgent(pydantic.BaseModel):
can_access_graph=can_access_graph,
is_latest_version=is_latest_version,
is_favorite=agent.isFavorite,
+ folder_id=agent.folderId,
+ folder_name=agent.Folder.name if agent.Folder else None,
recommended_schedule_cron=agent.AgentGraph.recommendedScheduleCron,
settings=_parse_settings(agent.settings),
marketplace_listing=marketplace_listing_data,
@@ -470,3 +564,7 @@ class LibraryAgentUpdateRequest(pydantic.BaseModel):
settings: Optional[GraphSettings] = pydantic.Field(
default=None, description="User-specific settings for this library agent"
)
+ folder_id: Optional[str] = pydantic.Field(
+ default=None,
+ description="Folder ID to move agent to (None to move to root)",
+ )
diff --git a/autogpt_platform/backend/backend/api/features/library/routes/__init__.py b/autogpt_platform/backend/backend/api/features/library/routes/__init__.py
index f62cbe7ff2..c414e35911 100644
--- a/autogpt_platform/backend/backend/api/features/library/routes/__init__.py
+++ b/autogpt_platform/backend/backend/api/features/library/routes/__init__.py
@@ -1,9 +1,11 @@
import fastapi
from .agents import router as agents_router
+from .folders import router as folders_router
from .presets import router as presets_router
router = fastapi.APIRouter()
router.include_router(presets_router)
+router.include_router(folders_router)
router.include_router(agents_router)
diff --git a/autogpt_platform/backend/backend/api/features/library/routes/agents.py b/autogpt_platform/backend/backend/api/features/library/routes/agents.py
index fa3d1a0f0c..b9c1cf1420 100644
--- a/autogpt_platform/backend/backend/api/features/library/routes/agents.py
+++ b/autogpt_platform/backend/backend/api/features/library/routes/agents.py
@@ -41,6 +41,14 @@ async def list_library_agents(
ge=1,
description="Number of agents per page (must be >= 1)",
),
+ folder_id: Optional[str] = Query(
+ None,
+ description="Filter by folder ID",
+ ),
+ include_root_only: bool = Query(
+ False,
+ description="Only return agents without a folder (root-level agents)",
+ ),
) -> library_model.LibraryAgentResponse:
"""
Get all agents in the user's library (both created and saved).
@@ -51,6 +59,8 @@ async def list_library_agents(
sort_by=sort_by,
page=page,
page_size=page_size,
+ folder_id=folder_id,
+ include_root_only=include_root_only,
)
@@ -168,6 +178,7 @@ async def update_library_agent(
is_favorite=payload.is_favorite,
is_archived=payload.is_archived,
settings=payload.settings,
+ folder_id=payload.folder_id,
)
diff --git a/autogpt_platform/backend/backend/api/features/library/routes/folders.py b/autogpt_platform/backend/backend/api/features/library/routes/folders.py
new file mode 100644
index 0000000000..8ed372bc8a
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/library/routes/folders.py
@@ -0,0 +1,287 @@
+from typing import Optional
+
+import autogpt_libs.auth as autogpt_auth_lib
+from fastapi import APIRouter, Query, Security, status
+from fastapi.responses import Response
+
+from .. import db as library_db
+from .. import model as library_model
+
+router = APIRouter(
+ prefix="/folders",
+ tags=["library", "folders", "private"],
+ dependencies=[Security(autogpt_auth_lib.requires_user)],
+)
+
+
+ "",
+ summary="List Library Folders",
+ response_model=library_model.FolderListResponse,
+ responses={
+ 200: {"description": "List of folders"},
+ 500: {"description": "Server error"},
+ },
+)
+async def list_folders(
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+ parent_id: Optional[str] = Query(
+ None,
+ description="Filter by parent folder ID. If not provided, returns root-level folders.",
+ ),
+ include_relations: bool = Query(
+ True,
+ description="Include agent and subfolder relations (for counts)",
+ ),
+) -> library_model.FolderListResponse:
+ """
+ List folders for the authenticated user.
+
+ Args:
+ user_id: ID of the authenticated user.
+ parent_id: Optional parent folder ID to filter by.
+ include_relations: Whether to include agent and subfolder relations for counts.
+
+ Returns:
+ A FolderListResponse containing folders.
+ """
+ folders = await library_db.list_folders(
+ user_id=user_id,
+ parent_id=parent_id,
+ include_relations=include_relations,
+ )
+ return library_model.FolderListResponse(
+ folders=folders,
+ pagination=library_model.Pagination(
+ total_items=len(folders),
+ total_pages=1,
+ current_page=1,
+ page_size=len(folders),
+ ),
+ )
+
+
+ "/tree",
+ summary="Get Folder Tree",
+ response_model=library_model.FolderTreeResponse,
+ responses={
+ 200: {"description": "Folder tree structure"},
+ 500: {"description": "Server error"},
+ },
+)
+async def get_folder_tree(
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> library_model.FolderTreeResponse:
+ """
+ Get the full folder tree for the authenticated user.
+
+ Args:
+ user_id: ID of the authenticated user.
+
+ Returns:
+ A FolderTreeResponse containing the nested folder structure.
+ """
+ tree = await library_db.get_folder_tree(user_id=user_id)
+ return library_model.FolderTreeResponse(tree=tree)
+
+
+ "/{folder_id}",
+ summary="Get Folder",
+ response_model=library_model.LibraryFolder,
+ responses={
+ 200: {"description": "Folder details"},
+ 404: {"description": "Folder not found"},
+ 500: {"description": "Server error"},
+ },
+)
+async def get_folder(
+ folder_id: str,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> library_model.LibraryFolder:
+ """
+ Get a specific folder.
+
+ Args:
+ folder_id: ID of the folder to retrieve.
+ user_id: ID of the authenticated user.
+
+ Returns:
+ The requested LibraryFolder.
+ """
+ return await library_db.get_folder(folder_id=folder_id, user_id=user_id)
+
+
+ "",
+ summary="Create Folder",
+ status_code=status.HTTP_201_CREATED,
+ response_model=library_model.LibraryFolder,
+ responses={
+ 201: {"description": "Folder created successfully"},
+ 400: {"description": "Validation error"},
+ 404: {"description": "Parent folder not found"},
+ 409: {"description": "Folder name conflict"},
+ 500: {"description": "Server error"},
+ },
+)
+async def create_folder(
+ payload: library_model.FolderCreateRequest,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> library_model.LibraryFolder:
+ """
+ Create a new folder.
+
+ Args:
+ payload: The folder creation request.
+ user_id: ID of the authenticated user.
+
+ Returns:
+ The created LibraryFolder.
+ """
+ return await library_db.create_folder(
+ user_id=user_id,
+ name=payload.name,
+ parent_id=payload.parent_id,
+ icon=payload.icon,
+ color=payload.color,
+ )
+
+
+ "/{folder_id}",
+ summary="Update Folder",
+ response_model=library_model.LibraryFolder,
+ responses={
+ 200: {"description": "Folder updated successfully"},
+ 400: {"description": "Validation error"},
+ 404: {"description": "Folder not found"},
+ 409: {"description": "Folder name conflict"},
+ 500: {"description": "Server error"},
+ },
+)
+async def update_folder(
+ folder_id: str,
+ payload: library_model.FolderUpdateRequest,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> library_model.LibraryFolder:
+ """
+ Update a folder's properties.
+
+ Args:
+ folder_id: ID of the folder to update.
+ payload: The folder update request.
+ user_id: ID of the authenticated user.
+
+ Returns:
+ The updated LibraryFolder.
+ """
+ return await library_db.update_folder(
+ folder_id=folder_id,
+ user_id=user_id,
+ name=payload.name,
+ icon=payload.icon,
+ color=payload.color,
+ )
+
+
+ "/{folder_id}/move",
+ summary="Move Folder",
+ response_model=library_model.LibraryFolder,
+ responses={
+ 200: {"description": "Folder moved successfully"},
+ 400: {"description": "Validation error (circular reference)"},
+ 404: {"description": "Folder or target parent not found"},
+ 409: {"description": "Folder name conflict in target location"},
+ 500: {"description": "Server error"},
+ },
+)
+async def move_folder(
+ folder_id: str,
+ payload: library_model.FolderMoveRequest,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> library_model.LibraryFolder:
+ """
+ Move a folder to a new parent.
+
+ Args:
+ folder_id: ID of the folder to move.
+ payload: The move request with target parent.
+ user_id: ID of the authenticated user.
+
+ Returns:
+ The moved LibraryFolder.
+ """
+ return await library_db.move_folder(
+ folder_id=folder_id,
+ user_id=user_id,
+ target_parent_id=payload.target_parent_id,
+ )
+
+
+ "/{folder_id}",
+ summary="Delete Folder",
+ status_code=status.HTTP_204_NO_CONTENT,
+ responses={
+ 204: {"description": "Folder deleted successfully"},
+ 404: {"description": "Folder not found"},
+ 500: {"description": "Server error"},
+ },
+)
+async def delete_folder(
+ folder_id: str,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> Response:
+ """
+ Soft-delete a folder and all its contents.
+
+ Args:
+ folder_id: ID of the folder to delete.
+ user_id: ID of the authenticated user.
+
+ Returns:
+ 204 No Content if successful.
+ """
+ await library_db.delete_folder(
+ folder_id=folder_id,
+ user_id=user_id,
+ soft_delete=True,
+ )
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
+
+
+# === Bulk Agent Operations ===
+
+
+ "/agents/bulk-move",
+ summary="Bulk Move Agents",
+ response_model=list[library_model.LibraryAgent],
+ responses={
+ 200: {"description": "Agents moved successfully"},
+ 404: {"description": "Folder not found"},
+ 500: {"description": "Server error"},
+ },
+)
+async def bulk_move_agents(
+ payload: library_model.BulkMoveAgentsRequest,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> list[library_model.LibraryAgent]:
+ """
+ Move multiple agents to a folder.
+
+ Args:
+ payload: The bulk move request with agent IDs and target folder.
+ user_id: ID of the authenticated user.
+
+ Returns:
+ The updated LibraryAgents.
+ """
+ return await library_db.bulk_move_agents_to_folder(
+ agent_ids=payload.agent_ids,
+ folder_id=payload.folder_id,
+ user_id=user_id,
+ )
diff --git a/autogpt_platform/backend/backend/api/features/library/routes_test.py b/autogpt_platform/backend/backend/api/features/library/routes_test.py
index 4d83812891..be1faf2779 100644
--- a/autogpt_platform/backend/backend/api/features/library/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/routes_test.py
@@ -115,6 +115,8 @@ async def test_get_library_agents_success(
sort_by=library_model.LibraryAgentSort.UPDATED_AT,
page=1,
page_size=15,
+ folder_id=None,
+ include_root_only=False,
)
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 965610cc07..7b8786dbc1 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -41,6 +41,10 @@ import backend.data.user
import backend.integrations.webhooks.utils
import backend.util.service
import backend.util.settings
+from backend.api.features.library.exceptions import (
+ FolderAlreadyExistsError,
+ FolderValidationError,
+)
from backend.blocks.llm import DEFAULT_LLM_MODEL
from backend.data.model import Credentials
from backend.integrations.providers import ProviderName
@@ -261,6 +265,10 @@ async def validation_error_handler(
app.add_exception_handler(PrismaError, handle_internal_http_error(500))
+app.add_exception_handler(
+ FolderAlreadyExistsError, handle_internal_http_error(409, False)
+)
+app.add_exception_handler(FolderValidationError, handle_internal_http_error(400, False))
app.add_exception_handler(NotFoundError, handle_internal_http_error(404, False))
app.add_exception_handler(NotAuthorizedError, handle_internal_http_error(403, False))
app.add_exception_handler(RequestValidationError, validation_error_handler)
diff --git a/autogpt_platform/backend/backend/data/includes.py b/autogpt_platform/backend/backend/data/includes.py
index bc3d5c9dd1..a8e79d55d2 100644
--- a/autogpt_platform/backend/backend/data/includes.py
+++ b/autogpt_platform/backend/backend/data/includes.py
@@ -79,6 +79,12 @@ INTEGRATION_WEBHOOK_INCLUDE: prisma.types.IntegrationWebhookInclude = {
}
+LIBRARY_FOLDER_INCLUDE: prisma.types.LibraryFolderInclude = {
+ "LibraryAgents": {"where": {"isDeleted": False}},
+ "Children": {"where": {"isDeleted": False}},
+}
+
+
def library_agent_include(
user_id: str,
include_nodes: bool = True,
@@ -105,6 +111,7 @@ def library_agent_include(
"""
result: prisma.types.LibraryAgentInclude = {
"Creator": True, # Always needed for creator info
+ "Folder": True, # Always needed for folder info
}
# Build AgentGraph include based on requested options
diff --git a/autogpt_platform/backend/migrations/20260123110033_add_folders_in_library/migration.sql b/autogpt_platform/backend/migrations/20260123110033_add_folders_in_library/migration.sql
new file mode 100644
index 0000000000..83ca008fe6
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260123110033_add_folders_in_library/migration.sql
@@ -0,0 +1,33 @@
+-- AlterTable
+ALTER TABLE "LibraryAgent" ADD COLUMN "folderId" TEXT;
+
+-- CreateTable
+CREATE TABLE "LibraryFolder" (
+ "id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "userId" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "icon" TEXT,
+ "color" TEXT,
+ "parentId" TEXT,
+ "isDeleted" BOOLEAN NOT NULL DEFAULT false,
+
+ CONSTRAINT "LibraryFolder_pkey" PRIMARY KEY ("id")
+);
+
+
+-- CreateIndex
+CREATE UNIQUE INDEX "LibraryFolder_userId_parentId_name_key" ON "LibraryFolder"("userId", "parentId", "name");
+
+-- CreateIndex
+CREATE INDEX "LibraryAgent_folderId_idx" ON "LibraryAgent"("folderId");
+
+-- AddForeignKey
+ALTER TABLE "LibraryAgent" ADD CONSTRAINT "LibraryAgent_folderId_fkey" FOREIGN KEY ("folderId") REFERENCES "LibraryFolder"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "LibraryFolder" ADD CONSTRAINT "LibraryFolder_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "LibraryFolder" ADD CONSTRAINT "LibraryFolder_parentId_fkey" FOREIGN KEY ("parentId") REFERENCES "LibraryFolder"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 2da898a7ce..5212ec0a3d 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -51,6 +51,7 @@ model User {
ChatSessions ChatSession[]
AgentPresets AgentPreset[]
LibraryAgents LibraryAgent[]
+ LibraryFolders LibraryFolder[]
Profile Profile[]
UserOnboarding UserOnboarding?
@@ -395,6 +396,9 @@ model LibraryAgent {
creatorId String?
Creator Profile? @relation(fields: [creatorId], references: [id])
+ folderId String?
+ Folder LibraryFolder? @relation(fields: [folderId], references: [id], onDelete: Restrict)
+
useGraphIsActiveVersion Boolean @default(false)
isFavorite Boolean @default(false)
@@ -407,6 +411,30 @@ model LibraryAgent {
@@unique([userId, agentGraphId, agentGraphVersion])
@@index([agentGraphId, agentGraphVersion])
@@index([creatorId])
+ @@index([folderId])
+}
+
+model LibraryFolder {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ userId String
+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ name String
+ icon String?
+ color String?
+
+ parentId String?
+ Parent LibraryFolder? @relation("FolderHierarchy", fields: [parentId], references: [id], onDelete: Cascade)
+ Children LibraryFolder[] @relation("FolderHierarchy")
+
+ isDeleted Boolean @default(false)
+
+ LibraryAgents LibraryAgent[]
+
+ @@unique([userId, parentId, name]) // Name unique per parent per user
}
////////////////////////////////////////////////////////////
diff --git a/autogpt_platform/backend/snapshots/lib_agts_search b/autogpt_platform/backend/snapshots/lib_agts_search
index 3ce8402b63..0d2331e73d 100644
--- a/autogpt_platform/backend/snapshots/lib_agts_search
+++ b/autogpt_platform/backend/snapshots/lib_agts_search
@@ -38,6 +38,8 @@
"can_access_graph": true,
"is_latest_version": true,
"is_favorite": false,
+ "folder_id": null,
+ "folder_name": null,
"recommended_schedule_cron": null,
"settings": {
"human_in_the_loop_safe_mode": true,
@@ -83,6 +85,8 @@
"can_access_graph": false,
"is_latest_version": true,
"is_favorite": false,
+ "folder_id": null,
+ "folder_name": null,
"recommended_schedule_cron": null,
"settings": {
"human_in_the_loop_safe_mode": true,
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index 80fb46beff..6112d8ecd9 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -32,6 +32,7 @@
"dependencies": {
"@ai-sdk/react": "3.0.61",
"@faker-js/faker": "10.0.0",
+ "@ferrucc-io/emoji-picker": "0.0.48",
"@hookform/resolvers": "5.2.2",
"@next/third-parties": "15.4.6",
"@phosphor-icons/react": "2.1.10",
diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yaml
index 4d76cd0cb9..122c135f38 100644
--- a/autogpt_platform/frontend/pnpm-lock.yaml
+++ b/autogpt_platform/frontend/pnpm-lock.yaml
@@ -18,6 +18,9 @@ importers:
'@faker-js/faker':
specifier: 10.0.0
version: 10.0.0
+ '@ferrucc-io/emoji-picker':
+ specifier: 0.0.48
'@hookform/resolvers':
specifier: 5.2.2
@@ -1507,6 +1510,14 @@ packages:
resolution: {integrity: sha512-UollFEUkVXutsaP+Vndjxar40Gs5JL2HeLcl8xO1QAjJgOdhc3OmBFWyEylS+RddWaaBiAzH+5/17PLQJwDiLw==}
engines: {node: ^20.19.0 || ^22.13.0 || ^23.5.0 || >=24.0.0, npm: '>=10'}
+ '@ferrucc-io/[email protected]':
+ resolution: {integrity: sha512-DJ5u+6VLF9OK7x+S/luwrVb5CHC6W16jL5b8vBUYNpxKWSuFgyliDHVtw1SGe6+dr5RUbf8WQwPJdKZmU3Ittg==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ react: ^18.2.0 || ^19.0.0
+ react-dom: ^18.2.0 || ^19.0.0
+ tailwindcss: '>=3.0.0'
+
'@floating-ui/[email protected]':
resolution: {integrity: sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==}
@@ -3114,6 +3125,10 @@ packages:
'@shikijs/[email protected]':
resolution: {integrity: sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==}
+ '@sindresorhus/[email protected]':
+ resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}
+ engines: {node: '>=10'}
+
'@standard-schema/[email protected]':
resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==}
@@ -3376,10 +3391,19 @@ packages:
react: '>=16.8'
react-dom: '>=16.8'
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-dZkhyfahpvlaV0rIKnvQiVoWPyURppl6w4m9IwMDpuIjcJ1sD9YGWrt0wISvgU7ewACXx2Ct46WPgI6qAD4v6A==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}
engines: {node: '>=12'}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-Mx86Hqu1k39icq2Zusq+Ey2J6dDWTjDvEv43PJtRCoEYTLyfaPnxIQ6iy7YAOK0NV/qOEmZQ/uCufrppZxTgcg==}
+
'@testing-library/[email protected]':
resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
engines: {node: '>=18'}
@@ -4373,6 +4397,10 @@ packages:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}
@@ -4990,6 +5018,9 @@ packages:
resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}
+ resolution: {integrity: sha512-5U0rVMU5Y2n2+ykNLQqMoqklN9ICBT/KsvC1Gz6vqHbz2AXXGkG+Pm5rMWk/8Vjrr/mY9985Hi8DYzn1F09Nyw==}
+
resolution: {integrity: sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==}
engines: {node: '>= 4'}
@@ -5970,6 +6001,24 @@ packages:
resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==}
hasBin: true
+ resolution: {integrity: sha512-TFNZZDa/0ewCLQyRC/Sq9crtixNj/Xdf/wmj9631xxMuKToVJZDbqcHIYN0OboH+7kh6P6tpIK7uKWClj86PKw==}
+ engines: {node: '>=12.20.0'}
+ peerDependencies:
+ '@babel/core': '>=7.0.0'
+ '@babel/template': '>=7.0.0'
+ '@types/react': '>=17.0.0'
+ react: '>=17.0.0'
+ peerDependenciesMeta:
+ '@babel/core':
+ optional: true
+ '@babel/template':
+ optional: true
+ '@types/react':
+ optional: true
+ react:
+ optional: true
+
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -6588,6 +6637,10 @@ packages:
resolution: {integrity: sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==}
+ resolution: {integrity: sha512-Z3lTE9pLaJF47NyMhd4ww1yFTAP8YhYI8SleJiHzM46Fgpm5cnNzSl9XfzFNqbaz+VlJrIj3fXQ4DeN1Rjm6cw==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==}
engines: {node: 4.x || >=6.0.0}
@@ -7686,6 +7739,10 @@ packages:
resolution: {integrity: sha512-LH7FpTAkeD+y5xQC4fzS+tFtaNlvt3Ib1zKzvhjv/Y+cioV4zIuw4IZr2yhRLu67CWL7FR9/6KXKnjRoZTvGGQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
engines: {node: '>=8'}
@@ -8163,6 +8220,13 @@ packages:
resolution: {integrity: sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-3wDXXvp6YGoKGhS2O2H7+V+bYduOBydN1lnI0uVfr1cIdY02uFFiEH1i3kE5CCE4l6UqbLKVmEFW9USxTAMD1g==}
+
+ resolution: {integrity: sha512-yLSH4py7oFH3oG/9K+XWrz1pSi3dfUrWEnInbxMfArOfc1+33BlGPQtLsOYwvdMy11AwUBetYuaRxSPqgkq+8g==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q==}
engines: {node: '>=4'}
@@ -9772,6 +9836,22 @@ snapshots:
'@faker-js/[email protected]': {}
+ dependencies:
+ '@tanstack/react-virtual': 3.13.18([email protected]([email protected]))([email protected])
+ clsx: 2.1.1
+ node-emoji: 2.2.0
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ tailwind-merge: 2.6.0
+ tailwindcss: 3.4.17
+ unicode-emoji-json: 0.8.0
+ transitivePeerDependencies:
+ - '@babel/core'
+ - '@babel/template'
+ - '@types/react'
+
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.10
@@ -11533,6 +11613,8 @@ snapshots:
'@shikijs/[email protected]': {}
+ '@sindresorhus/[email protected]': {}
+
'@standard-schema/[email protected]': {}
'@standard-schema/[email protected]': {}
@@ -12001,8 +12083,16 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@tanstack/virtual-core': 3.13.18
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+
'@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
+
'@testing-library/[email protected]':
dependencies:
'@babel/code-frame': 7.27.1
@@ -13094,6 +13184,8 @@ snapshots:
ansi-styles: 4.3.0
supports-color: 7.2.0
+
@@ -13737,6 +13829,8 @@ snapshots:
+
@@ -15018,6 +15112,13 @@ snapshots:
+ optionalDependencies:
+ '@babel/core': 7.28.5
+ '@babel/template': 7.27.2
+ '@types/react': 18.3.17
+ react: 18.3.1
+
@@ -15886,6 +15987,13 @@ snapshots:
+ dependencies:
+ '@sindresorhus/is': 4.6.0
+ char-regex: 1.0.2
+ emojilib: 2.4.0
+ skin-tone: 2.0.0
+
dependencies:
http2-client: 1.3.5
@@ -17186,6 +17294,10 @@ snapshots:
dependencies:
jsep: 1.4.0
+ dependencies:
+ unicode-emoji-modifier-base: 1.0.0
+
@@ -17701,6 +17813,10 @@ snapshots:
+
+
dependencies:
unicode-canonical-property-names-ecmascript: 2.0.1
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/FavoritesSection/FavoritesSection.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/FavoritesSection/FavoritesSection.tsx
index d1167cc747..f81b34ee92 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/FavoritesSection/FavoritesSection.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/FavoritesSection/FavoritesSection.tsx
@@ -1,17 +1,31 @@
"use client";
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
import { Text } from "@/components/atoms/Text/Text";
+import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
import { InfiniteScroll } from "@/components/contextual/InfiniteScroll/InfiniteScroll";
import { HeartIcon } from "@phosphor-icons/react";
import { useFavoriteAgents } from "../../hooks/useFavoriteAgents";
import { LibraryAgentCard } from "../LibraryAgentCard/LibraryAgentCard";
+import { LibraryTabs, Tab } from "../LibraryTabs/LibraryTabs";
+import { LibraryActionSubHeader } from "../LibraryActionSubHeader/LibraryActionSubHeader";
interface Props {
searchTerm: string;
+ tabs: Tab[];
+ activeTab: string;
+ onTabChange: (tabId: string) => void;
+ setLibrarySort: (value: LibraryAgentSort) => void;
}
-export function FavoritesSection({ searchTerm }: Props) {
+export function FavoritesSection({
+ searchTerm,
+ tabs,
+ activeTab,
+ onTabChange,
+ setLibrarySort,
+}: Props) {
const {
allAgents: favoriteAgents,
agentLoading: isLoading,
@@ -21,38 +35,33 @@ export function FavoritesSection({ searchTerm }: Props) {
isFetchingNextPage,
} = useFavoriteAgents({ searchTerm });
- if (isLoading || favoriteAgents.length === 0) {
- return null;
- }
-
return (
- <div className="!mb-8">
- <div className="mb-3 flex items-center gap-2 p-2">
- <HeartIcon className="h-5 w-5" weight="fill" />
- <div className="flex items-baseline gap-2">
- <Text variant="h4">Favorites</Text>
- {!isLoading && (
- <Text
- variant="body"
- data-testid="agents-count"
- className="relative bottom-px text-zinc-500"
- >
- {agentCount}
- </Text>
- )}
- </div>
- </div>
+ <>
+ <LibraryActionSubHeader
+ agentCount={agentCount}
+ setLibrarySort={setLibrarySort}
+ />
+ <LibraryTabs
+ tabs={tabs}
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ />
- <div className="relative">
+ {isLoading ? (
+ <div className="flex h-[200px] items-center justify-center">
+ <LoadingSpinner size="large" />
+ </div>
+ ) : favoriteAgents.length === 0 ? (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-2 text-zinc-500">
+ <HeartIcon className="h-10 w-10" />
+ <Text variant="body">No favorite agents yet</Text>
+ </div>
+ ) : (
<InfiniteScroll
isFetchingNextPage={isFetchingNextPage}
fetchNextPage={fetchNextPage}
hasNextPage={hasNextPage}
- loader={
- <div className="flex h-8 w-full items-center justify-center">
- <div className="h-6 w-6 animate-spin rounded-full border-b-2 border-t-2 border-neutral-800" />
- </div>
- }
+ loader={<LoadingSpinner size="medium" />}
>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{favoriteAgents.map((agent: LibraryAgent) => (
@@ -60,9 +69,7 @@ export function FavoritesSection({ searchTerm }: Props) {
))}
</div>
</InfiniteScroll>
- </div>
-
- {favoriteAgents.length > 0 && <div className="!mt-10 border-t" />}
- </div>
+ )}
+ </>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/FlyingHeart/FlyingHeart.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/FlyingHeart/FlyingHeart.tsx
new file mode 100644
index 0000000000..19c2e4328a
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/FlyingHeart/FlyingHeart.tsx
@@ -0,0 +1,71 @@
+"use client";
+
+import { motion, AnimatePresence, useReducedMotion } from "framer-motion";
+import { HeartIcon } from "@phosphor-icons/react";
+import { useEffect, useState } from "react";
+
+interface FlyingHeartProps {
+ startPosition: { x: number; y: number } | null;
+ targetPosition: { x: number; y: number } | null;
+ onAnimationComplete: () => void;
+}
+
+export function FlyingHeart({
+ startPosition,
+ targetPosition,
+ onAnimationComplete,
+}: FlyingHeartProps) {
+ const [isVisible, setIsVisible] = useState(false);
+ const shouldReduceMotion = useReducedMotion();
+
+ useEffect(() => {
+ if (startPosition && targetPosition) {
+ setIsVisible(true);
+ }
+ }, [startPosition, targetPosition]);
+
+ if (!startPosition || !targetPosition) return null;
+
+ return (
+ <AnimatePresence>
+ {isVisible && (
+ <motion.div
+ className="pointer-events-none fixed z-50"
+ initial={{
+ x: startPosition.x,
+ y: startPosition.y,
+ scale: 1,
+ opacity: 1,
+ }}
+ animate={{
+ x: shouldReduceMotion ? targetPosition.x : targetPosition.x,
+ y: shouldReduceMotion ? targetPosition.y : targetPosition.y,
+ scale: 0.5,
+ opacity: 0,
+ }}
+ exit={{ opacity: 0 }}
+ transition={
+ shouldReduceMotion
+ ? { duration: 0 }
+ : {
+ type: "spring",
+ damping: 20,
+ stiffness: 200,
+ duration: 0.5,
+ }
+ }
+ onAnimationComplete={() => {
+ setIsVisible(false);
+ onAnimationComplete();
+ }}
+ >
+ <HeartIcon
+ size={24}
+ weight="fill"
+ className="text-red-500 drop-shadow-md"
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LazyEmojiPicker.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LazyEmojiPicker.tsx
new file mode 100644
index 0000000000..3bc4afe98e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LazyEmojiPicker.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { EmojiPicker } from "@ferrucc-io/emoji-picker";
+
+interface Props {
+ onEmojiSelect: (emoji: string) => void;
+ containerHeight?: number;
+}
+
+export function LazyEmojiPicker({
+ onEmojiSelect,
+ containerHeight = 295,
+}: Props) {
+ return (
+ <EmojiPicker
+ onEmojiSelect={onEmojiSelect}
+ emojiSize={32}
+ className="w-full rounded-2xl px-2"
+ >
+ <EmojiPicker.Group>
+ <EmojiPicker.List hideStickyHeader containerHeight={containerHeight} />
+ </EmojiPicker.Group>
+ </EmojiPicker>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx
index edefa52911..86edb3debe 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx
@@ -13,7 +13,7 @@ export function LibraryActionSubHeader({ agentCount, setLibrarySort }: Props) {
return (
<div className="flex items-baseline justify-between">
<div className="flex items-baseline gap-4">
- <Text variant="h4">My agents</Text>
+ <Text variant="h5">My agents</Text>
<Text
variant="body"
data-testid="agents-count"
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
index 1327de5347..2209e82503 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
@@ -4,6 +4,7 @@ import { Text } from "@/components/atoms/Text/Text";
import { CaretCircleRightIcon } from "@phosphor-icons/react";
import Image from "next/image";
import NextLink from "next/link";
+import { motion } from "framer-motion";
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import Avatar, {
@@ -14,13 +15,21 @@ import { Link } from "@/components/atoms/Link/Link";
import { AgentCardMenu } from "./components/AgentCardMenu";
import { FavoriteButton } from "./components/FavoriteButton";
import { useLibraryAgentCard } from "./useLibraryAgentCard";
+import { useFavoriteAnimation } from "../../context/FavoriteAnimationContext";
interface Props {
agent: LibraryAgent;
+ draggable?: boolean;
}
-export function LibraryAgentCard({ agent }: Props) {
+export function LibraryAgentCard({ agent, draggable = true }: Props) {
const { id, name, graph_id, can_access_graph, image_url } = agent;
+ const { triggerFavoriteAnimation } = useFavoriteAnimation();
+
+ function handleDragStart(e: React.DragEvent<HTMLDivElement>) {
+ e.dataTransfer.setData("application/agent-id", id);
+ e.dataTransfer.effectAllowed = "move";
+ }
const {
isFromMarketplace,
@@ -28,103 +37,119 @@ export function LibraryAgentCard({ agent }: Props) {
profile,
creator_image_url,
handleToggleFavorite,
- } = useLibraryAgentCard({ agent });
+ } = useLibraryAgentCard({
+ agent,
+ onFavoriteAdd: triggerFavoriteAnimation,
+ });
return (
<div
- data-testid="library-agent-card"
- data-agent-id={id}
- className="group relative inline-flex h-[10.625rem] w-full max-w-[25rem] flex-col items-start justify-start gap-2.5 rounded-medium border border-zinc-100 bg-white transition-all duration-300 hover:shadow-md"
+ draggable={draggable}
+ onDragStart={handleDragStart}
+ className="[@media(pointer:fine)]:cursor-grab [@media(pointer:fine)]:active:cursor-grabbing"
>
- <NextLink href={`/library/agents/${id}`} className="flex-shrink-0">
- <div className="relative flex items-center gap-2 px-4 pt-3">
- <Avatar className="h-4 w-4 rounded-full">
- <AvatarImage
- src={
- isFromMarketplace
- ? creator_image_url || "/avatar-placeholder.png"
- : profile?.avatar_url || "/avatar-placeholder.png"
- }
- alt={`${name} creator avatar`}
- />
- <AvatarFallback size={48}>{name.charAt(0)}</AvatarFallback>
- </Avatar>
- <Text
- variant="small-medium"
- className="uppercase tracking-wide text-zinc-400"
- >
- {isFromMarketplace ? "FROM MARKETPLACE" : "Built by you"}
- </Text>
- </div>
- </NextLink>
- <FavoriteButton
- isFavorite={isFavorite}
- onClick={handleToggleFavorite}
- className="absolute right-10 top-0"
- />
- <AgentCardMenu agent={agent} />
-
- <div className="flex w-full flex-1 flex-col px-4 pb-2">
- <Link
- href={`/library/agents/${id}`}
- className="flex w-full items-start justify-between gap-2 no-underline hover:no-underline"
- >
- <Text
- variant="h5"
- data-testid="library-agent-card-name"
- className="line-clamp-3 hyphens-auto break-words no-underline hover:no-underline"
- >
- {name}
- </Text>
-
- {!image_url ? (
- <div
- className={`h-[3.64rem] w-[6.70rem] flex-shrink-0 rounded-small ${
- [
- "bg-gradient-to-r from-green-200 to-blue-200",
- "bg-gradient-to-r from-pink-200 to-purple-200",
- "bg-gradient-to-r from-yellow-200 to-orange-200",
- "bg-gradient-to-r from-blue-200 to-cyan-200",
- "bg-gradient-to-r from-indigo-200 to-purple-200",
- ][parseInt(id.slice(0, 8), 16) % 5]
- }`}
- style={{
- backgroundSize: "200% 200%",
- animation: "gradient 15s ease infinite",
- }}
- />
- ) : (
- <Image
- src={image_url}
- alt={`${name} preview image`}
- width={107}
- height={58}
- className="flex-shrink-0 rounded-small object-cover"
- />
- )}
- </Link>
+ <motion.div
+ layoutId={`agent-card-${id}`}
+ data-testid="library-agent-card"
+ data-agent-id={id}
+ className="group relative inline-flex h-[10.625rem] w-full max-w-[25rem] flex-col items-start justify-start gap-2.5 rounded-medium border border-zinc-100 bg-white hover:shadow-md"
+ transition={{
+ type: "spring",
+ damping: 25,
+ stiffness: 300,
+ }}
+ style={{ willChange: "transform" }}
+ >
+ <NextLink href={`/library/agents/${id}`} className="flex-shrink-0">
+ <div className="relative flex items-center gap-2 px-4 pt-3">
+ <Avatar className="h-4 w-4 rounded-full">
+ <AvatarImage
+ src={
+ isFromMarketplace
+ ? creator_image_url || "/avatar-placeholder.png"
+ : profile?.avatar_url || "/avatar-placeholder.png"
+ }
+ alt={`${name} creator avatar`}
+ />
+ <AvatarFallback size={48}>{name.charAt(0)}</AvatarFallback>
+ </Avatar>
+ <Text
+ variant="small-medium"
+ className="uppercase tracking-wide text-zinc-400"
+ >
+ {isFromMarketplace ? "FROM MARKETPLACE" : "Built by you"}
+ </Text>
+ </div>
+ </NextLink>
+ <FavoriteButton
+ isFavorite={isFavorite}
+ onClick={handleToggleFavorite}
+ className="absolute right-10 top-0"
+ />
+ <AgentCardMenu agent={agent} />
- <div className="mt-auto flex w-full justify-start gap-6 border-t border-zinc-100 pb-1 pt-3">
+ <div className="flex w-full flex-1 flex-col px-4 pb-2">
<Link
href={`/library/agents/${id}`}
- data-testid="library-agent-card-see-runs-link"
- className="flex items-center gap-1 text-[13px]"
+ className="flex w-full items-start justify-between gap-2 no-underline hover:no-underline focus:ring-0"
>
- See runs <CaretCircleRightIcon size={20} />
+ <Text
+ variant="h5"
+ data-testid="library-agent-card-name"
+ className="line-clamp-3 hyphens-auto break-words no-underline hover:no-underline"
+ >
+ {name}
+ </Text>
+
+ {!image_url ? (
+ <div
+ className={`h-[3.64rem] w-[6.70rem] flex-shrink-0 rounded-small ${
+ [
+ "bg-gradient-to-r from-green-200 to-blue-200",
+ "bg-gradient-to-r from-pink-200 to-purple-200",
+ "bg-gradient-to-r from-yellow-200 to-orange-200",
+ "bg-gradient-to-r from-blue-200 to-cyan-200",
+ "bg-gradient-to-r from-indigo-200 to-purple-200",
+ ][parseInt(id.slice(0, 8), 16) % 5]
+ }`}
+ style={{
+ backgroundSize: "200% 200%",
+ animation: "gradient 15s ease infinite",
+ }}
+ />
+ ) : (
+ <Image
+ src={image_url}
+ alt={`${name} preview image`}
+ width={107}
+ height={58}
+ className="flex-shrink-0 rounded-small object-cover"
+ />
+ )}
</Link>
- {can_access_graph && (
+ <div className="mt-auto flex w-full justify-start gap-6 border-t border-zinc-100 pb-1 pt-3">
<Link
- href={`/build?flowID=${graph_id}`}
- data-testid="library-agent-card-open-in-builder-link"
+ href={`/library/agents/${id}`}
+ data-testid="library-agent-card-see-runs-link"
className="flex items-center gap-1 text-[13px]"
- isExternal
>
- Open in builder <CaretCircleRightIcon size={20} />
+ See runs <CaretCircleRightIcon size={20} />
</Link>
- )}
+
+ {can_access_graph && (
+ <Link
+ href={`/build?flowID=${graph_id}`}
+ data-testid="library-agent-card-open-in-builder-link"
+ className="flex items-center gap-1 text-[13px]"
+ isExternal
+ >
+ Open in builder <CaretCircleRightIcon size={20} />
+ </Link>
+ )}
+ </div>
</div>
- </div>
+ </motion.div>
</div>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx
index 933cdd34fa..afea4e9fe7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx
@@ -5,6 +5,10 @@ import {
useDeleteV2DeleteLibraryAgent,
usePostV2ForkLibraryAgent,
} from "@/app/api/__generated__/endpoints/library/library";
+import {
+ usePostV2BulkMoveAgents,
+ getGetV2ListLibraryFoldersQueryKey,
+} from "@/app/api/__generated__/endpoints/folders/folders";
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
@@ -22,6 +26,7 @@ import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
+import { MoveToFolderDialog } from "../../MoveToFolderDialog/MoveToFolderDialog";
interface AgentCardMenuProps {
agent: LibraryAgent;
@@ -32,11 +37,25 @@ export function AgentCardMenu({ agent }: AgentCardMenuProps) {
const queryClient = useQueryClient();
const router = useRouter();
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
+ const [showMoveDialog, setShowMoveDialog] = useState(false);
const [isDeletingAgent, setIsDeletingAgent] = useState(false);
const [isDuplicatingAgent, setIsDuplicatingAgent] = useState(false);
+ const [isRemovingFromFolder, setIsRemovingFromFolder] = useState(false);
const { mutateAsync: deleteAgent } = useDeleteV2DeleteLibraryAgent();
const { mutateAsync: forkAgent } = usePostV2ForkLibraryAgent();
+ const { mutateAsync: bulkMoveAgents } = usePostV2BulkMoveAgents({
+ mutation: {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryAgentsQueryKey(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ },
+ },
+ });
async function handleDuplicateAgent() {
if (!agent.id) return;
@@ -70,6 +89,37 @@ export function AgentCardMenu({ agent }: AgentCardMenuProps) {
}
}
+ async function handleRemoveFromFolder() {
+ if (!agent.id) return;
+
+ setIsRemovingFromFolder(true);
+
+ try {
+ await bulkMoveAgents({
+ data: {
+ agent_ids: [agent.id],
+ folder_id: null,
+ },
+ });
+
+ toast({
+ title: "Removed from folder",
+ description: "Agent has been moved back to your library.",
+ });
+ } catch (error: unknown) {
+ toast({
+ title: "Failed to remove from folder",
+ description:
+ error instanceof Error
+ ? error.message
+ : "An unexpected error occurred.",
+ variant: "destructive",
+ });
+ } finally {
+ setIsRemovingFromFolder(false);
+ }
+ }
+
async function handleDeleteAgent() {
if (!agent.id) return;
@@ -138,6 +188,31 @@ export function AgentCardMenu({ agent }: AgentCardMenuProps) {
Duplicate agent
</DropdownMenuItem>
<DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowMoveDialog(true);
+ }}
+ className="flex items-center gap-2"
+ >
+ Move to folder
+ </DropdownMenuItem>
+ {agent.folder_id && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.stopPropagation();
+ handleRemoveFromFolder();
+ }}
+ disabled={isRemovingFromFolder}
+ className="flex items-center gap-2"
+ >
+ Remove from folder
+ </DropdownMenuItem>
+ </>
+ )}
+ <DropdownMenuSeparator />
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
@@ -183,6 +258,14 @@ export function AgentCardMenu({ agent }: AgentCardMenuProps) {
</div>
</Dialog.Content>
</Dialog>
+
+ <MoveToFolderDialog
+ agentId={agent.id}
+ agentName={agent.name}
+ currentFolderId={agent.folder_id}
+ isOpen={showMoveDialog}
+ setIsOpen={setShowMoveDialog}
+ />
</>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/FavoriteButton.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/FavoriteButton.tsx
index df11553ec1..2289ab918b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/FavoriteButton.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/FavoriteButton.tsx
@@ -3,10 +3,15 @@
import { cn } from "@/lib/utils";
import { HeartIcon } from "@phosphor-icons/react";
import type { MouseEvent } from "react";
+import { useRef } from "react";
+import { motion, AnimatePresence } from "framer-motion";
interface FavoriteButtonProps {
isFavorite: boolean;
- onClick: (e: MouseEvent<HTMLButtonElement>) => void;
+ onClick: (
+ e: MouseEvent<HTMLButtonElement>,
+ position: { x: number; y: number },
+ ) => void;
className?: string;
}
@@ -15,25 +20,49 @@ export function FavoriteButton({
onClick,
className,
}: FavoriteButtonProps) {
+ const buttonRef = useRef<HTMLButtonElement>(null);
+
+ function handleClick(e: MouseEvent<HTMLButtonElement>) {
+ const rect = buttonRef.current?.getBoundingClientRect();
+ const position = rect
+ ? {
+ x: rect.left + rect.width / 2 - 12,
+ y: rect.top + rect.height / 2 - 12,
+ }
+ : { x: 0, y: 0 };
+ onClick(e, position);
+ }
+
return (
<button
- onClick={onClick}
+ ref={buttonRef}
+ onClick={handleClick}
className={cn(
"rounded-full p-2 transition-all duration-200",
- "hover:scale-110",
+ "hover:scale-110 active:scale-95",
!isFavorite && "opacity-0 group-hover:opacity-100",
className,
)}
aria-label={isFavorite ? "Remove from favorites" : "Add to favorites"}
>
- <HeartIcon
- size={20}
- weight={isFavorite ? "fill" : "regular"}
- className={cn(
- "transition-colors duration-200",
- isFavorite ? "text-red-500" : "text-gray-600 hover:text-red-500",
- )}
- />
+ <AnimatePresence mode="wait" initial={false}>
+ <motion.div
+ key={isFavorite ? "filled" : "empty"}
+ initial={{ scale: 0.5, opacity: 0 }}
+ animate={{ scale: 1, opacity: 1 }}
+ exit={{ scale: 0.5, opacity: 0 }}
+ transition={{ type: "spring", damping: 15, stiffness: 300 }}
+ >
+ <HeartIcon
+ size={20}
+ weight={isFavorite ? "fill" : "regular"}
+ className={cn(
+ "transition-colors duration-200",
+ isFavorite ? "text-red-500" : "text-gray-600 hover:text-red-500",
+ )}
+ />
+ </motion.div>
+ </AnimatePresence>
</button>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/useLibraryAgentCard.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/useLibraryAgentCard.ts
index 87e9e9e9bc..4362da1ea8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/useLibraryAgentCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/useLibraryAgentCard.ts
@@ -14,11 +14,11 @@ import { updateFavoriteInQueries } from "./helpers";
interface Props {
agent: LibraryAgent;
+ onFavoriteAdd?: (position: { x: number; y: number }) => void;
}
-export function useLibraryAgentCard({ agent }: Props) {
- const { id, name, is_favorite, creator_image_url, marketplace_listing } =
- agent;
+export function useLibraryAgentCard({ agent, onFavoriteAdd }: Props) {
+ const { id, is_favorite, creator_image_url, marketplace_listing } = agent;
const isFromMarketplace = Boolean(marketplace_listing);
const [isFavorite, setIsFavorite] = useState(is_favorite);
@@ -49,26 +49,31 @@ export function useLibraryAgentCard({ agent }: Props) {
});
}
- async function handleToggleFavorite(e: React.MouseEvent) {
+ async function handleToggleFavorite(
+ e: React.MouseEvent,
+ position: { x: number; y: number },
+ ) {
e.preventDefault();
e.stopPropagation();
const newIsFavorite = !isFavorite;
+ // Optimistic update - update UI immediately
setIsFavorite(newIsFavorite);
updateQueryData(newIsFavorite);
+ // Trigger animation immediately for adding to favorites
+ if (newIsFavorite && onFavoriteAdd) {
+ onFavoriteAdd(position);
+ }
+
try {
await updateLibraryAgent({
libraryAgentId: id,
data: { is_favorite: newIsFavorite },
});
-
- toast({
- title: newIsFavorite ? "Added to favorites" : "Removed from favorites",
- description: `${name} has been ${newIsFavorite ? "added to" : "removed from"} your favorites.`,
- });
} catch {
+ // Revert on failure
setIsFavorite(!newIsFavorite);
updateQueryData(!newIsFavorite);
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
index 074cd8ae26..906b7cf0eb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
@@ -1,30 +1,123 @@
"use client";
+
import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";
import { InfiniteScroll } from "@/components/contextual/InfiniteScroll/InfiniteScroll";
import { LibraryActionSubHeader } from "../LibraryActionSubHeader/LibraryActionSubHeader";
import { LibraryAgentCard } from "../LibraryAgentCard/LibraryAgentCard";
+import { LibraryFolder } from "../LibraryFolder/LibraryFolder";
+import { LibrarySubSection } from "../LibrarySubSection/LibrarySubSection";
+import { Button } from "@/components/atoms/Button/Button";
+import { ArrowLeftIcon, HeartIcon } from "@phosphor-icons/react";
+import { Text } from "@/components/atoms/Text/Text";
+import { Tab } from "../LibraryTabs/LibraryTabs";
+import {
+ AnimatePresence,
+ LayoutGroup,
+ motion,
+ useReducedMotion,
+} from "framer-motion";
+import { LibraryFolderEditDialog } from "../LibraryFolderEditDialog/LibraryFolderEditDialog";
+import { LibraryFolderDeleteDialog } from "../LibraryFolderDeleteDialog/LibraryFolderDeleteDialog";
import { useLibraryAgentList } from "./useLibraryAgentList";
+// cancels the current spring and starts a new one from current state.
+const containerVariants = {
+ hidden: {},
+ show: {},
+ exit: {
+ opacity: 0,
+ filter: "blur(4px)",
+ transition: { duration: 0.12 },
+ },
+};
+
+const reducedContainerVariants = {
+ hidden: {},
+ show: {},
+ exit: {
+ opacity: 0,
+ transition: { duration: 0.12 },
+ },
+};
+
+const itemInitial = {
+ opacity: 0,
+ filter: "blur(4px)",
+};
+
+const itemAnimate = {
+ opacity: 1,
+ filter: "blur(0px)",
+};
+
+const itemTransition = {
+ type: "spring" as const,
+ stiffness: 300,
+ damping: 25,
+ opacity: { duration: 0.2 },
+ filter: { duration: 0.15 },
+};
+
+const reducedItemInitial = { opacity: 0 };
+const reducedItemAnimate = { opacity: 1 };
+const reducedItemTransition = { duration: 0.15 };
+
interface Props {
searchTerm: string;
librarySort: LibraryAgentSort;
setLibrarySort: (value: LibraryAgentSort) => void;
+ selectedFolderId: string | null;
+ onFolderSelect: (folderId: string | null) => void;
+ tabs: Tab[];
+ activeTab: string;
+ onTabChange: (tabId: string) => void;
}
export function LibraryAgentList({
searchTerm,
librarySort,
setLibrarySort,
+ selectedFolderId,
+ onFolderSelect,
+ tabs,
+ activeTab,
+ onTabChange,
}: Props) {
+ const shouldReduceMotion = useReducedMotion();
+ const activeContainerVariants = shouldReduceMotion
+ ? reducedContainerVariants
+ : containerVariants;
+ const activeInitial = shouldReduceMotion ? reducedItemInitial : itemInitial;
+ const activeAnimate = shouldReduceMotion ? reducedItemAnimate : itemAnimate;
+ const activeTransition = shouldReduceMotion
+ ? reducedItemTransition
+ : itemTransition;
+
const {
+ isFavoritesTab,
agentLoading,
agentCount,
- allAgents: agents,
+ agents,
hasNextPage,
isFetchingNextPage,
fetchNextPage,
- } = useLibraryAgentList({ searchTerm, librarySort });
+ foldersData,
+ currentFolder,
+ showFolders,
+ editingFolder,
+ setEditingFolder,
+ deletingFolder,
+ setDeletingFolder,
+ handleAgentDrop,
+ handleFolderDeleted,
+ } = useLibraryAgentList({
+ searchTerm,
+ librarySort,
+ selectedFolderId,
+ onFolderSelect,
+ activeTab,
+ });
return (
<>
@@ -32,11 +125,47 @@ export function LibraryAgentList({
agentCount={agentCount}
setLibrarySort={setLibrarySort}
/>
- <div className="px-2">
+ {!selectedFolderId && (
+ <LibrarySubSection
+ tabs={tabs}
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ />
+ )}
+
+ <div>
+ {selectedFolderId && (
+ <div className="mb-4 flex items-center gap-2">
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={() => onFolderSelect(null)}
+ className="gap-1 text-zinc-500 hover:text-zinc-900"
+ >
+ <ArrowLeftIcon className="h-4 w-4" />
+ My Library
+ </Button>
+ {currentFolder && (
+ <>
+ <Text variant="small" className="text-zinc-400">
+ /
+ </Text>
+ <Text variant="h4" className="text-zinc-700">
+ {currentFolder.icon} {currentFolder.name}
+ </Text>
+ </>
+ )}
+ </div>
+ )}
{agentLoading ? (
<div className="flex h-[200px] items-center justify-center">
<LoadingSpinner size="large" />
</div>
+ ) : isFavoritesTab && agents.length === 0 ? (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-2 text-zinc-500">
+ <HeartIcon className="h-10 w-10" />
+ <Text variant="body">No favorite agents yet</Text>
+ </div>
) : (
<InfiniteScroll
isFetchingNextPage={isFetchingNextPage}
@@ -44,14 +173,85 @@ export function LibraryAgentList({
hasNextPage={hasNextPage}
loader={<LoadingSpinner size="medium" />}
>
- <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
- {agents.map((agent) => (
- <LibraryAgentCard key={agent.id} agent={agent} />
- ))}
- </div>
+ <LayoutGroup>
+ <AnimatePresence mode="popLayout">
+ <motion.div
+ key={`${activeTab}-${selectedFolderId || "all"}`}
+ className="grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
+ variants={activeContainerVariants}
+ initial="hidden"
+ animate="show"
+ exit="exit"
+ >
+ {showFolders &&
+ foldersData?.folders.map((folder, i) => (
+ <motion.div
+ key={folder.id}
+ initial={activeInitial}
+ animate={activeAnimate}
+ transition={{
+ ...activeTransition,
+ delay: i * 0.04,
+ }}
+ >
+ <LibraryFolder
+ id={folder.id}
+ name={folder.name}
+ agentCount={folder.agent_count ?? 0}
+ color={folder.color ?? undefined}
+ icon={folder.icon ?? "📁"}
+ onAgentDrop={handleAgentDrop}
+ onClick={() => onFolderSelect(folder.id)}
+ onEdit={() => setEditingFolder(folder)}
+ onDelete={() => setDeletingFolder(folder)}
+ />
+ </motion.div>
+ ))}
+ {agents.map((agent, i) => (
+ <motion.div
+ key={agent.id}
+ initial={activeInitial}
+ animate={activeAnimate}
+ transition={{
+ ...activeTransition,
+ delay:
+ ((showFolders
+ ? (foldersData?.folders.length ?? 0)
+ : 0) +
+ i) *
+ 0.04,
+ }}
+ >
+ <LibraryAgentCard agent={agent} />
+ </motion.div>
+ ))}
+ </motion.div>
+ </AnimatePresence>
+ </LayoutGroup>
</InfiniteScroll>
)}
</div>
+
+ {editingFolder && (
+ <LibraryFolderEditDialog
+ folder={editingFolder}
+ isOpen={!!editingFolder}
+ setIsOpen={(open) => {
+ if (!open) setEditingFolder(null);
+ }}
+ />
+ )}
+
+ {deletingFolder && (
+ <LibraryFolderDeleteDialog
+ folder={deletingFolder}
+ isOpen={!!deletingFolder}
+ setIsOpen={(open) => {
+ if (!open) setDeletingFolder(null);
+ }}
+ onDeleted={handleFolderDeleted}
+ />
+ )}
</>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts
index 0b102ff545..2304a13e3e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts
@@ -1,36 +1,69 @@
"use client";
import { useGetV2ListLibraryAgentsInfinite } from "@/app/api/__generated__/endpoints/library/library";
+import { getGetV2ListLibraryAgentsQueryKey } from "@/app/api/__generated__/endpoints/library/library";
+import {
+ useGetV2ListLibraryFolders,
+ usePostV2BulkMoveAgents,
+ getGetV2ListLibraryFoldersQueryKey,
+} from "@/app/api/__generated__/endpoints/folders/folders";
+import type { getV2ListLibraryFoldersResponseSuccess } from "@/app/api/__generated__/endpoints/folders/folders";
+import type { LibraryFolder } from "@/app/api/__generated__/models/libraryFolder";
import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
import {
+ okData,
getPaginatedTotalCount,
getPaginationNextPageNumber,
unpaginate,
} from "@/app/api/helpers";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useFavoriteAgents } from "../../hooks/useFavoriteAgents";
import { getQueryClient } from "@/lib/react-query/queryClient";
-import { useEffect, useRef } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useEffect, useRef, useState } from "react";
interface Props {
searchTerm: string;
librarySort: LibraryAgentSort;
+ selectedFolderId: string | null;
+ onFolderSelect: (folderId: string | null) => void;
+ activeTab: string;
}
-export function useLibraryAgentList({ searchTerm, librarySort }: Props) {
- const queryClient = getQueryClient();
+export function useLibraryAgentList({
+ searchTerm,
+ librarySort,
+ selectedFolderId,
+ onFolderSelect,
+ activeTab,
+}: Props) {
+ const isFavoritesTab = activeTab === "favorites";
+ const { toast } = useToast();
+ const stableQueryClient = getQueryClient();
+ const queryClient = useQueryClient();
const prevSortRef = useRef<LibraryAgentSort | null>(null);
+ const [editingFolder, setEditingFolder] = useState<LibraryFolder | null>(
+ null,
+ );
+ const [deletingFolder, setDeletingFolder] = useState<LibraryFolder | null>(
+ null,
+ );
+
const {
data: agentsQueryData,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
- isLoading: agentLoading,
+ isLoading: allAgentsLoading,
} = useGetV2ListLibraryAgentsInfinite(
{
page: 1,
page_size: 20,
search_term: searchTerm || undefined,
sort_by: librarySort,
+ folder_id: selectedFolderId ?? undefined,
+ include_root_only: selectedFolderId === null ? true : undefined,
},
{
query: {
@@ -39,28 +72,147 @@ export function useLibraryAgentList({ searchTerm, librarySort }: Props) {
},
);
- // Reset queries when sort changes to ensure fresh data with correct sorting
useEffect(() => {
if (prevSortRef.current !== null && prevSortRef.current !== librarySort) {
- // Reset all library agent queries to ensure fresh fetch with new sort
- queryClient.resetQueries({
+ stableQueryClient.resetQueries({
queryKey: ["/api/library/agents"],
});
}
prevSortRef.current = librarySort;
- }, [librarySort, queryClient]);
+ }, [librarySort, stableQueryClient]);
- const allAgents = agentsQueryData
+ const allAgentsList = agentsQueryData
? unpaginate(agentsQueryData, "agents")
: [];
- const agentCount = getPaginatedTotalCount(agentsQueryData);
+ const allAgentsCount = getPaginatedTotalCount(agentsQueryData);
+
+ const favoriteAgentsData = useFavoriteAgents({ searchTerm });
+
+ const {
+ agentLoading,
+ agentCount,
+ allAgents: agents,
+ hasNextPage: agentsHasNextPage,
+ isFetchingNextPage: agentsIsFetchingNextPage,
+ fetchNextPage: agentsFetchNextPage,
+ } = isFavoritesTab
+ ? favoriteAgentsData
+ : {
+ agentLoading: allAgentsLoading,
+ agentCount: allAgentsCount,
+ allAgents: allAgentsList,
+ hasNextPage: hasNextPage,
+ isFetchingNextPage: isFetchingNextPage,
+ fetchNextPage: fetchNextPage,
+ };
+
+ const { data: rawFoldersData } = useGetV2ListLibraryFolders(undefined, {
+ query: { select: okData },
+ });
+
+ const foldersData = searchTerm ? undefined : rawFoldersData;
+
+ const { mutate: moveAgentToFolder } = usePostV2BulkMoveAgents({
+ mutation: {
+ onMutate: async ({ data }) => {
+ await queryClient.cancelQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ await queryClient.cancelQueries({
+ queryKey: getGetV2ListLibraryAgentsQueryKey(),
+ });
+
+ const previousFolders =
+ queryClient.getQueriesData<getV2ListLibraryFoldersResponseSuccess>({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+
+ if (data.folder_id) {
+ queryClient.setQueriesData<getV2ListLibraryFoldersResponseSuccess>(
+ { queryKey: getGetV2ListLibraryFoldersQueryKey() },
+ (old) => {
+ if (!old?.data?.folders) return old;
+ return {
+ ...old,
+ data: {
+ ...old.data,
+ folders: old.data.folders.map((f) =>
+ f.id === data.folder_id
+ ? {
+ ...f,
+ agent_count:
+ (f.agent_count ?? 0) + data.agent_ids.length,
+ }
+ : f,
+ ),
+ },
+ };
+ },
+ );
+ }
+
+ return { previousFolders };
+ },
+ onError: (_error, _variables, context) => {
+ if (context?.previousFolders) {
+ for (const [queryKey, data] of context.previousFolders) {
+ queryClient.setQueryData(queryKey, data);
+ }
+ }
+ toast({
+ title: "Error",
+ description: "Failed to move agent. Please try again.",
+ variant: "destructive",
+ });
+ },
+ onSettled: () => {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryAgentsQueryKey(),
+ });
+ },
+ },
+ });
+
+ function handleAgentDrop(agentId: string, folderId: string) {
+ moveAgentToFolder({
+ data: {
+ agent_ids: [agentId],
+ folder_id: folderId,
+ },
+ });
+ }
+
+ const currentFolder = selectedFolderId
+ ? foldersData?.folders.find((f) => f.id === selectedFolderId)
+ : null;
+
+ const showFolders = !isFavoritesTab && !selectedFolderId;
+
+ function handleFolderDeleted() {
+ if (selectedFolderId === deletingFolder?.id) {
+ onFolderSelect(null);
+ }
+ }
return {
- allAgents,
+ isFavoritesTab,
agentLoading,
- hasNextPage,
agentCount,
- isFetchingNextPage,
- fetchNextPage,
+ agents,
+ hasNextPage: agentsHasNextPage,
+ isFetchingNextPage: agentsIsFetchingNextPage,
+ fetchNextPage: agentsFetchNextPage,
+ foldersData,
+ currentFolder,
+ showFolders,
+ editingFolder,
+ setEditingFolder,
+ deletingFolder,
+ setDeletingFolder,
+ handleAgentDrop,
+ handleFolderDeleted,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/FolderIcon.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/FolderIcon.tsx
new file mode 100644
index 0000000000..5ad2c3093c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/FolderIcon.tsx
@@ -0,0 +1,255 @@
+import { motion } from "framer-motion";
+import { Text } from "@/components/atoms/Text/Text";
+
+type FolderSize = "xs" | "sm" | "md" | "lg" | "xl";
+export type FolderColorName = "blue" | "purple" | "emerald" | "orange" | "pink";
+
+export type FolderColor = FolderColorName | (string & {});
+
+const hexToColorName: Record<string, FolderColorName> = {
+ "#3B82F6": "blue",
+ "#3b82f6": "blue",
+ "#A855F7": "purple",
+ "#a855f7": "purple",
+ "#10B981": "emerald",
+ "#10b981": "emerald",
+ "#F97316": "orange",
+ "#f97316": "orange",
+ "#EC4899": "pink",
+ "#ec4899": "pink",
+};
+
+export function resolveColor(color: FolderColor | undefined): FolderColorName {
+ if (!color) return "blue";
+ if (color in hexToColorName) return hexToColorName[color];
+ if (color in colorMap) return color as FolderColorName;
+ return "blue";
+}
+
+interface Props {
+ className?: string;
+ size?: FolderSize | number;
+ color?: FolderColor;
+ icon?: string;
+ isOpen?: boolean;
+}
+
+const sizeMap: Record<FolderSize, number> = {
+ xs: 0.4,
+ sm: 0.75,
+ md: 1,
+ lg: 1.25,
+ xl: 1.5,
+};
+
+const colorMap: Record<
+ FolderColorName,
+ {
+ bg: string;
+ border: string;
+ borderLight: string;
+ fill: string;
+ stroke: string;
+ }
+> = {
+ blue: {
+ bg: "bg-blue-300",
+ border: "border-blue-300",
+ borderLight: "border-blue-200",
+ fill: "fill-blue-300",
+ stroke: "stroke-blue-400",
+ },
+ purple: {
+ bg: "bg-purple-200",
+ border: "border-purple-200",
+ borderLight: "border-purple-200",
+ fill: "fill-purple-200",
+ stroke: "stroke-purple-400",
+ },
+ emerald: {
+ bg: "bg-emerald-300",
+ border: "border-emerald-300",
+ borderLight: "border-emerald-200",
+ fill: "fill-emerald-300",
+ stroke: "stroke-emerald-400",
+ },
+ orange: {
+ bg: "bg-orange-200",
+ border: "border-orange-200",
+ borderLight: "border-orange-200",
+ fill: "fill-orange-200",
+ stroke: "stroke-orange-400",
+ },
+ pink: {
+ bg: "bg-pink-300",
+ border: "border-pink-300",
+ borderLight: "border-pink-200",
+ fill: "fill-pink-300",
+ stroke: "stroke-pink-400",
+ },
+};
+
+export const folderCardStyles: Record<
+ FolderColorName,
+ { bg: string; border: string; buttonBase: string; buttonHover: string }
+> = {
+ blue: {
+ bg: "bg-blue-50",
+ border: "border-blue-200",
+ buttonBase: "border-zinc-600 text-black",
+ buttonHover: "hover:bg-blue-200",
+ },
+ purple: {
+ bg: "bg-purple-50",
+ border: "border-purple-200",
+ buttonBase: "border-zinc-600 text-black ",
+ buttonHover: "hover:bg-purple-200",
+ },
+ emerald: {
+ bg: "bg-emerald-50",
+ border: "border-emerald-200",
+ buttonBase: "border-zinc-600 text-black",
+ buttonHover: "hover:bg-emerald-200",
+ },
+ orange: {
+ bg: "bg-orange-50",
+ border: "border-orange-200",
+ buttonBase: "border-zinc-600 text-black",
+ buttonHover: "hover:bg-orange-200",
+ },
+ pink: {
+ bg: "bg-pink-50",
+ border: "border-pink-200",
+ buttonBase: "border-zinc-600 text-black",
+ buttonHover: "hover:bg-pink-200",
+ },
+};
+
+export function FolderIcon({
+ className = "",
+ size = "xs",
+ color = "blue",
+ icon,
+ isOpen = false,
+}: Props) {
+ const scale = typeof size === "number" ? size : sizeMap[size];
+ const resolvedColor = resolveColor(color);
+ const colors = colorMap[resolvedColor];
+
+ return (
+ <div
+ className={`group relative cursor-pointer ${className}`}
+ style={{
+ width: 320 * scale,
+ height: 208 * scale,
+ }}
+ >
+ <div
+ className="h-52 w-80 origin-top-left"
+ style={{ transform: `scale(${scale})`, perspective: "500px" }}
+ >
+ <div
+ className={`folder-back relative mx-auto flex h-full w-[87.5%] justify-center overflow-visible rounded-3xl ${colors.bg} ${colors.border}`}
+ >
+ {[
+ {
+ initial: { rotate: -3, x: -38, y: 2 },
+ open: { rotate: -8, x: -70, y: -75 },
+ transition: {
+ type: "spring" as const,
+ bounce: 0.15,
+ stiffness: 160,
+ damping: 22,
+ },
+ className: "z-10",
+ },
+ {
+ initial: { rotate: 0, x: 0, y: 0 },
+ open: { rotate: 1, x: 2, y: -95 },
+ transition: {
+ type: "spring" as const,
+ duration: 0.55,
+ bounce: 0.12,
+ stiffness: 190,
+ damping: 24,
+ },
+ className: "z-20",
+ },
+ {
+ initial: { rotate: 3.5, x: 42, y: 1 },
+ open: { rotate: 9, x: 75, y: -80 },
+ transition: {
+ type: "spring" as const,
+ duration: 0.58,
+ bounce: 0.17,
+ stiffness: 170,
+ damping: 21,
+ },
+ className: "z-10",
+ },
+ ].map((page, i) => (
+ <motion.div
+ key={i}
+ initial={page.initial}
+ animate={isOpen ? page.open : page.initial}
+ transition={page.transition}
+ className={`absolute top-2 h-fit w-32 rounded-xl shadow-lg ${page.className}`}
+ >
+ <Page color={resolvedColor} />
+ </motion.div>
+ ))}
+ </div>
+
+ <motion.div
+ animate={{
+ rotateX: isOpen ? -15 : 0,
+ }}
+ transition={{ type: "spring", duration: 0.5, bounce: 0.25 }}
+ className="absolute inset-x-0 -bottom-px z-30 mx-auto flex h-44 w-[87.5%] origin-bottom items-end justify-center overflow-visible"
+ style={{ transformStyle: "preserve-3d" }}
+ >
+ <svg
+ className="h-auto w-full"
+ viewBox="0 0 173 109"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ preserveAspectRatio="none"
+ >
+ <path
+ className={`${colors.fill} ${colors.stroke}`}
+ d="M15.0423 0.500003C0.5 0.500009 0.5 14.2547 0.5 14.2547V92.5C0.5 101.337 7.66344 108.5 16.5 108.5H156.5C165.337 108.5 172.5 101.337 172.5 92.5V34.3302C172.5 25.4936 165.355 18.3302 156.519 18.3302H108.211C98.1341 18.3302 91.2921 5.57144 82.0156 1.63525C80.3338 0.921645 78.2634 0.500002 75.7187 0.500003H15.0423Z"
+ />
+ </svg>
+ <div className="absolute inset-0 flex items-center justify-center text-7xl">
+ {icon}
+ </div>
+ </motion.div>
+ </div>
+ </div>
+ );
+}
+
+interface PageProps {
+ color: FolderColorName;
+}
+
+function Page({ color = "blue" }: PageProps) {
+ const colors = colorMap[color];
+ return (
+ <div
+ className={`h-full w-full rounded-xl border bg-white p-4 ${colors.borderLight}`}
+ >
+ <div className="flex flex-col gap-2">
+ <Text variant="h5" className="text-black">
+ agent.json
+ </Text>
+ {Array.from({ length: 8 }).map((_, i) => (
+ <div key={i} className="flex gap-2">
+ <div className="h-1.5 flex-1 rounded-full bg-neutral-100" />
+ <div className="h-1.5 flex-1 rounded-full bg-neutral-100" />
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsx
new file mode 100644
index 0000000000..58e2392adb
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolder/LibraryFolder.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { Button } from "@/components/atoms/Button/Button";
+import {
+ FolderIcon,
+ FolderColor,
+ folderCardStyles,
+ resolveColor,
+} from "./FolderIcon";
+import { useState } from "react";
+import { PencilSimpleIcon, TrashIcon } from "@phosphor-icons/react";
+
+interface Props {
+ id: string;
+ name: string;
+ agentCount: number;
+ color?: FolderColor;
+ icon: string;
+ onEdit?: () => void;
+ onDelete?: () => void;
+ onAgentDrop?: (agentId: string, folderId: string) => void;
+ onClick?: () => void;
+}
+
+export function LibraryFolder({
+ id,
+ name,
+ agentCount,
+ color,
+ icon,
+ onEdit,
+ onDelete,
+ onAgentDrop,
+ onClick,
+}: Props) {
+ const [isHovered, setIsHovered] = useState(false);
+ const [isDragOver, setIsDragOver] = useState(false);
+ const resolvedColor = resolveColor(color);
+ const cardStyle = folderCardStyles[resolvedColor];
+
+ function handleDragOver(e: React.DragEvent<HTMLDivElement>) {
+ if (e.dataTransfer.types.includes("application/agent-id")) {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "move";
+ setIsDragOver(true);
+ }
+ }
+
+ function handleDragLeave() {
+ setIsDragOver(false);
+ }
+
+ function handleDrop(e: React.DragEvent<HTMLDivElement>) {
+ e.preventDefault();
+ setIsDragOver(false);
+ const agentId = e.dataTransfer.getData("application/agent-id");
+ if (agentId && onAgentDrop) {
+ onAgentDrop(agentId, id);
+ }
+ }
+
+ return (
+ <div
+ data-testid="library-folder"
+ data-folder-id={id}
+ className={`group relative inline-flex h-[10.625rem] w-full max-w-[25rem] cursor-pointer flex-col items-start justify-between gap-2.5 rounded-medium border p-4 transition-all duration-200 hover:shadow-md ${
+ isDragOver
+ ? "border-blue-400 bg-blue-50 ring-2 ring-blue-200"
+ : `${cardStyle.border} ${cardStyle.bg}`
+ }`}
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ onClick={onClick}
+ >
+ <div className="flex w-full items-start justify-between gap-4">
+ {/* Left side - Folder name and agent count */}
+ <div className="flex flex-1 flex-col gap-2">
+ <Text
+ variant="h5"
+ data-testid="library-folder-name"
+ className="line-clamp-2 hyphens-auto break-words"
+ >
+ {name}
+ </Text>
+ <Text
+ variant="small"
+ className="text-zinc-500"
+ data-testid="library-folder-agent-count"
+ >
+ {agentCount} {agentCount === 1 ? "agent" : "agents"}
+ </Text>
+ </div>
+
+ {/* Right side - Custom folder icon */}
+ <div className="flex-shrink-0">
+ <FolderIcon isOpen={isHovered} color={color} icon={icon} />
+ </div>
+ </div>
+
+ {/* Action buttons - visible on hover */}
+ <div
+ className="flex items-center justify-end gap-2"
+ data-testid="library-folder-actions"
+ >
+ <Button
+ variant="icon"
+ size="icon"
+ aria-label="Edit folder"
+ onClick={(e) => {
+ e.stopPropagation();
+ onEdit?.();
+ }}
+ className={`h-8 w-8 border p-2 ${cardStyle.buttonBase} ${cardStyle.buttonHover}`}
+ >
+ <PencilSimpleIcon className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="icon"
+ size="icon"
+ aria-label="Delete folder"
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete?.();
+ }}
+ className={`h-8 w-8 border p-2 ${cardStyle.buttonBase} ${cardStyle.buttonHover}`}
+ >
+ <TrashIcon className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderCreationDialog/LibraryFolderCreationDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderCreationDialog/LibraryFolderCreationDialog.tsx
new file mode 100644
index 0000000000..383ea97a3c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderCreationDialog/LibraryFolderCreationDialog.tsx
@@ -0,0 +1,224 @@
+"use client";
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Select } from "@/components/atoms/Select/Select";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormMessage,
+} from "@/components/molecules/Form/Form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { FolderSimpleIcon } from "@phosphor-icons/react";
+import { useState } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import dynamic from "next/dynamic";
+import {
+ usePostV2CreateFolder,
+ getGetV2ListLibraryFoldersQueryKey,
+} from "@/app/api/__generated__/endpoints/folders/folders";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useQueryClient } from "@tanstack/react-query";
+import { FOLDER_COLORS } from "../folder-constants";
+
+const LazyEmojiPicker = dynamic(
+ () =>
+ import("../LazyEmojiPicker").then((mod) => ({
+ default: mod.LazyEmojiPicker,
+ })),
+ { ssr: false },
+);
+
+export const libraryFolderCreationFormSchema = z.object({
+ folderName: z
+ .string()
+ .min(1, "Folder name is required")
+ .max(100, "Folder name must be 100 characters or less"),
+ folderColor: z.string().min(1, "Folder color is required"),
+ folderIcon: z.string().min(1, "Folder icon is required"),
+});
+
+export default function LibraryFolderCreationDialog() {
+ const [isOpen, setIsOpen] = useState(false);
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+
+ const { mutate: createFolder, isPending } = usePostV2CreateFolder({
+ mutation: {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ setIsOpen(false);
+ form.reset();
+ toast({
+ title: "Folder created",
+ description: "Your folder has been created successfully.",
+ });
+ },
+ onError: () => {
+ toast({
+ title: "Error",
+ description: "Failed to create folder. Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ const form = useForm<z.infer<typeof libraryFolderCreationFormSchema>>({
+ resolver: zodResolver(libraryFolderCreationFormSchema),
+ defaultValues: {
+ folderName: "",
+ folderColor: "",
+ folderIcon: "",
+ },
+ });
+
+ function onSubmit(values: z.infer<typeof libraryFolderCreationFormSchema>) {
+ createFolder({
+ data: {
+ name: values.folderName.trim(),
+ color: values.folderColor,
+ icon: values.folderIcon,
+ },
+ });
+ }
+
+ return (
+ <Dialog
+ title="Create Folder"
+ styling={{ maxWidth: "30rem" }}
+ controlled={{
+ isOpen,
+ set: setIsOpen,
+ }}
+ onClose={() => {
+ setIsOpen(false);
+ }}
+ >
+ <Dialog.Trigger>
+ <Button
+ data-testid="upload-agent-button"
+ variant="secondary"
+ className="h-fit w-fit"
+ size="small"
+ >
+ <FolderSimpleIcon width={18} height={18} />
+ <span className="create-folder">Create folder</span>
+ </Button>
+ </Dialog.Trigger>
+ <Dialog.Content>
+ <Form
+ form={form}
+ onSubmit={(values) => onSubmit(values)}
+ className="flex flex-col justify-center gap-2 px-1"
+ >
+ <FormField
+ control={form.control}
+ name="folderName"
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input
+ {...field}
+ id={field.name}
+ label="Folder name"
+ placeholder="Enter folder name"
+ className="!mb-0 w-full"
+ wrapperClassName="!mb-0"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="folderColor"
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Select
+ id="folderColor"
+ label="Folder color"
+ placeholder="Select a color"
+ value={field.value}
+ onValueChange={field.onChange}
+ options={FOLDER_COLORS.map((color) => ({
+ value: color.value,
+ label: color.label,
+ icon: (
+ <div
+ className="h-4 w-4 rounded-full"
+ style={{ backgroundColor: color.value }}
+ />
+ ),
+ }))}
+ wrapperClassName="!mb-0"
+ renderItem={(option) => (
+ <div className="flex items-center gap-2">
+ {option.icon}
+ <span>{option.label}</span>
+ </div>
+ )}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="folderIcon"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex flex-col gap-2">
+ <Text variant="large-medium" as="span" className="text-black">
+ Folder icon
+ </Text>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-3">
+ <Text variant="small" className="text-zinc-500">
+ Selected:
+ </Text>
+ <div className="flex h-10 w-10 items-center justify-center rounded-lg border border-zinc-200 bg-zinc-50 text-2xl">
+ {form.watch("folderIcon") || (
+ <span className="text-sm text-zinc-400">—</span>
+ )}
+ </div>
+ </div>
+ <div className="h-[295px] w-full overflow-hidden">
+ <LazyEmojiPicker
+ onEmojiSelect={(emoji) => {
+ field.onChange(emoji);
+ }}
+ />
+ </div>
+ </div>
+ <FormMessage />
+ </div>
+ </FormItem>
+ )}
+ />
+
+ <Button
+ type="submit"
+ variant="primary"
+ className="mt-2 min-w-[18rem]"
+ disabled={!form.formState.isValid || isPending}
+ loading={isPending}
+ >
+ Create
+ </Button>
+ </Form>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderDeleteDialog/LibraryFolderDeleteDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderDeleteDialog/LibraryFolderDeleteDialog.tsx
new file mode 100644
index 0000000000..96bca8f120
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderDeleteDialog/LibraryFolderDeleteDialog.tsx
@@ -0,0 +1,96 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ useDeleteV2DeleteFolder,
+ getGetV2ListLibraryFoldersQueryKey,
+} from "@/app/api/__generated__/endpoints/folders/folders";
+import { getGetV2ListLibraryAgentsQueryKey } from "@/app/api/__generated__/endpoints/library/library";
+import { useQueryClient } from "@tanstack/react-query";
+import type { LibraryFolder } from "@/app/api/__generated__/models/libraryFolder";
+
+interface Props {
+ folder: LibraryFolder;
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+ onDeleted?: () => void;
+}
+
+export function LibraryFolderDeleteDialog({
+ folder,
+ isOpen,
+ setIsOpen,
+ onDeleted,
+}: Props) {
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+
+ const { mutate: deleteFolder, isPending } = useDeleteV2DeleteFolder({
+ mutation: {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryAgentsQueryKey(),
+ });
+ toast({
+ title: "Folder deleted",
+ description: `"${folder.name}" has been deleted.`,
+ });
+ setIsOpen(false);
+ onDeleted?.();
+ },
+ onError: () => {
+ toast({
+ title: "Error",
+ description: "Failed to delete folder. Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ function handleDelete() {
+ deleteFolder({ folderId: folder.id });
+ }
+
+ return (
+ <Dialog
+ controlled={{
+ isOpen,
+ set: setIsOpen,
+ }}
+ styling={{ maxWidth: "32rem" }}
+ title="Delete folder"
+ >
+ <Dialog.Content>
+ <div>
+ <Text variant="large">
+ Are you sure you want to delete &ldquo;{folder.name}&rdquo;? Agents
+ inside this folder will be moved back to your library.
+ </Text>
+ <Dialog.Footer>
+ <Button
+ variant="secondary"
+ disabled={isPending}
+ onClick={() => setIsOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={handleDelete}
+ loading={isPending}
+ >
+ Delete Folder
+ </Button>
+ </Dialog.Footer>
+ </div>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderEditDialog/LibraryFolderEditDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderEditDialog/LibraryFolderEditDialog.tsx
new file mode 100644
index 0000000000..4c20cc6130
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderEditDialog/LibraryFolderEditDialog.tsx
@@ -0,0 +1,282 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Select } from "@/components/atoms/Select/Select";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import {
+ Form,
+ FormControl,
+ FormField,
+ FormItem,
+ FormMessage,
+} from "@/components/molecules/Form/Form";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useEffect } from "react";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import dynamic from "next/dynamic";
+import {
+ usePatchV2UpdateFolder,
+ getGetV2ListLibraryFoldersQueryKey,
+} from "@/app/api/__generated__/endpoints/folders/folders";
+import { useQueryClient } from "@tanstack/react-query";
+import type { LibraryFolder } from "@/app/api/__generated__/models/libraryFolder";
+import type { getV2ListLibraryFoldersResponseSuccess } from "@/app/api/__generated__/endpoints/folders/folders";
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { FOLDER_COLORS } from "../folder-constants";
+
+const LazyEmojiPicker = dynamic(
+ () =>
+ import("../LazyEmojiPicker").then((mod) => ({
+ default: mod.LazyEmojiPicker,
+ })),
+ { ssr: false },
+);
+
+const editFolderSchema = z.object({
+ folderName: z
+ .string()
+ .min(1, "Folder name is required")
+ .max(100, "Folder name must be 100 characters or less"),
+ folderColor: z.string().min(1, "Folder color is required"),
+ folderIcon: z.string().min(1, "Folder icon is required"),
+});
+
+interface Props {
+ folder: LibraryFolder;
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+}
+
+export function LibraryFolderEditDialog({ folder, isOpen, setIsOpen }: Props) {
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+
+ const form = useForm<z.infer<typeof editFolderSchema>>({
+ resolver: zodResolver(editFolderSchema),
+ defaultValues: {
+ folderName: folder.name,
+ folderColor: folder.color ?? "",
+ folderIcon: folder.icon ?? "",
+ },
+ });
+
+ useEffect(() => {
+ if (isOpen) {
+ form.reset({
+ folderName: folder.name,
+ folderColor: folder.color ?? "",
+ folderIcon: folder.icon ?? "",
+ });
+ }
+ }, [isOpen, folder, form]);
+
+ const { mutate: updateFolder, isPending } = usePatchV2UpdateFolder({
+ mutation: {
+ onMutate: async ({ folderId, data }) => {
+ await queryClient.cancelQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+
+ const previousData =
+ queryClient.getQueriesData<getV2ListLibraryFoldersResponseSuccess>({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+
+ queryClient.setQueriesData<getV2ListLibraryFoldersResponseSuccess>(
+ { queryKey: getGetV2ListLibraryFoldersQueryKey() },
+ (old) => {
+ if (!old?.data?.folders) return old;
+ return {
+ ...old,
+ data: {
+ ...old.data,
+ folders: old.data.folders.map((f) =>
+ f.id === folderId
+ ? {
+ ...f,
+ name: data.name ?? f.name,
+ color: data.color ?? f.color,
+ icon: data.icon ?? f.icon,
+ }
+ : f,
+ ),
+ },
+ };
+ },
+ );
+
+ return { previousData };
+ },
+ onError: (error: unknown, _variables, context) => {
+ if (context?.previousData) {
+ for (const [queryKey, data] of context.previousData) {
+ queryClient.setQueryData(queryKey, data);
+ }
+ }
+ if (error instanceof ApiError) {
+ const detail = (error.response as any)?.detail ?? "";
+ if (
+ typeof detail === "string" &&
+ detail.toLowerCase().includes("already exists")
+ ) {
+ form.setError("folderName", {
+ message: "A folder with this name already exists",
+ });
+ return;
+ }
+ }
+ toast({
+ title: "Error",
+ description: "Failed to update folder. Please try again.",
+ variant: "destructive",
+ });
+ },
+ onSuccess: () => {
+ setIsOpen(false);
+ toast({
+ title: "Folder updated",
+ description: "Your folder has been updated successfully.",
+ });
+ },
+ onSettled: () => {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ },
+ },
+ });
+
+ function onSubmit(values: z.infer<typeof editFolderSchema>) {
+ updateFolder({
+ folderId: folder.id,
+ data: {
+ name: values.folderName.trim(),
+ color: values.folderColor,
+ icon: values.folderIcon,
+ },
+ });
+ }
+
+ return (
+ <Dialog
+ title="Edit Folder"
+ styling={{ maxWidth: "30rem" }}
+ controlled={{
+ isOpen,
+ set: setIsOpen,
+ }}
+ >
+ <Dialog.Content>
+ <Form
+ form={form}
+ onSubmit={(values) => onSubmit(values)}
+ className="flex flex-col justify-center gap-2 px-1"
+ >
+ <FormField
+ control={form.control}
+ name="folderName"
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input
+ {...field}
+ id={field.name}
+ label="Folder name"
+ placeholder="Enter folder name"
+ className="w-full"
+ wrapperClassName="!mb-0"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="folderColor"
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Select
+ id="folderColor"
+ label="Folder color"
+ placeholder="Select a color"
+ value={field.value}
+ onValueChange={field.onChange}
+ wrapperClassName="!mb-0"
+ options={FOLDER_COLORS.map((color) => ({
+ value: color.value,
+ label: color.label,
+ icon: (
+ <div
+ className="h-4 w-4 rounded-full"
+ style={{ backgroundColor: color.value }}
+ />
+ ),
+ }))}
+ renderItem={(option) => (
+ <div className="flex items-center gap-2">
+ {option.icon}
+ <span>{option.label}</span>
+ </div>
+ )}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="folderIcon"
+ render={({ field }) => (
+ <FormItem>
+ <div className="flex flex-col gap-2">
+ <Text variant="large-medium" as="span" className="text-black">
+ Folder icon
+ </Text>
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center gap-3">
+ <Text variant="small" className="text-zinc-500">
+ Selected:
+ </Text>
+ <div className="flex h-10 w-10 items-center justify-center rounded-lg border border-zinc-200 bg-zinc-50 text-2xl">
+ {form.watch("folderIcon") || (
+ <span className="text-sm text-zinc-400">—</span>
+ )}
+ </div>
+ </div>
+ <div className="h-[295px] w-full overflow-hidden">
+ <LazyEmojiPicker
+ onEmojiSelect={(emoji) => {
+ field.onChange(emoji);
+ }}
+ />
+ </div>
+ </div>
+ <FormMessage />
+ </div>
+ </FormItem>
+ )}
+ />
+
+ <Button
+ type="submit"
+ variant="primary"
+ className="mt-2 min-w-[18rem]"
+ disabled={!form.formState.isValid || isPending}
+ loading={isPending}
+ >
+ Save Changes
+ </Button>
+ </Form>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsx
new file mode 100644
index 0000000000..f69f9f57ac
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySubSection/LibrarySubSection.tsx
@@ -0,0 +1,21 @@
+import LibraryFolderCreationDialog from "../LibraryFolderCreationDialog/LibraryFolderCreationDialog";
+import { LibraryTabs, Tab } from "../LibraryTabs/LibraryTabs";
+
+interface Props {
+ tabs: Tab[];
+ activeTab: string;
+ onTabChange: (tabId: string) => void;
+}
+
+export function LibrarySubSection({ tabs, activeTab, onTabChange }: Props) {
+ return (
+ <div className="flex items-center justify-between gap-4">
+ <LibraryTabs
+ tabs={tabs}
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ />
+ <LibraryFolderCreationDialog />
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryTabs/LibraryTabs.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryTabs/LibraryTabs.tsx
new file mode 100644
index 0000000000..88fd29bc0f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryTabs/LibraryTabs.tsx
@@ -0,0 +1,147 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import { motion } from "framer-motion";
+import { cn } from "@/lib/utils";
+import { Icon } from "@phosphor-icons/react";
+import { useFavoriteAnimation } from "../../context/FavoriteAnimationContext";
+
+export interface Tab {
+ id: string;
+ title: string;
+ icon: Icon;
+}
+
+interface Props {
+ tabs: Tab[];
+ activeTab: string;
+ onTabChange: (tabId: string) => void;
+ layoutId?: string;
+}
+
+export function LibraryTabs({
+ tabs,
+ activeTab,
+ onTabChange,
+ layoutId = "library-tabs",
+}: Props) {
+ const { registerFavoritesTabRef } = useFavoriteAnimation();
+
+ return (
+ <div className="flex items-center gap-2">
+ {tabs.map((tab) => (
+ <TabButton
+ key={tab.id}
+ tab={tab}
+ isActive={activeTab === tab.id}
+ onSelect={onTabChange}
+ layoutId={layoutId}
+ onRefReady={
+ tab.id === "favorites" ? registerFavoritesTabRef : undefined
+ }
+ />
+ ))}
+ </div>
+ );
+}
+
+interface TabButtonProps {
+ tab: Tab;
+ isActive: boolean;
+ onSelect: (tabId: string) => void;
+ layoutId: string;
+ onRefReady?: (element: HTMLElement | null) => void;
+}
+
+function TabButton({
+ tab,
+ isActive,
+ onSelect,
+ layoutId,
+ onRefReady,
+}: TabButtonProps) {
+ const [isLoaded, setIsLoaded] = useState(false);
+ const buttonRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (isActive && !isLoaded) {
+ setIsLoaded(true);
+ }
+ }, [isActive, isLoaded]);
+
+ useEffect(() => {
+ if (onRefReady) {
+ onRefReady(buttonRef.current);
+ }
+ }, [onRefReady]);
+
+ const ButtonIcon = tab.icon;
+ const activeColor = "text-primary";
+
+ return (
+ <motion.div
+ ref={buttonRef}
+ layoutId={`${layoutId}-button-${tab.id}`}
+ transition={{
+ layout: {
+ type: "spring",
+ damping: 20,
+ stiffness: 230,
+ mass: 1.2,
+ ease: [0.215, 0.61, 0.355, 1],
+ },
+ }}
+ onClick={() => {
+ onSelect(tab.id);
+ setIsLoaded(true);
+ }}
+ className="flex h-fit w-fit"
+ style={{ willChange: "transform" }}
+ >
+ <motion.div
+ layout
+ transition={{
+ layout: {
+ type: "spring",
+ damping: 20,
+ stiffness: 230,
+ mass: 1.2,
+ },
+ }}
+ className={cn(
+ "flex h-fit cursor-pointer items-center gap-1.5 overflow-hidden border border-zinc-200 px-3 py-2 text-black transition-colors duration-75 ease-out hover:border-zinc-300 hover:bg-zinc-300",
+ isActive && activeColor,
+ isActive ? "px-4" : "px-3",
+ )}
+ style={{
+ borderRadius: "25px",
+ }}
+ >
+ <motion.div
+ layoutId={`${layoutId}-icon-${tab.id}`}
+ className="shrink-0"
+ >
+ <ButtonIcon size={18} />
+ </motion.div>
+ {isActive && (
+ <motion.div
+ className="flex items-center"
+ initial={isLoaded ? { opacity: 0, filter: "blur(4px)" } : false}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ duration: isLoaded ? 0.2 : 0,
+ ease: [0.86, 0, 0.07, 1],
+ }}
+ >
+ <motion.span
+ layoutId={`${layoutId}-text-${tab.id}`}
+ className="font-sans text-sm font-medium text-black"
+ >
+ {tab.title}
+ </motion.span>
+ </motion.div>
+ )}
+ </motion.div>
+ </motion.div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/MoveToFolderDialog/MoveToFolderDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/MoveToFolderDialog/MoveToFolderDialog.tsx
new file mode 100644
index 0000000000..0374d86cd0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/MoveToFolderDialog/MoveToFolderDialog.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Text } from "@/components/atoms/Text/Text";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ useGetV2ListLibraryFolders,
+ usePostV2BulkMoveAgents,
+ getGetV2ListLibraryFoldersQueryKey,
+} from "@/app/api/__generated__/endpoints/folders/folders";
+import { getGetV2ListLibraryAgentsQueryKey } from "@/app/api/__generated__/endpoints/library/library";
+import { okData } from "@/app/api/helpers";
+import { useQueryClient } from "@tanstack/react-query";
+import { useMemo, useState } from "react";
+import type { LibraryFolder } from "@/app/api/__generated__/models/libraryFolder";
+
+interface Props {
+ agentId: string;
+ agentName: string;
+ currentFolderId?: string | null;
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+}
+
+export function MoveToFolderDialog({
+ agentId,
+ agentName,
+ currentFolderId,
+ isOpen,
+ setIsOpen,
+}: Props) {
+ const queryClient = useQueryClient();
+ const { toast } = useToast();
+ const [search, setSearch] = useState("");
+
+ const { data: foldersData } = useGetV2ListLibraryFolders(undefined, {
+ query: { select: okData },
+ });
+
+ const { mutate: moveAgent, isPending } = usePostV2BulkMoveAgents({
+ mutation: {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryAgentsQueryKey(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: getGetV2ListLibraryFoldersQueryKey(),
+ });
+ setIsOpen(false);
+ setSearch("");
+ toast({
+ title: "Agent moved",
+ description: `"${agentName}" has been moved.`,
+ });
+ },
+ onError: () => {
+ toast({
+ title: "Error",
+ description: "Failed to move agent. Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ const hierarchicalFolders = useMemo(() => {
+ const allFolders = foldersData?.folders ?? [];
+ const result: { folder: LibraryFolder; depth: number }[] = [];
+
+ function addChildren(parentId: string | null, depth: number) {
+ for (const f of allFolders) {
+ if ((f.parent_id ?? null) === parentId) {
+ result.push({ folder: f, depth });
+ addChildren(f.id, depth + 1);
+ }
+ }
+ }
+
+ addChildren(null, 0);
+ return result;
+ }, [foldersData]);
+
+ const folders = hierarchicalFolders.filter(
+ ({ folder: f }) =>
+ f.id !== currentFolderId &&
+ f.name.toLowerCase().includes(search.toLowerCase()),
+ );
+
+ function handleMoveToFolder(folderId: string | null) {
+ moveAgent({
+ data: {
+ agent_ids: [agentId],
+ folder_id: folderId,
+ },
+ });
+ }
+
+ return (
+ <Dialog
+ controlled={{ isOpen, set: setIsOpen }}
+ styling={{ maxWidth: "28rem" }}
+ title="Move to folder"
+ onClose={() => {
+ setSearch("");
+ }}
+ >
+ <Dialog.Content>
+ <div className="flex flex-col gap-3">
+ <Input
+ id="search-folders"
+ label="Search folders"
+ placeholder="Search folders..."
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ className="w-full"
+ />
+ <div className="max-h-[280px] overflow-y-auto">
+ {folders.length === 0 ? (
+ <div className="flex h-20 items-center justify-center">
+ <Text variant="small" className="text-zinc-400">
+ No folders found
+ </Text>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1">
+ {currentFolderId && (
+ <Button
+ variant="ghost"
+ className="w-full justify-start gap-3 px-3 py-2.5"
+ disabled={isPending}
+ onClick={() => handleMoveToFolder(null)}
+ >
+ <span className="text-lg">📂</span>
+ <div className="flex flex-col items-start">
+ <Text variant="small-medium">My Library (root)</Text>
+ <Text variant="small" className="text-zinc-400">
+ Remove from folder
+ </Text>
+ </div>
+ </Button>
+ )}
+ {folders.map(({ folder, depth }) => (
+ <Button
+ key={folder.id}
+ variant="ghost"
+ className="w-full justify-start gap-3 py-2.5"
+ style={{ paddingLeft: `${0.75 + depth * 1.25}rem` }}
+ disabled={isPending}
+ onClick={() => handleMoveToFolder(folder.id)}
+ >
+ <span className="text-lg">{folder.icon ?? "📁"}</span>
+ <div className="flex flex-col items-start">
+ <Text variant="small-medium">{folder.name}</Text>
+ <Text variant="small" className="text-zinc-400">
+ {folder.agent_count ?? 0}{" "}
+ {(folder.agent_count ?? 0) === 1 ? "agent" : "agents"}
+ </Text>
+ </div>
+ </Button>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/folder-constants.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/folder-constants.ts
new file mode 100644
index 0000000000..8327fe6bf7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/folder-constants.ts
@@ -0,0 +1,7 @@
+export const FOLDER_COLORS = [
+ { value: "#3B82F6", label: "Blue" },
+ { value: "#A855F7", label: "Purple" },
+ { value: "#10B981", label: "Green" },
+ { value: "#F97316", label: "Orange" },
+ { value: "#EC4899", label: "Pink" },
+];
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/context/FavoriteAnimationContext.tsx b/autogpt_platform/frontend/src/app/(platform)/library/context/FavoriteAnimationContext.tsx
new file mode 100644
index 0000000000..f2d7fa2051
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/context/FavoriteAnimationContext.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+import {
+ createContext,
+ useContext,
+ useState,
+ useCallback,
+ useRef,
+} from "react";
+import { FlyingHeart } from "../components/FlyingHeart/FlyingHeart";
+
+interface FavoriteAnimationContextType {
+ triggerFavoriteAnimation: (startPosition: { x: number; y: number }) => void;
+ registerFavoritesTabRef: (element: HTMLElement | null) => void;
+}
+
+const FavoriteAnimationContext =
+ createContext<FavoriteAnimationContextType | null>(null);
+
+interface FavoriteAnimationProviderProps {
+ children: React.ReactNode;
+ onAnimationComplete?: () => void;
+}
+
+export function FavoriteAnimationProvider({
+ children,
+ onAnimationComplete,
+}: FavoriteAnimationProviderProps) {
+ const [animationState, setAnimationState] = useState<{
+ startPosition: { x: number; y: number } | null;
+ targetPosition: { x: number; y: number } | null;
+ }>({
+ startPosition: null,
+ targetPosition: null,
+ });
+
+ const favoritesTabRef = useRef<HTMLElement | null>(null);
+
+ const registerFavoritesTabRef = useCallback((element: HTMLElement | null) => {
+ favoritesTabRef.current = element;
+ }, []);
+
+ const triggerFavoriteAnimation = useCallback(
+ (startPosition: { x: number; y: number }) => {
+ if (favoritesTabRef.current) {
+ const rect = favoritesTabRef.current.getBoundingClientRect();
+ const targetPosition = {
+ x: rect.left + rect.width / 2 - 12,
+ y: rect.top + rect.height / 2 - 12,
+ };
+ setAnimationState({ startPosition, targetPosition });
+ }
+ },
+ [],
+ );
+
+ function handleAnimationComplete() {
+ setAnimationState({ startPosition: null, targetPosition: null });
+ onAnimationComplete?.();
+ }
+
+ return (
+ <FavoriteAnimationContext.Provider
+ value={{ triggerFavoriteAnimation, registerFavoritesTabRef }}
+ >
+ {children}
+ <FlyingHeart
+ startPosition={animationState.startPosition}
+ targetPosition={animationState.targetPosition}
+ onAnimationComplete={handleAnimationComplete}
+ />
+ </FavoriteAnimationContext.Provider>
+ );
+}
+
+export function useFavoriteAnimation() {
+ const context = useContext(FavoriteAnimationContext);
+ if (!context) {
+ throw new Error(
+ "useFavoriteAnimation must be used within FavoriteAnimationProvider",
+ );
+ }
+ return context;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx b/autogpt_platform/frontend/src/app/(platform)/library/page.tsx
index c619d480e0..2510bd8f33 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/page.tsx
@@ -1,28 +1,55 @@
"use client";
-import { useEffect } from "react";
-import { FavoritesSection } from "./components/FavoritesSection/FavoritesSection";
+import { useEffect, useState, useCallback } from "react";
+import { HeartIcon, ListIcon } from "@phosphor-icons/react";
import { LibraryActionHeader } from "./components/LibraryActionHeader/LibraryActionHeader";
import { LibraryAgentList } from "./components/LibraryAgentList/LibraryAgentList";
+import { Tab } from "./components/LibraryTabs/LibraryTabs";
import { useLibraryListPage } from "./components/useLibraryListPage";
+import { FavoriteAnimationProvider } from "./context/FavoriteAnimationContext";
+
+const LIBRARY_TABS: Tab[] = [
+ { id: "all", title: "All", icon: ListIcon },
+ { id: "favorites", title: "Favorites", icon: HeartIcon },
+];
export default function LibraryPage() {
const { searchTerm, setSearchTerm, librarySort, setLibrarySort } =
useLibraryListPage();
+ const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
+ const [activeTab, setActiveTab] = useState(LIBRARY_TABS[0].id);
useEffect(() => {
document.title = "Library – AutoGPT Platform";
}, []);
+ function handleTabChange(tabId: string) {
+ setActiveTab(tabId);
+ setSelectedFolderId(null);
+ }
+
+ const handleFavoriteAnimationComplete = useCallback(() => {
+ setActiveTab("favorites");
+ setSelectedFolderId(null);
+ }, []);
+
return (
- <main className="pt-160 container min-h-screen space-y-4 pb-20 pt-16 sm:px-8 md:px-12">
- <LibraryActionHeader setSearchTerm={setSearchTerm} />
- <FavoritesSection searchTerm={searchTerm} />
- <LibraryAgentList
- searchTerm={searchTerm}
- librarySort={librarySort}
- setLibrarySort={setLibrarySort}
- />
- </main>
+ <FavoriteAnimationProvider
+ onAnimationComplete={handleFavoriteAnimationComplete}
+ >
+ <main className="pt-160 container min-h-screen space-y-4 pb-20 pt-16 sm:px-8 md:px-12">
+ <LibraryActionHeader setSearchTerm={setSearchTerm} />
+ <LibraryAgentList
+ searchTerm={searchTerm}
+ librarySort={librarySort}
+ setLibrarySort={setLibrarySort}
+ selectedFolderId={selectedFolderId}
+ onFolderSelect={setSelectedFolderId}
+ tabs={LIBRARY_TABS}
+ activeTab={activeTab}
+ onTabChange={handleTabChange}
+ />
+ </main>
+ </FavoriteAnimationProvider>
);
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 315ae4a9d7..dc1e24c13a 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3510,6 +3510,29 @@
"title": "Page Size"
},
"description": "Number of agents per page (must be >= 1)"
+ },
+ {
+ "name": "folder_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Filter by folder ID",
+ "title": "Folder Id"
+ },
+ "description": "Filter by folder ID"
+ },
+ {
+ "name": "include_root_only",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "description": "Only return agents without a folder (root-level agents)",
+ "default": false,
+ "title": "Include Root Only"
+ },
+ "description": "Only return agents without a folder (root-level agents)"
}
],
"responses": {
@@ -3877,6 +3900,338 @@
}
}
},
+ "/api/library/folders": {
+ "get": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "List Library Folders",
+ "description": "List folders for the authenticated user.\n\nArgs:\n user_id: ID of the authenticated user.\n parent_id: Optional parent folder ID to filter by.\n include_relations: Whether to include agent and subfolder relations for counts.\n\nReturns:\n A FolderListResponse containing folders.",
+ "operationId": "getV2List library folders",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "parent_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "description": "Filter by parent folder ID. If not provided, returns root-level folders.",
+ "title": "Parent Id"
+ },
+ "description": "Filter by parent folder ID. If not provided, returns root-level folders."
+ },
+ {
+ "name": "include_relations",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "description": "Include agent and subfolder relations (for counts)",
+ "default": true,
+ "title": "Include Relations"
+ },
+ "description": "Include agent and subfolder relations (for counts)"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of folders",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/FolderListResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ }
+ },
+ "post": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Create Folder",
+ "description": "Create a new folder.\n\nArgs:\n payload: The folder creation request.\n user_id: ID of the authenticated user.\n\nReturns:\n The created LibraryFolder.",
+ "operationId": "postV2Create folder",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/FolderCreateRequest" }
+ }
+ }
+ },
+ "responses": {
+ "201": {
+ "description": "Folder created successfully",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/LibraryFolder" }
+ }
+ }
+ },
+ "400": { "description": "Validation error" },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Parent folder not found" },
+ "409": { "description": "Folder name conflict" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ }
+ }
+ },
+ "/api/library/folders/agents/bulk-move": {
+ "post": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Bulk Move Agents",
+ "description": "Move multiple agents to a folder.\n\nArgs:\n payload: The bulk move request with agent IDs and target folder.\n user_id: ID of the authenticated user.\n\nReturns:\n The updated LibraryAgents.",
+ "operationId": "postV2Bulk move agents",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/BulkMoveAgentsRequest" }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Agents moved successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": { "$ref": "#/components/schemas/LibraryAgent" },
+ "type": "array",
+ "title": "Response Postv2Bulk Move Agents"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Folder not found" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
+ "/api/library/folders/tree": {
+ "get": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Get Folder Tree",
+ "description": "Get the full folder tree for the authenticated user.\n\nArgs:\n user_id: ID of the authenticated user.\n\nReturns:\n A FolderTreeResponse containing the nested folder structure.",
+ "operationId": "getV2Get folder tree",
+ "responses": {
+ "200": {
+ "description": "Folder tree structure",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/FolderTreeResponse" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "500": { "description": "Server error" }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
+ "/api/library/folders/{folder_id}": {
+ "delete": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Delete Folder",
+ "description": "Soft-delete a folder and all its contents.\n\nArgs:\n folder_id: ID of the folder to delete.\n user_id: ID of the authenticated user.\n\nReturns:\n 204 No Content if successful.",
+ "operationId": "deleteV2Delete folder",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "folder_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Folder Id" }
+ }
+ ],
+ "responses": {
+ "204": { "description": "Folder deleted successfully" },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Folder not found" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ }
+ },
+ "get": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Get Folder",
+ "description": "Get a specific folder.\n\nArgs:\n folder_id: ID of the folder to retrieve.\n user_id: ID of the authenticated user.\n\nReturns:\n The requested LibraryFolder.",
+ "operationId": "getV2Get folder",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "folder_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Folder Id" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Folder details",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/LibraryFolder" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Folder not found" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ }
+ },
+ "patch": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Update Folder",
+ "description": "Update a folder's properties.\n\nArgs:\n folder_id: ID of the folder to update.\n payload: The folder update request.\n user_id: ID of the authenticated user.\n\nReturns:\n The updated LibraryFolder.",
+ "operationId": "patchV2Update folder",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "folder_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Folder Id" }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/FolderUpdateRequest" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Folder updated successfully",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/LibraryFolder" }
+ }
+ }
+ },
+ "400": { "description": "Validation error" },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Folder not found" },
+ "409": { "description": "Folder name conflict" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ }
+ }
+ },
+ "/api/library/folders/{folder_id}/move": {
+ "post": {
+ "tags": ["v2", "library", "folders", "private"],
+ "summary": "Move Folder",
+ "description": "Move a folder to a new parent.\n\nArgs:\n folder_id: ID of the folder to move.\n payload: The move request with target parent.\n user_id: ID of the authenticated user.\n\nReturns:\n The moved LibraryFolder.",
+ "operationId": "postV2Move folder",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "folder_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Folder Id" }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/FolderMoveRequest" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Folder moved successfully",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/LibraryFolder" }
+ }
+ }
+ },
+ "400": { "description": "Validation error (circular reference)" },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "Folder or target parent not found" },
+ "409": { "description": "Folder name conflict in target location" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "500": { "description": "Server error" }
+ }
+ }
+ },
"/api/library/presets": {
"get": {
"tags": ["v2", "presets"],
@@ -7425,6 +7780,23 @@
"required": ["file"],
"title": "Body_postV2Upload submission media"
},
+ "BulkMoveAgentsRequest": {
+ "properties": {
+ "agent_ids": {
+ "items": { "type": "string" },
+ "type": "array",
+ "title": "Agent Ids"
+ },
+ "folder_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Folder Id"
+ }
+ },
+ "type": "object",
+ "required": ["agent_ids"],
+ "title": "BulkMoveAgentsRequest",
+ "description": "Request model for moving multiple agents to a folder."
+ },
"CancelSessionResponse": {
"properties": {
"cancelled": { "type": "boolean", "title": "Cancelled" },
@@ -8161,6 +8533,96 @@
"title": "ExecutionStartedResponse",
"description": "Response for run/schedule actions."
},
+ "FolderCreateRequest": {
+ "properties": {
+ "name": {
+ "type": "string",
+ "maxLength": 100,
+ "minLength": 1,
+ "title": "Name"
+ },
+ "icon": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Icon"
+ },
+ "color": {
+ "anyOf": [
+ { "type": "string", "pattern": "^#[0-9A-Fa-f]{6}$" },
+ { "type": "null" }
+ ],
+ "title": "Color",
+ "description": "Hex color code (#RRGGBB)"
+ },
+ "parent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Id"
+ }
+ },
+ "type": "object",
+ "required": ["name"],
+ "title": "FolderCreateRequest",
+ "description": "Request model for creating a folder."
+ },
+ "FolderListResponse": {
+ "properties": {
+ "folders": {
+ "items": { "$ref": "#/components/schemas/LibraryFolder" },
+ "type": "array",
+ "title": "Folders"
+ },
+ "pagination": { "$ref": "#/components/schemas/Pagination" }
+ },
+ "type": "object",
+ "required": ["folders", "pagination"],
+ "title": "FolderListResponse",
+ "description": "Response schema for a list of folders."
+ },
+ "FolderMoveRequest": {
+ "properties": {
+ "target_parent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Target Parent Id"
+ }
+ },
+ "type": "object",
+ "title": "FolderMoveRequest",
+ "description": "Request model for moving a folder to a new parent."
+ },
+ "FolderTreeResponse": {
+ "properties": {
+ "tree": {
+ "items": { "$ref": "#/components/schemas/LibraryFolderTree" },
+ "type": "array",
+ "title": "Tree"
+ }
+ },
+ "type": "object",
+ "required": ["tree"],
+ "title": "FolderTreeResponse",
+ "description": "Response schema for folder tree structure."
+ },
+ "FolderUpdateRequest": {
+ "properties": {
+ "name": {
+ "anyOf": [
+ { "type": "string", "maxLength": 100, "minLength": 1 },
+ { "type": "null" }
+ ],
+ "title": "Name"
+ },
+ "icon": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Icon"
+ },
+ "color": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Color"
+ }
+ },
+ "type": "object",
+ "title": "FolderUpdateRequest",
+ "description": "Request model for updating a folder."
+ },
"Graph": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -9049,6 +9511,14 @@
"title": "Is Latest Version"
},
"is_favorite": { "type": "boolean", "title": "Is Favorite" },
+ "folder_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Folder Id"
+ },
+ "folder_name": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Folder Name"
+ },
"recommended_schedule_cron": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Recommended Schedule Cron"
@@ -9316,12 +9786,109 @@
{ "type": "null" }
],
"description": "User-specific settings for this library agent"
+ },
+ "folder_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Folder Id",
+ "description": "Folder ID to move agent to (None to move to root)"
}
},
"type": "object",
"title": "LibraryAgentUpdateRequest",
"description": "Schema for updating a library agent via PUT.\n\nIncludes flags for auto-updating version, marking as favorite,\narchiving, or deleting."
},
+ "LibraryFolder": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "user_id": { "type": "string", "title": "User Id" },
+ "name": { "type": "string", "title": "Name" },
+ "icon": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Icon"
+ },
+ "color": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Color"
+ },
+ "parent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Id"
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Updated At"
+ },
+ "agent_count": {
+ "type": "integer",
+ "title": "Agent Count",
+ "default": 0
+ },
+ "subfolder_count": {
+ "type": "integer",
+ "title": "Subfolder Count",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "required": ["id", "user_id", "name", "created_at", "updated_at"],
+ "title": "LibraryFolder",
+ "description": "Represents a folder for organizing library agents."
+ },
+ "LibraryFolderTree": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "user_id": { "type": "string", "title": "User Id" },
+ "name": { "type": "string", "title": "Name" },
+ "icon": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Icon"
+ },
+ "color": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Color"
+ },
+ "parent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Id"
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Updated At"
+ },
+ "agent_count": {
+ "type": "integer",
+ "title": "Agent Count",
+ "default": 0
+ },
+ "subfolder_count": {
+ "type": "integer",
+ "title": "Subfolder Count",
+ "default": 0
+ },
+ "children": {
+ "items": { "$ref": "#/components/schemas/LibraryFolderTree" },
+ "type": "array",
+ "title": "Children",
+ "default": []
+ }
+ },
+ "type": "object",
+ "required": ["id", "user_id", "name", "created_at", "updated_at"],
+ "title": "LibraryFolderTree",
+ "description": "Folder with nested children for tree view."
+ },
"Link": {
"properties": {
"id": { "type": "string", "title": "Id" },
diff --git a/autogpt_platform/frontend/src/tests/pages/library.page.ts b/autogpt_platform/frontend/src/tests/pages/library.page.ts
index fae3b15c4d..c6d450346e 100644
--- a/autogpt_platform/frontend/src/tests/pages/library.page.ts
+++ b/autogpt_platform/frontend/src/tests/pages/library.page.ts
@@ -444,7 +444,10 @@ export async function navigateToAgentByName(
// Wait for the agent card to be visible before clicking
// This handles async loading of agents after page navigation
await agentCard.waitFor({ state: "visible", timeout: 15000 });
- await agentCard.click();
+ // Click the link inside the card to navigate reliably through
+ // the motion.div + draggable wrapper layers.
+ const link = agentCard.locator('a[href*="/library/agents/"]').first();
+ await link.click();
}
export async function clickRunButton(page: Page): Promise<void> {
@@ -481,19 +484,17 @@ export async function clickRunButton(page: Page): Promise<void> {
// Check which button is visible and click it
if (await setupTaskButton.isVisible()) {
await setupTaskButton.click();
- await page
- .getByRole("button", { name: /Start Task/i })
- .first()
- .click({ timeout: 10000 });
+ const startBtn = page.getByRole("button", { name: /Start Task/i }).first();
+ await startBtn.waitFor({ state: "visible", timeout: 15000 });
+ await startBtn.click();
return;
}
if (await newTaskButton.isVisible()) {
await newTaskButton.click();
- await page
- .getByRole("button", { name: /Start Task/i })
- .first()
- .click({ timeout: 10000 });
+ const startBtn = page.getByRole("button", { name: /Start Task/i }).first();
+ await startBtn.waitFor({ state: "visible", timeout: 15000 });
+ await startBtn.click();
return;
}