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.
feat(backend,frontend): optional credentials flag for blocks at agent level (#11716)
Nicholas Tindle47a3a5ef4104
diff --git a/autogpt_platform/backend/backend/blocks/smart_decision_maker.py b/autogpt_platform/backend/backend/blocks/smart_decision_maker.pyindex 751f6af37f..d96fa13efd 100644--- a/autogpt_platform/backend/backend/blocks/smart_decision_maker.py+++ b/autogpt_platform/backend/backend/blocks/smart_decision_maker.py@@ -975,10 +975,28 @@ class SmartDecisionMakerBlock(Block):graph_version: int,execution_context: ExecutionContext,execution_processor: "ExecutionProcessor",+ nodes_to_skip: set[str] | None = None,**kwargs,) -> BlockOutput:tool_functions = await self._create_tool_node_signatures(node_id)+ original_tool_count = len(tool_functions)++ # Filter out tools for nodes that should be skipped (e.g., missing optional credentials)+ if nodes_to_skip:+ tool_functions = [+ tf+ for tf in tool_functions+ if tf.get("function", {}).get("_sink_node_id") not in nodes_to_skip+ ]++ # Only raise error if we had tools but they were all filtered out+ if original_tool_count > 0 and not tool_functions:+ raise ValueError(+ "No available tools to execute - all downstream nodes are unavailable "+ "(possibly due to missing optional credentials)"+ )+yield "tool_functions", json.dumps(tool_functions)conversation_history = input_data.conversation_history or []diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.pyindex 020a5a1906..2759dfe179 100644--- a/autogpt_platform/backend/backend/data/execution.py+++ b/autogpt_platform/backend/backend/data/execution.py@@ -383,6 +383,7 @@ class GraphExecutionWithNodes(GraphExecution):self,execution_context: ExecutionContext,compiled_nodes_input_masks: Optional[NodesInputMasks] = None,+ nodes_to_skip: Optional[set[str]] = None,):return GraphExecutionEntry(user_id=self.user_id,@@ -390,6 +391,7 @@ class GraphExecutionWithNodes(GraphExecution):graph_version=self.graph_version or 0,graph_exec_id=self.id,nodes_input_masks=compiled_nodes_input_masks,+ nodes_to_skip=nodes_to_skip or set(),execution_context=execution_context,)@@ -1145,6 +1147,8 @@ class GraphExecutionEntry(BaseModel):graph_id: strgraph_version: intnodes_input_masks: Optional[NodesInputMasks] = None+ nodes_to_skip: set[str] = Field(default_factory=set)+ """Node IDs that should be skipped due to optional credentials not being configured."""execution_context: ExecutionContext = Field(default_factory=ExecutionContext)diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex 0757a86f4a..9a578c2e62 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -94,6 +94,15 @@ class Node(BaseDbModel):input_links: list[Link] = []output_links: list[Link] = []+ @property+ def credentials_optional(self) -> bool:+ """+ Whether credentials are optional for this node.+ When True and credentials are not configured, the node will be skipped+ during execution rather than causing a validation error.+ """+ return self.metadata.get("credentials_optional", False)+@propertydef block(self) -> AnyBlockSchema | "_UnknownBlockBase":"""Get the block for this node. Returns UnknownBlock if block is deleted/missing."""@@ -326,7 +335,35 @@ class Graph(BaseGraph):@computed_field@propertydef credentials_input_schema(self) -> dict[str, Any]:- return self._credentials_input_schema.jsonschema()+ schema = self._credentials_input_schema.jsonschema()++ # Determine which credential fields are required based on credentials_optional metadata+ graph_credentials_inputs = self.aggregate_credentials_inputs()+ required_fields = []++ # Build a map of node_id -> node for quick lookup+ all_nodes = {node.id: node for node in self.nodes}+ for sub_graph in self.sub_graphs:+ for node in sub_graph.nodes:+ all_nodes[node.id] = node++ for field_key, (+ _field_info,+ node_field_pairs,+ ) in graph_credentials_inputs.items():+ # A field is required if ANY node using it has credentials_optional=False+ is_required = False+ for node_id, _field_name in node_field_pairs:+ node = all_nodes.get(node_id)+ if node and not node.credentials_optional:+ is_required = True+ break++ if is_required:+ required_fields.append(field_key)++ schema["required"] = required_fields+ return schema@propertydef _credentials_input_schema(self) -> type[BlockSchema]:diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.pyindex 044d75e0ca..eea7277eb9 100644--- a/autogpt_platform/backend/backend/data/graph_test.py+++ b/autogpt_platform/backend/backend/data/graph_test.py@@ -396,3 +396,58 @@ async def test_access_store_listing_graph(server: SpinTestServer):created_graph.id, created_graph.version, "3e53486c-cf57-477e-ba2a-cb02dc828e1b")assert got_graph is not None+++# ============================================================================+# Tests for Optional Credentials Feature+# ============================================================================+++def test_node_credentials_optional_default():+ """Test that credentials_optional defaults to False when not set in metadata."""+ node = Node(+ id="test_node",+ block_id=StoreValueBlock().id,+ input_default={},+ metadata={},+ )+ assert node.credentials_optional is False+++def test_node_credentials_optional_true():+ """Test that credentials_optional returns True when explicitly set."""+ node = Node(+ id="test_node",+ block_id=StoreValueBlock().id,+ input_default={},+ metadata={"credentials_optional": True},+ )+ assert node.credentials_optional is True+++def test_node_credentials_optional_false():+ """Test that credentials_optional returns False when explicitly set to False."""+ node = Node(+ id="test_node",+ block_id=StoreValueBlock().id,+ input_default={},+ metadata={"credentials_optional": False},+ )+ assert node.credentials_optional is False+++def test_node_credentials_optional_with_other_metadata():+ """Test that credentials_optional works correctly with other metadata present."""+ node = Node(+ id="test_node",+ block_id=StoreValueBlock().id,+ input_default={},+ metadata={+ "position": {"x": 100, "y": 200},+ "customized_name": "My Custom Node",+ "credentials_optional": True,+ },+ )+ assert node.credentials_optional is True+ assert node.metadata["position"] == {"x": 100, "y": 200}+ assert node.metadata["customized_name"] == "My Custom Node"diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.pyindex 75459c5a2a..39d4f984eb 100644--- a/autogpt_platform/backend/backend/executor/manager.py+++ b/autogpt_platform/backend/backend/executor/manager.py@@ -178,6 +178,7 @@ async def execute_node(execution_processor: "ExecutionProcessor",execution_stats: NodeExecutionStats | None = None,nodes_input_masks: Optional[NodesInputMasks] = None,+ nodes_to_skip: Optional[set[str]] = None,) -> BlockOutput:"""Execute a node in the graph. This will trigger a block execution on a node,@@ -245,6 +246,7 @@ async def execute_node("user_id": user_id,"execution_context": execution_context,"execution_processor": execution_processor,+ "nodes_to_skip": nodes_to_skip or set(),}# Last-minute fetch credentials + acquire a system-wide read-write lock to prevent@@ -542,6 +544,7 @@ class ExecutionProcessor:node_exec_progress: NodeExecutionProgress,nodes_input_masks: Optional[NodesInputMasks],graph_stats_pair: tuple[GraphExecutionStats, threading.Lock],+ nodes_to_skip: Optional[set[str]] = None,) -> NodeExecutionStats:log_metadata = LogMetadata(logger=_logger,@@ -564,6 +567,7 @@ class ExecutionProcessor:db_client=db_client,log_metadata=log_metadata,nodes_input_masks=nodes_input_masks,+ nodes_to_skip=nodes_to_skip,)if isinstance(status, BaseException):raise status@@ -609,6 +613,7 @@ class ExecutionProcessor:db_client: "DatabaseManagerAsyncClient",log_metadata: LogMetadata,nodes_input_masks: Optional[NodesInputMasks] = None,+ nodes_to_skip: Optional[set[str]] = None,) -> ExecutionStatus:status = ExecutionStatus.RUNNING@@ -645,6 +650,7 @@ class ExecutionProcessor:execution_processor=self,execution_stats=stats,nodes_input_masks=nodes_input_masks,+ nodes_to_skip=nodes_to_skip,):await persist_output(output_name, output_data)@@ -956,6 +962,21 @@ class ExecutionProcessor:queued_node_exec = execution_queue.get()+ # Check if this node should be skipped due to optional credentials+ if queued_node_exec.node_id in graph_exec.nodes_to_skip:+ log_metadata.info(+ f"Skipping node execution {queued_node_exec.node_exec_id} "+ f"for node {queued_node_exec.node_id} - optional credentials not configured"+ )+ # Mark the node as completed without executing+ # No outputs will be produced, so downstream nodes won't trigger+ update_node_execution_status(+ db_client=db_client,+ exec_id=queued_node_exec.node_exec_id,+ status=ExecutionStatus.COMPLETED,+ )+ continue+log_metadata.debug(f"Dispatching node execution {queued_node_exec.node_exec_id} "f"for node {queued_node_exec.node_id}",@@ -1016,6 +1037,7 @@ class ExecutionProcessor:execution_stats,execution_stats_lock,),+ nodes_to_skip=graph_exec.nodes_to_skip,),self.node_execution_loop,)diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex bcd3dcf3b6..1fb2b9404f 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -239,14 +239,19 @@ async def _validate_node_input_credentials(graph: GraphModel,user_id: str,nodes_input_masks: Optional[NodesInputMasks] = None,-) -> dict[str, dict[str, str]]:+) -> tuple[dict[str, dict[str, str]], set[str]]:"""- Checks all credentials for all nodes of the graph and returns structured errors.+ Checks all credentials for all nodes of the graph and returns structured errors+ and a set of nodes that should be skipped due to optional missing credentials.Returns:- dict[node_id, dict[field_name, error_message]]: Credential validation errors per node+ tuple[+ dict[node_id, dict[field_name, error_message]]: Credential validation errors per node,+ set[node_id]: Nodes that should be skipped (optional credentials not configured)+ ]"""credential_errors: dict[str, dict[str, str]] = defaultdict(dict)+ nodes_to_skip: set[str] = set()for node in graph.nodes:block = node.block@@ -256,27 +261,46 @@ async def _validate_node_input_credentials(if not credentials_fields:continue+ # Track if any credential field is missing for this node+ has_missing_credentials = False+for field_name, credentials_meta_type in credentials_fields.items():try:+ # Check nodes_input_masks first, then input_default+ field_value = Noneif (nodes_input_masksand (node_input_mask := nodes_input_masks.get(node.id))and field_name in node_input_mask):- credentials_meta = credentials_meta_type.model_validate(- node_input_mask[field_name]- )+ field_value = node_input_mask[field_name]elif field_name in node.input_default:- credentials_meta = credentials_meta_type.model_validate(- node.input_default[field_name]- )- else:- # Missing credentials- credential_errors[node.id][- field_name- ] = "These credentials are required"- continue+ # For optional credentials, don't use input_default - treat as missing+ # This prevents stale credential IDs from failing validation+ if node.credentials_optional:+ field_value = None+ else:+ field_value = node.input_default[field_name]++ # Check if credentials are missing (None, empty, or not present)+ if field_value is None or (+ isinstance(field_value, dict) and not field_value.get("id")+ ):+ has_missing_credentials = True+ # If node has credentials_optional flag, mark for skipping instead of error+ if node.credentials_optional:+ continue # Don't add error, will be marked for skip after loop+ else:+ credential_errors[node.id][+ field_name+ ] = "These credentials are required"+ continue++ credentials_meta = credentials_meta_type.model_validate(field_value)+except ValidationError as e:+ # Validation error means credentials were provided but invalid+ # This should always be an error, even if optionalcredential_errors[node.id][field_name] = f"Invalid credentials: {e}"continue@@ -287,6 +311,7 @@ async def _validate_node_input_credentials()except Exception as e:# Handle any errors fetching credentials+ # If credentials were explicitly configured but unavailable, it's an errorcredential_errors[node.id][field_name] = f"Credentials not available: {e}"@@ -313,7 +338,19 @@ async def _validate_node_input_credentials(] = "Invalid credentials: type/provider mismatch"continue- return credential_errors+ # If node has optional credentials and any are missing, mark for skipping+ # But only if there are no other errors for this node+ if (+ has_missing_credentials+ and node.credentials_optional+ and node.id not in credential_errors+ ):+ nodes_to_skip.add(node.id)+ logger.info(+ f"Node #{node.id} will be skipped: optional credentials not configured"+ )++ return credential_errors, nodes_to_skipdef make_node_credentials_input_map(@@ -355,21 +392,25 @@ async def validate_graph_with_credentials(graph: GraphModel,user_id: str,nodes_input_masks: Optional[NodesInputMasks] = None,-) -> Mapping[str, Mapping[str, str]]:+) -> tuple[Mapping[str, Mapping[str, str]], set[str]]:"""- Validate graph including credentials and return structured errors per node.+ Validate graph including credentials and return structured errors per node,+ along with a set of nodes that should be skipped due to optional missing credentials.Returns:- dict[node_id, dict[field_name, error_message]]: Validation errors per node+ tuple[+ dict[node_id, dict[field_name, error_message]]: Validation errors per node,+ set[node_id]: Nodes that should be skipped (optional credentials not configured)+ ]"""# Get input validation errorsnode_input_errors = GraphModel.validate_graph_get_errors(graph, for_run=True, nodes_input_masks=nodes_input_masks)- # Get credential input/availability/validation errors- node_credential_input_errors = await _validate_node_input_credentials(- graph, user_id, nodes_input_masks+ # Get credential input/availability/validation errors and nodes to skip+ node_credential_input_errors, nodes_to_skip = (+ await _validate_node_input_credentials(graph, user_id, nodes_input_masks))# Merge credential errors with structural errors@@ -378,7 +419,7 @@ async def validate_graph_with_credentials(node_input_errors[node_id] = {}node_input_errors[node_id].update(field_errors)- return node_input_errors+ return node_input_errors, nodes_to_skipasync def _construct_starting_node_execution_input(@@ -386,7 +427,7 @@ async def _construct_starting_node_execution_input(user_id: str,graph_inputs: BlockInput,nodes_input_masks: Optional[NodesInputMasks] = None,-) -> list[tuple[str, BlockInput]]:+) -> tuple[list[tuple[str, BlockInput]], set[str]]:"""Validates and prepares the input data for executing a graph.This function checks the graph for starting nodes, validates the input data@@ -400,11 +441,14 @@ async def _construct_starting_node_execution_input(node_credentials_map: `dict[node_id, dict[input_name, CredentialsMetaInput]]`Returns:- list[tuple[str, BlockInput]]: A list of tuples, each containing the node ID and- the corresponding input data for that node.+ tuple[+ list[tuple[str, BlockInput]]: A list of tuples, each containing the node ID+ and the corresponding input data for that node.+ set[str]: Node IDs that should be skipped (optional credentials not configured)+ ]"""# Use new validation function that includes credentials- validation_errors = await validate_graph_with_credentials(+ validation_errors, nodes_to_skip = await validate_graph_with_credentials(graph, user_id, nodes_input_masks)n_error_nodes = len(validation_errors)@@ -445,7 +489,7 @@ async def _construct_starting_node_execution_input("No starting nodes found for the graph, make sure an AgentInput or blocks with no inbound links are present as starting nodes.")- return nodes_input+ return nodes_input, nodes_to_skipasync def validate_and_construct_node_execution_input(@@ -456,7 +500,7 @@ async def validate_and_construct_node_execution_input(graph_credentials_inputs: Optional[Mapping[str, CredentialsMetaInput]] = None,nodes_input_masks: Optional[NodesInputMasks] = None,is_sub_graph: bool = False,-) -> tuple[GraphModel, list[tuple[str, BlockInput]], NodesInputMasks]:+) -> tuple[GraphModel, list[tuple[str, BlockInput]], NodesInputMasks, set[str]]:"""Public wrapper that handles graph fetching, credential mapping, and validation+construction.This centralizes the logic used by both scheduler validation and actual execution.@@ -473,6 +517,7 @@ async def validate_and_construct_node_execution_input(GraphModel: Full graph object for the given `graph_id`.list[tuple[node_id, BlockInput]]: Starting node IDs with corresponding inputs.dict[str, BlockInput]: Node input masks including all passed-in credentials.+ set[str]: Node IDs that should be skipped (optional credentials not configured).Raises:NotFoundError: If the graph is not found.@@ -514,14 +559,16 @@ async def validate_and_construct_node_execution_input(nodes_input_masks or {},)- starting_nodes_input = await _construct_starting_node_execution_input(- graph=graph,- user_id=user_id,- graph_inputs=graph_inputs,- nodes_input_masks=nodes_input_masks,+ starting_nodes_input, nodes_to_skip = (+ await _construct_starting_node_execution_input(+ graph=graph,+ user_id=user_id,+ graph_inputs=graph_inputs,+ nodes_input_masks=nodes_input_masks,+ ))- return graph, starting_nodes_input, nodes_input_masks+ return graph, starting_nodes_input, nodes_input_masks, nodes_to_skipdef _merge_nodes_input_masks(@@ -779,6 +826,9 @@ async def add_graph_execution(# Use existing execution's compiled input maskscompiled_nodes_input_masks = graph_exec.nodes_input_masks or {}+ # For resumed executions, nodes_to_skip was already determined at creation time+ # TODO: Consider storing nodes_to_skip in DB if we need to preserve it across resumes+ nodes_to_skip: set[str] = set()logger.info(f"Resuming graph execution #{graph_exec.id} for graph #{graph_id}")else:@@ -787,7 +837,7 @@ async def add_graph_execution()# Create new execution- graph, starting_nodes_input, compiled_nodes_input_masks = (+ graph, starting_nodes_input, compiled_nodes_input_masks, nodes_to_skip = (await validate_and_construct_node_execution_input(graph_id=graph_id,user_id=user_id,@@ -836,6 +886,7 @@ async def add_graph_execution(try:graph_exec_entry = graph_exec.to_graph_execution_entry(compiled_nodes_input_masks=compiled_nodes_input_masks,+ nodes_to_skip=nodes_to_skip,execution_context=execution_context,)logger.info(f"Publishing execution {graph_exec.id} to execution queue")diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.pyindex 8854214e14..0e652f9627 100644--- a/autogpt_platform/backend/backend/executor/utils_test.py+++ b/autogpt_platform/backend/backend/executor/utils_test.py@@ -367,10 +367,13 @@ async def test_add_graph_execution_is_repeatable(mocker: MockerFixture):)# Setup mock returns+ # The function returns (graph, starting_nodes_input, compiled_nodes_input_masks, nodes_to_skip)+ nodes_to_skip: set[str] = set()mock_validate.return_value = (mock_graph,starting_nodes_input,compiled_nodes_input_masks,+ nodes_to_skip,)mock_prisma.is_connected.return_value = Truemock_edb.create_graph_execution = mocker.AsyncMock(return_value=mock_graph_exec)@@ -456,3 +459,212 @@ async def test_add_graph_execution_is_repeatable(mocker: MockerFixture):# Both executions should succeed (though they create different objects)assert result1 == mock_graph_execassert result2 == mock_graph_exec_2+++# ============================================================================+# Tests for Optional Credentials Feature+# ============================================================================+++async def test_validate_node_input_credentials_returns_nodes_to_skip(+ mocker: MockerFixture,+):+ """+ Test that _validate_node_input_credentials returns nodes_to_skip set+ for nodes with credentials_optional=True and missing credentials.+ """+ from backend.executor.utils import _validate_node_input_credentials++ # Create a mock node with credentials_optional=True+ mock_node = mocker.MagicMock()+ mock_node.id = "node-with-optional-creds"+ mock_node.credentials_optional = True+ mock_node.input_default = {} # No credentials configured++ # Create a mock block with credentials field+ mock_block = mocker.MagicMock()+ mock_credentials_field_type = mocker.MagicMock()+ mock_block.input_schema.get_credentials_fields.return_value = {+ "credentials": mock_credentials_field_type+ }+ mock_node.block = mock_block++ # Create mock graph+ mock_graph = mocker.MagicMock()+ mock_graph.nodes = [mock_node]++ # Call the function+ errors, nodes_to_skip = await _validate_node_input_credentials(+ graph=mock_graph,+ user_id="test-user-id",+ nodes_input_masks=None,+ )++ # Node should be in nodes_to_skip, not in errors+ assert mock_node.id in nodes_to_skip+ assert mock_node.id not in errors+++async def test_validate_node_input_credentials_required_missing_creds_error(+ mocker: MockerFixture,+):+ """+ Test that _validate_node_input_credentials returns errors+ for nodes with credentials_optional=False and missing credentials.+ """+ from backend.executor.utils import _validate_node_input_credentials++ # Create a mock node with credentials_optional=False (required)+ mock_node = mocker.MagicMock()+ mock_node.id = "node-with-required-creds"+ mock_node.credentials_optional = False+ mock_node.input_default = {} # No credentials configured++ # Create a mock block with credentials field+ mock_block = mocker.MagicMock()+ mock_credentials_field_type = mocker.MagicMock()+ mock_block.input_schema.get_credentials_fields.return_value = {+ "credentials": mock_credentials_field_type+ }+ mock_node.block = mock_block++ # Create mock graph+ mock_graph = mocker.MagicMock()+ mock_graph.nodes = [mock_node]++ # Call the function+ errors, nodes_to_skip = await _validate_node_input_credentials(+ graph=mock_graph,+ user_id="test-user-id",+ nodes_input_masks=None,+ )++ # Node should be in errors, not in nodes_to_skip+ assert mock_node.id in errors+ assert "credentials" in errors[mock_node.id]+ assert "required" in errors[mock_node.id]["credentials"].lower()+ assert mock_node.id not in nodes_to_skip+++async def test_validate_graph_with_credentials_returns_nodes_to_skip(+ mocker: MockerFixture,+):+ """+ Test that validate_graph_with_credentials returns nodes_to_skip set+ from _validate_node_input_credentials.+ """+ from backend.executor.utils import validate_graph_with_credentials++ # Mock _validate_node_input_credentials to return specific values+ mock_validate = mocker.patch(+ "backend.executor.utils._validate_node_input_credentials"+ )+ expected_errors = {"node1": {"field": "error"}}+ expected_nodes_to_skip = {"node2", "node3"}+ mock_validate.return_value = (expected_errors, expected_nodes_to_skip)++ # Mock GraphModel with validate_graph_get_errors method+ mock_graph = mocker.MagicMock()+ mock_graph.validate_graph_get_errors.return_value = {}++ # Call the function+ errors, nodes_to_skip = await validate_graph_with_credentials(+ graph=mock_graph,+ user_id="test-user-id",+ nodes_input_masks=None,+ )++ # Verify nodes_to_skip is passed through+ assert nodes_to_skip == expected_nodes_to_skip+ assert "node1" in errors+++async def test_add_graph_execution_with_nodes_to_skip(mocker: MockerFixture):+ """+ Test that add_graph_execution properly passes nodes_to_skip+ to the graph execution entry.+ """+ from backend.data.execution import GraphExecutionWithNodes+ from backend.executor.utils import add_graph_execution++ # Mock data+ graph_id = "test-graph-id"+ user_id = "test-user-id"+ inputs = {"test_input": "test_value"}+ graph_version = 1++ # Mock the graph object+ mock_graph = mocker.MagicMock()+ mock_graph.version = graph_version++ # Starting nodes and masks+ starting_nodes_input = [("node1", {"input1": "value1"})]+ compiled_nodes_input_masks = {}+ nodes_to_skip = {"skipped-node-1", "skipped-node-2"}++ # Mock the graph execution object+ mock_graph_exec = mocker.MagicMock(spec=GraphExecutionWithNodes)+ mock_graph_exec.id = "execution-id-123"+ mock_graph_exec.node_executions = []++ # Track what's passed to to_graph_execution_entry+ captured_kwargs = {}++ def capture_to_entry(**kwargs):+ captured_kwargs.update(kwargs)+ return mocker.MagicMock()++ mock_graph_exec.to_graph_execution_entry.side_effect = capture_to_entry++ # Setup mocks+ mock_validate = mocker.patch(+ "backend.executor.utils.validate_and_construct_node_execution_input"+ )+ mock_edb = mocker.patch("backend.executor.utils.execution_db")+ mock_prisma = mocker.patch("backend.executor.utils.prisma")+ mock_udb = mocker.patch("backend.executor.utils.user_db")+ mock_gdb = mocker.patch("backend.executor.utils.graph_db")+ mock_get_queue = mocker.patch("backend.executor.utils.get_async_execution_queue")+ mock_get_event_bus = mocker.patch(+ "backend.executor.utils.get_async_execution_event_bus"+ )++ # Setup returns - include nodes_to_skip in the tuple+ mock_validate.return_value = (+ mock_graph,+ starting_nodes_input,+ compiled_nodes_input_masks,+ nodes_to_skip, # This should be passed through+ )+ mock_prisma.is_connected.return_value = True+ mock_edb.create_graph_execution = mocker.AsyncMock(return_value=mock_graph_exec)+ mock_edb.update_graph_execution_stats = mocker.AsyncMock(+ return_value=mock_graph_exec+ )+ mock_edb.update_node_execution_status_batch = mocker.AsyncMock()++ mock_user = mocker.MagicMock()+ mock_user.timezone = "UTC"+ mock_settings = mocker.MagicMock()+ mock_settings.human_in_the_loop_safe_mode = True++ mock_udb.get_user_by_id = mocker.AsyncMock(return_value=mock_user)+ mock_gdb.get_graph_settings = mocker.AsyncMock(return_value=mock_settings)+ mock_get_queue.return_value = mocker.AsyncMock()+ mock_get_event_bus.return_value = mocker.MagicMock(publish=mocker.AsyncMock())++ # Call the function+ await add_graph_execution(+ graph_id=graph_id,+ user_id=user_id,+ inputs=inputs,+ graph_version=graph_version,+ )++ # Verify nodes_to_skip was passed to to_graph_execution_entry+ assert "nodes_to_skip" in captured_kwargs+ assert captured_kwargs["nodes_to_skip"] == nodes_to_skipdiff --git a/autogpt_platform/backend/snapshots/grph_single b/autogpt_platform/backend/snapshots/grph_singleindex 7ba26f6171..7ce8695e6b 100644--- a/autogpt_platform/backend/snapshots/grph_single+++ b/autogpt_platform/backend/snapshots/grph_single@@ -2,6 +2,7 @@"created_at": "2025-09-04T13:37:00","credentials_input_schema": {"properties": {},+ "required": [],"title": "TestGraphCredentialsInputSchema","type": "object"},diff --git a/autogpt_platform/backend/snapshots/grphs_all b/autogpt_platform/backend/snapshots/grphs_allindex d54df2bc18..f69b45a6de 100644--- a/autogpt_platform/backend/snapshots/grphs_all+++ b/autogpt_platform/backend/snapshots/grphs_all@@ -2,6 +2,7 @@{"credentials_input_schema": {"properties": {},+ "required": [],"title": "TestGraphCredentialsInputSchema","type": "object"},diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsxindex 431feeaade..bd08aa8ee0 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx@@ -66,6 +66,7 @@ export const RunInputDialog = ({formContext={{showHandles: false,size: "large",+ showOptionalToggle: false,}}/></div>diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.tsindex a71ad0bd07..ddd77bae48 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts@@ -66,7 +66,7 @@ export const useRunInputDialog = ({if (isCredentialFieldSchema(fieldSchema)) {dynamicUiSchema[fieldName] = {...dynamicUiSchema[fieldName],- "ui:field": "credentials",+ "ui:field": "custom/credential_field",};}});@@ -76,12 +76,18 @@ export const useRunInputDialog = ({}, [credentialsSchema]);const handleManualRun = async () => {+ // Filter out incomplete credentials (those without a valid id)+ // RJSF auto-populates const values (provider, type) but not id field+ const validCredentials = Object.fromEntries(+ Object.entries(credentialValues).filter(([_, cred]) => cred && cred.id),+ );+await executeGraph({graphId: flowID ?? "",graphVersion: flowVersion || null,data: {inputs: inputValues,- credentials_inputs: credentialValues,+ credentials_inputs: validCredentials,source: "builder",},});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/uiSchema.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/uiSchema.tsindex ad1fab7c95..065e697828 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/uiSchema.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/uiSchema.ts@@ -1,6 +1,6 @@export const uiSchema = {credentials: {- "ui:field": "credentials",+ "ui:field": "custom/credential_field",provider: { "ui:widget": "hidden" },type: { "ui:widget": "hidden" },id: { "ui:autofocus": true },diff --git a/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts b/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.tsindex 96478c5b6f..c151f90faa 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts@@ -68,6 +68,9 @@ type NodeStore = {clearAllNodeErrors: () => void; // Add thissyncHardcodedValuesWithHandleIds: (nodeId: string) => void;++ // Credentials optional helpers+ setCredentialsOptional: (nodeId: string, optional: boolean) => void;};export const useNodeStore = create<NodeStore>((set, get) => ({@@ -226,6 +229,9 @@ export const useNodeStore = create<NodeStore>((set, get) => ({...(node.data.metadata?.customized_name !== undefined && {customized_name: node.data.metadata.customized_name,}),+ ...(node.data.metadata?.credentials_optional !== undefined && {+ credentials_optional: node.data.metadata.credentials_optional,+ }),},};},@@ -342,4 +348,30 @@ export const useNodeStore = create<NodeStore>((set, get) => ({}));}},++ setCredentialsOptional: (nodeId: string, optional: boolean) => {+ set((state) => ({+ nodes: state.nodes.map((n) =>+ n.id === nodeId+ ? {+ ...n,+ data: {+ ...n.data,+ metadata: {+ ...n.data.metadata,+ credentials_optional: optional,+ },+ },+ }+ : n,+ ),+ }));++ const newState = {+ nodes: get().nodes,+ edges: useEdgeStore.getState().edges,+ };++ useHistoryStore.getState().pushState(newState);+ },}));diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/CredentialsInputs.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/CredentialsInputs.tsxindex 60d61fab57..79767c0c81 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/CredentialsInputs.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/CredentialsInputs.tsx@@ -34,6 +34,7 @@ type Props = {onSelectCredentials: (newValue?: CredentialsMetaInput) => void;onLoaded?: (loaded: boolean) => void;readOnly?: boolean;+ isOptional?: boolean;showTitle?: boolean;};@@ -45,6 +46,7 @@ export function CredentialsInput({siblingInputs,onLoaded,readOnly = false,+ isOptional = false,showTitle = true,}: Props) {const hookData = useCredentialsInput({@@ -54,6 +56,7 @@ export function CredentialsInput({siblingInputs,onLoaded,readOnly,+ isOptional,});if (!isLoaded(hookData)) {@@ -94,7 +97,14 @@ export function CredentialsInput({<div className={cn("mb-6", className)}>{showTitle && (<div className="mb-2 flex items-center gap-2">- <Text variant="large-medium">{displayName} credentials</Text>+ <Text variant="large-medium">+ {displayName} credentials+ {isOptional && (+ <span className="ml-1 text-sm font-normal text-gray-500">+ (optional)+ </span>+ )}+ </Text>{schema.description && (<InformationTooltip description={schema.description} />)}@@ -103,14 +113,16 @@ export function CredentialsInput({{hasCredentialsToShow ? (<>- {credentialsToShow.length > 1 && !readOnly ? (+ {(credentialsToShow.length > 1 || isOptional) && !readOnly ? (<CredentialsSelectcredentials={credentialsToShow}provider={provider}displayName={displayName}selectedCredentials={selectedCredential}onSelectCredential={handleCredentialSelect}+ onClearCredential={() => onSelectCredential(undefined)}readOnly={readOnly}+ allowNone={isOptional}/>) : (<div className="mb-4 space-y-2">diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/components/CredentialsSelect/CredentialsSelect.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/components/CredentialsSelect/CredentialsSelect.tsxindex 7adfa5772b..1ada56eb30 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/components/CredentialsSelect/CredentialsSelect.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/components/CredentialsSelect/CredentialsSelect.tsx@@ -23,7 +23,9 @@ interface Props {displayName: string;selectedCredentials?: CredentialsMetaInput;onSelectCredential: (credentialId: string) => void;+ onClearCredential?: () => void;readOnly?: boolean;+ allowNone?: boolean;}export function CredentialsSelect({@@ -32,20 +34,30 @@ export function CredentialsSelect({displayName,selectedCredentials,onSelectCredential,+ onClearCredential,readOnly = false,+ allowNone = true,}: Props) {- // Auto-select first credential if none is selected+ // Auto-select first credential if none is selected (only if allowNone is false)useEffect(() => {- if (!selectedCredentials && credentials.length > 0) {+ if (!allowNone && !selectedCredentials && credentials.length > 0) {onSelectCredential(credentials[0].id);}- }, [selectedCredentials, credentials, onSelectCredential]);+ }, [allowNone, selectedCredentials, credentials, onSelectCredential]);++ const handleValueChange = (value: string) => {+ if (value === "__none__") {+ onClearCredential?.();+ } else {+ onSelectCredential(value);+ }+ };return (<div className="mb-4 w-full"><Select- value={selectedCredentials?.id || ""}- onValueChange={(value) => onSelectCredential(value)}+ value={selectedCredentials?.id || (allowNone ? "__none__" : "")}+ onValueChange={handleValueChange}><SelectTrigger className="h-auto min-h-12 w-full rounded-medium border-zinc-200 p-0 pr-4 shadow-none">{selectedCredentials ? (@@ -70,6 +82,15 @@ export function CredentialsSelect({)}</SelectTrigger><SelectContent>+ {allowNone && (+ <SelectItem key="__none__" value="__none__">+ <div className="flex items-center gap-2">+ <Text variant="body" className="tracking-tight text-gray-500">+ None (skip this credential)+ </Text>+ </div>+ </SelectItem>+ )}{credentials.map((credential) => (<SelectItem key={credential.id} value={credential.id}><div className="flex items-center gap-2">diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/useCredentialsInput.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/useCredentialsInput.tsindex 6f5ca48126..c780ffeffc 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/useCredentialsInput.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/CredentialsInputs/useCredentialsInput.ts@@ -22,6 +22,7 @@ type Params = {siblingInputs?: Record<string, any>;onLoaded?: (loaded: boolean) => void;readOnly?: boolean;+ isOptional?: boolean;};export function useCredentialsInput({@@ -31,6 +32,7 @@ export function useCredentialsInput({siblingInputs,onLoaded,readOnly = false,+ isOptional = false,}: Params) {const [isAPICredentialsModalOpen, setAPICredentialsModalOpen] =useState(false);@@ -99,13 +101,20 @@ export function useCredentialsInput({: null;}, [credentials]);- // Auto-select the one available credential+ // Auto-select the one available credential (only if not optional)useEffect(() => {if (readOnly) return;+ if (isOptional) return; // Don't auto-select when credential is optionalif (singleCredential && !selectedCredential) {onSelectCredential(singleCredential);}- }, [singleCredential, selectedCredential, onSelectCredential, readOnly]);+ }, [+ singleCredential,+ selectedCredential,+ onSelectCredential,+ readOnly,+ isOptional,+ ]);if (!credentials ||diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/ModalRunSection.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/ModalRunSection.tsxindex f3b02bfbc9..aba4caee7a 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/ModalRunSection.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/components/ModalRunSection/ModalRunSection.tsx@@ -8,6 +8,7 @@ import { WebhookTriggerBanner } from "../WebhookTriggerBanner/WebhookTriggerBannexport function ModalRunSection() {const {+ agent,defaultRunType,presetName,setPresetName,@@ -24,6 +25,11 @@ export function ModalRunSection() {const inputFields = Object.entries(agentInputFields || {});const credentialFields = Object.entries(agentCredentialsInputFields || {});+ // Get the list of required credentials from the schema+ const requiredCredentials = new Set(+ (agent.credentials_input_schema?.required as string[]) || [],+ );+return (<div className="flex flex-col gap-4">{defaultRunType === "automatic-trigger" ||@@ -99,14 +105,12 @@ export function ModalRunSection() {schema={{ ...inputSubSchema, discriminator: undefined } as any}- selectedCredentials={- (inputCredentials && inputCredentials[key]) ??- inputSubSchema.default- }+ selectedCredentials={inputCredentials?.[key]}onSelectCredentials={(value) =>setInputCredentialsValue(key, value)}siblingInputs={inputValues}+ isOptional={!requiredCredentials.has(key)}/>),)}diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/useAgentRunModal.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/useAgentRunModal.tsxindex b997a33fcf..eb32083004 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/useAgentRunModal.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentModal/useAgentRunModal.tsx@@ -163,15 +163,21 @@ export function useAgentRunModal(}, [agentInputSchema.required, inputValues]);const [allCredentialsAreSet, missingCredentials] = useMemo(() => {- const availableCredentials = new Set(Object.keys(inputCredentials));- const allCredentials = new Set(- Object.keys(agentCredentialsInputFields || {}) ?? [],- );- const missing = [...allCredentials].filter(- (key) => !availableCredentials.has(key),+ // Only check required credentials from schema, not all properties+ // Credentials marked as optional in node metadata won't be in the required array+ const requiredCredentials = new Set(+ (agent.credentials_input_schema?.required as string[]) || [],);++ // Check if required credentials have valid id (not just key existence)+ // A credential is valid only if it has an id field set+ const missing = [...requiredCredentials].filter((key) => {+ const cred = inputCredentials[key];+ return !cred || !cred.id;+ });+return [missing.length === 0, missing];- }, [agentCredentialsInputFields, inputCredentials]);+ }, [agent.credentials_input_schema, inputCredentials]);const credentialsRequired = useMemo(() => Object.keys(agentCredentialsInputFields || {}).length > 0,@@ -239,12 +245,18 @@ export function useAgentRunModal(});} else {// Manual execution+ // Filter out incomplete credentials (optional ones not selected)+ // Only send credentials that have a valid id field+ const validCredentials = Object.fromEntries(+ Object.entries(inputCredentials).filter(([_, cred]) => cred && cred.id),+ );+executeGraphMutation.mutate({graphId: agent.graph_id,graphVersion: agent.graph_version,data: {inputs: inputValues,- credentials_inputs: inputCredentials,+ credentials_inputs: validCredentials,source: "library",},});diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsxindex f814fba93f..189b73e34b 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsx+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/CredentialField.tsx@@ -8,19 +8,34 @@ import { CredentialsInput } from "@/app/(platform)/library/agents/[id]/componentimport { useNodeStore } from "@/app/(platform)/build/stores/nodeStore";import { useShallow } from "zustand/react/shallow";import { CredentialFieldTitle } from "./components/CredentialFieldTitle";+import { Switch } from "@/components/atoms/Switch/Switch";export const CredentialsField = (props: FieldProps) => {- const { formData, onChange, schema, registry, fieldPathId } = props;+ const { formData, onChange, schema, registry, fieldPathId, required } = props;const formContext = registry.formContext;const uiOptions = getUiOptions(props.uiSchema);const nodeId = formContext?.nodeId;- // Get sibling inputs (hardcoded values) from the node store- const hardcodedValues = useNodeStore(- useShallow((state) => (nodeId ? state.getHardCodedValues(nodeId) : {})),+ // Get sibling inputs (hardcoded values) and credentials optional state from the node store+ // Note: We select the node data directly instead of using getter functions to avoid+ // creating new object references that would cause infinite re-render loops with useShallow+ const { node, setCredentialsOptional } = useNodeStore(+ useShallow((state) => ({+ node: nodeId ? state.nodes.find((n) => n.id === nodeId) : undefined,+ setCredentialsOptional: state.setCredentialsOptional,+ })),);+ const hardcodedValues = useMemo(+ () => node?.data?.hardcodedValues || {},+ [node?.data?.hardcodedValues],+ );+ const credentialsOptional = useMemo(() => {+ const value = node?.data?.metadata?.credentials_optional;+ return typeof value === "boolean" ? value : false;+ }, [node?.data?.metadata?.credentials_optional]);+const handleChange = (newValue: any) => {onChange(newValue, fieldPathId?.path);};@@ -52,6 +67,10 @@ export const CredentialsField = (props: FieldProps) => {[formData?.id, formData?.provider, formData?.title, formData?.type],);+ // In builder canvas (nodeId exists): show star based on credentialsOptional toggle+ // In run dialogs (no nodeId): show star based on schema's required array+ const isRequired = nodeId ? !credentialsOptional : required;+return (<div className="flex flex-col gap-2"><CredentialFieldTitle@@ -59,6 +78,7 @@ export const CredentialsField = (props: FieldProps) => {registry={registry}uiOptions={uiOptions}schema={schema}+ required={isRequired}/><CredentialsInputschema={schema as BlockIOCredentialsSubSchema}@@ -67,7 +87,29 @@ export const CredentialsField = (props: FieldProps) => {siblingInputs={hardcodedValues}showTitle={false}readOnly={formContext?.readOnly}+ isOptional={!isRequired}/>++ {/* Optional credentials toggle - only show in builder canvas, not run dialogs */}+ {nodeId &&+ !formContext?.readOnly &&+ formContext?.showOptionalToggle !== false && (+ <div className="mt-1 flex items-center gap-2">+ <Switch+ id={`credentials-optional-${nodeId}`}+ checked={credentialsOptional}+ onCheckedChange={(checked) =>+ setCredentialsOptional(nodeId, checked)+ }+ />+ <label+ htmlFor={`credentials-optional-${nodeId}`}+ className="cursor-pointer text-xs text-gray-500"+ >+ Optional - skip block if not configured+ </label>+ </div>+ )}</div>);};diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/components/CredentialFieldTitle.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/components/CredentialFieldTitle.tsxindex ca14c8a4ce..347f4e089a 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/components/CredentialFieldTitle.tsx+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/components/CredentialFieldTitle.tsx@@ -18,8 +18,9 @@ export const CredentialFieldTitle = (props: {uiOptions: UiSchema;schema: RJSFSchema;fieldPathId: FieldPathId;+ required?: boolean;}) => {- const { registry, uiOptions, schema, fieldPathId } = props;+ const { registry, uiOptions, schema, fieldPathId, required = false } = props;const { nodeId } = registry.formContext;const TitleFieldTemplate = getTemplate(@@ -50,7 +51,7 @@ export const CredentialFieldTitle = (props: {<TitleFieldTemplateid={titleId(fieldPathId ?? "")}title={credentialProvider ?? ""}- required={true}+ required={required}schema={schema}registry={registry}uiSchema={updatedUiSchema}diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/types.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/types.tsindex af2e8b7866..e667e27e2d 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/types.ts+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/types.ts@@ -6,6 +6,7 @@ export interface ExtendedFormContextType extends FormContextType {uiType?: BlockUIType;showHandles?: boolean;size?: "small" | "medium" | "large";+ showOptionalToggle?: boolean;}export type PathSegment = {