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): plumb ExecutionContext at direct-block-execute boundary (#13236)
Ryker_Feng4449625801b6
diff --git a/autogpt_platform/backend/backend/api/external/v1/routes.py b/autogpt_platform/backend/backend/api/external/v1/routes.pyindex 2442c8496d..cfbfd60e0a 100644--- a/autogpt_platform/backend/backend/api/external/v1/routes.py+++ b/autogpt_platform/backend/backend/api/external/v1/routes.py@@ -19,6 +19,7 @@ from backend.data import graph as graph_dbfrom backend.data import user as user_dbfrom backend.data.auth.base import APIAuthorizationInfofrom backend.data.block import BlockInput, CompletedBlockOutput+from backend.data.execution import ExecutionContextfrom backend.executor.utils import (add_graph_execution,charge_for_direct_block_execution,@@ -26,6 +27,7 @@ from backend.executor.utils import (from backend.integrations.webhooks.graph_lifecycle_hooks import on_graph_activatefrom backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.settings import Settings+from backend.util.timezone_utils import get_user_timezone_or_utcfrom .integrations import integrations_routerfrom .tools import tools_router@@ -103,6 +105,10 @@ async def execute_graph_block(if obj.disabled:raise HTTPException(status_code=403, detail=f"Block #{block_id} is disabled.")+ user = await user_db.get_user_by_id(auth.user_id)+ if not user:+ raise HTTPException(status_code=404, detail="User not found.")+try:await charge_for_direct_block_execution(user_id=auth.user_id, block=obj, input_data=data, source="external"@@ -112,8 +118,16 @@ async def execute_graph_block(status_code=status.HTTP_402_PAYMENT_REQUIRED, detail=str(e)) from e+ # Direct block execution has no graph; build a minimal ExecutionContext+ # carrying the caller's identity + timezone so blocks that depend on+ # those (e.g. time blocks) get correct data.+ execution_context = ExecutionContext(+ user_id=auth.user_id,+ user_timezone=get_user_timezone_or_utc(user.timezone),+ )+output = defaultdict(list)- async for name, data in obj.execute(data):+ async for name, data in obj.execute(data, execution_context=execution_context):output[name].append(data)return outputdiff --git a/autogpt_platform/backend/backend/api/external/v1/routes_test.py b/autogpt_platform/backend/backend/api/external/v1/routes_test.pyindex 7a443ca0bb..bee06710b0 100644--- a/autogpt_platform/backend/backend/api/external/v1/routes_test.py+++ b/autogpt_platform/backend/backend/api/external/v1/routes_test.py@@ -40,24 +40,42 @@ def _stub_block(block_id: str = "00000000-0000-0000-0000-000000000001",name: str = "TestBlock",disabled: bool = False,+ capture: dict | None = None,):"""Build a minimal block stub for get_block(...) replacement.Async-iterable execute() yields one (name, value) pair so the route's- `async for` loop can iterate without touching real block logic.+ `async for` loop can iterate without touching real block logic. If+ ``capture`` is supplied, the stub stores the kwargs it was called with+ so tests can assert on them (e.g. ``execution_context``)."""block = MagicMock()block.id = block_idblock.name = nameblock.disabled = disabled- async def _execute(_data):+ async def _execute(_data, **kwargs):+ if capture is not None:+ capture.update(kwargs)yield "result", "ok"block.execute = _executereturn block[email protected](autouse=True)+def stub_user_lookup(monkeypatch: pytest.MonkeyPatch, test_user_id: str):+ """The direct-block-execute route fetches the user to build an+ ExecutionContext; stub it so block-route tests don't need a real DB."""+ user = MagicMock()+ user.id = test_user_id+ user.timezone = "UTC"+ monkeypatch.setattr(+ "backend.api.external.v1.routes.user_db.get_user_by_id",+ AsyncMock(return_value=user),+ )++def test_zero_balance_returns_402_on_paid_block(monkeypatch: pytest.MonkeyPatch):"""Zero-credit user calling a paid block must be rejected before execution."""block = _stub_block(name="PaidBlock")@@ -134,6 +152,37 @@ def test_free_block_runs_without_charging(monkeypatch: pytest.MonkeyPatch):spend_mock.assert_not_awaited()+def test_execute_block_forwards_execution_context(+ monkeypatch: pytest.MonkeyPatch, test_user_id: str+):+ """Regression for #12648: blocks that read ``execution_context`` (e.g.+ time blocks) crashed because this route didn't forward one. The route+ must build an ExecutionContext carrying the caller's user_id ++ timezone and pass it through to ``Block.execute``."""+ captured: dict = {}+ block = _stub_block(name="FreeBlock", capture=captured)+ monkeypatch.setattr("backend.blocks.get_block", lambda _: block)+ monkeypatch.setattr(+ "backend.executor.utils.block_usage_cost", lambda *_a, **_k: (0, {})+ )++ user = MagicMock()+ user.id = test_user_id+ user.timezone = "Europe/Amsterdam"+ monkeypatch.setattr(+ "backend.api.external.v1.routes.user_db.get_user_by_id",+ AsyncMock(return_value=user),+ )++ response = client.post(f"/blocks/{block.id}/execute", json={})++ assert response.status_code == 200, f"got {response.status_code}: {response.text}"+ assert "execution_context" in captured+ ctx = captured["execution_context"]+ assert ctx.user_id == test_user_id+ assert ctx.user_timezone == "Europe/Amsterdam"++def test_disabled_block_still_403(monkeypatch: pytest.MonkeyPatch):"""Pre-existing behavior: disabled blocks return 403, not bypassed by new gates."""block = _stub_block(name="DisabledBlock", disabled=True)diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex 898aae167d..4fb4c4689b 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -88,6 +88,7 @@ from backend.data.credit import (sync_subscription_schedule_from_stripe,sync_tier_from_checkout_session,)+from backend.data.execution import ExecutionContextfrom backend.data.execution_cost_summary import (UserExecutionCostSummary,get_user_cost_summary,@@ -503,13 +504,21 @@ async def execute_graph_block(except InsufficientBalanceError as e:raise HTTPException(status_code=HTTP_402_PAYMENT_REQUIRED, detail=str(e)) from e+ # Direct block execution has no graph; build a minimal ExecutionContext+ # carrying the caller's identity + timezone so blocks that depend on+ # those (e.g. time blocks) get correct data.+ execution_context = ExecutionContext(+ user_id=user_id,+ user_timezone=get_user_timezone_or_utc(user.timezone),+ )+start_time = time.time()try:output = defaultdict(list)async for name, data in obj.execute(data,user_id=user_id,- # Note: graph_exec_id and graph_id are not available for direct block execution+ execution_context=execution_context,):output[name].append(data)diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex 51e6434ab0..f803835036 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -200,6 +200,52 @@ def test_execute_graph_block()+def test_execute_graph_block_forwards_execution_context(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ """Regression for #12648: blocks that read execution_context (e.g. time+ blocks) crashed because the direct-block-execute route didn't forward+ one. The route must construct an ExecutionContext carrying the caller's+ user_id + timezone and pass it through to ``Block.execute``."""+ captured_kwargs: dict = {}++ mock_block = Mock()+ mock_block.disabled = False+ mock_block.name = "TestBlock"++ async def mock_execute(*args, **kwargs):+ captured_kwargs.update(kwargs)+ yield "output", {"data": "ok"}++ mock_block.execute = mock_execute++ mocker.patch(+ "backend.api.features.v1.get_block",+ return_value=mock_block,+ )++ mock_user = Mock()+ mock_user.timezone = "America/New_York"+ mocker.patch(+ "backend.api.features.v1.get_user_by_id",+ return_value=mock_user,+ )++ mocker.patch(+ "backend.api.features.v1.execution_utils.block_usage_cost",+ return_value=(0, {}),+ )++ response = client.post("/blocks/test-block/execute", json={"x": "y"})++ assert response.status_code == 200+ assert "execution_context" in captured_kwargs+ ctx = captured_kwargs["execution_context"]+ assert ctx.user_id == test_user_id+ assert ctx.user_timezone == "America/New_York"++def test_execute_graph_block_charges_when_cost_positive(mocker: pytest_mock.MockFixture,) -> None:diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.pyindex 55a0383a7f..780961bd34 100644--- a/autogpt_platform/backend/backend/blocks/_base.py+++ b/autogpt_platform/backend/backend/blocks/_base.py@@ -683,9 +683,17 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):uiType=self.block_type.value,)- async def execute(self, input_data: BlockInput, **kwargs) -> BlockOutput:+ async def execute(+ self,+ input_data: BlockInput,+ *,+ execution_context: "ExecutionContext",+ **kwargs,+ ) -> BlockOutput:try:- async for output_name, output_data in self._execute(input_data, **kwargs):+ async for output_name, output_data in self._execute(+ input_data, execution_context=execution_context, **kwargs+ ):yield output_name, output_dataexcept Exception as ex:if isinstance(ex, BlockError):@@ -767,21 +775,19 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):)return False, reviewed_data- async def _execute(self, input_data: BlockInput, **kwargs) -> BlockOutput:- # Check for review requirement only if running within a graph execution context- # Direct block execution (e.g., from chat) skips the review process- has_graph_context = all(- key in kwargs- for key in (- "node_exec_id",- "graph_exec_id",- "graph_id",- "execution_context",- )- )- if has_graph_context:+ async def _execute(+ self,+ input_data: BlockInput,+ *,+ execution_context: "ExecutionContext",+ **kwargs,+ ) -> BlockOutput:+ # Review is only meaningful inside a graph execution. Direct block+ # execution (e.g. from the /blocks/{id}/execute API) has no graph+ # context and skips the review path.+ if execution_context.graph_exec_id is not None:should_pause, input_data = await self.is_block_exec_need_review(- input_data, **kwargs+ input_data, execution_context=execution_context, **kwargs)if should_pause:return@@ -791,7 +797,7 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):# that would fail JSON schema required checks. We still validate the# non-credential fields so blocks that execute for real during dry-run# (e.g. AgentExecutorBlock) get proper input validation.- is_dry_run = getattr(kwargs.get("execution_context"), "dry_run", False)+ is_dry_run = execution_context.dry_runif is_dry_run:# Credential fields may be absent (LLM-built agents often skip# wiring them) or nullified earlier in the pipeline. Validate@@ -874,6 +880,7 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):# Use the validated input dataasync for output_name, output_data in self.run(self.input_schema(**{k: v for k, v in input_data.items() if v is not None}),+ execution_context=execution_context,**kwargs,):if output_name == "error":diff --git a/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py b/autogpt_platform/backend/backend/blocks/github/test_github_blocks.pyindex 2123afc1d3..b8b97e5693 100644--- a/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py+++ b/autogpt_platform/backend/backend/blocks/github/test_github_blocks.py@@ -82,7 +82,11 @@ async def test_merge_pr_error_path():"credentials": TEST_CREDENTIALS_INPUT,}with pytest.raises(BlockExecutionError, match="PR not mergeable"):- async for _ in block.execute(input_data, credentials=TEST_CREDENTIALS):+ async for _ in block.execute(+ input_data,+ credentials=TEST_CREDENTIALS,+ execution_context=ExecutionContext(),+ ):passdiff --git a/autogpt_platform/backend/backend/blocks/google/sheets_test.py b/autogpt_platform/backend/backend/blocks/google/sheets_test.pyindex 40a28f3cc7..a5a8b36306 100644--- a/autogpt_platform/backend/backend/blocks/google/sheets_test.py+++ b/autogpt_platform/backend/backend/blocks/google/sheets_test.py@@ -11,6 +11,7 @@ credentials must surface a clean, user-facing ``BlockExecutionError``import pytestfrom backend.blocks.google.sheets import GoogleSheetsReadBlock+from backend.data.execution import ExecutionContextfrom backend.util.exceptions import BlockExecutionError@@ -30,7 +31,7 @@ async def test_sheets_read_missing_credentials_yields_clean_error():}with pytest.raises(BlockExecutionError, match="Missing credentials"):- async for _ in block.execute(input_data):+ async for _ in block.execute(input_data, execution_context=ExecutionContext()):pass@@ -44,7 +45,7 @@ async def test_sheets_read_no_spreadsheet_still_hits_credentials_guard():input_data = {"range": "Sheet1!A1:B2"} # no spreadsheet, no credentialswith pytest.raises(BlockExecutionError, match="Missing credentials"):- async for _ in block.execute(input_data):+ async for _ in block.execute(input_data, execution_context=ExecutionContext()):pass@@ -79,7 +80,7 @@ async def test_sheets_read_upstream_chained_value_skips_guard(mocker):}with pytest.raises(Exception) as exc_info:- async for _ in block.execute(input_data):+ async for _ in block.execute(input_data, execution_context=ExecutionContext()):pass# The guard should skip (chained data present) and let us reach run(),@@ -121,7 +122,7 @@ async def test_sheets_read_upstream_chained_with_explicit_none_cred_id_skips_gua}with pytest.raises(Exception) as exc_info:- async for _ in block.execute(input_data):+ async for _ in block.execute(input_data, execution_context=ExecutionContext()):pass# The guard must not raise "Missing credentials" for this shape.diff --git a/autogpt_platform/backend/backend/blocks/test/test_time_blocks.py b/autogpt_platform/backend/backend/blocks/test/test_time_blocks.pynew file mode 100644index 0000000000..ca174e3983--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/test/test_time_blocks.py@@ -0,0 +1,118 @@+from datetime import datetime, timedelta+from zoneinfo import ZoneInfo++import pytest++from backend.blocks.time_blocks import (+ DateStrftimeFormat,+ GetCurrentDateAndTimeBlock,+ GetCurrentDateBlock,+ GetCurrentTimeBlock,+ TimeStrftimeFormat,+)+from backend.data.execution import ExecutionContext+++async def _collect_single_output(output_stream):+ results = [output async for output in output_stream]++ assert len(results) == 1+ return results[0]+++def _assert_time_close_to_now(value: str, timezone: str, max_delta_seconds: int = 60):+ now = datetime.now(tz=ZoneInfo(timezone))+ parsed_time = datetime.strptime(value, "%H:%M:%S").time()+ parsed_datetime = datetime.combine(now.date(), parsed_time, tzinfo=now.tzinfo)+ candidates = (+ parsed_datetime - timedelta(days=1),+ parsed_datetime,+ parsed_datetime + timedelta(days=1),+ )++ assert min(abs(now - candidate) for candidate in candidates) <= timedelta(+ seconds=max_delta_seconds+ )+++# Issue #12648: direct-block-execute paths used to crash GetCurrentDateBlock+# because execution_context wasn't plumbed through. The fix is at the API+# boundary (a real ExecutionContext is constructed there), and Block.execute()+# now requires execution_context explicitly. These tests cover the block's+# behavior across the contexts it can actually receive.+++async def test_get_current_date_falls_back_to_default_timezone_when_user_tz_unset():+ block = GetCurrentDateBlock()+ input_data = block.Input(trigger="Hello", offset="0")++ key, value = await _collect_single_output(+ block.run(input_data=input_data, execution_context=ExecutionContext())+ )++ assert key == "date"+ parsed = datetime.strptime(value, "%Y-%m-%d").date()+ assert abs((datetime.now(tz=ZoneInfo("UTC")).date() - parsed).days) <= 1+++async def test_get_current_date_uses_user_timezone_from_execution_context():+ block = GetCurrentDateBlock()+ input_data = block.Input(+ trigger="Hello",+ offset="0",+ format_type=DateStrftimeFormat(+ discriminator="strftime",+ format="%Y-%m-%d",+ timezone="UTC",+ use_user_timezone=True,+ ),+ )+ execution_context = ExecutionContext(user_timezone="America/New_York")++ before = datetime.now(tz=ZoneInfo("America/New_York")).strftime("%Y-%m-%d")+ key, value = await _collect_single_output(+ block.run(input_data=input_data, execution_context=execution_context)+ )+ after = datetime.now(tz=ZoneInfo("America/New_York")).strftime("%Y-%m-%d")++ assert key == "date"+ # Window allows for midnight rollover between capture points.+ assert value in {before, after}+++async def test_get_current_time_runs_with_minimal_execution_context():+ block = GetCurrentTimeBlock()+ input_data = block.Input(+ trigger="Hello",+ format_type=TimeStrftimeFormat(+ discriminator="strftime",+ format="%H:%M:%S",+ timezone="UTC",+ ),+ )++ key, value = await _collect_single_output(+ block.run(input_data=input_data, execution_context=ExecutionContext())+ )++ assert key == "time"+ _assert_time_close_to_now(value, "UTC")+++async def test_get_current_date_and_time_runs_with_minimal_execution_context():+ block = GetCurrentDateAndTimeBlock()+ input_data = block.Input(trigger="Hello")++ key, value = await _collect_single_output(+ block.run(input_data=input_data, execution_context=ExecutionContext())+ )++ assert key == "date_time"+ parsed = datetime.strptime(value, "%Y-%m-%d %H:%M:%S").replace(+ tzinfo=ZoneInfo("UTC")+ )+ assert abs(datetime.now(tz=ZoneInfo("UTC")) - parsed) <= timedelta(seconds=10)diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.mdindex 6a7d9f7671..b88c5b3d32 100644--- a/docs/integrations/block-integrations/misc.md+++ b/docs/integrations/block-integrations/misc.md@@ -58,7 +58,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run| system_context | Optional additional context prepended to the prompt. Use this to constrain autopilot behavior, provide domain context, or set output format requirements. | str | No || session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No || max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "delete_folder" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_folders" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "store_skill" \| "update_folder" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delete_folder" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_folders" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "store_skill" \| "update_folder" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No || tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No || blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No || blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |