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): make graph save atomic + surface clear credential errors (#13264)
Reinier van der Leer465111e8d45b
diff --git a/autogpt_platform/backend/backend/api/external/fastapi_app.py b/autogpt_platform/backend/backend/api/external/fastapi_app.pyindex 69e9b6154d..914a36cbd4 100644--- a/autogpt_platform/backend/backend/api/external/fastapi_app.py+++ b/autogpt_platform/backend/backend/api/external/fastapi_app.py@@ -4,6 +4,7 @@ from fastapi.responses import JSONResponsefrom backend.api.middleware.security import SecurityHeadersMiddlewarefrom backend.copilot.rate_limit import UserPaywalledError+from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationErrorfrom backend.monitoring.instrumentation import instrument_fastapifrom .v1.routes import v1_router@@ -27,6 +28,13 @@ async def _user_paywalled_handler(_request: Request, exc: UserPaywalledError):return JSONResponse(status_code=402, content={"detail": str(exc)})+# Mirror of rest_api.py's mapping — bad/revoked node credentials during graph+# activation surface as a clear 400 instead of an opaque 500.+@external_api.exception_handler(GraphActivationError)+async def _graph_activation_error_handler(_request: Request, exc: GraphActivationError):+ return JSONResponse(status_code=400, content={"detail": str(exc)})++# Add Prometheus instrumentationinstrument_fastapi(external_api,diff --git a/autogpt_platform/backend/backend/api/external/v1/routes.py b/autogpt_platform/backend/backend/api/external/v1/routes.pyindex cfbfd60e0a..ffb05a76bf 100644--- a/autogpt_platform/backend/backend/api/external/v1/routes.py+++ b/autogpt_platform/backend/backend/api/external/v1/routes.py@@ -24,7 +24,7 @@ from backend.executor.utils import (add_graph_execution,charge_for_direct_block_execution,)-from backend.integrations.webhooks.graph_lifecycle_hooks import on_graph_activate+from backend.integrations.webhooks.graph_lifecycle_hooks import before_graph_activatefrom backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.settings import Settingsfrom backend.util.timezone_utils import get_user_timezone_or_utc@@ -162,11 +162,14 @@ async def create_graph(graph_model.reassign_ids(user_id=auth.user_id, reassign_graph_id=True)graph_model.validate_graph(for_run=False)+ # Validate BEFORE persisting so a credential issue can't leave the graph+ # and library agent half-saved.+ graph_model = await before_graph_activate(graph_model, user_id=auth.user_id)+await graph_db.create_graph(graph_model, user_id=auth.user_id)await library_db.create_library_agent(graph_model, auth.user_id)- activated_graph = await on_graph_activate(graph_model, user_id=auth.user_id)- return activated_graph+ return graph_model@v1_router.post(diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex d886cf8a64..ea2d62bc95 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -28,7 +28,7 @@ from backend.data.includes import (from backend.data.model import CredentialsMetaInput, GraphInputfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.integrations.webhooks.graph_lifecycle_hooks import (- on_graph_activate,+ before_graph_activate,on_graph_deactivate,)from backend.util.clients import get_scheduler_client@@ -686,6 +686,13 @@ async def create_graph_in_library(graph_model = graph_db.make_graph_model(graph, user_id)graph_model.reassign_ids(user_id=user_id, reassign_graph_id=True)+ # Validate credentials (and clean stale optional ones) BEFORE+ # persisting so a credential issue can't leave the graph and library+ # agent half-saved. Raises GraphActivationError for the caller to map+ # to a user-friendly response.+ if graph_model.is_active:+ graph_model = await before_graph_activate(graph_model, user_id=user_id)+created_graph = await graph_db.create_graph(graph_model, user_id)library_agents = await create_library_agent(@@ -697,9 +704,6 @@ async def create_graph_in_library(is_hidden=is_hidden,)- if created_graph.is_active:- created_graph = await on_graph_activate(created_graph, user_id=user_id)-return created_graph, library_agents[0]@@ -721,6 +725,11 @@ async def update_graph_in_library(graph_model = graph_db.make_graph_model(graph, user_id)graph_model.reassign_ids(user_id=user_id, reassign_graph_id=False)+ # Validate BEFORE persisting so a credential issue can't leave the new+ # version half-saved. Raises GraphActivationError for the caller.+ if graph_model.is_active:+ graph_model = await before_graph_activate(graph_model, user_id=user_id)+created_graph = await graph_db.create_graph(graph_model, user_id)library_agent = await get_library_agent_by_graph_id(@@ -734,7 +743,6 @@ async def update_graph_in_library()if created_graph.is_active:- created_graph = await on_graph_activate(created_graph, user_id=user_id)await graph_db.set_graph_active_version(graph_id=created_graph.id,version=created_graph.version,@@ -2052,11 +2060,15 @@ async def fork_library_agent(# f"User {user_id} cannot access library agent graph {library_agent_id}"# )- # Fork the underlying graph and nodes+ # Fork the underlying graph and nodes. We activate after the fork rather+ # than before because the fork performs its own DB writes that we can't+ # easily roll back here. If activation fails the user gets a clear+ # GraphActivationError, but the forked graph row exists; callers should+ # surface that as a 400 to the user.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)+ new_graph = await before_graph_activate(new_graph, user_id=user_id)# Create a library agent for the new graph, preserving safe mode settingsreturn (diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.pyindex 8e598f5ebd..94deebe6ba 100644--- a/autogpt_platform/backend/backend/api/features/library/db_test.py+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py@@ -307,7 +307,7 @@ async def test_get_library_agent_by_graph_id_can_include_archived(mocker):async def test_update_graph_in_library_allows_archived_library_agent(mocker):graph = mocker.Mock(id="graph-id")existing_version = mocker.Mock(version=1, is_active=True)- graph_model = mocker.Mock()+ graph_model = mocker.Mock(is_active=False)created_graph = mocker.Mock(id="graph-id", version=2, is_active=False)current_library_agent = mocker.Mock()updated_library_agent = mocker.Mock()diff --git a/autogpt_platform/backend/backend/api/features/library/routes/agents.py b/autogpt_platform/backend/backend/api/features/library/routes/agents.pyindex 16f84534fb..40421aa243 100644--- a/autogpt_platform/backend/backend/api/features/library/routes/agents.py+++ b/autogpt_platform/backend/backend/api/features/library/routes/agents.py@@ -213,6 +213,11 @@ async def fork_library_agent(library_agent_id: str,user_id: str = Security(autogpt_auth_lib.get_user_id),) -> library_model.LibraryAgent:+ # `library_db.fork_library_agent` activates the forked graph (validates+ # node credentials) after the fork's own DB write. A GraphActivationError+ # raised by that activation propagates to the app-level handler in+ # rest_api.py and becomes a 400. Making the save itself atomic is a+ # follow-up.return await library_db.fork_library_agent(library_agent_id=library_agent_id,user_id=user_id,diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex a7e9c13fa9..9ae5472613 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -127,7 +127,7 @@ from backend.data.workspace import get_workspace_file_by_idfrom backend.executor import schedulerfrom backend.executor import utils as execution_utilsfrom backend.integrations.webhooks.graph_lifecycle_hooks import (- on_graph_activate,+ before_graph_activate,on_graph_deactivate,)from backend.monitoring.instrumentation import (@@ -1663,11 +1663,16 @@ async def create_new_graph(graph.reassign_ids(user_id=user_id, reassign_graph_id=True)graph.validate_graph(for_run=False)+ # Validate node credentials (and clear stale optional ones) BEFORE+ # persisting, so a credential issue can't leave the graph/library agent+ # half-saved. before_graph_activate may also mutate input_default; those+ # edits need to be persisted, so it must run before create_graph.+ graph = await before_graph_activate(graph, user_id=user_id)+await graph_db.create_graph(graph, user_id=user_id)await library_db.create_library_agent(graph, user_id)- activated_graph = await on_graph_activate(graph, user_id=user_id)- return activated_graph+ return graph@v1_router.delete(@@ -1712,13 +1717,19 @@ async def update_graph(graph.reassign_ids(user_id=user_id, reassign_graph_id=False)graph.validate_graph(for_run=False)+ # If this new version is going to be active, validate node credentials+ # BEFORE persisting so a credential issue can't leave a half-saved version+ # behind. before_graph_activate may also clear stale optional credentials —+ # those edits must be persisted, hence the pre-save call.+ if graph.is_active:+ graph = await before_graph_activate(graph, user_id=user_id)+new_graph_version = await graph_db.create_graph(graph, user_id=user_id)if new_graph_version.is_active:await library_db.update_library_agent_version_and_settings(user_id, new_graph_version)- new_graph_version = await on_graph_activate(new_graph_version, user_id=user_id)await graph_db.set_graph_active_version(graph_id=graph_id, version=new_graph_version.version, user_id=user_id)@@ -1768,8 +1779,11 @@ async def set_graph_active_version(user_id=user_id,)- # Handle activation of the new graph first to ensure continuity- await on_graph_activate(new_active_graph, user_id=user_id)+ # Validate the new graph's credentials before flipping the active version.+ # Capture the returned graph: before_graph_activate may clear stale+ # optional credential references, which we want propagated to the library+ # agent's settings sync below.+ new_active_graph = await before_graph_activate(new_active_graph, user_id=user_id)# Ensure new version is the only active versionawait graph_db.set_graph_active_version(graph_id=graph_id,diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex eea50f5775..da6428ec69 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -11,6 +11,7 @@ import starlette.datastructuresfrom fastapi import HTTPException, UploadFilefrom pytest_snapshot.plugin import Snapshot+from backend.api.rest_api import handle_internal_http_errorfrom backend.copilot.tools.skills import (BuiltInSkillError,ParsedSkill,@@ -18,12 +19,16 @@ from backend.copilot.tools.skills import ()from backend.data.credit import AutoTopUpConfigfrom backend.data.graph import GraphModel+from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationErrorfrom backend.util.exceptions import InsufficientBalanceErrorfrom .v1 import upload_file, v1_routerapp = fastapi.FastAPI()app.include_router(v1_router)+# Mirror rest_api.py's GraphActivationError → 400 mapping so the atomicity+# tests below verify the same behaviour the real app exposes.+app.add_exception_handler(GraphActivationError, handle_internal_http_error(400))client = fastapi.testclient.TestClient(app)@@ -875,6 +880,105 @@ def test_delete_graph()+def test_create_new_graph_returns_400_and_persists_nothing_on_activation_error(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Core atomicity guarantee: when before_graph_activate raises,+ POST /graphs must return 400 and never call create_graph / create_library_agent.+ Reordering activation back to post-save would break this test."""+ from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError++ mock_graph_model = Mock()+ mocker.patch(+ "backend.api.features.v1.graph_db.make_graph_model",+ return_value=mock_graph_model,+ )+ activate_mock = mocker.patch(+ "backend.api.features.v1.before_graph_activate",+ new=AsyncMock(+ side_effect=GraphActivationError(+ "Credential #cred-1 needs reconnect — please reconnect"+ )+ ),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.v1.graph_db.create_graph", new=AsyncMock()+ )+ create_lib_agent_mock = mocker.patch(+ "backend.api.features.v1.library_db.create_library_agent",+ new=AsyncMock(),+ )++ response = client.post(+ "/graphs",+ json={+ "graph": {+ "name": "Test Graph",+ "description": "Test",+ "nodes": [],+ "links": [],+ }+ },+ )++ assert response.status_code == 400+ assert "reconnect" in response.json()["detail"]+ activate_mock.assert_awaited_once()+ create_graph_mock.assert_not_awaited()+ create_lib_agent_mock.assert_not_awaited()+++def test_update_graph_returns_400_and_persists_nothing_on_activation_error(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Same atomicity guarantee on PUT /graphs/{id}: an activation failure+ must short-circuit with 400 before any new graph version is written."""+ from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError++ mock_graph_model = Mock(is_active=True)+ existing_version = Mock(version=1, is_active=True)+ mocker.patch(+ "backend.api.features.v1.graph_db.get_graph_all_versions",+ new=AsyncMock(return_value=[existing_version]),+ )+ mocker.patch(+ "backend.api.features.v1.graph_db.make_graph_model",+ return_value=mock_graph_model,+ )+ activate_mock = mocker.patch(+ "backend.api.features.v1.before_graph_activate",+ new=AsyncMock(+ side_effect=GraphActivationError(+ "Credential #cred-1 needs reconnect — please reconnect"+ )+ ),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.v1.graph_db.create_graph", new=AsyncMock()+ )+ update_lib_agent_mock = mocker.patch(+ "backend.api.features.v1.library_db.update_library_agent_version_and_settings",+ new=AsyncMock(),+ )++ response = client.put(+ "/graphs/graph-123",+ json={+ "id": "graph-123",+ "name": "Test Graph",+ "description": "Test",+ "nodes": [],+ "links": [],+ },+ )++ assert response.status_code == 400+ assert "reconnect" in response.json()["detail"]+ activate_mock.assert_awaited_once()+ create_graph_mock.assert_not_awaited()+ update_lib_agent_mock.assert_not_awaited()++# Invalid request testsdef test_invalid_json_request() -> None:"""Test endpoint with invalid JSON"""diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex dba0bc8406..7472782b85 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -60,6 +60,7 @@ from backend.blocks.llm import DEFAULT_LLM_MODELfrom backend.copilot.rate_limit import UserPaywalledErrorfrom backend.data.model import Credentialsfrom backend.integrations.providers import ProviderName+from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationErrorfrom backend.monitoring.instrumentation import instrument_fastapifrom backend.util import jsonfrom backend.util.cloud_storage import shutdown_cloud_storage_handler@@ -307,6 +308,7 @@ 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))app.add_exception_handler(FolderValidationError, handle_internal_http_error(400))+app.add_exception_handler(GraphActivationError, handle_internal_http_error(400))app.add_exception_handler(NotFoundError, handle_internal_http_error(404))app.add_exception_handler(NotAuthorizedError, handle_internal_http_error(403))app.add_exception_handler(RequestValidationError, validation_error_handler)diff --git a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.pyindex 8fdbe10383..6a59b73b89 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py@@ -10,7 +10,7 @@ from backend.integrations.creds_manager import IntegrationCredentialsManagerfrom . import get_webhook_manager, supports_webhooksif TYPE_CHECKING:- from backend.data.graph import BaseGraph, GraphModel, NodeModel+ from backend.data.graph import BaseGraph, GraphModel, Node, NodeModelfrom backend.data.model import Credentialsfrom ._base import BaseWebhooksManager@@ -19,61 +19,173 @@ logger = logging.getLogger(__name__)credentials_manager = IntegrationCredentialsManager()-async def on_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModel":+class GraphActivationError(Exception):+ """Raised when a graph cannot be activated (e.g. a required credential is+ missing, revoked, or its OAuth token can no longer be refreshed).++ Callers in the API layer should map this to HTTP 400 so the user sees a+ clear, actionable message instead of an opaque 500."""- Hook to be called when a graph is activated/created.- ⚠️ Assuming node entities are not re-used between graph versions, ⚠️- this hook calls `on_node_activate` on all nodes in this graph.++async def before_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModel":+ """+ Pre-activation hook: validates node credentials and clears stale optional+ credential references in-memory. MUST be called BEFORE the graph is+ persisted (and before it is marked active) — a failure here means nothing+ should be saved, and the returned graph carries cleanup mutations that+ need to be persisted by the caller.++ Do not use this for post-activation state changes; it has no DB writes+ and is intentionally side-effect-free outside the passed-in graph object.++ ⚠️ Assumes node entities are not re-used between graph versions. ⚠️++ Raises:+ GraphActivationError: when a required node credential is missing or+ unusable."""- graph = await _on_graph_activate(graph, user_id)+ graph = await _before_graph_activate(graph, user_id)graph.sub_graphs = await asyncio.gather(- *(_on_graph_activate(sub_graph, user_id) for sub_graph in graph.sub_graphs)+ *(_before_graph_activate(sub_graph, user_id) for sub_graph in graph.sub_graphs))return graph@overload-async def _on_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModel": ...+async def _before_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModel": ...@overload-async def _on_graph_activate(graph: "BaseGraph", user_id: str) -> "BaseGraph": ...+async def _before_graph_activate(graph: "BaseGraph", user_id: str) -> "BaseGraph": ...-async def _on_graph_activate(graph: "BaseGraph | GraphModel", user_id: str):+async def _before_graph_activate(graph: "BaseGraph | GraphModel", user_id: str):get_credentials = credentials_manager.cached_getter(user_id)++ # Collect every (node, field) credential reference up front so we can+ # resolve them in one parallel batch — important when a graph has+ # several distinct OAuth credentials that each need a refresh round-trip.+ refs: list[tuple["Node | NodeModel", str, dict, BlockSchema]] = []for new_node in graph.nodes:block_input_schema = cast(BlockSchema, new_node.block.input_schema)-for creds_field_name in block_input_schema.get_credentials_fields().keys():- # Prevent saving graph with non-existent credentials- if (- creds_meta := new_node.input_default.get(creds_field_name)- ) and not await get_credentials(creds_meta["id"]):- # If the credential field is optional (has a default in the- # schema, or node metadata marks it optional), clear the stale- # reference instead of blocking the save.- creds_field_optional = (- new_node.credentials_optional- or creds_field_name not in block_input_schema.get_required_fields()- )- if creds_field_optional:- new_node.input_default[creds_field_name] = {}- logger.warning(- f"Node #{new_node.id}: cleared stale optional "- f"credentials #{creds_meta['id']} for "- f"'{creds_field_name}'"- )- continue- raise ValueError(- f"Node #{new_node.id} input '{creds_field_name}' updated with "- f"non-existent credentials #{creds_meta['id']}"- )+ creds_meta = new_node.input_default.get(creds_field_name)+ if not creds_meta:+ continue+ refs.append((new_node, creds_field_name, creds_meta, block_input_schema))++ unique_ids = list({m["id"] for _, _, m, _ in refs})+ results = await asyncio.gather(+ *(get_credentials(cid) for cid in unique_ids),+ return_exceptions=True,+ )+ cred_by_id: dict[str, "Credentials | None | BaseException"] = dict(+ zip(unique_ids, results)+ )++ for new_node, creds_field_name, creds_meta, block_input_schema in refs:+ _apply_credential_result(+ new_node,+ creds_field_name,+ creds_meta,+ block_input_schema,+ cred_by_id[creds_meta["id"]],+ )return graph+def _apply_credential_result(+ new_node: "Node | NodeModel",+ creds_field_name: str,+ creds_meta: dict,+ block_input_schema: BlockSchema,+ result: "Credentials | None | BaseException",+) -> None:+ """Apply the resolution outcome for one credential reference: leave+ usable ones alone, clear stale optional ones in-memory, or raise+ `GraphActivationError` for required + unusable ones.++ Treats both `None` (credential missing from DB) and an exception+ (OAuth refresh raised, infra error) as "unusable" — failures are+ logged here so the caller doesn't have to.+ """+ refresh_error: str | None = None+ if isinstance(result, BaseException):+ # Distinguish known credential-side failures (OAuth refresh rejected,+ # 401/403 from the provider) from infra failures (DB pool exhaustion,+ # Redis timeout, TypeError, …) so the latter show up at error level+ # with a stack trace instead of being silently misreported as+ # "please reconnect".+ error_str = repr(result).lower()+ is_known_credential_error = any(+ sig in error_str+ for sig in (+ "invalid_grant",+ "invalid_token",+ "unauthorized",+ "forbidden",+ " 401",+ " 403",+ )+ )+ log_message = (+ f"Node #{new_node.id}: failed to load credentials "+ f"#{creds_meta['id']} for '{creds_field_name}': {result!r}"+ )+ if is_known_credential_error:+ logger.warning(log_message)+ else:+ logger.error(log_message, exc_info=result)+ refresh_error = str(result) or result.__class__.__name__+ resolved = None+ else:+ resolved = result++ if resolved:+ return++ # If the credential field is optional (has a default in the schema, or+ # node metadata marks it optional), clear the stale reference instead+ # of blocking the save.+ creds_field_optional = (+ new_node.credentials_optional+ or creds_field_name not in block_input_schema.get_required_fields()+ )+ if creds_field_optional:+ new_node.input_default[creds_field_name] = {}+ logger.warning(+ f"Node #{new_node.id}: cleared stale optional "+ f"credentials #{creds_meta['id']} for "+ f"'{creds_field_name}'"+ )+ return++ # User-facing reference: prefer the credential's user-set title and the+ # block name over internal UUIDs, since users can't act on them. UUIDs+ # still appear in the warning/error log above for support lookups.+ credential_label = (+ f'"{creds_meta["title"]}" {creds_meta["provider"]}'+ if creds_meta.get("title")+ else creds_meta.get("provider", "unknown")+ )+ credential_ref = (+ f"The {credential_label} credential used by the " f"{new_node.block.name} node"+ )++ if refresh_error:+ raise GraphActivationError(+ f"{credential_ref} could not be loaded ({refresh_error}). "+ "It may have been revoked or its access expired — please "+ "reconnect this integration and try again."+ )+ raise GraphActivationError(+ f"{credential_ref} no longer exists. Please pick a different "+ "credential and try again."+ )++async def on_graph_deactivate(graph: "GraphModel", user_id: str):"""Hook to be called when a graph is deactivated/deleted.diff --git a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.pynew file mode 100644index 0000000000..dd289f1ef0--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py@@ -0,0 +1,122 @@+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.integrations.webhooks.graph_lifecycle_hooks import (+ GraphActivationError,+ _before_graph_activate,+)+++def _make_node(+ *,+ creds_field: str = "credentials",+ creds_id: str = "cred-1",+ creds_title: str | None = "My GitHub key",+ creds_provider: str = "github",+ block_name: str = "GithubCommentBlock",+ required: bool = True,+ optional_marker: bool = False,+):+ block_input_schema = MagicMock()+ block_input_schema.get_credentials_fields.return_value = {creds_field: object()}+ block_input_schema.get_required_fields.return_value = (+ {creds_field} if required else set()+ )++ node = MagicMock()+ node.id = "node-1"+ node.credentials_optional = optional_marker+ cred = {"id": creds_id, "provider": creds_provider}+ if creds_title is not None:+ cred["title"] = creds_title+ node.input_default = {creds_field: cred}+ node.block.input_schema = block_input_schema+ node.block.name = block_name+ return node+++async def test_before_graph_activate_oauth_refresh_failure_raises_clear_error():+ """A required credential whose OAuth refresh raises (e.g. invalid_grant)+ must surface as GraphActivationError with a 'please reconnect' message —+ not as an opaque 500."""+ node = _make_node()+ graph = MagicMock(nodes=[node])++ async def failing_getter(_creds_id):+ raise Exception("invalid_grant: Bad Request")++ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = failing_getter+ with pytest.raises(GraphActivationError) as excinfo:+ await _before_graph_activate(graph, "user-1")++ msg = str(excinfo.value)+ # User-facing reference must use the credential title + provider + block+ # name (the things a user can act on), not internal UUIDs.+ assert "My GitHub key" in msg+ assert "github" in msg.lower()+ assert "GithubCommentBlock" in msg+ assert "cred-1" not in msg+ assert "node-1" not in msg+ assert "reconnect" in msg.lower()+ assert "invalid_grant" in msg+++async def test_before_graph_activate_clears_optional_unloadable_credentials():+ """An optional credential whose refresh fails should be cleared, not raise."""+ node = _make_node(required=False, optional_marker=True)+ graph = MagicMock(nodes=[node])++ async def failing_getter(_creds_id):+ raise Exception("invalid_grant: Bad Request")++ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = failing_getter+ await _before_graph_activate(graph, "user-1")++ assert node.input_default["credentials"] == {}+++async def test_before_graph_activate_missing_required_credential_raises_clear_error():+ """A required credential that no longer exists in the DB (returns None)+ raises GraphActivationError that names the missing credential and asks+ the user to pick a different one."""+ node = _make_node()+ graph = MagicMock(nodes=[node])++ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = AsyncMock(return_value=None)+ with pytest.raises(GraphActivationError) as excinfo:+ await _before_graph_activate(graph, "user-1")++ msg = str(excinfo.value)+ assert "My GitHub key" in msg+ assert "github" in msg.lower()+ assert "GithubCommentBlock" in msg+ assert "cred-1" not in msg+ assert "no longer exists" in msg.lower()+++async def test_before_graph_activate_succeeds_when_credentials_resolve():+ """The happy path should be a no-op (no mutation, no raise)."""+ node = _make_node()+ graph = MagicMock(nodes=[node])++ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = AsyncMock(return_value=MagicMock())+ await _before_graph_activate(graph, "user-1")++ assert node.input_default["credentials"]["id"] == "cred-1"diff --git a/autogpt_platform/backend/test/test_migrate_webhook_presets.py b/autogpt_platform/backend/test/test_migrate_webhook_presets.pyindex 54156e5e1b..a77db40547 100644--- a/autogpt_platform/backend/test/test_migrate_webhook_presets.py+++ b/autogpt_platform/backend/test/test_migrate_webhook_presets.py@@ -146,7 +146,7 @@ async def test_update_graph_in_library_migrates_when_webhook_node_present(return_value=AsyncMock(),)mocker.patch.object(- library_db, "on_graph_activate", side_effect=lambda g, user_id: g+ library_db, "before_graph_activate", side_effect=lambda g, user_id: g)mocker.patch.object(library_db, "on_graph_deactivate", return_value=None)mocker.patch.object(library_db.graph_db, "set_graph_active_version")@@ -186,7 +186,7 @@ async def test_update_graph_in_library_skips_when_no_webhook_node(mocker):return_value=AsyncMock(),)mocker.patch.object(- library_db, "on_graph_activate", side_effect=lambda g, user_id: g+ library_db, "before_graph_activate", side_effect=lambda g, user_id: g)mocker.patch.object(library_db, "on_graph_deactivate", return_value=None)mocker.patch.object(library_db.graph_db, "set_graph_active_version")@@ -232,7 +232,7 @@ async def test_v1_update_graph_migrates_when_webhook_node_present(mocker):"migrate_webhook_presets_to_new_version",return_value=1,)- mocker.patch.object(v1, "on_graph_activate", side_effect=lambda g, user_id: g)+ mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)mocker.patch.object(v1, "on_graph_deactivate", return_value=None)await v1.update_graph(graph_id=new_graph.id, graph=incoming, user_id="user-1")@@ -275,7 +275,7 @@ async def test_v1_update_graph_skips_when_no_webhook_node(mocker):"migrate_webhook_presets_to_new_version",return_value=0,)- mocker.patch.object(v1, "on_graph_activate", side_effect=lambda g, user_id: g)+ mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)mocker.patch.object(v1, "on_graph_deactivate", return_value=None)await v1.update_graph(graph_id=new_graph.id, graph=incoming, user_id="user-1")@@ -308,7 +308,7 @@ async def test_v1_set_graph_active_version_migrates_when_webhook_node_present("migrate_webhook_presets_to_new_version",return_value=2,)- mocker.patch.object(v1, "on_graph_activate", return_value=None)+ mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)mocker.patch.object(v1, "on_graph_deactivate", return_value=None)body = v1.SetGraphActiveVersion(active_graph_version=target_graph.version)@@ -347,7 +347,7 @@ async def test_v1_set_graph_active_version_skips_when_no_webhook_node(mocker):"migrate_webhook_presets_to_new_version",return_value=0,)- mocker.patch.object(v1, "on_graph_activate", return_value=None)+ mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)mocker.patch.object(v1, "on_graph_deactivate", return_value=None)body = v1.SetGraphActiveVersion(active_graph_version=target_graph.version)