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 execution routes into features/graph_executions (#14474)
Reinier van der Leerd520335e1330
diff --git a/autogpt_platform/backend/backend/api/features/briefings/routes_test.py b/autogpt_platform/backend/backend/api/features/briefings/routes_test.pyindex ce17ed3b74..d6711989b4 100644--- a/autogpt_platform/backend/backend/api/features/briefings/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/briefings/routes_test.py@@ -1,6 +1,6 @@"""Tests for the briefings API routes.-Pattern mirrors backend/api/features/executions/review/review_routes_test.py:+Pattern mirrors backend/api/features/graph_executions/review/review_routes_test.py:the full app from backend.api.rest_api, the session-scoped `server` fixture(real Prisma DB), and `mock_jwt_user` for auth overrides. Unlike the reviewtests, these seed real rows via backend.data.briefing.create_briefing ratherdiff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.pyindex 202b5e1744..62ea373f39 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py@@ -14,6 +14,7 @@ import prisma.errorsimport prisma.modelsimport pydanticimport pytest+import pytest_asyncioimport backend.api.features.store.model as store_modelfrom backend.api.features.experts import experts_db, raise_attachments, scheduling, seed@@ -160,6 +161,18 @@ async def _delete_seeded_rows(template_ids: list[str], user_ids: list[str]) -> Nawait prisma.models.User.prisma().delete_many(where={"id": {"in": user_ids}})+@pytest_asyncio.fixture(autouse=True)+async def absorb_a_stale_event_loop(server: SpinTestServer):+ """An earlier test can leave the shared Prisma client bound to a loop that+ has since closed; only the first query on the new loop fails, and the engine+ re-establishes itself. Spend that failure here rather than in a fixture."""+ try:+ await db_client.execute_raw("SELECT 1")+ except RuntimeError as error:+ if "Event loop is closed" not in str(error):+ raise++@pytest.fixtureasync def test_user():return await _create_seed_user()diff --git a/autogpt_platform/backend/backend/api/features/executions/__init__.py b/autogpt_platform/backend/backend/api/features/graph_executions/__init__.pysimilarity index 100%rename from autogpt_platform/backend/backend/api/features/executions/__init__.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/__init__.pydiff --git a/autogpt_platform/backend/backend/api/features/executions/activity_gate.py b/autogpt_platform/backend/backend/api/features/graph_executions/activity_gate.pysimilarity index 100%rename from autogpt_platform/backend/backend/api/features/executions/activity_gate.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/activity_gate.pydiff --git a/autogpt_platform/backend/backend/api/features/graph_executions/model.py b/autogpt_platform/backend/backend/api/features/graph_executions/model.pynew file mode 100644index 0000000000..c1a7b6b9f6--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graph_executions/model.py@@ -0,0 +1,14 @@+import pydantic+++class ShareRequest(pydantic.BaseModel):+ """Optional request body for share endpoint."""++ pass # Empty body is fine+++class ShareResponse(pydantic.BaseModel):+ """Response from share endpoints."""++ share_url: str+ share_token: strdiff --git a/autogpt_platform/backend/backend/api/features/executions/review/__init__.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/__init__.pysimilarity index 100%rename from autogpt_platform/backend/backend/api/features/executions/review/__init__.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/review/__init__.pydiff --git a/autogpt_platform/backend/backend/api/features/executions/review/model.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.pysimilarity index 100%rename from autogpt_platform/backend/backend/api/features/executions/review/model.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/review/model.pydiff --git a/autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.pysimilarity index 86%rename from autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.pyindex aa5bf6b5d9..94cff74959 100644--- a/autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/review_routes_test.py@@ -72,7 +72,7 @@ async def test_get_pending_reviews_empty() -> None:"""Test getting pending reviews when none exist"""mock_get_reviews = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_user"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_user")mock_get_reviews.return_value = []@@ -93,7 +93,7 @@ async def test_get_pending_reviews_with_data() -> None:"""Test getting pending reviews with data"""mock_get_reviews = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_user"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_user")mock_get_reviews.return_value = [sample_pending_review]@@ -117,7 +117,7 @@ async def test_get_pending_reviews_for_execution_success() -> None:"""Test getting pending reviews for specific execution"""mock_get_graph_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_get_graph_execution.return_value = {"id": "test_graph_exec_456",@@ -125,7 +125,7 @@ async def test_get_pending_reviews_for_execution_success(}mock_get_reviews = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_execution")mock_get_reviews.return_value = [sample_pending_review]@@ -144,7 +144,7 @@ async def test_get_pending_reviews_for_execution_not_available() -> None:"""Test access denied when user doesn't own the execution"""mock_get_graph_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_get_graph_execution.return_value = None@@ -166,17 +166,17 @@ async def test_process_review_action_approve_success(# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")mock_get_reviews_for_user.return_value = {"test_node_123": sample_pending_review}mock_get_reviews_for_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_execution")mock_get_reviews_for_execution.return_value = [sample_pending_review]mock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")# Create approved review for returnapproved_review = PendingHumanReviewModel(@@ -200,18 +200,20 @@ async def test_process_review_action_approve_success(# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEWmock_get_graph_exec.return_value = mock_graph_exec_metamock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False- mocker.patch("backend.api.features.executions.review.routes.add_graph_execution")+ mocker.patch(+ "backend.api.features.graph_executions.review.routes.add_graph_execution"+ )request_data = {"reviews": [@@ -246,25 +248,25 @@ async def test_process_review_action_reject_success(# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")mock_get_reviews_for_user.return_value = {"test_node_123": sample_pending_review}# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEWmock_get_graph_exec.return_value = mock_graph_exec_metamock_get_reviews_for_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_execution")mock_get_reviews_for_execution.return_value = [sample_pending_review]mock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")rejected_review = PendingHumanReviewModel(node_exec_id="test_node_123",@@ -286,7 +288,7 @@ async def test_process_review_action_reject_success(mock_process_all_reviews.return_value = {"test_node_123": rejected_review}mock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False@@ -341,7 +343,7 @@ async def test_process_review_action_mixed_success(# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")mock_get_reviews_for_user.return_value = {"test_node_123": sample_pending_review,@@ -349,12 +351,12 @@ async def test_process_review_action_mixed_success(}mock_get_reviews_for_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_execution")mock_get_reviews_for_execution.return_value = [sample_pending_review, second_review]mock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")# Create approved version of first reviewapproved_review = PendingHumanReviewModel(@@ -399,14 +401,14 @@ async def test_process_review_action_mixed_success(# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEWmock_get_graph_exec.return_value = mock_graph_exec_metamock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False@@ -465,14 +467,14 @@ async def test_process_review_action_review_not_found("""Test error when review is not found"""# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")# Return empty dict to simulate review not foundmock_get_reviews_for_user.return_value = {}# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -480,13 +482,13 @@ async def test_process_review_action_review_not_found(# Mock the functions that extract graph execution ID from the requestmock_get_reviews_for_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_execution")mock_get_reviews_for_execution.return_value = [] # No reviews found# Mock process_all_reviews to simulate not finding reviewsmock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")# This should raise a ValueError with "Reviews not found" message based on the data/human_review.py logicmock_process_all_reviews.side_effect = ValueError(@@ -519,13 +521,13 @@ async def test_process_review_action_partial_failure("""Test handling of partial failures in review processing"""# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")mock_get_reviews_for_user.return_value = {"test_node_123": sample_pending_review}# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -533,13 +535,13 @@ async def test_process_review_action_partial_failure(# Mock the route functionsmock_get_reviews_for_execution = mocker.patch(- "backend.api.features.executions.review.routes.get_pending_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.get_pending_reviews_for_execution")mock_get_reviews_for_execution.return_value = [sample_pending_review]# Mock partial failure in processingmock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")mock_process_all_reviews.side_effect = ValueError("Some reviews failed validation")@@ -569,14 +571,14 @@ async def test_process_review_action_invalid_node_exec_id("""Test failure when trying to process review with invalid node execution ID"""# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")# Return empty dict to simulate review not foundmock_get_reviews_for_user.return_value = {}# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -609,13 +611,13 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records("""Test that auto_approve_future_actions flag creates auto-approval records"""# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")mock_get_reviews_for_user.return_value = {"test_node_123": sample_pending_review}# Mock process_all_reviewsmock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")approved_review = PendingHumanReviewModel(node_exec_id="test_node_123",@@ -638,7 +640,7 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(# Mock get_node_executions to return node_id mappingmock_get_node_executions = mocker.patch(- "backend.api.features.executions.review.routes.get_node_executions"+ "backend.api.features.graph_executions.review.routes.get_node_executions")mock_node_exec = mocker.Mock(spec=NodeExecutionResult)mock_node_exec.node_exec_id = "test_node_123"@@ -647,12 +649,12 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(# Mock create_auto_approval_recordmock_create_auto_approval = mocker.patch(- "backend.api.features.executions.review.routes.create_auto_approval_record"+ "backend.api.features.graph_executions.review.routes.create_auto_approval_record")# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -660,13 +662,13 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(# Mock has_pending_reviews_for_graph_execmock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False# Mock get_graph_settings to return custom settingsmock_get_settings = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_settings"+ "backend.api.features.graph_executions.review.routes.get_graph_settings")mock_get_settings.return_value = GraphSettings(human_in_the_loop_safe_mode=True,@@ -675,7 +677,7 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(# Mock get_user_by_id to prevent database accessmock_get_user = mocker.patch(- "backend.api.features.executions.review.routes.get_user_by_id"+ "backend.api.features.graph_executions.review.routes.get_user_by_id")mock_user = mocker.Mock()mock_user.timezone = "UTC"@@ -683,7 +685,7 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(# Mock add_graph_executionmock_add_execution = mocker.patch(- "backend.api.features.executions.review.routes.add_graph_execution"+ "backend.api.features.graph_executions.review.routes.add_graph_execution")request_data = {@@ -739,13 +741,13 @@ async def test_process_review_action_without_auto_approve_still_loads_settings("""Test that execution context is created with settings even without auto-approve"""# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")mock_get_reviews_for_user.return_value = {"test_node_123": sample_pending_review}# Mock process_all_reviewsmock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")approved_review = PendingHumanReviewModel(node_exec_id="test_node_123",@@ -768,12 +770,12 @@ async def test_process_review_action_without_auto_approve_still_loads_settings(# Mock create_auto_approval_record - should NOT be called when auto_approve is Falsemock_create_auto_approval = mocker.patch(- "backend.api.features.executions.review.routes.create_auto_approval_record"+ "backend.api.features.graph_executions.review.routes.create_auto_approval_record")# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -781,13 +783,13 @@ async def test_process_review_action_without_auto_approve_still_loads_settings(# Mock has_pending_reviews_for_graph_execmock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False# Mock get_graph_settings with sensitive_action_safe_mode enabledmock_get_settings = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_settings"+ "backend.api.features.graph_executions.review.routes.get_graph_settings")mock_get_settings.return_value = GraphSettings(human_in_the_loop_safe_mode=False,@@ -796,7 +798,7 @@ async def test_process_review_action_without_auto_approve_still_loads_settings(# Mock get_user_by_id to prevent database accessmock_get_user = mocker.patch(- "backend.api.features.executions.review.routes.get_user_by_id"+ "backend.api.features.graph_executions.review.routes.get_user_by_id")mock_user = mocker.Mock()mock_user.timezone = "UTC"@@ -804,7 +806,7 @@ async def test_process_review_action_without_auto_approve_still_loads_settings(# Mock add_graph_executionmock_add_execution = mocker.patch(- "backend.api.features.executions.review.routes.add_graph_execution"+ "backend.api.features.graph_executions.review.routes.add_graph_execution")# Request WITHOUT auto_approve_future (defaults to False)@@ -887,7 +889,7 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie# Mock get_reviews_by_node_exec_ids (called to find the graph_exec_id)mock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")# Need to return both reviews in WAITING state (before processing)approved_review_waiting = PendingHumanReviewModel(@@ -927,7 +929,7 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie# Mock process_all_reviewsmock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")mock_process_all_reviews.return_value = {"node_exec_approved": approved_review,@@ -936,7 +938,7 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie# Mock get_node_executions to return node_id mappingmock_get_node_executions = mocker.patch(- "backend.api.features.executions.review.routes.get_node_executions"+ "backend.api.features.graph_executions.review.routes.get_node_executions")mock_node_exec = mocker.Mock(spec=NodeExecutionResult)mock_node_exec.node_exec_id = "node_exec_approved"@@ -945,12 +947,12 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie# Mock create_auto_approval_recordmock_create_auto_approval = mocker.patch(- "backend.api.features.executions.review.routes.create_auto_approval_record"+ "backend.api.features.graph_executions.review.routes.create_auto_approval_record")# Mock get_graph_execution_meta to return execution in REVIEW statusmock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -958,19 +960,19 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie# Mock has_pending_reviews_for_graph_execmock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False# Mock get_graph_settingsmock_get_settings = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_settings"+ "backend.api.features.graph_executions.review.routes.get_graph_settings")mock_get_settings.return_value = GraphSettings()# Mock get_user_by_id to prevent database accessmock_get_user = mocker.patch(- "backend.api.features.executions.review.routes.get_user_by_id"+ "backend.api.features.graph_executions.review.routes.get_user_by_id")mock_user = mocker.Mock()mock_user.timezone = "UTC"@@ -978,7 +980,7 @@ async def test_process_review_action_auto_approve_only_applies_to_approved_revie# Mock add_graph_executionmock_add_execution = mocker.patch(- "backend.api.features.executions.review.routes.add_graph_execution"+ "backend.api.features.graph_executions.review.routes.add_graph_execution")request_data = {@@ -1033,7 +1035,7 @@ async def test_process_review_action_per_review_auto_approve_granularity("""Test that auto-approval can be set per-review (granular control)"""# Mock get_reviews_by_node_exec_ids - return different reviews based on node_exec_idmock_get_reviews_for_user = mocker.patch(- "backend.api.features.executions.review.routes.get_reviews_by_node_exec_ids"+ "backend.api.features.graph_executions.review.routes.get_reviews_by_node_exec_ids")# Create a mapping of node_exec_id to review@@ -1090,7 +1092,7 @@ async def test_process_review_action_per_review_auto_approve_granularity(# Mock process_all_reviews - return 3 approved reviewsmock_process_all_reviews = mocker.patch(- "backend.api.features.executions.review.routes.process_all_reviews_for_execution"+ "backend.api.features.graph_executions.review.routes.process_all_reviews_for_execution")mock_process_all_reviews.return_value = {"node_1_auto": PendingHumanReviewModel(@@ -1148,7 +1150,7 @@ async def test_process_review_action_per_review_auto_approve_granularity(# Mock get_node_executions to return batch node datamock_get_node_executions = mocker.patch(- "backend.api.features.executions.review.routes.get_node_executions"+ "backend.api.features.graph_executions.review.routes.get_node_executions")# Create mock node executions for each reviewmock_node_execs = []@@ -1161,12 +1163,12 @@ async def test_process_review_action_per_review_auto_approve_granularity(# Mock create_auto_approval_recordmock_create_auto_approval = mocker.patch(- "backend.api.features.executions.review.routes.create_auto_approval_record"+ "backend.api.features.graph_executions.review.routes.create_auto_approval_record")# Mock get_graph_execution_metamock_get_graph_exec = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_execution_meta"+ "backend.api.features.graph_executions.review.routes.get_graph_execution_meta")mock_graph_exec_meta = mocker.Mock()mock_graph_exec_meta.status = ExecutionStatus.REVIEW@@ -1174,20 +1176,22 @@ async def test_process_review_action_per_review_auto_approve_granularity(# Mock has_pending_reviews_for_graph_execmock_has_pending = mocker.patch(- "backend.api.features.executions.review.routes.has_pending_reviews_for_graph_exec"+ "backend.api.features.graph_executions.review.routes.has_pending_reviews_for_graph_exec")mock_has_pending.return_value = False# Mock settings and executionmock_get_settings = mocker.patch(- "backend.api.features.executions.review.routes.get_graph_settings"+ "backend.api.features.graph_executions.review.routes.get_graph_settings")mock_get_settings.return_value = GraphSettings(human_in_the_loop_safe_mode=False, sensitive_action_safe_mode=False)- mocker.patch("backend.api.features.executions.review.routes.add_graph_execution")- mocker.patch("backend.api.features.executions.review.routes.get_user_by_id")+ mocker.patch(+ "backend.api.features.graph_executions.review.routes.add_graph_execution"+ )+ mocker.patch("backend.api.features.graph_executions.review.routes.get_user_by_id")# Request with granular auto-approval:# - node_1_auto: auto_approve_future=Truediff --git a/autogpt_platform/backend/backend/api/features/executions/review/routes.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/routes.pysimilarity index 100%rename from autogpt_platform/backend/backend/api/features/executions/review/routes.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/review/routes.pydiff --git a/autogpt_platform/backend/backend/api/features/graph_executions/routes.py b/autogpt_platform/backend/backend/api/features/graph_executions/routes.pynew file mode 100644index 0000000000..c958da7680--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graph_executions/routes.py@@ -0,0 +1,387 @@+import asyncio+from datetime import datetime, timezone+from typing import Annotated, Optional++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, HTTPException, Path, Query, Response, Security+from starlette.status import HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND++from backend.api.features.graph_executions.activity_gate import (+ hide_activity_summaries_if_disabled,+ hide_activity_summary_if_disabled,+)+from backend.api.features.graph_executions.model import ShareRequest, ShareResponse+from backend.api.features.workspace.routes import create_file_download_response+from backend.data import execution as execution_db+from backend.data import graph as graph_db+from backend.data.execution_cost_summary import (+ UserExecutionCostSummary,+ get_user_cost_summary,+)+from backend.data.onboarding import (+ OnboardingStep,+ complete_onboarding_step,+ get_user_onboarding,+)+from backend.data.sharing.tokens import SHARE_TOKEN_PATTERN, generate_share_token+from backend.data.workspace import get_workspace_file_by_id+from backend.executor import utils as execution_utils+from backend.util.exceptions import NotFoundError+from backend.util.settings import Settings++settings = Settings()++# No router-level auth dependency: the two /public/shared routes are+# deliberately unauthenticated, so each route keeps its own.+router = APIRouter()+++ path="/graphs/{graph_id}/executions/{graph_exec_id}/stop",+ summary="Stop graph execution",+ tags=["graphs"],+ dependencies=[Security(requires_user)],+)+async def stop_graph_run(+ graph_id: str, graph_exec_id: str, user_id: Annotated[str, Security(get_user_id)]+) -> execution_db.GraphExecutionMeta | None:+ res = await _stop_graph_run(+ user_id=user_id,+ graph_id=graph_id,+ graph_exec_id=graph_exec_id,+ )+ if not res:+ return None+ return res[0]+++async def _stop_graph_run(+ user_id: str,+ graph_id: Optional[str] = None,+ graph_exec_id: Optional[str] = None,+) -> list[execution_db.GraphExecutionMeta]:+ graph_execs = await execution_db.get_graph_executions(+ user_id=user_id,+ graph_id=graph_id,+ graph_exec_id=graph_exec_id,+ statuses=[+ execution_db.ExecutionStatus.INCOMPLETE,+ execution_db.ExecutionStatus.QUEUED,+ execution_db.ExecutionStatus.RUNNING,+ ],+ )+ stopped_execs = [+ execution_utils.stop_graph_execution(graph_exec_id=exec.id, user_id=user_id)+ for exec in graph_execs+ ]+ await asyncio.gather(*stopped_execs)+ return graph_execs+++ path="/executions",+ summary="List all executions",+ tags=["graphs"],+ dependencies=[Security(requires_user)],+)+async def list_graphs_executions(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> list[execution_db.GraphExecutionMeta]:+ paginated_result = await execution_db.get_graph_executions_paginated(+ user_id=user_id,+ page=1,+ page_size=250,+ organization_id=ctx.org_id,+ )++ # Apply feature flags to filter out disabled features+ filtered_executions = await hide_activity_summaries_if_disabled(+ paginated_result.executions, user_id+ )+ return filtered_executions+++ path="/executions/cost-summary",+ summary="User cost summary",+ tags=["graphs"],+ dependencies=[Security(requires_user)],+)+async def get_executions_cost_summary(+ user_id: Annotated[str, Security(get_user_id)],+ since: datetime | None = Query(+ None,+ description="Window start (UTC). Defaults to start of current calendar month.",+ ),+ until: datetime | None = Query(+ None,+ description="Window end (UTC). Defaults to now.",+ ),+ top_runs_limit: int = Query(+ 10,+ ge=1,+ le=50,+ description="Maximum number of top-cost runs to return.",+ ),+) -> UserExecutionCostSummary:+ """Aggregated cost breakdown for the calling user's graph executions."""+ if since is not None and until is not None and since > until:+ raise HTTPException(+ status_code=422,+ detail="`since` must be earlier than or equal to `until`.",+ )+ return await get_user_cost_summary(+ user_id=user_id,+ since=since,+ until=until,+ top_runs_limit=top_runs_limit,+ )+++ path="/graphs/{graph_id}/executions",+ summary="List graph executions",+ tags=["graphs"],+ dependencies=[Security(requires_user)],+)+async def list_graph_executions(+ graph_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ page: int = Query(1, ge=1, description="Page number (1-indexed)"),+ page_size: int = Query(+ 25, ge=1, le=100, description="Number of executions per page"+ ),+) -> execution_db.GraphExecutionsPaginated:+ paginated_result = await execution_db.get_graph_executions_paginated(+ graph_id=graph_id,+ user_id=user_id,+ page=page,+ page_size=page_size,+ organization_id=ctx.org_id,+ )++ # Apply feature flags to filter out disabled features+ filtered_executions = await hide_activity_summaries_if_disabled(+ paginated_result.executions, user_id+ )+ onboarding = await get_user_onboarding(user_id)+ if (+ onboarding.onboardingAgentExecutionId+ and onboarding.onboardingAgentExecutionId+ in [exec.id for exec in filtered_executions]+ and OnboardingStep.GET_RESULTS not in onboarding.completedSteps+ ):+ await complete_onboarding_step(user_id, OnboardingStep.GET_RESULTS)++ return execution_db.GraphExecutionsPaginated(+ executions=filtered_executions, pagination=paginated_result.pagination+ )+++ path="/graphs/{graph_id}/executions/{graph_exec_id}",+ summary="Get execution details",+ tags=["graphs"],+ dependencies=[Security(requires_user)],+)+async def get_graph_execution(+ graph_id: str,+ graph_exec_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> execution_db.GraphExecution | execution_db.GraphExecutionWithNodes:+ result = await execution_db.get_graph_execution(+ user_id=user_id,+ execution_id=graph_exec_id,+ include_node_executions=True,+ organization_id=ctx.org_id,+ )+ if not result or result.graph_id != graph_id:+ raise HTTPException(+ status_code=404, detail=f"Graph execution #{graph_exec_id} not found."+ )++ if not await graph_db.get_graph(+ graph_id=result.graph_id,+ version=result.graph_version,+ user_id=user_id,+ organization_id=ctx.org_id,+ ):+ raise HTTPException(+ status_code=HTTP_404_NOT_FOUND, detail=f"Graph #{graph_id} not found"+ )++ # Apply feature flags to filter out disabled features+ result = await hide_activity_summary_if_disabled(result, user_id)+ onboarding = await get_user_onboarding(user_id)+ if (+ onboarding.onboardingAgentExecutionId == graph_exec_id+ and OnboardingStep.GET_RESULTS not in onboarding.completedSteps+ ):+ await complete_onboarding_step(user_id, OnboardingStep.GET_RESULTS)++ return result+++ path="/executions/{graph_exec_id}",+ summary="Delete graph execution",+ tags=["graphs"],+ dependencies=[Security(requires_user)],+ status_code=HTTP_204_NO_CONTENT,+)+async def delete_graph_execution(+ graph_exec_id: str,+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> None:+ await execution_db.delete_graph_execution(+ graph_exec_id=graph_exec_id, user_id=user_id+ )+++ "/graphs/{graph_id}/executions/{graph_exec_id}/share",+ dependencies=[Security(requires_user)],+)+async def enable_execution_sharing(+ graph_id: Annotated[str, Path],+ graph_exec_id: Annotated[str, Path],+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ _body: ShareRequest = Body(default=ShareRequest()),+) -> ShareResponse:+ """Enable sharing for a graph execution."""+ # Verify the execution belongs to the user+ execution = await execution_db.get_graph_execution(+ user_id=user_id, execution_id=graph_exec_id+ )+ if not execution:+ raise HTTPException(status_code=404, detail="Execution not found")++ # Generate a unique share token+ share_token = generate_share_token()++ # Remove stale allowlist records before updating the token — prevents a+ # window where old records + new token could coexist.+ await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)++ # Update the execution with share info — the underlying update_many+ # also enforces (id, user_id) at the DB layer, so a TOCTOU delete+ # between the pre-check above and this write surfaces as 404 rather+ # than a silent no-op.+ try:+ await execution_db.update_graph_execution_share_status(+ execution_id=graph_exec_id,+ user_id=user_id,+ is_shared=True,+ share_token=share_token,+ shared_at=datetime.now(timezone.utc),+ )+ except NotFoundError as exc:+ raise HTTPException(status_code=404, detail=str(exc))++ # Create allowlist of workspace files referenced in outputs+ await execution_db.create_shared_execution_files(+ execution_id=graph_exec_id,+ share_token=share_token,+ user_id=user_id,+ outputs=execution.outputs,+ )++ # Return the share URL+ frontend_url = settings.config.frontend_base_url or "http://localhost:3000"+ share_url = f"{frontend_url}/share/{share_token}"++ return ShareResponse(share_url=share_url, share_token=share_token)+++ "/graphs/{graph_id}/executions/{graph_exec_id}/share",+ status_code=HTTP_204_NO_CONTENT,+ dependencies=[Security(requires_user)],+)+async def disable_execution_sharing(+ graph_id: Annotated[str, Path],+ graph_exec_id: Annotated[str, Path],+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> None:+ """Disable sharing for a graph execution."""+ # Verify the execution belongs to the user+ execution = await execution_db.get_graph_execution(+ user_id=user_id, execution_id=graph_exec_id+ )+ if not execution:+ raise HTTPException(status_code=404, detail="Execution not found")++ # Remove shared file allowlist records+ await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)++ # Remove share info — owner-gated at the DB layer; TOCTOU delete+ # after the pre-check surfaces as 404.+ try:+ await execution_db.update_graph_execution_share_status(+ execution_id=graph_exec_id,+ user_id=user_id,+ is_shared=False,+ share_token=None,+ shared_at=None,+ )+ except NotFoundError as exc:+ raise HTTPException(status_code=404, detail=str(exc))++[email protected]("/public/shared/{share_token}")+async def get_shared_execution(+ share_token: Annotated[+ str,+ Path(pattern=SHARE_TOKEN_PATTERN),+ ],+) -> execution_db.SharedExecutionResponse:+ """Get a shared graph execution by share token (no auth required)."""+ execution = await execution_db.get_graph_execution_by_share_token(share_token)+ if not execution:+ raise HTTPException(status_code=404, detail="Shared execution not found")++ return execution+++ "/public/shared/{share_token}/files/{file_id}/download",+ summary="Download a file from a shared execution",+ operation_id="download_shared_file",+ tags=["graphs"],+)+async def download_shared_file(+ share_token: Annotated[+ str,+ Path(pattern=SHARE_TOKEN_PATTERN),+ ],+ file_id: Annotated[+ str,+ Path(pattern=SHARE_TOKEN_PATTERN),+ ],+) -> Response:+ """Download a workspace file from a shared execution (no auth required).++ Validates that the file was explicitly exposed when sharing was enabled.+ Returns a uniform 404 for all failure modes to prevent enumeration attacks.+ """+ # Single-query validation against the allowlist+ execution_id = await execution_db.get_shared_execution_file(+ share_token=share_token, file_id=file_id+ )+ if not execution_id:+ raise HTTPException(status_code=404, detail="Not found")++ # Look up the actual file (no workspace scoping needed — the allowlist+ # already validated that this file belongs to the shared execution)+ file = await get_workspace_file_by_id(file_id)+ if not file:+ raise HTTPException(status_code=404, detail="Not found")++ return await create_file_download_response(file)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.pynew file mode 100644index 0000000000..95fedc4995--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graph_executions/routes_test.py@@ -0,0 +1,518 @@+"""Tests for the execution routes."""++from datetime import datetime, timezone+from unittest.mock import AsyncMock, Mock++import fastapi+import fastapi.testclient+import pytest+import pytest_mock+from fastapi.routing import APIRoute++from backend.api.features.graph_executions.routes import router+from backend.api.rest_api import app as real_app+from backend.data import execution as execution_db+from backend.util.exceptions import NotFoundError+from backend.util.models import Pagination++app = fastapi.FastAPI()+app.include_router(router)+client = fastapi.testclient.TestClient(app)++[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"]++ # The real get_request_context queries Prisma to resolve the personal org,+ # which closes the test event loop between sync TestClient calls.+ async def _fake_request_context() -> RequestContext:+ return RequestContext(+ user_id=test_user_id,+ org_id="test-org",+ team_id=None,+ 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",+ )++ app.dependency_overrides[get_request_context] = _fake_request_context+ yield+ app.dependency_overrides.clear()+++# The ten operations this module owns, with the tag list and auth posture each+# publishes. Two are deliberately unauthenticated and three carry no tag of+# their own, so neither can be hoisted to the router.+EXPECTED_OPERATIONS = {+ ("get", "/api/executions"): (["v1", "graphs"], True),+ ("get", "/api/executions/cost-summary"): (["v1", "graphs"], True),+ ("delete", "/api/executions/{graph_exec_id}"): (["v1", "graphs"], True),+ ("get", "/api/graphs/{graph_id}/executions"): (["v1", "graphs"], True),+ ("get", "/api/graphs/{graph_id}/executions/{graph_exec_id}"): (+ ["v1", "graphs"],+ True,+ ),+ ("post", "/api/graphs/{graph_id}/executions/{graph_exec_id}/stop"): (+ ["v1", "graphs"],+ True,+ ),+ ("post", "/api/graphs/{graph_id}/executions/{graph_exec_id}/share"): (["v1"], True),+ ("delete", "/api/graphs/{graph_id}/executions/{graph_exec_id}/share"): (+ ["v1"],+ True,+ ),+ ("get", "/api/public/shared/{share_token}"): (["v1"], False),+ ("get", "/api/public/shared/{share_token}/files/{file_id}/download"): (+ ["v1", "graphs"],+ False,+ ),+}+++ "method,path,tags,authenticated",+ [(m, p, t, a) for (m, p), (t, a) in EXPECTED_OPERATIONS.items()],+)+def test_execution_operation_is_published(+ method: str, path: str, tags: list[str], authenticated: bool+):+ operation = real_app.openapi()["paths"][path][method]+ assert operation["tags"] == tags+ assert ("security" in operation) is authenticated+++def test_execution_surface_has_no_other_operations():+ """Keyed on the owning module, not a path prefix: /api/executions/admin/* and+ /api/public/shared/chats/* belong to other modules and share these prefixes."""+ served = {+ (method.lower(), route.path)+ for route in real_app.routes+ if isinstance(route, APIRoute)+ and route.endpoint.__module__ == "backend.api.features.graph_executions.routes"+ for method in route.methods+ if method != "HEAD"+ }+ assert served == set(EXPECTED_OPERATIONS)++[email protected]("path", sorted({p for _, p in EXPECTED_OPERATIONS}))+def test_execution_path_is_served_by_this_module(path: str):+ handlers = {+ route.endpoint.__module__+ for route in real_app.routes+ if isinstance(route, APIRoute) and route.path == path+ }+ 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.+ "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}/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_executions_cost_summary_returns_payload(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The /executions/cost-summary route returns the aggregated payload."""+ from prisma.enums import AgentExecutionStatus++ from backend.data.execution_cost_summary import (+ UserAgentCostRollup,+ UserDailyCost,+ UserExecutionCostSummary,+ UserTopRun,+ )++ summary = UserExecutionCostSummary(+ total_cents=4200,+ run_count=12,+ billable_run_count=10,+ failed_cost_cents=500,+ by_agent=[+ UserAgentCostRollup(graph_id="g-1", cost_cents=3000, run_count=8),+ UserAgentCostRollup(graph_id="g-2", cost_cents=1200, run_count=4),+ ],+ top_runs=[+ UserTopRun(+ execution_id="exec-1",+ graph_id="g-1",+ cost_cents=2500,+ started_at=datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc),+ status=AgentExecutionStatus.COMPLETED,+ duration_seconds=45.5,+ node_error_count=0,+ ),+ ],+ daily=[+ UserDailyCost(date="2026-05-10", cost_cents=3000, run_count=8),+ UserDailyCost(date="2026-05-11", cost_cents=1200, run_count=4),+ ],+ )++ mock_fn = mocker.patch(+ "backend.api.features.graph_executions.routes.get_user_cost_summary",+ AsyncMock(return_value=summary),+ )++ response = client.get("/executions/cost-summary")++ assert response.status_code == 200+ payload = response.json()+ assert payload["total_cents"] == 4200+ assert payload["run_count"] == 12+ assert payload["billable_run_count"] == 10+ assert payload["failed_cost_cents"] == 500+ assert len(payload["by_agent"]) == 2+ assert payload["by_agent"][0]["graph_id"] == "g-1"+ assert payload["by_agent"][0]["cost_cents"] == 3000+ assert len(payload["top_runs"]) == 1+ assert payload["top_runs"][0]["execution_id"] == "exec-1"+ assert payload["top_runs"][0]["cost_cents"] == 2500+ assert payload["top_runs"][0]["status"] == "COMPLETED"+ assert payload["top_runs"][0]["started_at"] == "2026-05-10T12:00:00Z"+ assert payload["top_runs"][0]["duration_seconds"] == 45.5+ assert len(payload["daily"]) == 2+ assert payload["daily"][0]["date"] == "2026-05-10"+ mock_fn.assert_awaited_once()+++def test_executions_cost_summary_forwards_since_until(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ """since/until query params should reach get_user_cost_summary."""+ from backend.data.execution_cost_summary import UserExecutionCostSummary++ mock_fn = mocker.patch(+ "backend.api.features.graph_executions.routes.get_user_cost_summary",+ AsyncMock(+ return_value=UserExecutionCostSummary(+ total_cents=0,+ run_count=0,+ billable_run_count=0,+ failed_cost_cents=0,+ by_agent=[],+ top_runs=[],+ daily=[],+ )+ ),+ )++ response = client.get(+ "/executions/cost-summary"+ "?since=2026-05-01T00:00:00Z"+ "&until=2026-05-15T00:00:00Z"+ "&top_runs_limit=5"+ )++ assert response.status_code == 200+ kwargs = mock_fn.await_args.kwargs+ assert kwargs["user_id"] == test_user_id+ assert kwargs["since"] == datetime(2026, 5, 1, tzinfo=timezone.utc)+ assert kwargs["until"] == datetime(2026, 5, 15, tzinfo=timezone.utc)+ assert kwargs["top_runs_limit"] == 5+++def test_executions_cost_summary_rejects_out_of_range_limit(+ mocker: pytest_mock.MockFixture,+) -> None:+ """top_runs_limit must be within [1, 50]."""+ mock_fn = mocker.patch(+ "backend.api.features.graph_executions.routes.get_user_cost_summary",+ AsyncMock(),+ )++ response = client.get("/executions/cost-summary?top_runs_limit=500")++ assert response.status_code == 422+ mock_fn.assert_not_awaited()+++def test_executions_cost_summary_rejects_inverted_window(+ mocker: pytest_mock.MockFixture,+) -> None:+ """`since > until` is bad client input — surface 422, don't quietly return zeros."""+ mock_fn = mocker.patch(+ "backend.api.features.graph_executions.routes.get_user_cost_summary",+ AsyncMock(),+ )++ response = client.get(+ "/executions/cost-summary"+ "?since=2026-05-15T00:00:00Z"+ "&until=2026-05-01T00:00:00Z"+ )++ assert response.status_code == 422+ mock_fn.assert_not_awaited()+++def _paginated(*executions):+ return execution_db.GraphExecutionsPaginated(+ executions=list(executions),+ pagination=Pagination(+ total_items=len(executions), total_pages=1, current_page=1, page_size=25+ ),+ )+++def test_list_all_executions_applies_the_activity_gate(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The gate is what keeps flag-disabled activity summaries out of the+ response; bypassing it leaks them to every caller."""+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".get_graph_executions_paginated",+ AsyncMock(return_value=_paginated()),+ )+ gate = mocker.patch(+ "backend.api.features.graph_executions.routes.hide_activity_summaries_if_disabled",+ AsyncMock(return_value=[]),+ )++ response = client.get("/executions")++ assert response.status_code == 200+ gate.assert_awaited_once()+++def test_list_all_executions_is_not_scoped_to_a_graph(+ mocker: pytest_mock.MockFixture,+) -> None:+ """This route and the per-graph one share a db call; a graph_id here would+ silently narrow the user-wide list."""+ query = mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".get_graph_executions_paginated",+ AsyncMock(return_value=_paginated()),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.hide_activity_summaries_if_disabled",+ AsyncMock(return_value=[]),+ )++ client.get("/executions")++ assert "graph_id" not in query.await_args.kwargs+++def test_list_graph_executions_forwards_pagination(+ mocker: pytest_mock.MockFixture,+) -> None:+ query = mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".get_graph_executions_paginated",+ AsyncMock(return_value=_paginated()),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.hide_activity_summaries_if_disabled",+ AsyncMock(return_value=[]),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.get_user_onboarding",+ AsyncMock(return_value=Mock(onboardingAgentExecutionId=None)),+ )++ response = client.get("/graphs/graph-1/executions?page=3&page_size=10")++ assert response.status_code == 200+ kwargs = query.await_args.kwargs+ assert (kwargs["graph_id"], kwargs["page"], kwargs["page_size"]) == (+ "graph-1",+ 3,+ 10,+ )+++def test_delete_execution_returns_204(mocker: pytest_mock.MockFixture) -> None:+ deleted = mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db.delete_graph_execution",+ AsyncMock(),+ )++ response = client.delete("/executions/exec-1")++ assert response.status_code == 204+ assert deleted.await_args.kwargs["graph_exec_id"] == "exec-1"+++def test_get_shared_execution_returns_404_for_an_unknown_token(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".get_graph_execution_by_share_token",+ AsyncMock(return_value=None),+ )++ response = client.get("/public/shared/550e8400-e29b-41d4-a716-446655440000")++ assert response.status_code == 404+++def test_get_shared_execution_rejects_a_malformed_token() -> None:+ """The token is the only credential this public route has, so its pattern+ is the access control."""+ response = client.get("/public/shared/not-a-uuid")++ assert response.status_code == 422+++def test_get_graph_execution_rejects_a_graph_id_mismatch(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The execution is fetched by id alone, so the graph_id in the path is+ only checked here — dropping it would let any graph's URL read any of the+ caller's executions."""+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db.get_graph_execution",+ AsyncMock(return_value=Mock(graph_id="other-graph", graph_version=1)),+ )++ response = client.get("/graphs/graph-1/executions/exec-1")++ assert response.status_code == 404+++def test_enable_sharing_clears_stale_allowlist_before_issuing_a_token(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Order matters: leaving old file records in place while a new token is+ written would expose files the previous share allowed."""+ calls: list[str] = []+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db.get_graph_execution",+ AsyncMock(return_value=Mock(outputs={})),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".delete_shared_execution_files",+ AsyncMock(side_effect=lambda **_: calls.append("delete")),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".update_graph_execution_share_status",+ AsyncMock(side_effect=lambda **_: calls.append("update")),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".create_shared_execution_files",+ AsyncMock(side_effect=lambda **_: calls.append("create")),+ )++ response = client.post("/graphs/graph-1/executions/exec-1/share")++ assert response.status_code == 200+ assert calls == ["delete", "update", "create"]+ assert response.json()["share_url"].endswith(response.json()["share_token"])+++def test_enable_sharing_maps_a_lost_execution_to_404(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The write enforces (id, user_id) at the DB layer, so a delete racing the+ pre-check must surface as 404 rather than a silent no-op."""+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db.get_graph_execution",+ AsyncMock(return_value=Mock(outputs={})),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".delete_shared_execution_files",+ AsyncMock(),+ )+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".update_graph_execution_share_status",+ AsyncMock(side_effect=NotFoundError("gone")),+ )++ response = client.post("/graphs/graph-1/executions/exec-1/share")++ assert response.status_code == 404+++def test_enable_sharing_requires_an_execution(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db.get_graph_execution",+ AsyncMock(return_value=None),+ )++ response = client.post("/graphs/graph-1/executions/exec-1/share")++ assert response.status_code == 404+++def test_disable_sharing_revokes_the_token_and_the_file_allowlist(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Revoking the token without clearing the allowlist would leave the files+ reachable to anyone who kept the old link."""+ mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db.get_graph_execution",+ AsyncMock(return_value=Mock()),+ )+ delete_files = mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".delete_shared_execution_files",+ AsyncMock(),+ )+ update = mocker.patch(+ "backend.api.features.graph_executions.routes.execution_db"+ ".update_graph_execution_share_status",+ AsyncMock(),+ )++ response = client.delete("/graphs/graph-1/executions/exec-1/share")++ assert response.status_code == 204+ delete_files.assert_awaited_once()+ assert update.await_args.kwargs["is_shared"] is Falsediff --git a/autogpt_platform/backend/backend/api/features/v1_share_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/share_test.pysimilarity index 82%rename from autogpt_platform/backend/backend/api/features/v1_share_test.pyrename to autogpt_platform/backend/backend/api/features/graph_executions/share_test.pyindex e9c1d7fd1b..27637cf3e0 100644--- a/autogpt_platform/backend/backend/api/features/v1_share_test.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/share_test.py@@ -8,11 +8,11 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom starlette.responses import Response-from backend.api.features.v1 import v1_router+from backend.api.features.graph_executions.routes import routerfrom backend.data.workspace import WorkspaceFileapp = FastAPI()-app.include_router(v1_router, prefix="/api")+app.include_router(router, prefix="/api")VALID_TOKEN = "550e8400-e29b-41d4-a716-446655440000"VALID_FILE_ID = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"@@ -68,17 +68,17 @@ class TestDownloadSharedFile:def test_valid_token_and_file_returns_attachment(self):with (patch(- "backend.api.features.v1.execution_db.get_shared_execution_file",+ "backend.api.features.graph_executions.routes.execution_db.get_shared_execution_file",new_callable=AsyncMock,return_value="exec-123",),patch(- "backend.api.features.v1.get_workspace_file_by_id",+ "backend.api.features.graph_executions.routes.get_workspace_file_by_id",new_callable=AsyncMock,return_value=_make_workspace_file(),),patch(- "backend.api.features.v1.create_file_download_response",+ "backend.api.features.graph_executions.routes.create_file_download_response",side_effect=_mock_download_response(),),):@@ -98,7 +98,7 @@ class TestDownloadSharedFile:def test_token_not_in_allowlist_returns_404(self):with patch(- "backend.api.features.v1.execution_db.get_shared_execution_file",+ "backend.api.features.graph_executions.routes.execution_db.get_shared_execution_file",new_callable=AsyncMock,return_value=None,):@@ -110,12 +110,12 @@ class TestDownloadSharedFile:def test_file_missing_from_workspace_returns_404(self):with (patch(- "backend.api.features.v1.execution_db.get_shared_execution_file",+ "backend.api.features.graph_executions.routes.execution_db.get_shared_execution_file",new_callable=AsyncMock,return_value="exec-123",),patch(- "backend.api.features.v1.get_workspace_file_by_id",+ "backend.api.features.graph_executions.routes.get_workspace_file_by_id",new_callable=AsyncMock,return_value=None,),@@ -128,7 +128,7 @@ class TestDownloadSharedFile:def test_uniform_404_prevents_enumeration(self):"""Both failure modes produce identical 404 — no information leak."""with patch(- "backend.api.features.v1.execution_db.get_shared_execution_file",+ "backend.api.features.graph_executions.routes.execution_db.get_shared_execution_file",new_callable=AsyncMock,return_value=None,):@@ -138,12 +138,12 @@ class TestDownloadSharedFile:with (patch(- "backend.api.features.v1.execution_db.get_shared_execution_file",+ "backend.api.features.graph_executions.routes.execution_db.get_shared_execution_file",new_callable=AsyncMock,return_value="exec-123",),patch(- "backend.api.features.v1.get_workspace_file_by_id",+ "backend.api.features.graph_executions.routes.get_workspace_file_by_id",new_callable=AsyncMock,return_value=None,),diff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.pyindex 02552eb106..aa4443201c 100644--- a/autogpt_platform/backend/backend/api/features/home/attention.py+++ b/autogpt_platform/backend/backend/api/features/home/attention.py@@ -2,9 +2,9 @@ import jsonfrom datetime import datetime, timedelta, timezonefrom urllib.parse import quote-from backend.api.features.executions.review.model import PendingHumanReviewModelfrom backend.api.features.experts.models import Expertfrom backend.api.features.experts.spend_approval import is_spend_review+from backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.copilot.briefing.outcome import as_utc, run_linkfrom backend.copilot.constants import AUTOPILOT_NAMEfrom backend.copilot.model import ChatSessionInfo, PendingQuestiondiff --git a/autogpt_platform/backend/backend/api/features/home/attention_test.py b/autogpt_platform/backend/backend/api/features/home/attention_test.pyindex b92dd288d8..84ec8f314a 100644--- a/autogpt_platform/backend/backend/api/features/home/attention_test.py+++ b/autogpt_platform/backend/backend/api/features/home/attention_test.py@@ -2,8 +2,8 @@ from datetime import datetime, timedelta, timezonefrom prisma.enums import ReviewStatus-from backend.api.features.executions.review.model import PendingHumanReviewModelfrom backend.api.features.experts.models import Expert, ExpertWorkflowRef+from backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.copilot.model import ChatSessionInfo, ChatSessionMetadata, PendingQuestionfrom backend.executor.scheduler import GraphExecutionJobInfodiff --git a/autogpt_platform/backend/backend/api/features/home/compose.py b/autogpt_platform/backend/backend/api/features/home/compose.pyindex 556b95318e..47dac853e9 100644--- a/autogpt_platform/backend/backend/api/features/home/compose.py+++ b/autogpt_platform/backend/backend/api/features/home/compose.py@@ -1,7 +1,7 @@from datetime import datetime-from backend.api.features.executions.review.model import PendingHumanReviewModelfrom backend.api.features.experts.models import Expert+from backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.api.features.library.model import LibraryAgentReffrom backend.copilot.briefing.models import BriefingContentfrom backend.copilot.model import ChatSessionInfodiff --git a/autogpt_platform/backend/backend/api/features/home/models.py b/autogpt_platform/backend/backend/api/features/home/models.pyindex 944fc31dc5..927c734ff0 100644--- a/autogpt_platform/backend/backend/api/features/home/models.py+++ b/autogpt_platform/backend/backend/api/features/home/models.py@@ -3,7 +3,7 @@ from typing import Literalfrom pydantic import BaseModel, ConfigDict, Field-from backend.api.features.executions.review.model import PendingHumanReviewModel+from backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.copilot.constants import AUTOPILOT_NAME, AUTOPILOT_ROLEdiff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.pyindex b30737f7c9..259d5336b9 100644--- a/autogpt_platform/backend/backend/api/features/home/service.py+++ b/autogpt_platform/backend/backend/api/features/home/service.py@@ -6,12 +6,12 @@ from zoneinfo import ZoneInfofrom pydantic import BaseModel, ValidationError-from backend.api.features.executions.activity_gate import (- hide_activity_summaries_if_disabled,-)-from backend.api.features.executions.review.model import PendingHumanReviewModelfrom backend.api.features.experts import experts_dbfrom backend.api.features.experts.models import Expert+from backend.api.features.graph_executions.activity_gate import (+ hide_activity_summaries_if_disabled,+)+from backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.api.features.library import db as library_dbfrom backend.copilot import db as chat_dbfrom backend.copilot.briefing.models import BriefingContentdiff --git a/autogpt_platform/backend/backend/api/features/home/service_test.py b/autogpt_platform/backend/backend/api/features/home/service_test.pyindex 765693c5a9..2ae15ad669 100644--- a/autogpt_platform/backend/backend/api/features/home/service_test.py+++ b/autogpt_platform/backend/backend/api/features/home/service_test.py@@ -144,7 +144,7 @@ async def test_briefing_anchors_on_todays_persisted_row(mocker: MockerFixture, home_dependencies) -> None:mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)mocker.patch(@@ -174,7 +174,7 @@ async def test_briefing_rejects_a_row_with_negative_totals(otherwise taken as canonical — a negative total is a corrupt row, so ithas to fail validation and drop home onto the live path."""mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)corrupt = _stored_briefing().model_dump(mode="json") | {"completed_total": -3}@@ -194,7 +194,7 @@ async def test_briefing_anchors_on_a_row_the_job_could_not_deliver(failed. The job redelivers that same stored content, so it is still thecanonical story — going live here would drift from the pending message."""mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)mocker.patch(@@ -223,7 +223,7 @@ async def test_briefing_falls_back_to_live_when_the_stored_row_is_malformed(mocker: MockerFixture, home_dependencies) -> None:mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)_patch_stored_briefing(mocker, {"unexpected": "shape"})@@ -241,7 +241,7 @@ async def test_briefing_falls_back_to_live_when_the_lookup_raises("""A briefing the page cannot read is not worth a 500 — /home is thelanding page, and every other tile on it is still fine."""mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)mocker.patch(@@ -261,7 +261,7 @@ async def test_briefing_is_live_when_no_row_exists_yet() -> None:"""A user who signed up after 9am has no briefing to anchor on."""mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)@@ -291,7 +291,7 @@ async def test_briefing_date_comes_from_the_requests_own_clock("backend.api.features.home.service.briefing_db.get_briefing_for_date", lookup)mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)@@ -308,7 +308,7 @@ async def test_persisted_summaries_are_scrubbed_when_the_activity_flag_is_off("""Summaries are stored regardless of the flag, so the persisted path hasto scrub them too — otherwise the card leaks what the gate hides."""mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=False),)mocker.patch(@@ -333,7 +333,7 @@ async def test_activity_summary_surfaces_when_flag_enabled(mocker: MockerFixture, home_dependencies) -> None:mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)@@ -347,7 +347,7 @@ async def test_activity_summary_hidden_when_flag_disabled(mocker: MockerFixture, home_dependencies) -> None:mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=False),)@@ -361,7 +361,7 @@ async def test_schedules_stay_owner_scoped_inside_an_organization(mocker: MockerFixture, home_dependencies) -> None:mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)scheduler = MagicMock()@@ -389,7 +389,7 @@ async def test_scheduler_and_credit_failures_degrade_instead_of_failing_the_pagemocker: MockerFixture, home_dependencies) -> None:mocker.patch(- "backend.api.features.executions.activity_gate.is_feature_enabled",+ "backend.api.features.graph_executions.activity_gate.is_feature_enabled",AsyncMock(return_value=True),)scheduler = MagicMock()diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex af717d2485..e510840ae2 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -25,7 +25,6 @@ from fastapi import (File,Header,HTTPException,- Path,Query,Request,Response,@@ -35,21 +34,12 @@ from fastapi import (from fastapi.concurrency import run_in_threadpoolfrom prisma.enums import BriefingFrequency, SubscriptionTierfrom pydantic import BaseModel, Field-from starlette.status import (- HTTP_204_NO_CONTENT,- HTTP_402_PAYMENT_REQUIRED,- HTTP_404_NOT_FOUND,-)+from starlette.status import HTTP_402_PAYMENT_REQUIREDfrom typing_extensions import Optional, TypedDictfrom backend.api.features.credits_rate_limit import (enforce_subscription_status_rate_limit,)-from backend.api.features.executions.activity_gate import (- hide_activity_summaries_if_disabled,- hide_activity_summary_if_disabled,-)-from backend.api.features.workspace.routes import create_file_download_responsefrom backend.api.model import (CreateGraph,GraphExecutionSource,@@ -91,10 +81,6 @@ from backend.data.credit import (sync_tier_from_checkout_session,)from backend.data.execution import ExecutionContext-from backend.data.execution_cost_summary import (- UserExecutionCostSummary,- get_user_cost_summary,-)from backend.data.graph import GraphSettingsfrom backend.data.model import CredentialsMetaInput, UserOnboardingfrom backend.data.notifications import (@@ -115,7 +101,6 @@ from backend.data.onboarding import (update_user_onboarding,)from backend.data.redis_client import get_redis_async-from backend.data.sharing.tokens import SHARE_TOKEN_PATTERN, generate_share_tokenfrom backend.data.stripe_client import stripe_callfrom backend.data.subscription_trial_billing import (TRIAL_BILLING_EVENTS,@@ -136,7 +121,6 @@ from backend.data.user import (update_user_timezone,verify_preference_token,)-from backend.data.workspace import get_workspace_file_by_idfrom backend.executor import utils as execution_utilsfrom backend.integrations.webhooks.graph_lifecycle_hooks import (before_graph_activate,@@ -151,11 +135,7 @@ from 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,- NotFoundError,-)+from backend.util.exceptions import GraphValidationError, InsufficientBalanceErrorfrom backend.util.feature_flag import Flag, evaluate_feature_flagfrom backend.util.json import dumpsfrom backend.util.settings import Settings@@ -2190,366 +2170,3 @@ async def execute_graph(except Exception:record_graph_operation(operation="execute", status="error")raise---@v1_router.post(- path="/graphs/{graph_id}/executions/{graph_exec_id}/stop",- summary="Stop graph execution",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def stop_graph_run(- graph_id: str, graph_exec_id: str, user_id: Annotated[str, Security(get_user_id)]-) -> execution_db.GraphExecutionMeta | None:- res = await _stop_graph_run(- user_id=user_id,- graph_id=graph_id,- graph_exec_id=graph_exec_id,- )- if not res:- return None- return res[0]---async def _stop_graph_run(- user_id: str,- graph_id: Optional[str] = None,- graph_exec_id: Optional[str] = None,-) -> list[execution_db.GraphExecutionMeta]:- graph_execs = await execution_db.get_graph_executions(- user_id=user_id,- graph_id=graph_id,- graph_exec_id=graph_exec_id,- statuses=[- execution_db.ExecutionStatus.INCOMPLETE,- execution_db.ExecutionStatus.QUEUED,- execution_db.ExecutionStatus.RUNNING,- ],- )- stopped_execs = [- execution_utils.stop_graph_execution(graph_exec_id=exec.id, user_id=user_id)- for exec in graph_execs- ]- await asyncio.gather(*stopped_execs)- return graph_execs---@v1_router.get(- path="/executions",- summary="List all executions",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def list_graphs_executions(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> list[execution_db.GraphExecutionMeta]:- paginated_result = await execution_db.get_graph_executions_paginated(- user_id=user_id,- page=1,- page_size=250,- organization_id=ctx.org_id,- )-- # Apply feature flags to filter out disabled features- filtered_executions = await hide_activity_summaries_if_disabled(- paginated_result.executions, user_id- )- return filtered_executions---@v1_router.get(- path="/executions/cost-summary",- summary="User cost summary",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def get_executions_cost_summary(- user_id: Annotated[str, Security(get_user_id)],- since: datetime | None = Query(- None,- description="Window start (UTC). Defaults to start of current calendar month.",- ),- until: datetime | None = Query(- None,- description="Window end (UTC). Defaults to now.",- ),- top_runs_limit: int = Query(- 10,- ge=1,- le=50,- description="Maximum number of top-cost runs to return.",- ),-) -> UserExecutionCostSummary:- """Aggregated cost breakdown for the calling user's graph executions."""- if since is not None and until is not None and since > until:- raise HTTPException(- status_code=422,- detail="`since` must be earlier than or equal to `until`.",- )- return await get_user_cost_summary(- user_id=user_id,- since=since,- until=until,- top_runs_limit=top_runs_limit,- )---@v1_router.get(- path="/graphs/{graph_id}/executions",- summary="List graph executions",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def list_graph_executions(- graph_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- page: int = Query(1, ge=1, description="Page number (1-indexed)"),- page_size: int = Query(- 25, ge=1, le=100, description="Number of executions per page"- ),-) -> execution_db.GraphExecutionsPaginated:- paginated_result = await execution_db.get_graph_executions_paginated(- graph_id=graph_id,- user_id=user_id,- page=page,- page_size=page_size,- organization_id=ctx.org_id,- )-- # Apply feature flags to filter out disabled features- filtered_executions = await hide_activity_summaries_if_disabled(- paginated_result.executions, user_id- )- onboarding = await get_user_onboarding(user_id)- if (- onboarding.onboardingAgentExecutionId- and onboarding.onboardingAgentExecutionId- in [exec.id for exec in filtered_executions]- and OnboardingStep.GET_RESULTS not in onboarding.completedSteps- ):- await complete_onboarding_step(user_id, OnboardingStep.GET_RESULTS)-- return execution_db.GraphExecutionsPaginated(- executions=filtered_executions, pagination=paginated_result.pagination- )---@v1_router.get(- path="/graphs/{graph_id}/executions/{graph_exec_id}",- summary="Get execution details",- tags=["graphs"],- dependencies=[Security(requires_user)],-)-async def get_graph_execution(- graph_id: str,- graph_exec_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> execution_db.GraphExecution | execution_db.GraphExecutionWithNodes:- result = await execution_db.get_graph_execution(- user_id=user_id,- execution_id=graph_exec_id,- include_node_executions=True,- organization_id=ctx.org_id,- )- if not result or result.graph_id != graph_id:- raise HTTPException(- status_code=404, detail=f"Graph execution #{graph_exec_id} not found."- )-- if not await graph_db.get_graph(- graph_id=result.graph_id,- version=result.graph_version,- user_id=user_id,- organization_id=ctx.org_id,- ):- raise HTTPException(- status_code=HTTP_404_NOT_FOUND, detail=f"Graph #{graph_id} not found"- )-- # Apply feature flags to filter out disabled features- result = await hide_activity_summary_if_disabled(result, user_id)- onboarding = await get_user_onboarding(user_id)- if (- onboarding.onboardingAgentExecutionId == graph_exec_id- and OnboardingStep.GET_RESULTS not in onboarding.completedSteps- ):- await complete_onboarding_step(user_id, OnboardingStep.GET_RESULTS)-- return result---@v1_router.delete(- path="/executions/{graph_exec_id}",- summary="Delete graph execution",- tags=["graphs"],- dependencies=[Security(requires_user)],- status_code=HTTP_204_NO_CONTENT,-)-async def delete_graph_execution(- graph_exec_id: str,- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> None:- await execution_db.delete_graph_execution(- graph_exec_id=graph_exec_id, user_id=user_id- )---class ShareRequest(pydantic.BaseModel):- """Optional request body for share endpoint."""-- pass # Empty body is fine---class ShareResponse(pydantic.BaseModel):- """Response from share endpoints."""-- share_url: str- share_token: str---@v1_router.post(- "/graphs/{graph_id}/executions/{graph_exec_id}/share",- dependencies=[Security(requires_user)],-)-async def enable_execution_sharing(- graph_id: Annotated[str, Path],- graph_exec_id: Annotated[str, Path],- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- _body: ShareRequest = Body(default=ShareRequest()),-) -> ShareResponse:- """Enable sharing for a graph execution."""- # Verify the execution belongs to the user- execution = await execution_db.get_graph_execution(- user_id=user_id, execution_id=graph_exec_id- )- if not execution:- raise HTTPException(status_code=404, detail="Execution not found")-- # Generate a unique share token- share_token = generate_share_token()-- # Remove stale allowlist records before updating the token — prevents a- # window where old records + new token could coexist.- await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)-- # Update the execution with share info — the underlying update_many- # also enforces (id, user_id) at the DB layer, so a TOCTOU delete- # between the pre-check above and this write surfaces as 404 rather- # than a silent no-op.- try:- await execution_db.update_graph_execution_share_status(- execution_id=graph_exec_id,- user_id=user_id,- is_shared=True,- share_token=share_token,- shared_at=datetime.now(timezone.utc),- )- except NotFoundError as exc:- raise HTTPException(status_code=404, detail=str(exc))-- # Create allowlist of workspace files referenced in outputs- await execution_db.create_shared_execution_files(- execution_id=graph_exec_id,- share_token=share_token,- user_id=user_id,- outputs=execution.outputs,- )-- # Return the share URL- frontend_url = settings.config.frontend_base_url or "http://localhost:3000"- share_url = f"{frontend_url}/share/{share_token}"-- return ShareResponse(share_url=share_url, share_token=share_token)---@v1_router.delete(- "/graphs/{graph_id}/executions/{graph_exec_id}/share",- status_code=HTTP_204_NO_CONTENT,- dependencies=[Security(requires_user)],-)-async def disable_execution_sharing(- graph_id: Annotated[str, Path],- graph_exec_id: Annotated[str, Path],- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> None:- """Disable sharing for a graph execution."""- # Verify the execution belongs to the user- execution = await execution_db.get_graph_execution(- user_id=user_id, execution_id=graph_exec_id- )- if not execution:- raise HTTPException(status_code=404, detail="Execution not found")-- # Remove shared file allowlist records- await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)-- # Remove share info — owner-gated at the DB layer; TOCTOU delete- # after the pre-check surfaces as 404.- try:- await execution_db.update_graph_execution_share_status(- execution_id=graph_exec_id,- user_id=user_id,- is_shared=False,- share_token=None,- shared_at=None,- )- except NotFoundError as exc:- raise HTTPException(status_code=404, detail=str(exc))---@v1_router.get("/public/shared/{share_token}")-async def get_shared_execution(- share_token: Annotated[- str,- Path(pattern=SHARE_TOKEN_PATTERN),- ],-) -> execution_db.SharedExecutionResponse:- """Get a shared graph execution by share token (no auth required)."""- execution = await execution_db.get_graph_execution_by_share_token(share_token)- if not execution:- raise HTTPException(status_code=404, detail="Shared execution not found")-- return execution---@v1_router.get(- "/public/shared/{share_token}/files/{file_id}/download",- summary="Download a file from a shared execution",- operation_id="download_shared_file",- tags=["graphs"],-)-async def download_shared_file(- share_token: Annotated[- str,- Path(pattern=SHARE_TOKEN_PATTERN),- ],- file_id: Annotated[- str,- Path(pattern=SHARE_TOKEN_PATTERN),- ],-) -> Response:- """Download a workspace file from a shared execution (no auth required).-- Validates that the file was explicitly exposed when sharing was enabled.- Returns a uniform 404 for all failure modes to prevent enumeration attacks.- """- # Single-query validation against the allowlist- execution_id = await execution_db.get_shared_execution_file(- share_token=share_token, file_id=file_id- )- if not execution_id:- raise HTTPException(status_code=404, detail="Not found")-- # Look up the actual file (no workspace scoping needed — the allowlist- # already validated that this file belongs to the shared execution)- file = await get_workspace_file_by_id(file_id)- if not file:- raise HTTPException(status_code=404, detail="Not found")-- return await create_file_download_response(file)diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex 19bc62bd9e..72428597ae 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -708,141 +708,6 @@ def test_list_invoices_default_limit(mocker: pytest_mock.MockFixture) -> None:assert mock_credit_model.list_invoices.await_args.kwargs == {"limit": 24}-# Executions cost summary tests-def test_executions_cost_summary_returns_payload(- mocker: pytest_mock.MockFixture,-) -> None:- """The /executions/cost-summary route returns the aggregated payload."""- from prisma.enums import AgentExecutionStatus-- from backend.data.execution_cost_summary import (- UserAgentCostRollup,- UserDailyCost,- UserExecutionCostSummary,- UserTopRun,- )-- summary = UserExecutionCostSummary(- total_cents=4200,- run_count=12,- billable_run_count=10,- failed_cost_cents=500,- by_agent=[- UserAgentCostRollup(graph_id="g-1", cost_cents=3000, run_count=8),- UserAgentCostRollup(graph_id="g-2", cost_cents=1200, run_count=4),- ],- top_runs=[- UserTopRun(- execution_id="exec-1",- graph_id="g-1",- cost_cents=2500,- started_at=datetime(2026, 5, 10, 12, 0, tzinfo=timezone.utc),- status=AgentExecutionStatus.COMPLETED,- duration_seconds=45.5,- node_error_count=0,- ),- ],- daily=[- UserDailyCost(date="2026-05-10", cost_cents=3000, run_count=8),- UserDailyCost(date="2026-05-11", cost_cents=1200, run_count=4),- ],- )-- mock_fn = mocker.patch(- "backend.api.features.v1.get_user_cost_summary",- AsyncMock(return_value=summary),- )-- response = client.get("/executions/cost-summary")-- assert response.status_code == 200- payload = response.json()- assert payload["total_cents"] == 4200- assert payload["run_count"] == 12- assert payload["billable_run_count"] == 10- assert payload["failed_cost_cents"] == 500- assert len(payload["by_agent"]) == 2- assert payload["by_agent"][0]["graph_id"] == "g-1"- assert payload["by_agent"][0]["cost_cents"] == 3000- assert len(payload["top_runs"]) == 1- assert payload["top_runs"][0]["execution_id"] == "exec-1"- assert payload["top_runs"][0]["cost_cents"] == 2500- assert len(payload["daily"]) == 2- assert payload["daily"][0]["date"] == "2026-05-10"- mock_fn.assert_awaited_once()---def test_executions_cost_summary_forwards_since_until(- mocker: pytest_mock.MockFixture,- test_user_id: str,-) -> None:- """since/until query params should reach get_user_cost_summary."""- from backend.data.execution_cost_summary import UserExecutionCostSummary-- mock_fn = mocker.patch(- "backend.api.features.v1.get_user_cost_summary",- AsyncMock(- return_value=UserExecutionCostSummary(- total_cents=0,- run_count=0,- billable_run_count=0,- failed_cost_cents=0,- by_agent=[],- top_runs=[],- daily=[],- )- ),- )-- response = client.get(- "/executions/cost-summary"- "?since=2026-05-01T00:00:00Z"- "&until=2026-05-15T00:00:00Z"- "&top_runs_limit=5"- )-- assert response.status_code == 200- kwargs = mock_fn.await_args.kwargs- assert kwargs["user_id"] == test_user_id- assert kwargs["since"] == datetime(2026, 5, 1, tzinfo=timezone.utc)- assert kwargs["until"] == datetime(2026, 5, 15, tzinfo=timezone.utc)- assert kwargs["top_runs_limit"] == 5---def test_executions_cost_summary_rejects_out_of_range_limit(- mocker: pytest_mock.MockFixture,-) -> None:- """top_runs_limit must be within [1, 50]."""- mock_fn = mocker.patch(- "backend.api.features.v1.get_user_cost_summary",- AsyncMock(),- )-- response = client.get("/executions/cost-summary?top_runs_limit=500")-- assert response.status_code == 422- mock_fn.assert_not_awaited()---def test_executions_cost_summary_rejects_inverted_window(- mocker: pytest_mock.MockFixture,-) -> None:- """`since > until` is bad client input — surface 422, don't quietly return zeros."""- mock_fn = mocker.patch(- "backend.api.features.v1.get_user_cost_summary",- AsyncMock(),- )-- response = client.get(- "/executions/cost-summary"- "?since=2026-05-15T00:00:00Z"- "&until=2026-05-01T00:00:00Z"- )-- assert response.status_code == 422- mock_fn.assert_not_awaited()--# Graphs endpoints testsdef test_get_graphs(mocker: pytest_mock.MockFixture,diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 478fe7c5a6..aded2c6c92 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -36,9 +36,10 @@ import backend.api.features.builder.routesimport backend.api.features.chat.routes as chat_routesimport backend.api.features.chat.share as chat_shareimport backend.api.features.chat.speech as chat_speech-import backend.api.features.executions.review.routesimport backend.api.features.experimentsimport backend.api.features.experts.routes as experts_routes+import backend.api.features.graph_executions.review.routes+import backend.api.features.graph_executions.routes as graph_executions_routesimport backend.api.features.home.routes as home_routesimport backend.api.features.library.dbimport backend.api.features.library.model@@ -403,6 +404,11 @@ app.include_router(tags=["v1", "schedules"],prefix="/api",)+app.include_router(+ graph_executions_routes.router,+ tags=["v1"],+ prefix="/api",+)app.include_router(auth_email_routes.auth_email_router,prefix="/api/auth/email",@@ -494,7 +500,7 @@ if settings.config.app_env == backend.util.settings.AppEnvironment.LOCAL:prefix="/api",)app.include_router(- backend.api.features.executions.review.routes.router,+ backend.api.features.graph_executions.review.routes.router,tags=["v2", "executions", "review"],prefix="/api/review",)diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.pyindex 831b02f713..d403600735 100644--- a/autogpt_platform/backend/backend/copilot/briefing/generate.py+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py@@ -9,8 +9,8 @@ from zoneinfo import ZoneInfofrom pydantic import ValidationError-from backend.api.features.executions.review.model import PendingHumanReviewModelfrom backend.api.features.experts.models import Expert+from backend.api.features.graph_executions.review.model import PendingHumanReviewModelfrom backend.copilot.constants import COPILOT_SESSION_PREFIXfrom backend.data.db_accessors import (execution_db,diff --git a/autogpt_platform/backend/backend/data/human_review.py b/autogpt_platform/backend/backend/data/human_review.pyindex 2a356d8ac2..f15808341a 100644--- a/autogpt_platform/backend/backend/data/human_review.py+++ b/autogpt_platform/backend/backend/data/human_review.py@@ -19,7 +19,7 @@ from prisma.models import (from prisma.types import PendingHumanReviewUpdateInputfrom pydantic import BaseModel-from backend.api.features.executions.review.model import (+from backend.api.features.graph_executions.review.model import (PendingHumanReviewModel,SafeJsonData,)diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 90db4de9d2..4b9941126f 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -7846,7 +7846,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/backend__api__features__v1__ShareResponse"+ "$ref": "#/components/schemas/backend__api__features__graph_executions__model__ShareResponse"}}}@@ -32501,7 +32501,7 @@"required": ["share_url", "share_token"],"title": "ShareResponse"},- "backend__api__features__v1__ShareResponse": {+ "backend__api__features__graph_executions__model__ShareResponse": {"properties": {"share_url": { "type": "string", "title": "Share Url" },"share_token": { "type": "string", "title": "Share Token" }