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.
refactor(backend): move the graph routes into their own feature module (#14475)
Reinier van der Leer634f91484dea
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/routes_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/routes_test.pyindex 95fedc4995..5a5cccad6b 100644--- a/autogpt_platform/backend/backend/api/features/graph_executions/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/routes_test.py@@ -113,17 +113,27 @@ def test_execution_path_is_served_by_this_module(path: str):assert handlers == {"backend.api.features.graph_executions.routes"}-# Three modules serve /graphs/{graph_id}/*: four executions paths here, six in v1,-# one in schedules. A wildcard fourth segment on any side would swallow the others.+# Three modules serve /graphs/{graph_id}/*: four executions paths here, six in+# graphs, one in schedules. A wildcard fourth segment on any side would+# swallow the others.@pytest.mark.parametrize("path,module",[- ("/api/graphs/{graph_id}", "backend.api.features.v1"),- ("/api/graphs/{graph_id}/execute/{graph_version}", "backend.api.features.v1"),- ("/api/graphs/{graph_id}/settings", "backend.api.features.v1"),- ("/api/graphs/{graph_id}/versions", "backend.api.features.v1"),- ("/api/graphs/{graph_id}/versions/active", "backend.api.features.v1"),- ("/api/graphs/{graph_id}/versions/{version}", "backend.api.features.v1"),+ ("/api/graphs/{graph_id}", "backend.api.features.graphs.routes"),+ (+ "/api/graphs/{graph_id}/execute/{graph_version}",+ "backend.api.features.graphs.routes",+ ),+ ("/api/graphs/{graph_id}/settings", "backend.api.features.graphs.routes"),+ ("/api/graphs/{graph_id}/versions", "backend.api.features.graphs.routes"),+ (+ "/api/graphs/{graph_id}/versions/active",+ "backend.api.features.graphs.routes",+ ),+ (+ "/api/graphs/{graph_id}/versions/{version}",+ "backend.api.features.graphs.routes",+ ),("/api/graphs/{graph_id}/schedules","backend.api.features.schedules.routes",diff --git a/autogpt_platform/backend/backend/api/features/graphs/__init__.py b/autogpt_platform/backend/backend/api/features/graphs/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/graphs/model.py b/autogpt_platform/backend/backend/api/features/graphs/model.pynew file mode 100644index 0000000000..0faa632b61--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graphs/model.py@@ -0,0 +1,36 @@+from pydantic import BaseModel, Field+from typing_extensions import TypedDict++from backend.api.features.library import model as library_model+from backend.data import graph as graph_db+++class DeleteGraphResponse(TypedDict):+ version_counts: int+++class UpdateGraphResponse(BaseModel):+ """Response for creating/activating a new graph version.++ Carries the new graph version plus any webhook presets that were left+ pinned to their old version because the new version's trigger block is+ incompatible and needs to be reconfigured.+ """++ graph: graph_db.GraphModel+ skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = Field(+ default_factory=list+ )+++class SetActiveGraphVersionResponse(BaseModel):+ """Response for activating an existing graph version.++ Carries any webhook presets that were left pinned to their old version+ because the newly activated version's trigger block is incompatible and+ needs to be reconfigured.+ """++ skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = Field(+ default_factory=list+ )diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes.py b/autogpt_platform/backend/backend/api/features/graphs/routes.pynew file mode 100644index 0000000000..81ca6c1677--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graphs/routes.py@@ -0,0 +1,381 @@+from typing import Annotated, Any, Sequence++from autogpt_libs.auth import get_request_context, get_user_id, requires_user+from autogpt_libs.auth.models import RequestContext+from fastapi import APIRouter, Body, Depends, HTTPException, Security+from typing_extensions import Optional++from backend.api.features.graphs.model import (+ DeleteGraphResponse,+ SetActiveGraphVersionResponse,+ UpdateGraphResponse,+)+from backend.api.features.library import db as library_db+from backend.api.features.library import model as library_model+from backend.api.model import CreateGraph, GraphExecutionSource, SetGraphActiveVersion+from backend.copilot.rate_limit import enforce_payment_paywall+from backend.data import execution as execution_db+from backend.data import graph as graph_db+from backend.data.credit import get_credit_model+from backend.data.graph import GraphSettings+from backend.data.model import CredentialsMetaInput+from backend.data.onboarding import OnboardingStep, complete_onboarding_step+from backend.executor import utils as execution_utils+from backend.integrations.webhooks.graph_lifecycle_hooks import (+ before_graph_activate,+ on_graph_deactivate,+)+from backend.monitoring.instrumentation import record_graph_operation+from backend.util.exceptions import GraphValidationError++# Every route here is authenticated by the router and tagged "graphs" at the+# mount; execute_graph adds Depends(enforce_payment_paywall) on top.+router = APIRouter(dependencies=[Security(requires_user)])+++ path="/graphs",+ summary="List user graphs",+)+async def list_graphs(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> Sequence[graph_db.GraphMeta]:+ paginated_result = await graph_db.list_graphs_paginated(+ user_id=user_id,+ page=1,+ page_size=250,+ filter_by="active",+ organization_id=ctx.org_id,+ )+ return paginated_result.graphs+++ path="/graphs/{graph_id}",+ summary="Get specific graph",+)+ path="/graphs/{graph_id}/versions/{version}",+ summary="Get graph version",+)+async def get_graph(+ graph_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ version: int | None = None,+ for_export: bool = False,+) -> graph_db.GraphModel:+ graph = await graph_db.get_graph(+ graph_id,+ version,+ user_id=user_id,+ for_export=for_export,+ include_subgraphs=True, # needed to construct full credentials input schema+ organization_id=ctx.org_id,+ )+ if not graph:+ raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")+ return graph+++ path="/graphs/{graph_id}/versions",+ summary="Get all graph versions",+)+async def get_graph_all_versions(+ graph_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> Sequence[graph_db.GraphModel]:+ graphs = await graph_db.get_graph_all_versions(+ graph_id, user_id=user_id, organization_id=ctx.org_id+ )+ if not graphs:+ raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")+ return graphs+++ path="/graphs",+ summary="Create new graph",+)+async def create_new_graph(+ create_graph: CreateGraph,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> graph_db.GraphModel:+ graph = graph_db.make_graph_model(create_graph.graph, user_id)+ 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,+ organization_id=ctx.org_id,+ team_id=ctx.team_id,+ )+ await library_db.create_library_agent(+ graph, user_id, organization_id=ctx.org_id, team_id=ctx.team_id+ )++ return graph+++ path="/graphs/{graph_id}",+ summary="Delete graph permanently",+)+async def delete_graph(+ graph_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> DeleteGraphResponse:+ if active_version := await graph_db.get_graph(+ graph_id=graph_id, version=None, user_id=user_id+ ):+ await on_graph_deactivate(active_version, user_id=user_id)++ return {+ "version_counts": await graph_db.delete_graph(+ graph_id, user_id=user_id, organization_id=ctx.org_id+ )+ }+++ path="/graphs/{graph_id}",+ summary="Update graph version",+)+async def update_graph(+ graph_id: str,+ graph: graph_db.Graph,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> UpdateGraphResponse:+ if graph.id and graph.id != graph_id:+ raise HTTPException(400, detail="Graph ID does not match ID in URI")++ existing_versions = await graph_db.get_graph_all_versions(graph_id, user_id=user_id)+ if not existing_versions:+ raise HTTPException(404, detail=f"Graph #{graph_id} not found")++ graph.version = max(g.version for g in existing_versions) + 1+ current_active_version = next((v for v in existing_versions if v.is_active), None)++ graph = graph_db.make_graph_model(graph, user_id)+ 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,+ organization_id=ctx.org_id,+ team_id=ctx.team_id,+ )++ skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = []+ if new_graph_version.is_active:+ await library_db.update_library_agent_version_and_settings(+ user_id, new_graph_version+ )+ await graph_db.set_graph_active_version(+ graph_id=graph_id, version=new_graph_version.version, user_id=user_id+ )+ if current_active_version:+ await on_graph_deactivate(current_active_version, user_id=user_id)++ # Migrate webhook-attached presets to the new version so that+ # existing webhook URLs continue to trigger the latest agent version.+ if new_graph_version.webhook_input_node:+ migration = await library_db.migrate_webhook_presets_to_new_version(+ user_id=user_id,+ new_graph=new_graph_version,+ )+ skipped_webhook_presets = migration.skipped_presets++ new_graph_version_with_subgraphs = await graph_db.get_graph(+ graph_id,+ new_graph_version.version,+ user_id=user_id,+ include_subgraphs=True,+ )+ assert new_graph_version_with_subgraphs+ return UpdateGraphResponse(+ graph=new_graph_version_with_subgraphs,+ skipped_webhook_presets=skipped_webhook_presets,+ )+++ path="/graphs/{graph_id}/versions/active",+ summary="Set active graph version",+)+async def set_graph_active_version(+ graph_id: str,+ request_body: SetGraphActiveVersion,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> SetActiveGraphVersionResponse:+ new_active_version = request_body.active_graph_version+ new_active_graph = await graph_db.get_graph(+ graph_id, new_active_version, user_id=user_id+ )+ if not new_active_graph:+ raise HTTPException(404, f"Graph #{graph_id} v{new_active_version} not found")++ current_active_graph = await graph_db.get_graph(+ graph_id=graph_id,+ version=None,+ 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 version+ await graph_db.set_graph_active_version(+ graph_id=graph_id,+ version=new_active_version,+ user_id=user_id,+ )++ # Keep the library agent up to date with the new active version+ await library_db.update_library_agent_version_and_settings(+ user_id, new_active_graph+ )++ if current_active_graph and current_active_graph.version != new_active_version:+ # Handle deactivation of the previously active version+ await on_graph_deactivate(current_active_graph, user_id=user_id)++ # Migrate webhook-attached presets to the new active version so that+ # existing webhook URLs continue to trigger the latest agent version.+ skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = []+ if new_active_graph.webhook_input_node:+ migration = await library_db.migrate_webhook_presets_to_new_version(+ user_id=user_id,+ new_graph=new_active_graph,+ )+ skipped_webhook_presets = migration.skipped_presets++ return SetActiveGraphVersionResponse(+ skipped_webhook_presets=skipped_webhook_presets+ )+++ path="/graphs/{graph_id}/settings",+ summary="Update graph settings",+)+async def update_graph_settings(+ graph_id: str,+ settings: GraphSettings,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> GraphSettings:+ """Update graph settings for the user's library agent."""+ library_agent = await library_db.get_library_agent_by_graph_id(+ graph_id=graph_id, user_id=user_id+ )+ if not library_agent:+ raise HTTPException(404, f"Graph #{graph_id} not found in user's library")++ updated_agent = await library_db.update_library_agent(+ library_agent_id=library_agent.id,+ user_id=user_id,+ settings=settings,+ )++ return GraphSettings.model_validate(updated_agent.settings)+++ path="/graphs/{graph_id}/execute/{graph_version}",+ summary="Execute graph agent",+ dependencies=[Depends(enforce_payment_paywall)],+ # The route dep enforces fail-closed (503-on-blip) so a transient+ # Supabase outage surfaces as a retryable error, not a free run+ # for a paywalled user. The deep gate inside ``add_graph_execution``+ # still covers scheduled / webhook / copilot-internal runs that+ # don't pass through this route — those callers prefer fail-open+ # so background work doesn't abandon valid jobs during a blip.+ responses={+ 402: {+ "description": "Payment required: NO_TIER paywall, or insufficient credit balance"+ },+ 503: {"description": "Subscription state temporarily unavailable"},+ },+)+async def execute_graph(+ graph_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ inputs: Annotated[dict[str, Any], Body(..., embed=True, default_factory=dict)],+ credentials_inputs: Annotated[+ dict[str, CredentialsMetaInput], Body(..., embed=True, default_factory=dict)+ ],+ source: Annotated[GraphExecutionSource | None, Body(embed=True)] = None,+ graph_version: Optional[int] = None,+ preset_id: Optional[str] = None,+ dry_run: Annotated[bool, Body(embed=True)] = False,+) -> execution_db.GraphExecutionMeta:+ if not dry_run:+ credit_model = await get_credit_model(user_id, ctx.org_id)+ current_balance = await credit_model.get_credits(user_id)+ if current_balance <= 0:+ raise HTTPException(+ status_code=402,+ detail="Insufficient balance to execute the agent. Please top up your account.",+ )++ try:+ result = await execution_utils.add_graph_execution(+ graph_id=graph_id,+ user_id=user_id,+ inputs=inputs,+ preset_id=preset_id,+ graph_version=graph_version,+ graph_credentials_inputs=credentials_inputs,+ dry_run=dry_run,+ organization_id=ctx.org_id,+ team_id=ctx.team_id,+ trigger=execution_db.ExecutionTrigger.MANUAL,+ trigger_ref=source,+ )+ record_graph_operation(operation="execute", status="success")+ if source == "library":+ await complete_onboarding_step(user_id, OnboardingStep.LIBRARY_RUN_AGENT)+ elif source == "builder":+ await complete_onboarding_step(user_id, OnboardingStep.BUILDER_RUN_AGENT)+ return result+ except GraphValidationError as e:+ record_graph_operation(operation="execute", status="validation_error")+ # Return structured validation errors that the frontend can parse+ raise HTTPException(+ status_code=400,+ detail={+ "type": "validation_error",+ "message": e.message,+ # TODO: only return node-specific errors if user has access to graph+ "node_errors": e.node_errors,+ },+ )+ except Exception:+ record_graph_operation(operation="execute", status="error")+ raisediff --git a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py b/autogpt_platform/backend/backend/api/features/graphs/routes_test.pynew file mode 100644index 0000000000..641ac37a61--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graphs/routes_test.py@@ -0,0 +1,781 @@+"""Tests for the graph routes."""++import json+from datetime import datetime+from unittest.mock import AsyncMock, Mock++import fastapi+import fastapi.testclient+import pytest+import pytest_mock+from fastapi.routing import APIRoute+from pytest_snapshot.plugin import Snapshot++from backend.api.features.graphs.routes import router+from backend.api.rest_api import app as real_app+from backend.api.rest_api import handle_internal_http_error+from backend.data import execution as execution_db+from backend.data.execution import ExecutionStatus+from backend.data.graph import GraphModel+from backend.data.onboarding import OnboardingStep+from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError+from backend.util.exceptions import GraphValidationError++app = fastapi.FastAPI()+app.include_router(router)+# Mirror rest_api.py's GraphActivationError -> 400 mapping so the atomicity+# tests verify the same behaviour the real app exposes.+app.add_exception_handler(GraphActivationError, handle_internal_http_error(400))+client = fastapi.testclient.TestClient(app)+++def _request_context(user_id: str, team_id: str | None = None):+ from autogpt_libs.auth.models import RequestContext++ return RequestContext(+ user_id=user_id,+ org_id="test-org",+ team_id=team_id,+ is_org_owner=True,+ is_org_admin=True,+ is_org_billing_manager=False,+ is_team_admin=True,+ is_team_billing_manager=False,+ seat_status="ACTIVE",+ )++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user, test_user_id):+ from autogpt_libs.auth.dependencies import get_request_context+ from autogpt_libs.auth.jwt_utils import get_jwt_payload+ from autogpt_libs.auth.models import RequestContext++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]++ async def _fake_request_context() -> RequestContext:+ return _request_context(test_user_id)++ app.dependency_overrides[get_request_context] = _fake_request_context+ yield+ app.dependency_overrides.clear()+++def _execution_meta() -> execution_db.GraphExecutionMeta:+ return execution_db.GraphExecutionMeta(+ id="exec-1",+ user_id="user-1",+ graph_id="graph-1",+ graph_version=1,+ inputs={},+ credential_inputs=None,+ nodes_input_masks=None,+ preset_id=None,+ status=ExecutionStatus.QUEUED,+ stats=None,+ )+++EXPECTED_OPERATIONS = {+ ("get", "/api/graphs"): "getV1List user graphs",+ ("post", "/api/graphs"): "postV1Create new graph",+ ("get", "/api/graphs/{graph_id}"): "getV1Get specific graph",+ ("put", "/api/graphs/{graph_id}"): "putV1Update graph version",+ ("delete", "/api/graphs/{graph_id}"): "deleteV1Delete graph permanently",+ ("get", "/api/graphs/{graph_id}/versions"): "getV1Get all graph versions",+ ("get", "/api/graphs/{graph_id}/versions/{version}"): "getV1Get graph version",+ ("put", "/api/graphs/{graph_id}/versions/active"): "putV1Set active graph version",+ ("patch", "/api/graphs/{graph_id}/settings"): "patchV1Update graph settings",+ ("post", "/api/graphs/{graph_id}/execute/{graph_version}"): (+ "postV1Execute graph agent"+ ),+}+++ "method,path,operation_id",+ [(m, p, oid) for (m, p), oid in EXPECTED_OPERATIONS.items()],+)+def test_graph_operation_is_published(method: str, path: str, operation_id: str):+ operation = real_app.openapi()["paths"][path][method]+ assert operation["operationId"] == operation_id+ assert operation["tags"] == ["v1", "graphs"]+ # Publishing `security` is all this proves; the dependency behind it is+ # asserted by test_graph_route_requires_an_authenticated_user below.+ assert "security" in operation++[email protected]("path", sorted({p for _, p in EXPECTED_OPERATIONS}))+def test_graph_route_requires_an_authenticated_user(path: str):+ """`security` in the spec does not prove this: each handler's own+ Security(get_user_id) puts it there, so removing the router's+ requires_user leaves the schema unchanged. Assert the dependency."""+ for route in real_app.routes:+ if isinstance(route, APIRoute) and route.path == path:+ assert "requires_user" in {+ d.call.__name__ for d in route.dependant.dependencies if d.call+ }+++def test_execute_graph_is_behind_the_payment_paywall():+ """The only route with a dependency beyond auth, and the one whose loss+ would be silent: it gates spending, and no other test exercises it."""+ route = next(+ r+ for r in real_app.routes+ if isinstance(r, APIRoute)+ and r.path == "/api/graphs/{graph_id}/execute/{graph_version}"+ )+ assert "enforce_payment_paywall" in {+ d.call.__name__ for d in route.dependant.dependencies if d.call+ }+++def test_graph_surface_has_no_other_operations():+ served = {+ (method.lower(), route.path)+ for route in real_app.routes+ if isinstance(route, APIRoute)+ and route.endpoint.__module__ == "backend.api.features.graphs.routes"+ for method in route.methods+ if method != "HEAD"+ }+ assert served == set(EXPECTED_OPERATIONS)+++# /api/graphs/{graph_id}/* is served by three modules. Every fourth segment+# is literal, so order between them is unobservable - this is what keeps it so.+ "path,module",+ [+ ("/api/graphs/{graph_id}", "backend.api.features.graphs.routes"),+ (+ "/api/graphs/{graph_id}/execute/{graph_version}",+ "backend.api.features.graphs.routes",+ ),+ ("/api/graphs/{graph_id}/settings", "backend.api.features.graphs.routes"),+ ("/api/graphs/{graph_id}/versions", "backend.api.features.graphs.routes"),+ (+ "/api/graphs/{graph_id}/versions/active",+ "backend.api.features.graphs.routes",+ ),+ (+ "/api/graphs/{graph_id}/versions/{version}",+ "backend.api.features.graphs.routes",+ ),+ ("/api/graphs/{graph_id}/schedules", "backend.api.features.schedules.routes"),+ (+ "/api/graphs/{graph_id}/executions",+ "backend.api.features.graph_executions.routes",+ ),+ (+ "/api/graphs/{graph_id}/executions/{graph_exec_id}",+ "backend.api.features.graph_executions.routes",+ ),+ (+ "/api/graphs/{graph_id}/executions/{graph_exec_id}/stop",+ "backend.api.features.graph_executions.routes",+ ),+ (+ "/api/graphs/{graph_id}/executions/{graph_exec_id}/share",+ "backend.api.features.graph_executions.routes",+ ),+ ],+)+def test_graph_subpath_is_served_by_the_expected_module(path: str, module: str):+ handlers = {+ route.endpoint.__module__+ for route in real_app.routes+ if isinstance(route, APIRoute) and route.path == path+ }+ assert handlers == {module}+++def test_agent_server_helpers_reference_this_module():+ """rest_api.py's AgentServer test helpers call these five directly, and the+ whole backend suite reaches graphs through them."""+ import backend.api.rest_api as rest_api++ for name in (+ "execute_graph",+ "get_graph",+ "CreateGraph",+ "create_new_graph",+ "delete_graph",+ ):+ assert getattr(rest_api.graphs_routes, name) is not None+++def test_get_graphs(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+ test_user_id: str,+) -> None:+ """Test get graphs endpoint"""+ mock_graph = GraphModel(+ id="graph-123",+ version=1,+ is_active=True,+ name="Test Graph",+ description="A test graph",+ user_id=test_user_id,+ created_at=datetime(2025, 9, 4, 13, 37),+ )++ mocker.patch(+ "backend.data.graph.list_graphs_paginated",+ return_value=Mock(graphs=[mock_graph]),+ )++ response = client.get("/graphs")++ assert response.status_code == 200+ response_data = response.json()+ assert len(response_data) == 1+ assert response_data[0]["id"] == "graph-123"++ snapshot.snapshot_dir = "snapshots"+ snapshot.assert_match(+ json.dumps(response_data, indent=2, sort_keys=True),+ "grphs_all",+ )+++def test_get_graph(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+ test_user_id: str,+) -> None:+ """Test get single graph endpoint"""+ mock_graph = GraphModel(+ id="graph-123",+ version=1,+ is_active=True,+ name="Test Graph",+ description="A test graph",+ user_id=test_user_id,+ created_at=datetime(2025, 9, 4, 13, 37),+ )++ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph",+ return_value=mock_graph,+ )++ response = client.get("/graphs/graph-123")++ assert response.status_code == 200+ response_data = response.json()+ assert response_data["id"] == "graph-123"++ snapshot.snapshot_dir = "snapshots"+ snapshot.assert_match(+ json.dumps(response_data, indent=2, sort_keys=True),+ "grph_single",+ )+++def test_get_graph_not_found(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Test get graph with non-existent ID"""+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph",+ return_value=None,+ )++ response = client.get("/graphs/nonexistent-graph")++ assert response.status_code == 404+ assert "not found" in response.json()["detail"]+++def test_delete_graph(+ mocker: pytest_mock.MockFixture,+ snapshot: Snapshot,+ test_user_id: str,+) -> None:+ """Test delete graph endpoint"""+ # Mock active graph for deactivation+ mock_graph = GraphModel(+ id="graph-123",+ version=1,+ is_active=True,+ name="Test Graph",+ description="A test graph",+ user_id=test_user_id,+ created_at=datetime(2025, 9, 4, 13, 37),+ )++ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph",+ return_value=mock_graph,+ )+ mocker.patch(+ "backend.api.features.graphs.routes.on_graph_deactivate",+ return_value=None,+ )+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.delete_graph",+ return_value=3, # Number of versions deleted+ )++ response = client.delete("/graphs/graph-123")++ assert response.status_code == 200+ response_data = response.json()+ assert response_data["version_counts"] == 3++ snapshot.snapshot_dir = "snapshots"+ snapshot.assert_match(+ json.dumps(response_data, indent=2, sort_keys=True),+ "grphs_del",+ )+++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.graphs.routes.graph_db.make_graph_model",+ return_value=mock_graph_model,+ )+ activate_mock = mocker.patch(+ "backend.api.features.graphs.routes.before_graph_activate",+ new=AsyncMock(+ side_effect=GraphActivationError(+ "Credential #cred-1 needs reconnect — please reconnect"+ )+ ),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph", new=AsyncMock()+ )+ create_lib_agent_mock = mocker.patch(+ "backend.api.features.graphs.routes.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.graphs.routes.graph_db.get_graph_all_versions",+ new=AsyncMock(return_value=[existing_version]),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.make_graph_model",+ return_value=mock_graph_model,+ )+ activate_mock = mocker.patch(+ "backend.api.features.graphs.routes.before_graph_activate",+ new=AsyncMock(+ side_effect=GraphActivationError(+ "Credential #cred-1 needs reconnect — please reconnect"+ )+ ),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph", new=AsyncMock()+ )+ update_lib_agent_mock = mocker.patch(+ "backend.api.features.graphs.routes.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()+++def test_get_graph_all_versions_returns_404_when_empty(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",+ AsyncMock(return_value=[]),+ )++ response = client.get("/graphs/graph-1/versions")++ assert response.status_code == 404+++def test_update_graph_settings_requires_a_library_agent(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Settings live on the caller's library agent, so a graph the caller has+ not added must not be settable."""+ mocker.patch(+ "backend.api.features.graphs.routes.library_db.get_library_agent_by_graph_id",+ AsyncMock(return_value=None),+ )++ response = client.patch("/graphs/graph-1/settings", json={})++ assert response.status_code == 404+++def test_update_graph_settings_scopes_the_write_to_the_caller(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ mocker.patch(+ "backend.api.features.graphs.routes.library_db.get_library_agent_by_graph_id",+ AsyncMock(return_value=Mock(id="lib-1")),+ )+ update = mocker.patch(+ "backend.api.features.graphs.routes.library_db.update_library_agent",+ AsyncMock(return_value=Mock(settings={})),+ )++ response = client.patch("/graphs/graph-1/settings", json={})++ assert response.status_code == 200+ kwargs = update.await_args.kwargs+ assert kwargs["library_agent_id"] == "lib-1"+ assert kwargs["user_id"] == test_user_id+++def test_execute_graph_refuses_a_zero_balance(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The balance gate is the last thing between an empty account and a paid+ run; a 402 here is what stops it."""+ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=0)+ mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )+ started = mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(),+ )++ response = client.post("/graphs/graph-1/execute/1", json={})++ assert response.status_code == 402+ started.assert_not_awaited()+++def test_execute_graph_skips_the_balance_check_for_a_dry_run(+ mocker: pytest_mock.MockFixture,+) -> None:+ """A dry run costs nothing, so it must not be blocked by an empty balance+ — and must not consult the credit model at all."""+ credit = mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model", AsyncMock()+ )+ mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(return_value=_execution_meta()),+ )+ mocker.patch("backend.api.features.graphs.routes.record_graph_operation", Mock())++ response = client.post("/graphs/graph-1/execute/1", json={"dry_run": True})++ assert response.status_code == 200+ credit.assert_not_awaited()+++def test_execute_graph_forwards_the_org_and_team_scope(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ """Dropping either would run the graph outside the caller's tenancy.++ The file-wide context has team_id=None, which cannot tell a forwarded team+ from a dropped one, so this test supplies a context that carries one.+ """+ from autogpt_libs.auth.dependencies import get_request_context++ async def _team_scoped_context():+ return _request_context(test_user_id, team_id="test-team")++ app.dependency_overrides[get_request_context] = _team_scoped_context++ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=100)+ mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )+ started = mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(return_value=_execution_meta()),+ )+ mocker.patch("backend.api.features.graphs.routes.record_graph_operation", Mock())++ response = client.post("/graphs/graph-1/execute/2", json={})++ assert response.status_code == 200+ kwargs = started.await_args.kwargs+ assert kwargs["organization_id"] == "test-org"+ assert kwargs["team_id"] == "test-team"+ assert kwargs["graph_version"] == 2+++def test_execute_graph_marks_the_onboarding_step_for_a_library_run(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The step is keyed off `source`, so a run started from the library is the+ only thing that can complete it."""+ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=100)+ mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(return_value=_execution_meta()),+ )+ mocker.patch("backend.api.features.graphs.routes.record_graph_operation", Mock())+ step = mocker.patch(+ "backend.api.features.graphs.routes.complete_onboarding_step", AsyncMock()+ )++ response = client.post("/graphs/graph-1/execute/1", json={"source": "library"})++ assert response.status_code == 200+ assert step.await_args.args[1] is OnboardingStep.LIBRARY_RUN_AGENT+++def test_execute_graph_returns_structured_validation_errors(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The builder parses `node_errors` to highlight the offending nodes; a+ plain 500 would lose that."""+ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=100)+ mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(+ side_effect=GraphValidationError(+ message="bad graph", node_errors={"node-1": "missing input"}+ )+ ),+ )+ mocker.patch("backend.api.features.graphs.routes.record_graph_operation", Mock())++ response = client.post("/graphs/graph-1/execute/1", json={})++ assert response.status_code == 400+ detail = response.json()["detail"]+ assert detail["type"] == "validation_error"+ assert detail["node_errors"] == {"node-1": "missing input"}+++def test_update_graph_rejects_an_id_that_contradicts_the_uri(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Without this the body's id would silently win over the URI's."""+ response = client.put(+ "/graphs/graph-1",+ json={+ "id": "graph-2",+ "name": "x",+ "description": "",+ "nodes": [],+ "links": [],+ },+ )++ assert response.status_code == 400+++def test_update_graph_returns_404_for_an_unknown_graph(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",+ AsyncMock(return_value=[]),+ )++ response = client.put(+ "/graphs/graph-1",+ json={+ "id": "graph-1",+ "name": "x",+ "description": "",+ "nodes": [],+ "links": [],+ },+ )++ assert response.status_code == 404+++def test_create_new_graph_reassigns_ids_and_persists_in_order(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The graph gets fresh ids before anything is written, and the library+ agent is created only after the graph — the same ordering the activation+ -error test above pins from the failure side. Reassignment matters because+ a submitted id would otherwise let a caller collide with someone else's."""+ calls: list[str] = []+ mocker.patch(+ "backend.api.features.graphs.routes.before_graph_activate",+ new=AsyncMock(side_effect=lambda g, **_: g),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph",+ new=AsyncMock(side_effect=lambda *a, **k: calls.append("graph")),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.library_db.create_library_agent",+ new=AsyncMock(side_effect=lambda *a, **k: calls.append("library")),+ )++ response = client.post(+ "/graphs",+ json={+ "graph": {+ "id": "submitted-id",+ "name": "x",+ "description": "",+ "nodes": [],+ "links": [],+ }+ },+ )++ assert response.status_code == 200+ assert calls == ["graph", "library"]+ assert response.json()["id"] != "submitted-id"+++def test_set_active_version_returns_404_for_an_unknown_version(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The lookup is scoped to the caller, so a version belonging to someone+ else reads as absent rather than being activated."""+ lookup = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph",+ AsyncMock(return_value=None),+ )+ activate = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.set_graph_active_version",+ AsyncMock(),+ )++ response = client.put(+ "/graphs/graph-1/versions/active", json={"active_graph_version": 7}+ )++ assert response.status_code == 404+ activate.assert_not_awaited()+ assert lookup.await_args.kwargs["user_id"]+++def test_get_graph_all_versions_scopes_to_the_caller_org(+ mocker: pytest_mock.MockFixture,+) -> None:+ lookup = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",+ AsyncMock(return_value=[]),+ )++ client.get("/graphs/graph-1/versions")++ assert lookup.await_args.kwargs["organization_id"] == "test-org"+++def test_execute_graph_marks_the_builder_onboarding_step(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Sibling of the library case: the two sources complete different steps,+ so collapsing them would silently mark the wrong one."""+ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=100)+ mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(return_value=_execution_meta()),+ )+ mocker.patch("backend.api.features.graphs.routes.record_graph_operation", Mock())+ step = mocker.patch(+ "backend.api.features.graphs.routes.complete_onboarding_step", AsyncMock()+ )++ response = client.post("/graphs/graph-1/execute/1", json={"source": "builder"})++ assert response.status_code == 200+ assert step.await_args.args[1] is OnboardingStep.BUILDER_RUN_AGENT+++def test_execute_graph_records_a_failure_and_re_raises(+ mocker: pytest_mock.MockFixture,+) -> None:+ """An unexpected error must still be counted; swallowing it would make the+ execute metric read as if nothing went wrong."""+ credit_model = Mock()+ credit_model.get_credits = AsyncMock(return_value=100)+ mocker.patch(+ "backend.api.features.graphs.routes.get_credit_model",+ AsyncMock(return_value=credit_model),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.execution_utils.add_graph_execution",+ AsyncMock(side_effect=RuntimeError("boom")),+ )+ record = mocker.patch(+ "backend.api.features.graphs.routes.record_graph_operation", Mock()+ )++ with pytest.raises(RuntimeError):+ client.post("/graphs/graph-1/execute/1", json={})++ assert record.call_args.kwargs["status"] == "error"diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex e510840ae2..cb645caacc 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -4,7 +4,7 @@ import loggingimport timefrom collections import defaultdictfrom datetime import datetime, timezone-from typing import Annotated, Any, Literal, Sequence, cast, get_args+from typing import Annotated, Literal, cast, get_argsfrom urllib.parse import urlparseimport pydantic@@ -35,24 +35,19 @@ from fastapi.concurrency import run_in_threadpoolfrom prisma.enums import BriefingFrequency, SubscriptionTierfrom pydantic import BaseModel, Fieldfrom starlette.status import HTTP_402_PAYMENT_REQUIRED-from typing_extensions import Optional, TypedDict+from typing_extensions import Optionalfrom backend.api.features.credits_rate_limit import (enforce_subscription_status_rate_limit,)from backend.api.model import (- CreateGraph,- GraphExecutionSource,RequestTopUp,- SetGraphActiveVersion,TimezoneResponse,UpdateTimezoneRequest,UploadFileResponse,)from backend.blocks import get_block, get_blocksfrom backend.copilot.rate_limit import enforce_payment_paywall, get_tier_multipliers-from backend.data import execution as execution_db-from backend.data import graph as graph_dbfrom backend.data.block import BlockInput, CompletedBlockOutputfrom backend.data.credit import (AutoTopUpConfig,@@ -81,8 +76,7 @@ from backend.data.credit import (sync_tier_from_checkout_session,)from backend.data.execution import ExecutionContext-from backend.data.graph import GraphSettings-from backend.data.model import CredentialsMetaInput, UserOnboarding+from backend.data.model import UserOnboardingfrom backend.data.notifications import (NotificationPreference,NotificationPreferenceDTO,@@ -122,28 +116,19 @@ from backend.data.user import (verify_preference_token,)from backend.executor import utils as execution_utils-from backend.integrations.webhooks.graph_lifecycle_hooks import (- before_graph_activate,- on_graph_deactivate,-)-from backend.monitoring.instrumentation import (- record_block_execution,- record_graph_operation,-)+from backend.monitoring.instrumentation import record_block_executionfrom backend.notifications import lifecyclefrom backend.notifications.queue import queue_pass_workfrom backend.notifications.trial import notify_trial, on_trial_invoicefrom backend.util.cache import cachedfrom backend.util.cloud_storage import get_cloud_storage_handler-from backend.util.exceptions import GraphValidationError, InsufficientBalanceError+from backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.feature_flag import Flag, evaluate_feature_flagfrom backend.util.json import dumpsfrom backend.util.settings import Settingsfrom backend.util.timezone_utils import get_user_timezone_or_utcfrom backend.util.virus_scanner import scan_content_safe-from .library import db as library_db-from .library import model as library_modelfrom .store.model import StoreAgentDetails@@ -1767,406 +1752,3 @@ async def list_invoices("""credit_model = await get_credit_model(user_id, ctx.org_id)return await credit_model.list_invoices(user_id, limit=limit)---########################################################-##################### Graphs ###########################-########################################################---class DeleteGraphResponse(TypedDict):- version_counts: int---class UpdateGraphResponse(BaseModel):- """Response for creating/activating a new graph version.-- Carries the new graph version plus any webhook presets that were left- pinned to their old version because the new version's trigger block is- incompatible and needs to be reconfigured.- """-- graph: graph_db.GraphModel- skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = Field(- default_factory=list- )---class SetActiveGraphVersionResponse(BaseModel):- """Response for activating an existing graph version.-- Carries any webhook presets that were left pinned to their old version- because the newly activated version's trigger block is incompatible and- needs to be reconfigured.- """-- skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = Field(- default_factory=list- )---@v1_router.get(- path="/graphs",- summary="List user graphs",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def list_graphs(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> Sequence[graph_db.GraphMeta]:- paginated_result = await graph_db.list_graphs_paginated(- user_id=user_id,- page=1,- page_size=250,- filter_by="active",- organization_id=ctx.org_id,- )- return paginated_result.graphs---@v1_router.get(- path="/graphs/{graph_id}",- summary="Get specific graph",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-@v1_router.get(- path="/graphs/{graph_id}/versions/{version}",- summary="Get graph version",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def get_graph(- graph_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- version: int | None = None,- for_export: bool = False,-) -> graph_db.GraphModel:- graph = await graph_db.get_graph(- graph_id,- version,- user_id=user_id,- for_export=for_export,- include_subgraphs=True, # needed to construct full credentials input schema- organization_id=ctx.org_id,- )- if not graph:- raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")- return graph---@v1_router.get(- path="/graphs/{graph_id}/versions",- summary="Get all graph versions",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def get_graph_all_versions(- graph_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> Sequence[graph_db.GraphModel]:- graphs = await graph_db.get_graph_all_versions(- graph_id, user_id=user_id, organization_id=ctx.org_id- )- if not graphs:- raise HTTPException(status_code=404, detail=f"Graph #{graph_id} not found.")- return graphs---@v1_router.post(- path="/graphs",- summary="Create new graph",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def create_new_graph(- create_graph: CreateGraph,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> graph_db.GraphModel:- graph = graph_db.make_graph_model(create_graph.graph, user_id)- 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,- organization_id=ctx.org_id,- team_id=ctx.team_id,- )- await library_db.create_library_agent(- graph, user_id, organization_id=ctx.org_id, team_id=ctx.team_id- )-- return graph---@v1_router.delete(- path="/graphs/{graph_id}",- summary="Delete graph permanently",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def delete_graph(- graph_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> DeleteGraphResponse:- if active_version := await graph_db.get_graph(- graph_id=graph_id, version=None, user_id=user_id- ):- await on_graph_deactivate(active_version, user_id=user_id)-- return {- "version_counts": await graph_db.delete_graph(- graph_id, user_id=user_id, organization_id=ctx.org_id- )- }---@v1_router.put(- path="/graphs/{graph_id}",- summary="Update graph version",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def update_graph(- graph_id: str,- graph: graph_db.Graph,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> UpdateGraphResponse:- if graph.id and graph.id != graph_id:- raise HTTPException(400, detail="Graph ID does not match ID in URI")-- existing_versions = await graph_db.get_graph_all_versions(graph_id, user_id=user_id)- if not existing_versions:- raise HTTPException(404, detail=f"Graph #{graph_id} not found")-- graph.version = max(g.version for g in existing_versions) + 1- current_active_version = next((v for v in existing_versions if v.is_active), None)-- graph = graph_db.make_graph_model(graph, user_id)- 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,- organization_id=ctx.org_id,- team_id=ctx.team_id,- )-- skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = []- if new_graph_version.is_active:- await library_db.update_library_agent_version_and_settings(- user_id, new_graph_version- )- await graph_db.set_graph_active_version(- graph_id=graph_id, version=new_graph_version.version, user_id=user_id- )- if current_active_version:- await on_graph_deactivate(current_active_version, user_id=user_id)-- # Migrate webhook-attached presets to the new version so that- # existing webhook URLs continue to trigger the latest agent version.- if new_graph_version.webhook_input_node:- migration = await library_db.migrate_webhook_presets_to_new_version(- user_id=user_id,- new_graph=new_graph_version,- )- skipped_webhook_presets = migration.skipped_presets-- new_graph_version_with_subgraphs = await graph_db.get_graph(- graph_id,- new_graph_version.version,- user_id=user_id,- include_subgraphs=True,- )- assert new_graph_version_with_subgraphs- return UpdateGraphResponse(- graph=new_graph_version_with_subgraphs,- skipped_webhook_presets=skipped_webhook_presets,- )---@v1_router.put(- path="/graphs/{graph_id}/versions/active",- summary="Set active graph version",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def set_graph_active_version(- graph_id: str,- request_body: SetGraphActiveVersion,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> SetActiveGraphVersionResponse:- new_active_version = request_body.active_graph_version- new_active_graph = await graph_db.get_graph(- graph_id, new_active_version, user_id=user_id- )- if not new_active_graph:- raise HTTPException(404, f"Graph #{graph_id} v{new_active_version} not found")-- current_active_graph = await graph_db.get_graph(- graph_id=graph_id,- version=None,- 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 version- await graph_db.set_graph_active_version(- graph_id=graph_id,- version=new_active_version,- user_id=user_id,- )-- # Keep the library agent up to date with the new active version- await library_db.update_library_agent_version_and_settings(- user_id, new_active_graph- )-- if current_active_graph and current_active_graph.version != new_active_version:- # Handle deactivation of the previously active version- await on_graph_deactivate(current_active_graph, user_id=user_id)-- # Migrate webhook-attached presets to the new active version so that- # existing webhook URLs continue to trigger the latest agent version.- skipped_webhook_presets: list[library_model.SkippedWebhookPreset] = []- if new_active_graph.webhook_input_node:- migration = await library_db.migrate_webhook_presets_to_new_version(- user_id=user_id,- new_graph=new_active_graph,- )- skipped_webhook_presets = migration.skipped_presets-- return SetActiveGraphVersionResponse(- skipped_webhook_presets=skipped_webhook_presets- )---@v1_router.patch(- path="/graphs/{graph_id}/settings",- summary="Update graph settings",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def update_graph_settings(- graph_id: str,- settings: GraphSettings,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> GraphSettings:- """Update graph settings for the user's library agent."""- library_agent = await library_db.get_library_agent_by_graph_id(- graph_id=graph_id, user_id=user_id- )- if not library_agent:- raise HTTPException(404, f"Graph #{graph_id} not found in user's library")-- updated_agent = await library_db.update_library_agent(- library_agent_id=library_agent.id,- user_id=user_id,- settings=settings,- )-- return GraphSettings.model_validate(updated_agent.settings)---@v1_router.post(- path="/graphs/{graph_id}/execute/{graph_version}",- summary="Execute graph agent",- tags=["graphs"],- dependencies=[Security(requires_user), Depends(enforce_payment_paywall)],- # The route dep enforces fail-closed (503-on-blip) so a transient- # Supabase outage surfaces as a retryable error, not a free run- # for a paywalled user. The deep gate inside ``add_graph_execution``- # still covers scheduled / webhook / copilot-internal runs that- # don't pass through this route — those callers prefer fail-open- # so background work doesn't abandon valid jobs during a blip.- responses={- 402: {- "description": "Payment required: NO_TIER paywall, or insufficient credit balance"- },- 503: {"description": "Subscription state temporarily unavailable"},- },-)-async def execute_graph(- graph_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- inputs: Annotated[dict[str, Any], Body(..., embed=True, default_factory=dict)],- credentials_inputs: Annotated[- dict[str, CredentialsMetaInput], Body(..., embed=True, default_factory=dict)- ],- source: Annotated[GraphExecutionSource | None, Body(embed=True)] = None,- graph_version: Optional[int] = None,- preset_id: Optional[str] = None,- dry_run: Annotated[bool, Body(embed=True)] = False,-) -> execution_db.GraphExecutionMeta:- if not dry_run:- credit_model = await get_credit_model(user_id, ctx.org_id)- current_balance = await credit_model.get_credits(user_id)- if current_balance <= 0:- raise HTTPException(- status_code=402,- detail="Insufficient balance to execute the agent. Please top up your account.",- )-- try:- result = await execution_utils.add_graph_execution(- graph_id=graph_id,- user_id=user_id,- inputs=inputs,- preset_id=preset_id,- graph_version=graph_version,- graph_credentials_inputs=credentials_inputs,- dry_run=dry_run,- organization_id=ctx.org_id,- team_id=ctx.team_id,- trigger=execution_db.ExecutionTrigger.MANUAL,- trigger_ref=source,- )- record_graph_operation(operation="execute", status="success")- if source == "library":- await complete_onboarding_step(user_id, OnboardingStep.LIBRARY_RUN_AGENT)- elif source == "builder":- await complete_onboarding_step(user_id, OnboardingStep.BUILDER_RUN_AGENT)- return result- except GraphValidationError as e:- record_graph_operation(operation="execute", status="validation_error")- # Return structured validation errors that the frontend can parse- raise HTTPException(- status_code=400,- detail={- "type": "validation_error",- "message": e.message,- # TODO: only return node-specific errors if user has access to graph- "node_errors": e.node_errors,- },- )- except Exception:- record_graph_operation(operation="execute", status="error")- raisediff --git a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.pyindex 2dd7894b8b..c0e4528143 100644--- a/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_credits_authz_test.py@@ -35,6 +35,7 @@ from autogpt_libs.auth.permissions import OrgActionfrom fastapi.dependencies.models import Dependantfrom fastapi.routing import APIRoute+from backend.api.rest_api import app as real_appfrom backend.data.model import AutoTopUpConfig, TransactionHistoryfrom backend.data.org_credit import OrgCreditModel@@ -334,9 +335,19 @@ def test_every_credits_route_is_gated_or_explicitly_exempt():"""Introspect the mounted app so a *new* ungated /credits route fails.``GATED_ROUTES`` above is hand-maintained, so on its own it can only prove- that the routes someone remembered to list are gated. This walks the real- routing table instead: every ``/credits*`` route must either carry the- MANAGE_BILLING dependency or be an explicit, documented exemption.+ that the routes someone remembered to list are gated. This walks the routing+ table instead: every ``/credits*`` route must either carry the MANAGE_BILLING+ dependency or be an explicit, documented exemption.++ Scope, deliberately: this walks ``v1_router``'s own mount, not the real app,+ so it does not see the eight ``/api/credits*`` routes served by other modules+ (admin, trials, exports). Widening it to ``real_app`` makes all eight+ unexpected at once and needs each audited against this rule on its own —+ a security review, not a refactor, tracked as SECRT-2650. Until then this+ cannot catch an ungated route outside ``v1_router``, and once the credits+ section moves to its own module it will see nothing at all: that move must+ mount ``real_app`` and carry the eight in a ``PENDING_AUDIT`` set, so a+ ninth unexpected route still fails while none of the eight is signed off."""gated: set[str] = set()ungated: set[str] = set()@@ -383,7 +394,7 @@ def test_every_org_balance_reader_is_gated_or_explicitly_exempt():"""ungated = {route.name- for route in app.routes+ for route in real_app.routesif isinstance(route, APIRoute)and "get_credit_model" in inspect.getsource(route.endpoint)and OrgAction.MANAGE_BILLING not in _enforced_org_actions(route.dependant)diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex 72428597ae..9234078390 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -14,7 +14,6 @@ from pytest_snapshot.plugin import Snapshotfrom backend.api.rest_api import handle_internal_http_errorfrom backend.data.credit import AutoTopUpConfig-from backend.data.graph import GraphModelfrom backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationErrorfrom backend.util.exceptions import ConflictError, InsufficientBalanceError@@ -708,233 +707,6 @@ def test_list_invoices_default_limit(mocker: pytest_mock.MockFixture) -> None:assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}-# Graphs endpoints tests-def test_get_graphs(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,- test_user_id: str,-) -> None:- """Test get graphs endpoint"""- mock_graph = GraphModel(- id="graph-123",- version=1,- is_active=True,- name="Test Graph",- description="A test graph",- user_id=test_user_id,- created_at=datetime(2025, 9, 4, 13, 37),- )-- mocker.patch(- "backend.data.graph.list_graphs_paginated",- return_value=Mock(graphs=[mock_graph]),- )-- response = client.get("/graphs")-- assert response.status_code == 200- response_data = response.json()- assert len(response_data) == 1- assert response_data[0]["id"] == "graph-123"-- snapshot.snapshot_dir = "snapshots"- snapshot.assert_match(- json.dumps(response_data, indent=2, sort_keys=True),- "grphs_all",- )---def test_get_graph(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,- test_user_id: str,-) -> None:- """Test get single graph endpoint"""- mock_graph = GraphModel(- id="graph-123",- version=1,- is_active=True,- name="Test Graph",- description="A test graph",- user_id=test_user_id,- created_at=datetime(2025, 9, 4, 13, 37),- )-- mocker.patch(- "backend.api.features.v1.graph_db.get_graph",- return_value=mock_graph,- )-- response = client.get("/graphs/graph-123")-- assert response.status_code == 200- response_data = response.json()- assert response_data["id"] == "graph-123"-- snapshot.snapshot_dir = "snapshots"- snapshot.assert_match(- json.dumps(response_data, indent=2, sort_keys=True),- "grph_single",- )---def test_get_graph_not_found(- mocker: pytest_mock.MockFixture,-) -> None:- """Test get graph with non-existent ID"""- mocker.patch(- "backend.api.features.v1.graph_db.get_graph",- return_value=None,- )-- response = client.get("/graphs/nonexistent-graph")-- assert response.status_code == 404- assert "not found" in response.json()["detail"]---def test_delete_graph(- mocker: pytest_mock.MockFixture,- snapshot: Snapshot,- test_user_id: str,-) -> None:- """Test delete graph endpoint"""- # Mock active graph for deactivation- mock_graph = GraphModel(- id="graph-123",- version=1,- is_active=True,- name="Test Graph",- description="A test graph",- user_id=test_user_id,- created_at=datetime(2025, 9, 4, 13, 37),- )-- mocker.patch(- "backend.api.features.v1.graph_db.get_graph",- return_value=mock_graph,- )- mocker.patch(- "backend.api.features.v1.on_graph_deactivate",- return_value=None,- )- mocker.patch(- "backend.api.features.v1.graph_db.delete_graph",- return_value=3, # Number of versions deleted- )-- response = client.delete("/graphs/graph-123")-- assert response.status_code == 200- response_data = response.json()- assert response_data["version_counts"] == 3-- snapshot.snapshot_dir = "snapshots"- snapshot.assert_match(- json.dumps(response_data, indent=2, sort_keys=True),- "grphs_del",- )---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 aded2c6c92..939b623f05 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -40,6 +40,7 @@ import backend.api.features.experimentsimport backend.api.features.experts.routes as experts_routesimport backend.api.features.graph_executions.review.routesimport backend.api.features.graph_executions.routes as graph_executions_routes+import backend.api.features.graphs.routes as graphs_routesimport backend.api.features.home.routes as home_routesimport backend.api.features.library.dbimport backend.api.features.library.model@@ -409,6 +410,11 @@ app.include_router(tags=["v1"],prefix="/api",)+app.include_router(+ graphs_routes.router,+ tags=["v1", "graphs"],+ prefix="/api",+)app.include_router(auth_email_routes.auth_email_router,prefix="/api/auth/email",@@ -684,7 +690,7 @@ class AgentServer(backend.util.service.AppProcess):is_team_billing_manager=False,seat_status="ACTIVE",)- return await backend.api.features.v1.execute_graph(+ return await graphs_routes.execute_graph(user_id=user_id,ctx=ctx,graph_id=graph_id,@@ -717,13 +723,13 @@ class AgentServer(backend.util.service.AppProcess):is_team_billing_manager=False,seat_status="ACTIVE",)- return await backend.api.features.v1.get_graph(+ return await graphs_routes.get_graph(graph_id, user_id, ctx, graph_version, for_export)@staticmethodasync def test_create_graph(- create_graph: backend.api.features.v1.CreateGraph,+ create_graph: graphs_routes.CreateGraph,user_id: str,):from autogpt_libs.auth.models import RequestContext@@ -743,9 +749,7 @@ class AgentServer(backend.util.service.AppProcess):is_team_billing_manager=False,seat_status="ACTIVE",)- return await backend.api.features.v1.create_new_graph(- create_graph, user_id, ctx- )+ return await graphs_routes.create_new_graph(create_graph, user_id, ctx)@staticmethodasync def test_get_graph_run_status(graph_exec_id: str, user_id: str):@@ -781,7 +785,7 @@ class AgentServer(backend.util.service.AppProcess):is_team_billing_manager=False,seat_status="ACTIVE",)- return await backend.api.features.v1.delete_graph(graph_id, user_id, ctx)+ return await graphs_routes.delete_graph(graph_id, user_id, ctx)@staticmethodasync def test_get_presets(user_id: str, page: int = 1, page_size: int = 10):diff --git a/autogpt_platform/backend/test/test_migrate_webhook_presets.py b/autogpt_platform/backend/test/test_migrate_webhook_presets.pyindex b1c4ed8d27..3236688bde 100644--- a/autogpt_platform/backend/test/test_migrate_webhook_presets.py+++ b/autogpt_platform/backend/test/test_migrate_webhook_presets.py@@ -408,7 +408,7 @@ async def test_update_graph_in_library_skips_when_no_webhook_node(mocker):@pytest.mark.asyncioasync def test_v1_update_graph_migrates_when_webhook_node_present(mocker):"""The PUT /graphs/{id} route triggers migration on the new active version."""- from backend.api.features import v1+ from backend.api.features.graphs import routes as graph_routesnew_graph = _make_graph_mock(has_webhook=True, version=3)incoming = AsyncMock()@@ -418,24 +418,26 @@ async def test_v1_update_graph_migrates_when_webhook_node_present(mocker):existing_version.version = new_graph.version - 1existing_version.is_active = Truemocker.patch.object(- v1.graph_db,+ graph_routes.graph_db,"get_graph_all_versions",return_value=[existing_version],)- mocker.patch.object(v1.graph_db, "make_graph_model", return_value=new_graph)- mocker.patch.object(v1.graph_db, "create_graph", return_value=new_graph)- mocker.patch.object(v1.graph_db, "set_graph_active_version")+ mocker.patch.object(+ graph_routes.graph_db, "make_graph_model", return_value=new_graph+ )+ mocker.patch.object(graph_routes.graph_db, "create_graph", return_value=new_graph)+ mocker.patch.object(graph_routes.graph_db, "set_graph_active_version")# get_graph feeds UpdateGraphResponse.graph (a real GraphModel field), so# return an actual GraphModel instance rather than a MagicMock.mocker.patch.object(- v1.graph_db,+ graph_routes.graph_db,"get_graph",- return_value=v1.graph_db.GraphModel.model_construct(+ return_value=graph_routes.graph_db.GraphModel.model_construct(id=new_graph.id, version=new_graph.version),)mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"update_library_agent_version_and_settings",return_value=AsyncMock(),)@@ -443,16 +445,18 @@ async def test_v1_update_graph_migrates_when_webhook_node_present(mocker):id="preset-1", name="My Trigger", pinned_version=2)migrate_mock = mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"migrate_webhook_presets_to_new_version",return_value=library_model.WebhookPresetMigrationResult(migrated_count=1, skipped_presets=[skipped]),)- mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)- mocker.patch.object(v1, "on_graph_deactivate", return_value=None)+ mocker.patch.object(+ graph_routes, "before_graph_activate", side_effect=lambda g, user_id: g+ )+ mocker.patch.object(graph_routes, "on_graph_deactivate", return_value=None)- response = await v1.update_graph(+ response = await graph_routes.update_graph(graph_id=new_graph.id,graph=incoming,user_id="user-1",@@ -469,7 +473,7 @@ async def test_v1_update_graph_migrates_when_webhook_node_present(mocker):@pytest.mark.asyncioasync def test_v1_update_graph_skips_when_no_webhook_node(mocker):"""No migration call from PUT /graphs/{id} when graph has no webhook node."""- from backend.api.features import v1+ from backend.api.features.graphs import routes as graph_routesnew_graph = _make_graph_mock(has_webhook=False, version=3)incoming = AsyncMock()@@ -479,36 +483,40 @@ async def test_v1_update_graph_skips_when_no_webhook_node(mocker):existing_version.version = new_graph.version - 1existing_version.is_active = Truemocker.patch.object(- v1.graph_db,+ graph_routes.graph_db,"get_graph_all_versions",return_value=[existing_version],)- mocker.patch.object(v1.graph_db, "make_graph_model", return_value=new_graph)- mocker.patch.object(v1.graph_db, "create_graph", return_value=new_graph)- mocker.patch.object(v1.graph_db, "set_graph_active_version")+ mocker.patch.object(+ graph_routes.graph_db, "make_graph_model", return_value=new_graph+ )+ mocker.patch.object(graph_routes.graph_db, "create_graph", return_value=new_graph)+ mocker.patch.object(graph_routes.graph_db, "set_graph_active_version")# get_graph feeds UpdateGraphResponse.graph (a real GraphModel field), so# return an actual GraphModel instance rather than a MagicMock.mocker.patch.object(- v1.graph_db,+ graph_routes.graph_db,"get_graph",- return_value=v1.graph_db.GraphModel.model_construct(+ return_value=graph_routes.graph_db.GraphModel.model_construct(id=new_graph.id, version=new_graph.version),)mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"update_library_agent_version_and_settings",return_value=AsyncMock(),)migrate_mock = mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"migrate_webhook_presets_to_new_version",return_value=library_model.WebhookPresetMigrationResult(),)- mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)- mocker.patch.object(v1, "on_graph_deactivate", return_value=None)+ mocker.patch.object(+ graph_routes, "before_graph_activate", side_effect=lambda g, user_id: g+ )+ mocker.patch.object(graph_routes, "on_graph_deactivate", return_value=None)- response = await v1.update_graph(+ response = await graph_routes.update_graph(graph_id=new_graph.id,graph=incoming,user_id="user-1",@@ -524,18 +532,18 @@ async def test_v1_set_graph_active_version_migrates_when_webhook_node_present(mocker,):"""PUT /graphs/{id}/versions/active triggers migration on the activated version."""- from backend.api.features import v1+ from backend.api.features.graphs import routes as graph_routestarget_graph = _make_graph_mock(has_webhook=True, version=4)mocker.patch.object(- v1.graph_db,+ graph_routes.graph_db,"get_graph",side_effect=[target_graph, target_graph],)- mocker.patch.object(v1.graph_db, "set_graph_active_version")+ mocker.patch.object(graph_routes.graph_db, "set_graph_active_version")mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"update_library_agent_version_and_settings",return_value=AsyncMock(),)@@ -543,18 +551,20 @@ async def test_v1_set_graph_active_version_migrates_when_webhook_node_present(id="preset-9", name="Old Telegram Trigger", pinned_version=3)migrate_mock = mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"migrate_webhook_presets_to_new_version",return_value=library_model.WebhookPresetMigrationResult(migrated_count=2, skipped_presets=[skipped]),)- mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)- mocker.patch.object(v1, "on_graph_deactivate", return_value=None)+ mocker.patch.object(+ graph_routes, "before_graph_activate", side_effect=lambda g, user_id: g+ )+ mocker.patch.object(graph_routes, "on_graph_deactivate", return_value=None)- body = v1.SetGraphActiveVersion(active_graph_version=target_graph.version)+ body = graph_routes.SetGraphActiveVersion(active_graph_version=target_graph.version)- response = await v1.set_graph_active_version(+ response = await graph_routes.set_graph_active_version(graph_id=target_graph.id,request_body=body,user_id="user-1",@@ -571,32 +581,34 @@ async def test_v1_set_graph_active_version_migrates_when_webhook_node_present(@pytest.mark.asyncioasync def test_v1_set_graph_active_version_skips_when_no_webhook_node(mocker):"""PUT /graphs/{id}/versions/active skips migration when no webhook node."""- from backend.api.features import v1+ from backend.api.features.graphs import routes as graph_routestarget_graph = _make_graph_mock(has_webhook=False, version=4)mocker.patch.object(- v1.graph_db,+ graph_routes.graph_db,"get_graph",side_effect=[target_graph, target_graph],)- mocker.patch.object(v1.graph_db, "set_graph_active_version")+ mocker.patch.object(graph_routes.graph_db, "set_graph_active_version")mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"update_library_agent_version_and_settings",return_value=AsyncMock(),)migrate_mock = mocker.patch.object(- v1.library_db,+ graph_routes.library_db,"migrate_webhook_presets_to_new_version",return_value=library_model.WebhookPresetMigrationResult(),)- mocker.patch.object(v1, "before_graph_activate", side_effect=lambda g, user_id: g)- mocker.patch.object(v1, "on_graph_deactivate", return_value=None)+ mocker.patch.object(+ graph_routes, "before_graph_activate", side_effect=lambda g, user_id: g+ )+ mocker.patch.object(graph_routes, "on_graph_deactivate", return_value=None)- body = v1.SetGraphActiveVersion(active_graph_version=target_graph.version)+ body = graph_routes.SetGraphActiveVersion(active_graph_version=target_graph.version)- response = await v1.set_graph_active_version(+ response = await graph_routes.set_graph_active_version(graph_id=target_graph.id,request_body=body,user_id="user-1",