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.
fix(backend/library): refuse a template from a pre-credentials run with a 400, not a 500 (#15613)
Reinier van der Leer60e48de70b8d
diff --git a/autogpt_platform/backend/backend/api/features/library/routes/presets.py b/autogpt_platform/backend/backend/api/features/library/routes/presets.pyindex 24d10bc81c..8b37329059 100644--- a/autogpt_platform/backend/backend/api/features/library/routes/presets.py+++ b/autogpt_platform/backend/backend/api/features/library/routes/presets.py@@ -1,4 +1,3 @@-import loggingfrom typing import Any, Optionalimport autogpt_libs.auth as autogpt_auth_lib@@ -11,8 +10,6 @@ from backend.data.model import CredentialsMetaInputfrom backend.executor.utils import add_graph_executionfrom backend.util.exceptions import (ExpertRunPausedError,- MissingConfigError,- NotFoundError,WebhookRegistrationError,WebhookSetupUnavailableError,)@@ -25,8 +22,6 @@ from ..triggers import (update_triggered_preset,)-logger = logging.getLogger(__name__)-router = APIRouter(tags=["presets"],dependencies=[Security(autogpt_auth_lib.requires_user)],@@ -58,18 +53,12 @@ async def list_presets(Returns:models.LibraryAgentPresetResponse: A response containing the list of presets."""- try:- return await db.list_presets(- user_id=user_id,- graph_id=graph_id,- page=page,- page_size=page_size,- )- except Exception as e:- logger.exception("Failed to list presets for user %s: %s", user_id, e)- raise HTTPException(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)- )+ return await db.list_presets(+ user_id=user_id,+ graph_id=graph_id,+ page=page,+ page_size=page_size,+ )@router.get(@@ -92,18 +81,9 @@ async def get_preset(models.LibraryAgentPreset: The preset details.Raises:- HTTPException: If the preset is not found or an error occurs.+ HTTPException: If the preset is not found."""- try:- preset = await db.get_preset(user_id, preset_id)- except Exception as e:- logger.exception(- "Error retrieving preset %s for user %s: %s", preset_id, user_id, e- )- raise HTTPException(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)- )-+ preset = await db.get_preset(user_id, preset_id)if not preset:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,@@ -133,32 +113,18 @@ async def create_preset(Returns:models.LibraryAgentPreset: The created preset.-- Raises:- HTTPException: If an error occurs while creating the preset."""- try:- if isinstance(preset, models.LibraryAgentPresetCreatable):- return await db.create_preset(- user_id,- preset,- expert_id=await experts_db.resolve_expert_for_graph(- user_id, preset.graph_id- ),- )- else:- return await db.create_preset_from_graph_execution(user_id, preset)- except NotFoundError as e:- raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))- except MissingConfigError as e:- raise HTTPException(- status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=str(e)- )- except Exception as e:- logger.exception("Preset creation failed for user %s: %s", user_id, e)- raise HTTPException(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)+ # Errors are answered by the global handlers in rest_api.py: NotFoundError+ # → 404, MissingConfigError → 503, any other ValueError → 400.+ if isinstance(preset, models.LibraryAgentPresetCreatable):+ return await db.create_preset(+ user_id,+ preset,+ expert_id=await experts_db.resolve_expert_for_graph(+ user_id, preset.graph_id+ ),)+ return await db.create_preset_from_graph_execution(user_id, preset)@router.post("/presets/setup-trigger")@@ -189,7 +155,7 @@ async def setup_trigger()except WebhookSetupUnavailableError as e:# Server-side availability problem (e.g. Redis lock), not a bad- # request — retryable, mirroring create_preset's MissingConfigError.+ # request — retryable, like MissingConfigError's global 503.raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,detail=f"Trigger setup is temporarily unavailable: {e}",diff --git a/autogpt_platform/backend/backend/api/features/library/routes_test.py b/autogpt_platform/backend/backend/api/features/library/routes_test.pyindex d909ade9f0..fe3583457f 100644--- a/autogpt_platform/backend/backend/api/features/library/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/library/routes_test.py@@ -7,13 +7,15 @@ import pytestimport pytest_mockfrom pytest_snapshot.plugin import Snapshot+from backend.api.rest_api import app as rest_appfrom backend.util.exceptions import MissingConfigErrorfrom backend.util.models import Paginationfrom . import model as library_modelfrom .routes import router as library_router-app = fastapi.FastAPI()+# The preset routes leave error mapping to the app-wide handlers.+app = fastapi.FastAPI(exception_handlers=rest_app.exception_handlers)app.include_router(library_router)client = fastapi.testclient.TestClient(app)@@ -51,9 +53,35 @@ def test_create_expert_preset_missing_workspace_returns_503()assert response.status_code == 503- assert response.json() == {- "detail": "Your expert workspace is still being set up. Try again shortly."- }+ assert (+ response.json()["detail"]+ == "Your expert workspace is still being set up. Try again shortly."+ )+++def test_create_preset_from_run_without_saved_credentials_returns_400(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.library.db.get_graph_execution",+ new_callable=AsyncMock,+ return_value=mocker.MagicMock(credential_inputs=None),+ )+ mocker.patch(+ "backend.api.features.library.db.graph_db.get_graph",+ new_callable=AsyncMock,+ return_value=mocker.MagicMock(+ regular_credentials_inputs={"credentials": mocker.MagicMock()}+ ),+ )++ response = client.post(+ "/presets",+ json={"graph_execution_id": "exec-1", "name": "Preset", "description": ""},+ )++ assert response.status_code == 400+ assert "can't be turned into a preset" in response.json()["detail"]@pytest.fixture(autouse=True)