Skip to content

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(blocks): make the AutoPilot transport an explicit choice (#14070)

Nicholas Tindleb88b86a96abd
diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.py
index 588414626d..5aaf85d1aa 100644
--- a/autogpt_platform/backend/backend/api/rest_api.py
+++ b/autogpt_platform/backend/backend/api/rest_api.py
@@ -1,3 +1,4 @@
+import asyncio
import contextlib
import logging
import platform
@@ -55,6 +56,7 @@ import backend.api.features.transfers.routes as transfer_routes
import backend.api.features.v1
import backend.api.features.workspace.folder_routes as workspace_folder_routes
import backend.api.features.workspace.routes as team_routes
+import backend.data.autopilot_migrate
import backend.data.block
import backend.data.db
import backend.data.graph
@@ -165,6 +167,19 @@ async def lifespan_context(app: fastapi.FastAPI):
await backend.integrations.webhooks.utils.migrate_legacy_triggered_graphs()
await backend.data.org_migration.run_migration()
+ # Guarded, unlike its neighbours above: this backfill only corrects what
+ # the builder displays for AutoPilot nodes saved before `transport`
+ # existed. The block honours the connection either way, so a failure here
+ # changes nothing about which account pays — and refusing to boot the
+ # platform over a cosmetic migration would be the worse outcome.
+ try:
+ await asyncio.wait_for(
+ backend.data.autopilot_migrate.migrate_autopilot_transport(apply=True),
+ timeout=30,
+ )
+ except Exception:
+ logger.error("AutoPilot transport backfill failed", exc_info=True)
+
# Fail-hard: the catalog is load-bearing — a broken load stops the boot.
backend.data.llm_registry.load_catalog()
diff --git a/autogpt_platform/backend/backend/blocks/autopilot.py b/autogpt_platform/backend/backend/blocks/autopilot.py
index fa9b5dab2b..16246edee8 100644
--- a/autogpt_platform/backend/backend/blocks/autopilot.py
+++ b/autogpt_platform/backend/backend/blocks/autopilot.py
@@ -5,6 +5,7 @@ import contextvars
import json
import logging
import uuid
+from enum import Enum
from typing import TYPE_CHECKING, Any, Literal
from pydantic import field_validator
@@ -95,6 +96,24 @@ CodexAutoPilotCredentials = CredentialsMetaInput[
]
+class AutoPilotTransport(str, Enum):
+ """Which account pays for the model calls this block makes.
+
+ `platform` spends AutoGPT credits; `codex_app_server` spends the user's own
+ ChatGPT subscription. Because the two bill differently, the choice is
+ explicit rather than inferred from whether a credential happens to be set.
+ """
+
+ PLATFORM = "platform"
+ CODEX_APP_SERVER = "codex_app_server"
+
+ @classmethod
+ def __get_pydantic_json_schema__(cls, schema, handler):
+ json_schema = handler(schema)
+ json_schema["enumNames"] = ["AutoGPT Platform", "ChatGPT"]
+ return json_schema
+
+
class AutoPilotBlock(Block):
"""Execute tasks using AutoGPT AutoPilot with full access to platform tools.
@@ -133,14 +152,29 @@ class AutoPilotBlock(Block):
advanced=True,
)
- codex_credentials: CodexAutoPilotCredentials = CredentialsField(
- title="ChatGPT / Codex connection",
+ transport: AutoPilotTransport | None = SchemaField(
+ title="Transport",
+ default=None,
+ placeholder="Select a transport",
description=(
- "Optional connected ChatGPT plan. Leave empty to use the "
- "normal platform-funded AutoPilot transport."
+ "Run on platform credits, or on your connected ChatGPT "
+ "subscription if supported by your plan."
),
+ advanced=False,
+ )
+
+ codex_credentials: CodexAutoPilotCredentials = CredentialsField(
+ title="ChatGPT / Codex connection",
+ description="Connected ChatGPT subscription used by the Codex transport.",
default=None,
credential_reference_only=True,
+ discriminator="transport",
+ # `platform` is deliberately absent: it needs no credential at all,
+ # and an unmapped discriminator value makes the credential input
+ # hide itself rather than asking for something that does not exist.
+ discriminator_mapping={
+ AutoPilotTransport.CODEX_APP_SERVER.value: ProviderName.CODEX,
+ },
json_schema_extra={
"secret": True,
"advanced": False,
@@ -501,6 +535,37 @@ class AutoPilotBlock(Block):
# Create session eagerly so the user always gets the session_id,
# even if the downstream stream fails (avoids orphaned sessions).
codex_connection = input_data.codex_credentials
+ # `transport` is optional precisely so "never chosen" stays
+ # distinguishable from "deliberately platform". A filled-in default
+ # cannot express that difference, and reading one as a real choice
+ # would silently move legacy agents onto platform credits.
+ if input_data.transport is None:
+ # Saved before the field existed: the connection *is* the choice.
+ use_codex = codex_connection is not None
+ if use_codex:
+ logger.warning(
+ "AutoPilot node has a ChatGPT connection but no transport "
+ "set — billing to the connection. Run "
+ "`python -m backend.data.autopilot_migrate --apply`."
+ )
+ elif input_data.transport == AutoPilotTransport.CODEX_APP_SERVER:
+ if codex_connection is None:
+ # Falling back to platform here would bill a different account
+ # than the one the user asked for, without saying so.
+ yield "error", (
+ "The ChatGPT transport needs a connected ChatGPT account. "
+ "Connect one, or switch this step to platform credits."
+ )
+ return
+ use_codex = True
+ elif input_data.transport == AutoPilotTransport.PLATFORM:
+ # Explicit platform: honour it even if a connection is still
+ # attached, otherwise the user cannot move a step back onto
+ # platform credits once codex has been configured.
+ use_codex = False
+ else:
+ yield "error", f"Unsupported AutoPilot transport: {input_data.transport}"
+ return
sid = input_data.session_id
if not sid:
sid = await self.create_session(
@@ -508,27 +573,39 @@ class AutoPilotBlock(Block):
dry_run=input_data.dry_run or execution_context.dry_run,
organization_id=execution_context.organization_id,
team_id=execution_context.team_id,
- llm_auth_provider=(
- "codex" if codex_connection is not None else "platform"
- ),
- llm_credential_id=(
- codex_connection.id if codex_connection is not None else None
- ),
+ llm_auth_provider=("codex" if use_codex else "platform"),
+ llm_credential_id=(codex_connection.id if use_codex else None),
)
- elif codex_connection is not None:
- from backend.copilot.model import get_chat_session
-
- existing_session = await get_chat_session(
+ else:
+ # Validate on every resume, not just codex ones. Gating this on
+ # `use_codex` let an explicit `platform` node resume a session that
+ # was created against codex, which then billed the ChatGPT
+ # subscription the user had just opted out of.
+ from backend.copilot.model import get_chat_session_metadata
+
+ existing_session = await get_chat_session_metadata(
sid,
execution_context.user_id,
)
- if not (
- existing_session is not None
- and existing_session.metadata.llm_auth_provider == "codex"
- and existing_session.metadata.llm_credential_id == codex_connection.id
+ if existing_session is None:
+ yield "session_id", sid
+ yield "error", (
+ "The AutoPilot session was not found. Start a new session "
+ "or check that the session ID belongs to this account."
+ )
+ return
+
+ expected_provider = "codex" if use_codex else "platform"
+ expected_credential = codex_connection.id if use_codex else None
+ if (
+ existing_session.metadata.llm_auth_provider != expected_provider
+ or existing_session.metadata.llm_credential_id != expected_credential
):
yield "session_id", sid
- yield "error", "codex_session_route_mismatch"
+ yield "error", (
+ "The AutoPilot session uses a different transport or connection. "
+ "Start a new session for this selection."
+ )
return
# NOTE: No asyncio.timeout() here — the SDK manages its own
diff --git a/autogpt_platform/backend/backend/blocks/autopilot_codex_test.py b/autogpt_platform/backend/backend/blocks/autopilot_codex_test.py
index 7e1745532c..4d248adc9b 100644
--- a/autogpt_platform/backend/backend/blocks/autopilot_codex_test.py
+++ b/autogpt_platform/backend/backend/blocks/autopilot_codex_test.py
@@ -1,5 +1,5 @@
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -103,7 +103,25 @@ async def test_autopilot_block_routes_new_session_to_selected_codex_connection()
@pytest.mark.asyncio
-async def test_autopilot_block_rejects_codex_connection_change_on_resume():
+ ("existing", "error_fragment"),
+ [
+ (None, "session was not found"),
+ (
+ SimpleNamespace(
+ metadata=SimpleNamespace(
+ llm_auth_provider="codex",
+ llm_credential_id="different-credential",
+ )
+ ),
+ "different transport or connection",
+ ),
+ ],
+)
+async def test_autopilot_block_rejects_invalid_session_route(
+ existing: SimpleNamespace | None,
+ error_fragment: str,
+):
block = AutoPilotBlock()
execute_copilot = AsyncMock()
input_data = AutoPilotBlock.Input(
@@ -123,16 +141,9 @@ async def test_autopilot_block_rejects_codex_connection_change_on_resume():
node_id="node-1",
node_exec_id="node-exec-1",
)
- existing = SimpleNamespace(
- metadata=SimpleNamespace(
- llm_auth_provider="codex",
- llm_credential_id="different-credential",
- )
- )
-
with (
patch(
- "backend.copilot.model.get_chat_session",
+ "backend.copilot.model.get_chat_session_metadata",
new=AsyncMock(return_value=existing),
),
patch.object(block, "execute_copilot", execute_copilot),
@@ -145,8 +156,200 @@ async def test_autopilot_block_rejects_codex_connection_change_on_resume():
)
]
- assert outputs == [
- ("session_id", "session-1"),
- ("error", "codex_session_route_mismatch"),
- ]
+ assert outputs[0] == ("session_id", "session-1")
+ assert outputs[1][0] == "error"
+ assert error_fragment in outputs[1][1]
+ execute_copilot.assert_not_awaited()
+
+
+def test_transport_is_an_explicit_choice_not_inferred_from_the_credential():
+ """Which account pays used to be encoded as "is a credential set", visible
+ only by noticing an empty field. `platform` spends AutoGPT credits;
+ `codex_app_server` spends the user's own ChatGPT subscription."""
+
+ schema = AutoPilotBlock.Input.jsonschema()
+ transport = schema["properties"]["transport"]
+
+ assert transport["advanced"] is False
+ # Optional on purpose: a filled-in default cannot distinguish "never
+ # chosen" from "deliberately platform", and reading one as the other
+ # silently rebills legacy nodes.
+ assert transport.get("default") is None
+ assert transport["placeholder"] == "Select a transport"
+ assert transport["anyOf"][0]["enumNames"] == ["AutoGPT Platform", "ChatGPT"]
+
+
+def test_platform_transport_maps_to_no_provider():
+ """`platform` is deliberately absent from the mapping: it needs no
+ credential, and an unmapped value makes the credential input hide itself
+ rather than asking for something that does not exist."""
+ schema = AutoPilotBlock.Input.jsonschema()
+ field_schema = schema["properties"]["codex_credentials"]
+
+ assert field_schema["discriminator"] == "transport"
+ assert field_schema["discriminator_mapping"] == {"codex_app_server": "codex"}
+ assert "platform" not in field_schema["discriminator_mapping"]
+
+
+def test_codex_credentials_stays_optional_under_the_discriminator():
+ """Adding the discriminator must not make the connection mandatory —
+ the platform transport is the default and needs nothing."""
+ assert "codex_credentials" not in AutoPilotBlock.Input.get_required_fields()
+
+
+def test_autopilot_does_not_use_discriminator_type_mapping():
+ """Both of its options are a single credential type (or none), so the
+ graph-aggregation fallback that CodeGeneration needs does not apply here.
+ Pinned because `test_only_known_blocks_use_discriminator_type_mapping`
+ asserts CodeGeneration is the sole user."""
+ info = AutoPilotBlock.Input.get_credentials_fields_info()["codex_credentials"]
+
+ assert not info.discriminator_type_mapping
+
+
+def test_legacy_node_has_no_transport_so_its_connection_decides():
+ """A node saved before the field existed carries a connection and no
+ transport. That must stay distinguishable from a deliberate platform
+ choice, or those agents get silently moved onto platform credits."""
+ legacy = AutoPilotBlock.Input(
+ prompt="do the thing",
+ codex_credentials={
+ "id": "codex-1",
+ "provider": "codex",
+ "type": "oauth2",
+ "title": "ChatGPT for Codex",
+ },
+ )
+
+ assert legacy.transport is None
+ assert legacy.codex_credentials is not None
+
+
+def test_explicit_platform_is_distinguishable_from_unset():
+ """The whole reason the field is optional: a user moving a step back onto
+ platform credits must not be mistaken for a legacy node."""
+ from backend.blocks.autopilot import AutoPilotTransport
+
+ chosen = AutoPilotBlock.Input(
+ prompt="do the thing",
+ transport=AutoPilotTransport.PLATFORM,
+ codex_credentials={
+ "id": "codex-1",
+ "provider": "codex",
+ "type": "oauth2",
+ "title": "ChatGPT for Codex",
+ },
+ )
+
+ assert chosen.transport == AutoPilotTransport.PLATFORM
+
+
+CODEX_META = {
+ "id": "cred-1",
+ "provider": "codex",
+ "type": "oauth2",
+ "title": "Personal ChatGPT",
+}
+
+
+def _context():
+ return ExecutionContext(
+ user_id="user-1",
+ graph_id="graph-1",
+ graph_exec_id="graph-exec-1",
+ node_id="node-1",
+ node_exec_id="node-exec-1",
+ )
+
+
+async def _run_block(input_data):
+ """Drive run() far enough to observe which account the session bills."""
+ block = AutoPilotBlock()
+ create_session = AsyncMock(return_value="session-1")
+ execute_copilot = AsyncMock(
+ return_value=(
+ "done",
+ [],
+ "[]",
+ "session-1",
+ {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ )
+ )
+ with (
+ patch.object(block, "create_session", create_session),
+ patch.object(block, "execute_copilot", execute_copilot),
+ ):
+ outputs = {
+ name: value
+ async for name, value in block.run(input_data, execution_context=_context())
+ }
+ return outputs, create_session
+
+
+async def test_run_honours_explicit_platform_over_an_attached_connection():
+ """Without this a user could never move a step back onto platform credits:
+ the leftover connection kept deciding."""
+ from backend.blocks.autopilot import AutoPilotTransport
+
+ outputs, create_session = await _run_block(
+ AutoPilotBlock.Input(
+ prompt="go",
+ transport=AutoPilotTransport.PLATFORM,
+ codex_credentials=CODEX_META,
+ )
+ )
+
+ assert outputs["response"] == "done"
+ assert create_session.await_args.kwargs["llm_auth_provider"] == "platform"
+ assert create_session.await_args.kwargs["llm_credential_id"] is None
+
+
+async def test_run_fails_closed_when_codex_is_chosen_without_a_connection():
+ """Falling back to platform would bill a different account than the one
+ asked for, without saying so."""
+ from backend.blocks.autopilot import AutoPilotTransport
+
+ outputs, create_session = await _run_block(
+ AutoPilotBlock.Input(prompt="go", transport=AutoPilotTransport.CODEX_APP_SERVER)
+ )
+
+ assert "ChatGPT" in outputs["error"]
+ create_session.assert_not_awaited()
+
+
+async def test_run_rejects_resuming_a_codex_session_on_platform():
+ """Regression: gating the resume check on `use_codex` skipped it entirely
+ for a platform node, so it silently continued on the codex session and
+ billed the subscription the user had just opted out of."""
+ from backend.blocks.autopilot import AutoPilotTransport
+
+ block = AutoPilotBlock()
+ execute_copilot = AsyncMock()
+ session = MagicMock()
+ session.metadata.llm_auth_provider = "codex"
+ session.metadata.llm_credential_id = "cred-1"
+
+ input_data = AutoPilotBlock.Input(
+ prompt="continue",
+ session_id="session-1",
+ transport=AutoPilotTransport.PLATFORM,
+ codex_credentials=CODEX_META,
+ )
+
+ with (
+ patch.object(block, "execute_copilot", execute_copilot),
+ patch(
+ "backend.copilot.model.get_chat_session_metadata",
+ new=AsyncMock(return_value=session),
+ ),
+ ):
+ outputs = {
+ name: value
+ async for name, value in block.run(input_data, execution_context=_context())
+ }
+
+ assert "different transport or connection" in outputs["error"]
execute_copilot.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index 97a6ac2f95..bf1d022283 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -950,6 +950,7 @@ def _resolve_discriminated_credentials(
return {}
resolved: dict[str, CredentialsFieldInfo] = {}
+ required_fields = set(block.input_schema.get_required_fields())
for field_name, field_info in credentials_fields_info.items():
effective_field_info = field_info
@@ -961,6 +962,12 @@ def _resolve_discriminated_credentials(
if field and field.default is not PydanticUndefined:
discriminator_value = field.default
+ if (
+ field_name not in required_fields
+ and not field_info.requires_credentials(discriminator_value)
+ ):
+ continue
+
if discriminator_value is not None:
if field_info.discriminator_mapping:
# Provider-based discrimination (e.g. model -> provider)
diff --git a/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py b/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py
index 30254df80b..ba1d28d300 100644
--- a/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/http_credentials_test.py
@@ -124,6 +124,19 @@ class TestResolveDiscriminatedCredentials:
assert ProviderName.OPENAI in field_info.provider
assert "gpt-4o-mini" in field_info.discriminator_values
+ def test_optional_unmapped_discriminator_needs_no_credentials(self):
+ from backend.blocks.autopilot import AutoPilotBlock
+
+ block = AutoPilotBlock()
+
+ assert (
+ _resolve_discriminated_credentials(block, {"transport": "platform"}) == {}
+ )
+ assert "codex_credentials" in _resolve_discriminated_credentials(
+ block, {"transport": "codex_app_server"}
+ )
+ assert "codex_credentials" in _resolve_discriminated_credentials(block, {})
+
# ---------------------------------------------------------------------------
# find_matching_credential tests (host-scoped)
diff --git a/autogpt_platform/backend/backend/data/autopilot_migrate.py b/autogpt_platform/backend/backend/data/autopilot_migrate.py
new file mode 100644
index 0000000000..8d36d66281
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/autopilot_migrate.py
@@ -0,0 +1,102 @@
+"""Backfill `transport` on AutoPilot nodes saved before the field existed.
+
+Those nodes encode "use my ChatGPT subscription" as the mere presence of a
+codex credential, and carry no transport at all. The block reads that absence
+correctly (see `AutoPilotBlock.run`), so this migration changes what the
+builder *displays*, not which account pays.
+
+Runs automatically at API startup (see `api/rest_api.py`) and is idempotent:
+the statement only matches rows that still need it, so repeated boots are a
+no-op. Also runnable by hand; dry-run by default, pass --apply to write.
+"""
+
+import argparse
+import asyncio
+import logging
+
+from backend.blocks.autopilot import AUTOPILOT_BLOCK_ID, AutoPilotTransport
+from backend.data.db import (
+ connect,
+ disconnect,
+ execute_raw_with_schema,
+ query_raw_with_schema,
+)
+
+logger = logging.getLogger(__name__)
+
+
+# A single atomic statement rather than read-modify-write. Sibling startup
+# migrations either lock (org_migration) or use jsonb_set (migrate_llm_models);
+# reading every node and writing the whole blob back would let two booting pods
+# clobber each other, and any concurrent user edit in between.
+#
+# The predicate is the idempotency guarantee: it matches only nodes with a real
+# connection (an id-less meta means nothing was selected) and no transport yet,
+# so re-running selects nothing.
+def _match(block_id_parameter: int) -> str:
+ return f"""
+ "agentBlockId" = ${block_id_parameter}
+ AND "constantInput"->'codex_credentials'->>'id' IS NOT NULL
+ AND "constantInput"->>'transport' IS NULL
+"""
+
+
+_COUNT_QUERY = f"""
+ SELECT COUNT(*)::int AS count
+ FROM {{schema_prefix}}"AgentNode"
+ WHERE {_match(1)}
+"""
+
+# ARRAY['transport'] rather than the '{transport}' path literal: these
+# templates are run through str.format() to inject the schema prefix, so a
+# literal brace becomes a format field and raises KeyError at apply time.
+_UPDATE_QUERY = f"""
+ UPDATE {{schema_prefix}}"AgentNode"
+ SET "constantInput" = jsonb_set("constantInput", ARRAY['transport'], to_jsonb($1::text), true)
+ WHERE {_match(2)}
+"""
+
+
+async def migrate_autopilot_transport(*, apply: bool) -> int:
+ """Set transport=codex_app_server on nodes carrying a codex connection.
+
+ Returns the number of nodes that needed the backfill.
+ """
+ if apply:
+ updated = await execute_raw_with_schema(
+ _UPDATE_QUERY,
+ AutoPilotTransport.CODEX_APP_SERVER.value,
+ AUTOPILOT_BLOCK_ID,
+ )
+ if updated:
+ logger.info(
+ "%d AutoPilot node(s) given transport=codex_app_server", updated
+ )
+ return updated
+
+ rows = await query_raw_with_schema(_COUNT_QUERY, AUTOPILOT_BLOCK_ID)
+ pending = int(rows[0]["count"]) if rows else 0
+ if pending:
+ logger.info(
+ "%d AutoPilot node(s) need backfill (dry run — pass --apply to write)",
+ pending,
+ )
+ return pending
+
+
+async def _main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--apply", action="store_true", help="write the changes")
+ args = parser.parse_args()
+
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
+
+ await connect()
+ try:
+ await migrate_autopilot_transport(apply=args.apply)
+ finally:
+ await disconnect()
+
+
+if __name__ == "__main__":
+ asyncio.run(_main())
diff --git a/autogpt_platform/backend/backend/data/autopilot_migrate_test.py b/autogpt_platform/backend/backend/data/autopilot_migrate_test.py
new file mode 100644
index 0000000000..81f3903283
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/autopilot_migrate_test.py
@@ -0,0 +1,189 @@
+import uuid
+from unittest.mock import AsyncMock, patch
+
+import prisma.models
+import pytest
+
+from backend.data.autopilot_migrate import (
+ AUTOPILOT_BLOCK_ID,
+ migrate_autopilot_transport,
+)
+
+
+async def test_dry_run_counts_without_writing():
+ with patch(
+ "backend.data.autopilot_migrate.query_raw_with_schema",
+ new=AsyncMock(return_value=[{"count": 3}]),
+ ), patch(
+ "backend.data.autopilot_migrate.execute_raw_with_schema",
+ new=AsyncMock(),
+ ) as execute:
+ assert await migrate_autopilot_transport(apply=False) == 3
+
+ execute.assert_not_awaited()
+
+
+async def test_apply_writes_the_transport_value():
+ with patch(
+ "backend.data.autopilot_migrate.query_raw_with_schema",
+ new=AsyncMock(),
+ ) as query, patch(
+ "backend.data.autopilot_migrate.execute_raw_with_schema",
+ new=AsyncMock(return_value=1),
+ ) as execute:
+ assert await migrate_autopilot_transport(apply=True) == 1
+
+ query.assert_not_awaited()
+ sql, transport, block_id = execute.await_args.args
+ assert transport == "codex_app_server"
+ assert block_id == AUTOPILOT_BLOCK_ID
+ # Atomic single-key write, not a whole-blob replace: two booting pods must
+ # not be able to clobber each other or a concurrent user edit.
+ assert "jsonb_set" in sql
+ assert "UPDATE" in sql
+
+
+async def test_apply_nothing_pending_is_a_silent_no_op():
+ with patch(
+ "backend.data.autopilot_migrate.query_raw_with_schema",
+ new=AsyncMock(),
+ ) as query, patch(
+ "backend.data.autopilot_migrate.execute_raw_with_schema",
+ new=AsyncMock(return_value=0),
+ ) as execute:
+ assert await migrate_autopilot_transport(apply=True) == 0
+
+ query.assert_not_awaited()
+ execute.assert_awaited_once()
+
+
+async def test_dry_run_nothing_pending_is_a_silent_no_op():
+ with patch(
+ "backend.data.autopilot_migrate.query_raw_with_schema",
+ new=AsyncMock(return_value=[{"count": 0}]),
+ ), patch(
+ "backend.data.autopilot_migrate.execute_raw_with_schema",
+ new=AsyncMock(),
+ ) as execute:
+ assert await migrate_autopilot_transport(apply=False) == 0
+
+ execute.assert_not_awaited()
+
+
+async def test_predicate_scopes_to_autopilot_nodes_needing_the_backfill():
+ """The predicate is the idempotency guarantee — it must exclude nodes that
+ have a concrete transport, and id-less credential metas (nothing selected)."""
+ query = AsyncMock(return_value=[{"count": 0}])
+ with patch("backend.data.autopilot_migrate.query_raw_with_schema", new=query):
+ await migrate_autopilot_transport(apply=False)
+
+ sql, block_id = query.await_args.args
+ assert block_id == AUTOPILOT_BLOCK_ID
+ assert "\"constantInput\"->>'transport' IS NULL" in sql
+ assert "'codex_credentials'->>'id' IS NOT NULL" in sql
+
+
[email protected](loop_scope="session")
+async def test_apply_is_idempotent_against_database(server):
+ user_id = str(uuid.uuid4())
+ graph_id = str(uuid.uuid4())
+ await prisma.models.User.prisma().create(
+ data={
+ "id": user_id,
+ "email": f"autopilot-migrate-{user_id}@example.com",
+ "name": "AutoPilot Migration Test",
+ }
+ )
+ await prisma.models.AgentGraph.prisma().create(
+ data={
+ "id": graph_id,
+ "version": 1,
+ "name": "autopilot-migrate-test",
+ "description": "autopilot-migrate-test",
+ "userId": user_id,
+ "isActive": True,
+ }
+ )
+
+ autopilot_block = await prisma.models.AgentBlock.prisma().find_unique(
+ where={"id": AUTOPILOT_BLOCK_ID}
+ )
+ assert autopilot_block is not None
+ other_blocks = await prisma.models.AgentBlock.prisma().find_many()
+ other_block = next(
+ block for block in other_blocks if block.id != AUTOPILOT_BLOCK_ID
+ )
+
+ async def seed(block_id: str, constant_input: dict) -> str:
+ node = await prisma.models.AgentNode.prisma().create(
+ data={
+ "agentBlockId": block_id,
+ "agentGraphId": graph_id,
+ "agentGraphVersion": 1,
+ "constantInput": prisma.Json(constant_input),
+ }
+ )
+ return node.id
+
+ try:
+ matching = await seed(
+ AUTOPILOT_BLOCK_ID,
+ {"codex_credentials": {"id": "cred-1"}},
+ )
+ already_migrated = await seed(
+ AUTOPILOT_BLOCK_ID,
+ {
+ "transport": "platform",
+ "codex_credentials": {"id": "cred-2"},
+ },
+ )
+ null_transport = await seed(
+ AUTOPILOT_BLOCK_ID,
+ {
+ "transport": None,
+ "codex_credentials": {"id": "cred-null"},
+ },
+ )
+ idless = await seed(
+ AUTOPILOT_BLOCK_ID,
+ {"codex_credentials": {"provider": "codex", "type": "oauth2"}},
+ )
+ other = await seed(
+ other_block.id,
+ {"codex_credentials": {"id": "cred-3"}},
+ )
+
+ assert await migrate_autopilot_transport(apply=True) == 2
+ assert await migrate_autopilot_transport(apply=True) == 0
+
+ async def constant_input(node_id: str) -> dict:
+ node = await prisma.models.AgentNode.prisma().find_unique(
+ where={"id": node_id}
+ )
+ assert node is not None
+ return dict(node.constantInput or {})
+
+ assert (await constant_input(matching))["transport"] == "codex_app_server"
+ assert (await constant_input(null_transport))["transport"] == "codex_app_server"
+ assert (await constant_input(already_migrated))["transport"] == "platform"
+ assert "transport" not in await constant_input(idless)
+ assert "transport" not in await constant_input(other)
+ finally:
+ await prisma.models.AgentGraph.prisma().delete_many(where={"id": graph_id})
+ await prisma.models.User.prisma().delete_many(where={"id": user_id})
+
+
+def test_query_templates_survive_schema_formatting():
+ """These templates are run through str.format() to inject the schema
+ prefix, so any literal brace becomes a format field. A '{transport}'
+ jsonb_set path raised KeyError at apply time — the second way this
+ migration crashed only when actually run."""
+ from backend.data.autopilot_migrate import _COUNT_QUERY, _UPDATE_QUERY
+
+ for template in (_COUNT_QUERY, _UPDATE_QUERY):
+ template.format(schema_prefix="platform.", schema="platform")
diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.py
index e3c3aa7225..b94231ed3e 100644
--- a/autogpt_platform/backend/backend/data/graph.py
+++ b/autogpt_platform/backend/backend/data/graph.py
@@ -642,6 +642,23 @@ class GraphModel(Graph, GraphMeta):
node_credential_data.append((field_info, (node.id, field_name)))
continue
+ # A selection that needs no credential contributes no slot.
+ # Discriminating on it would raise, and this runs inside a
+ # computed_field where that breaks schema generation for
+ # the whole graph.
+ #
+ # Only for an optional field. A *required* credential whose
+ # discriminator maps to nothing is not "credit-funded", it
+ # is broken — a node pinned to a since-removed LLM model
+ # lands here, and `discriminate()` raising is what produces
+ # the actionable "Model 'X' is not supported. It may have
+ # been deprecated." Skipping instead would drop the slot
+ # silently and the run form would never ask for the key.
+ if field_name not in block_required and not (
+ field_info.requires_credentials(discriminator_value)
+ ):
+ continue
+
discriminated_info = field_info.discriminate(discriminator_value)
discriminated_info.discriminator_values.add(discriminator_value)
@@ -1037,22 +1054,39 @@ class GraphModel(Graph, GraphMeta):
if for_run:
dependencies.extend(field_json_schema.get("depends_on", []))
- # Require presence of credentials discriminator (always).
+ field_is_required = field_name in required_fields
+
+ # Require presence of credentials discriminator.
# The `discriminator` is either the name of a sibling field (str),
# or an object that discriminates between possible types for this field:
# {"propertyName": prop_name, "mapping": {prop_value: sub_schema}}
+ #
+ # Skipped only when both the credentials field and the
+ # discriminator are optional, which is exactly the shape of a
+ # node saved before the discriminator was added: it carries a
+ # credential and no discriminator value. Erroring on it made
+ # every such graph unsaveable, unrunnable and unimportable —
+ # naming a field their exported JSON does not contain — while
+ # the block itself already defines what "unset" means.
+ #
+ # `has_value` treats any field with a schema default as set
+ # (a required field's default is `PydanticUndefined`, which is
+ # not None), so in practice this check only ever fires for a
+ # discriminator declared `default=None`. The kept branch is
+ # therefore defensive: a *required* credential whose provider
+ # cannot be determined is unresolvable, and no block declares
+ # that shape today.
if (
- discriminator := field_json_schema.get("discriminator")
- ) and isinstance(discriminator, str):
+ (discriminator := field_json_schema.get("discriminator"))
+ and isinstance(discriminator, str)
+ and (field_is_required or discriminator in required_fields)
+ ):
dependencies.append(discriminator)
if not dependencies:
continue
- # Check if dependent field has value in input_default
field_has_value = has_value(node, field_name)
- field_is_required = field_name in required_fields
-
# Check for missing dependencies when dependent field is present
missing_deps = [dep for dep in dependencies if not has_value(node, dep)]
if missing_deps and (field_has_value or field_is_required):
diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.py
index 0bee8331c4..29c7f47301 100644
--- a/autogpt_platform/backend/backend/data/graph_test.py
+++ b/autogpt_platform/backend/backend/data/graph_test.py
@@ -11,6 +11,7 @@ from pytest_snapshot.plugin import Snapshot
import backend.api.features.store.model as store
from backend.api.model import CreateGraph
from backend.blocks._base import BlockSchema, BlockSchemaInput
+from backend.blocks.autopilot import AUTOPILOT_BLOCK_ID, AutoPilotTransport
from backend.blocks.basic import StoreValueBlock
from backend.blocks.code_executor import ExecuteCodeBlock
from backend.blocks.io import AgentInputBlock, AgentOutputBlock
@@ -2393,7 +2394,7 @@ async def test_get_graph_without_org_keeps_strict_ownership(mocker):
# ============================================================================
CODEX_CODEGEN_BLOCK_ID = "86a2a099-30df-47b4-b7e4-34ae5f83e0d5"
-AUTOPILOT_BLOCK_ID = "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"
+AI_STRUCTURED_RESPONSE_BLOCK_ID = "ed55ac19-356e-4243-a6cb-bc599e9b716f"
def _graph_with(nodes: list[NodeModel]) -> GraphModel:
@@ -2616,3 +2617,137 @@ def test_graph_credential_slots_agree_with_executor_defaults():
"blocks failed to construct, so they were not covered by this guard: "
+ "; ".join(construction_failures)
)
+
+
+def test_unmapped_discriminator_value_contributes_no_credential():
+ """AutoPilot's `platform` transport is deliberately absent from
+ `discriminator_mapping` because it needs no credential. Discriminating on
+ it raises ("is not supported. It may have been deprecated"), and this runs
+ inside the `credentials_input_schema` computed_field — so an unguarded
+ call crashed schema generation for any graph containing a node saved with
+ the default transport."""
+ graph = _graph_with(
+ [
+ _node(
+ "n1",
+ AUTOPILOT_BLOCK_ID,
+ {"prompt": "hi", "transport": "platform"},
+ )
+ ]
+ )
+
+ slots = _slots(graph)
+
+ # The node asks for nothing, so it adds no credential slot at all.
+ assert slots == {}
+
+
+def test_unmapped_discriminator_on_a_required_credential_still_raises():
+ """The skip above is scoped to optional credentials fields on purpose.
+
+ A node pinned to a model since removed from the catalog also lands on an
+ unmapped discriminator value, but there the credential is required and the
+ node is simply broken. `discriminate()` raising is what surfaces the
+ actionable "may have been deprecated" message; skipping would drop the
+ slot silently, and the run form would never ask for the key.
+ """
+ graph = _graph_with(
+ [
+ _node(
+ "n1",
+ AI_STRUCTURED_RESPONSE_BLOCK_ID,
+ {"prompt": "hi", "model": "a-model-that-was-retired"},
+ )
+ ]
+ )
+
+ with pytest.raises(ValueError, match="may have been deprecated"):
+ _slots(graph)
+
+
+def test_mapped_discriminator_value_still_yields_its_slot():
+ graph = _graph_with(
+ [
+ _node(
+ "n1",
+ AUTOPILOT_BLOCK_ID,
+ {"prompt": "hi", "transport": "codex_app_server"},
+ )
+ ]
+ )
+
+ providers = {p for providers, _, _ in _slots(graph).values() for p in providers}
+
+ assert providers == {"codex"}
+
+
+# ============================================================================
+# Tests for the credentials-discriminator dependency check
+# (a node saved before a block gained a discriminator carries a credential
+# and no discriminator value — that shape must stay valid)
+# ============================================================================
+
+
+_LEGACY_CODEX_META = {
+ "id": "11111111-1111-1111-1111-111111111111",
+ "provider": "codex",
+ "type": "oauth2",
+ "title": "My ChatGPT",
+}
+
+
+def _autopilot_graph(input_default: dict) -> Graph:
+ """Build a 1-node AutoPilot graph with whatever input shape the test pins."""
+ node = Node(
+ id="00000000-0000-0000-0000-0000000000a1",
+ block_id=AUTOPILOT_BLOCK_ID,
+ input_default=input_default,
+ )
+ return Graph(
+ id="autopilot-graph",
+ name="Test",
+ description="Test",
+ nodes=[node],
+ links=[],
+ )
+
+
[email protected]("for_run", [False, True])
+def test_legacy_autopilot_node_without_transport_is_valid(for_run: bool):
+ """Every AutoPilot node saved before `transport` existed has a codex
+ connection and no transport. Making `codex_credentials` depend on
+ `transport` turned that shape into "Requires transport to be set" — a 400
+ on save *and* on execute, naming a field the user's exported JSON does not
+ contain. The startup backfill only repairs rows already in the database,
+ so imports and older API clients would have stayed broken permanently.
+
+ Both fields are optional, so "unset" is a legal state and the block
+ decides what it means (an attached connection is the choice).
+ """
+ graph = _autopilot_graph(
+ {"prompt": "do a thing", "codex_credentials": _LEGACY_CODEX_META}
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph, for_run=for_run)
+
+ assert errors.get(graph.nodes[0].id, {}) == {}, errors
+
+
+ "transport", [AutoPilotTransport.PLATFORM, AutoPilotTransport.CODEX_APP_SERVER]
+)
+def test_autopilot_node_with_an_explicit_transport_is_valid(
+ transport: AutoPilotTransport,
+):
+ """The migrated shape keeps validating, on both branches."""
+ graph = _autopilot_graph(
+ {
+ "prompt": "do a thing",
+ "transport": transport.value,
+ "codex_credentials": _LEGACY_CODEX_META,
+ }
+ )
+
+ errors = GraphModel._validate_graph_get_errors(graph, for_run=True)
+
+ assert errors.get(graph.nodes[0].id, {}) == {}, errors
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index b5edd3b0c4..714c9afe1c 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -737,6 +737,24 @@ class CredentialsFieldInfo(BaseModel, Generic[CP, CT]):
return result
+ def requires_credentials(self, discriminator_value: Any) -> bool:
+ """Whether this selection needs a credential at all.
+
+ A field may declare a discriminator value that maps to no provider,
+ meaning that choice is credential-free — AutoPilot's `platform`
+ transport runs on platform credits and needs nothing connected.
+
+ Callers must consult this before resolving, discriminating, or
+ enforcing entitlement on a field: `discriminate()` raises on an
+ unmapped value, and resolving a credential the selection will never
+ use can fail a run that was not going to touch that provider.
+ """
+ if not (self.discriminator and self.discriminator_mapping):
+ return True
+ if discriminator_value is None:
+ return True
+ return discriminator_value in self.discriminator_mapping
+
def discriminate(self, discriminator_value: Any) -> CredentialsFieldInfo:
if not (self.discriminator and self.discriminator_mapping):
return self
diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.py
index 646171e852..08126e9500 100644
--- a/autogpt_platform/backend/backend/executor/manager.py
+++ b/autogpt_platform/backend/backend/executor/manager.py
@@ -256,6 +256,23 @@ async def execute_node(
if node_block.disabled:
raise ValueError(f"Block {node_block.id} is disabled and cannot be executed")
+ input_model = cast(type[BlockSchema], node_block.input_schema)
+ credential_fields_info = input_model.get_credentials_fields_info()
+ required_credential_fields = set(input_model.get_required_fields())
+
+ # Remove optional credential metadata that the selected discriminator does
+ # not use before schema validation. Empty or stale objects would otherwise
+ # fail their nested credential schema before the executor can ignore them.
+ for field_name, field_info in credential_fields_info.items():
+ if not field_info.discriminator or field_name in required_credential_fields:
+ continue
+ discriminator_value = data.inputs.get(
+ field_info.discriminator,
+ node.input_default.get(field_info.discriminator),
+ )
+ if not field_info.requires_credentials(discriminator_value):
+ data.inputs[field_name] = None
+
# Sanity check: validate the execution input.
input_data, error = validate_exec(
node, data.inputs, resolve_input=False, dry_run=execution_context.dry_run
@@ -335,11 +352,8 @@ async def execute_node(
creds_locks: list[AsyncRedisLock] = []
credential_leases: dict[str, CredentialLease] = {}
runtime_credential_leases: dict[str, CredentialLease] = {}
- input_model = cast(type[BlockSchema], node_block.input_schema)
-
try:
# Handle regular credentials fields
- credential_fields_info = input_model.get_credentials_fields_info()
for field_name, input_type in input_model.get_credentials_fields().items():
# Dry-run platform credentials bypass the credential store.
# Keep the existing credential metadata so _execute's input_schema(**...)
@@ -369,7 +383,8 @@ async def execute_node(
# Write normalized values back so JSON schema validation also passes
# (model_validator may have fixed legacy formats like "ProviderName.MCP")
input_data[field_name] = credentials_meta.model_dump(mode="json")
- if credential_fields_info[field_name].credential_reference_only:
+ field_info = credential_fields_info[field_name]
+ if field_info.credential_reference_only:
credentials = await creds_manager.get(
user_id,
credentials_meta.id,
diff --git a/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py b/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py
index 5326b84dcc..87a2eaca9a 100644
--- a/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_credential_lease_test.py
@@ -9,6 +9,7 @@ from backend.copilot.rate_limit import UserPaywalledError
from backend.data.execution import ExecutionContext, NodeExecutionEntry
from backend.data.model import (
APIKeyCredentials,
+ CredentialsFieldInfo,
CredentialsMetaInput,
NodeExecutionStats,
OAuth2Credentials,
@@ -155,6 +156,128 @@ async def test_reference_only_credential_is_validated_without_outer_lease():
assert "credential_leases" not in captured
+def _discriminated_reference_block(
+ captured: dict[str, object],
+ *,
+ required: bool = False,
+) -> MagicMock:
+ block = _block_with_credentials(
+ {"codex_credentials": CodexCredentialsInput},
+ captured,
+ reference_only_fields={"codex_credentials"},
+ )
+ block.input_schema.get_credentials_fields_info.return_value = {
+ "codex_credentials": CredentialsFieldInfo(
+ credentials_provider=frozenset({ProviderName.CODEX}),
+ credentials_types=frozenset({"oauth2"}),
+ credential_reference_only=True,
+ discriminator="transport",
+ discriminator_mapping={"codex_app_server": ProviderName.CODEX},
+ )
+ }
+ block.input_schema.get_required_fields.return_value = (
+ {"codex_credentials"} if required else set()
+ )
+ return block
+
+
[email protected]("transport_in_defaults", [False, True])
+async def test_platform_transport_ignores_attached_codex_credential(
+ transport_in_defaults: bool,
+):
+ manager = MagicMock()
+ manager.get = AsyncMock()
+ manager.acquire_lease = AsyncMock()
+ captured: dict[str, Any] = {}
+ block = _discriminated_reference_block(captured)
+ gate = AsyncMock()
+ node = _node(block)
+ inputs: dict[str, object] = {"codex_credentials": _credential_metadata("cred-1")}
+ if transport_in_defaults:
+ node.input_default = {"transport": "platform"}
+ else:
+ inputs["transport"] = "platform"
+
+ validation = MagicMock(side_effect=lambda _node, inputs, **_kwargs: (inputs, None))
+ with (
+ patch("backend.executor.manager.enforce_codex_access", new=gate),
+ patch("backend.executor.manager.validate_exec", new=validation),
+ ):
+ outputs = [
+ item
+ async for item in execute_node(
+ node,
+ _entry(inputs),
+ SimpleNamespace(creds_manager=manager),
+ )
+ ]
+
+ assert outputs == [("response", "ok")]
+ assert validation.call_args.args[1]["codex_credentials"] is None
+ manager.get.assert_not_awaited()
+ manager.acquire_lease.assert_not_awaited()
+ gate.assert_not_awaited()
+ assert captured["input_data"]["codex_credentials"] is None
+ assert "codex_credentials" not in captured
+
+
[email protected]("transport", [None, "codex_app_server"])
+async def test_legacy_and_codex_transports_resolve_attached_codex_credential(
+ transport: str | None,
+):
+ credentials = _codex_credentials("cred-1")
+ manager = MagicMock()
+ manager.get = AsyncMock(return_value=credentials)
+ manager.acquire_lease = AsyncMock()
+ captured: dict[str, Any] = {}
+ block = _discriminated_reference_block(captured)
+ gate = AsyncMock()
+ inputs: dict[str, object] = {"codex_credentials": _credential_metadata("cred-1")}
+ if transport is not None:
+ inputs["transport"] = transport
+
+ with patch("backend.executor.manager.enforce_codex_access", new=gate):
+ outputs = [
+ item
+ async for item in execute_node(
+ _node(block),
+ _entry(inputs),
+ SimpleNamespace(creds_manager=manager),
+ )
+ ]
+
+ assert outputs == [("response", "ok")]
+ manager.get.assert_awaited_once_with("user-1", "cred-1")
+ gate.assert_awaited_once_with("user-1")
+ assert captured["input_data"]["codex_credentials"]["id"] == "cred-1"
+
+
+async def test_required_unmapped_credential_still_fails_closed():
+ manager = MagicMock()
+ manager.get = AsyncMock(return_value=None)
+ manager.acquire_lease = AsyncMock()
+ block = _discriminated_reference_block({}, required=True)
+
+ with pytest.raises(ValueError, match="Credentials #cred-1 .* not found"):
+ await anext(
+ execute_node(
+ _node(block),
+ _entry(
+ {
+ "transport": "platform",
+ "codex_credentials": _credential_metadata("cred-1"),
+ }
+ ),
+ SimpleNamespace(creds_manager=manager),
+ )
+ )
+
+ manager.get.assert_awaited_once_with("user-1", "cred-1")
+
+
@pytest.mark.asyncio
async def test_codex_credential_is_rejected_and_released_without_entitlement():
credentials = _codex_credentials("cred-1")
@@ -225,9 +348,15 @@ def _block_with_credentials(
reference_only_fields = reference_only_fields or set()
input_schema = MagicMock()
input_schema.get_credentials_fields.return_value = credential_fields
+ # A real `CredentialsFieldInfo`, not a stand-in carrying only the one
+ # attribute the test happens to need: `execute_node` reads whatever the
+ # field declares, so a partial fake fails with an AttributeError the moment
+ # the executor consults another one.
input_schema.get_credentials_fields_info.return_value = {
- field_name: SimpleNamespace(
- credential_reference_only=field_name in reference_only_fields
+ field_name: CredentialsFieldInfo(
+ credentials_provider=frozenset({ProviderName.CODEX}),
+ credentials_types=frozenset({"oauth2"}),
+ credential_reference_only=field_name in reference_only_fields,
)
for field_name in credential_fields
}
@@ -251,6 +380,7 @@ def _block_with_credentials(
def _node(block: MagicMock) -> MagicMock:
node = MagicMock()
node.block = block
+ node.input_default = {}
return node
diff --git a/autogpt_platform/backend/backend/usecases/sample.py b/autogpt_platform/backend/backend/usecases/sample.py
index 55859d29ed..591ae323e2 100644
--- a/autogpt_platform/backend/backend/usecases/sample.py
+++ b/autogpt_platform/backend/backend/usecases/sample.py
@@ -5,6 +5,7 @@ from backend.data import graph
from backend.data.graph import create_graph
from backend.data.model import User
from backend.data.user import get_or_create_user
+from backend.util.exceptions import DatabaseError
from backend.util.test import SpinTestServer, wait_execution
@@ -21,8 +22,13 @@ async def create_test_user(alt_user: bool = False) -> User:
"email": "[email protected]",
"name": "Test User",
}
- user = await get_or_create_user(test_user_data)
- return user
+ try:
+ return await get_or_create_user(test_user_data)
+ except DatabaseError as error:
+ if "Event loop is closed" not in str(error):
+ raise
+
+ return await get_or_create_user(test_user_data)
def create_test_graph() -> graph.Graph:
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/FormCreator.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/FormCreator.tsx
index a26a8d992e..82188051e3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/FormCreator.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/FormCreator.tsx
@@ -7,6 +7,8 @@ import { BlockUIType } from "../../types";
import { FormRenderer } from "@/components/renderers/InputRenderer/FormRenderer";
import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";
import { gateDiscriminatorOptions } from "@/components/renderers/InputRenderer/custom/CredentialField/gateDiscriminatorOptions";
+import { credentialNotApplicable } from "@/components/renderers/InputRenderer/custom/CredentialField/helpers";
+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";
function isCredentialsProperty(schema: RJSFSchema, key: string): boolean {
const property = schema.properties?.[key];
@@ -61,8 +63,23 @@ export const FormCreator: React.FC<FormCreatorProps> = React.memo(
// `*_credentials` while being ordinary values; a name test deleted them.
for (const key of Object.keys(formData)) {
if (!isCredentialsProperty(jsonSchema, key)) continue;
- const value = formData[key] as { id?: unknown } | undefined;
- if (!value?.id) {
+ const value = formData[key] as
+ | { id?: unknown; provider?: unknown }
+ | undefined;
+ // Also drop a credential the current selection no longer needs, or a
+ // connection chosen under one transport survives a switch to another
+ // that uses none — invisible, because its row is hidden.
+ const property = jsonSchema.properties?.[key];
+ const stale =
+ !jsonSchema.required?.includes(key) &&
+ typeof property === "object" &&
+ property !== null &&
+ credentialNotApplicable(
+ formData,
+ property as unknown as BlockIOCredentialsSubSchema,
+ typeof value?.provider === "string" ? value.provider : undefined,
+ );
+ if (!value?.id || stale) {
delete formData[key];
}
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/__tests__/FormCreator.credentials.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/__tests__/FormCreator.credentials.test.tsx
index c706568ec2..d1a93fae15 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/__tests__/FormCreator.credentials.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/__tests__/FormCreator.credentials.test.tsx
@@ -41,6 +41,24 @@ const autopilotSchema = {
required: ["prompt"],
} as unknown as RJSFSchema;
+const requiredUnmappedAutopilotSchema = {
+ ...autopilotSchema,
+ properties: {
+ ...autopilotSchema.properties,
+ transport: {
+ enum: ["platform", "codex_app_server"],
+ title: "Transport",
+ type: "string",
+ },
+ codex_credentials: {
+ ...(autopilotSchema.properties?.codex_credentials as RJSFSchema),
+ discriminator: "transport",
+ discriminator_mapping: { codex_app_server: "codex" },
+ },
+ },
+ required: ["prompt", "codex_credentials"],
+} as RJSFSchema;
+
function makeNode(schema: RJSFSchema): CustomNode {
return {
id: "autopilot-node",
@@ -134,14 +152,15 @@ describe("FormCreator credential emission", () => {
// Seeded as an initial value so the credential travels through FormCreator's
// handleChange — the same path that strips id-less objects. Writing straight
// to the store after render would bypass the code under test entirely.
- it("keeps a credential field once it carries an id", async () => {
+ it("keeps a required credential when its discriminator is unmapped", async () => {
useNodeStore.setState({
nodes: [
{
- ...makeNode(autopilotSchema),
+ ...makeNode(requiredUnmappedAutopilotSchema),
data: {
- ...makeNode(autopilotSchema).data,
+ ...makeNode(requiredUnmappedAutopilotSchema).data,
hardcodedValues: {
+ transport: "platform",
codex_credentials: {
id: "codex-oauth-1",
provider: "codex",
@@ -171,7 +190,7 @@ describe("FormCreator credential emission", () => {
})}
>
<FormCreator
- jsonSchema={autopilotSchema}
+ jsonSchema={requiredUnmappedAutopilotSchema}
nodeId="autopilot-node"
uiType={BlockUIType.STANDARD}
showHandles={false}
diff --git a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
index 93b8fac228..0639a17b7c 100644
--- a/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
+++ b/autogpt_platform/frontend/src/components/contextual/CredentialsInput/useCredentialsInput.ts
@@ -72,7 +72,11 @@ export function useCredentialsInput({
>(null);
const api = useBackendAPI();
- const credentials = useCredentials(schema, siblingInputs);
+ const credentials = useCredentials(
+ schema,
+ siblingInputs,
+ selectedCredential?.provider,
+ );
const hasAttemptedAutoSelect = useRef(false);
const oauthAbortRef = useRef<((reason?: string) => void) | null>(null);
const oauthFlowIdRef = useRef(0);
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx
index fddbaee9ca..a16b608a96 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/CodeGenerationTransport.test.tsx
@@ -376,6 +376,131 @@ describe("Transport options gated by provider entitlement", () => {
});
});
+describe("An optional discriminator is still gated", () => {
+ // `AutoPilotTransport | None` serialises as anyOf[{enum}, {type:null}] with no
+ // top-level enum. The filter used to require a top-level enum, so making a
+ // field optional silently switched the gate off and left the gated option on
+ // offer to accounts that cannot use it.
+ const optionalTransportSchema = {
+ type: "object",
+ properties: {
+ prompt: { advanced: false, title: "Prompt", type: "string" },
+ transport: {
+ advanced: false,
+ default: null,
+ title: "Transport",
+ anyOf: [
+ {
+ enum: ["platform", "codex_app_server"],
+ enumNames: ["AutoGPT Platform", "ChatGPT"],
+ type: "string",
+ },
+ { type: "null" },
+ ],
+ },
+ codex_credentials: {
+ credentials_provider: ["codex"],
+ credentials_types: ["oauth2"],
+ discriminator: "transport",
+ discriminator_mapping: { codex_app_server: "codex" },
+ properties: {
+ id: { type: "string" },
+ provider: { enum: ["codex"], type: "string" },
+ type: { enum: ["oauth2"], type: "string" },
+ },
+ required: ["id", "provider", "type"],
+ title: "Credentials",
+ type: "object",
+ },
+ },
+ required: ["prompt"],
+ } as RJSFSchema;
+
+ it("removes the gated option from inside anyOf", () => {
+ useNodeStore.setState({
+ nodes: [
+ {
+ ...createCodeGenerationNode(),
+ data: {
+ ...createCodeGenerationNode().data,
+ hardcodedValues: { prompt: "hi" },
+ inputSchema: optionalTransportSchema,
+ },
+ },
+ ],
+ nodeAdvancedStates: {},
+ });
+
+ render(
+ <CredentialsProvidersContext.Provider value={{}}>
+ <FormCreator
+ jsonSchema={optionalTransportSchema}
+ nodeId="code-generation-node"
+ uiType={BlockUIType.STANDARD}
+ showHandles={false}
+ />
+ </CredentialsProvidersContext.Provider>,
+ );
+
+ const select = screen.getByLabelText("agpt_%_transport");
+ const labels = Array.from(select.querySelectorAll("option")).map(
+ (o) => o.textContent,
+ );
+ expect(labels).toEqual(["AutoGPT Platform"]);
+ expect(screen.queryByText("credential")).toBeNull();
+ });
+
+ it("clears a hidden credential when switching to platform transport", async () => {
+ const node = createCodeGenerationNode();
+ useNodeStore.setState({
+ nodes: [
+ {
+ ...node,
+ data: {
+ ...node.data,
+ hardcodedValues: {
+ prompt: "hi",
+ transport: "codex_app_server",
+ codex_credentials: codexCredential,
+ },
+ inputSchema: optionalTransportSchema,
+ },
+ },
+ ],
+ nodeAdvancedStates: {},
+ });
+
+ render(
+ <CredentialsProvidersContext.Provider
+ value={{ codex: makeProvider("codex", "Codex", [codexCredential]) }}
+ >
+ <FormCreator
+ jsonSchema={optionalTransportSchema}
+ nodeId="code-generation-node"
+ uiType={BlockUIType.STANDARD}
+ showHandles={false}
+ />
+ </CredentialsProvidersContext.Provider>,
+ );
+
+ const select = screen.getByLabelText("agpt_%_transport");
+ const platform = Array.from(select.querySelectorAll("option")).find(
+ (option) => option.textContent === "AutoGPT Platform",
+ );
+ if (!platform) throw new Error("expected the platform transport option");
+
+ fireEvent.change(select, { target: { value: platform.value } });
+
+ await waitFor(() => {
+ const values = useNodeStore
+ .getState()
+ .getHardCodedValues("code-generation-node");
+ expect(values.transport).toBe("platform");
+ expect(values).not.toHaveProperty("codex_credentials");
+ });
+ });
+});
+
describe("LLM blocks keep every model option", () => {
const llmSchema = {
type: "object",
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx
index 3029eb98f4..3b7bd403fd 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx
@@ -2,7 +2,7 @@ import {
enumOptionsIndexForValue,
enumOptionsValueForIndex,
} from "@rjsf/utils";
-import type { EnumOptionsType, WidgetProps } from "@rjsf/utils";
+import type { EnumOptionsType, RJSFSchema, WidgetProps } from "@rjsf/utils";
import {
InputType,
mapJsonSchemaTypeToInputType,
@@ -17,6 +17,28 @@ import {
MultiSelectorTrigger,
} from "@/components/__legacy__/ui/multiselect";
+function isSchema(value: unknown): value is RJSFSchema {
+ return typeof value === "object" && value !== null;
+}
+
+function getEnumNames(schema: RJSFSchema) {
+ const candidates: unknown[] = [
+ schema,
+ ...(Array.isArray(schema.anyOf) ? schema.anyOf : []),
+ ...(Array.isArray(schema.oneOf) ? schema.oneOf : []),
+ ];
+ for (const candidate of candidates) {
+ if (isSchema(candidate) && Array.isArray(candidate.enumNames)) {
+ return candidate.enumNames;
+ }
+ }
+}
+
+function getFieldSchema(props: WidgetProps) {
+ const rootProperty = props.registry?.rootSchema?.properties?.[props.name];
+ return isSchema(rootProperty) ? rootProperty : props.schema;
+}
+
export function SelectWidget(props: WidgetProps) {
const {
options,
@@ -27,9 +49,31 @@ export function SelectWidget(props: WidgetProps) {
className,
id,
formContext,
+ label,
+ placeholder,
} = props;
const rawEnumOptions: EnumOptionsType[] = options.enumOptions || [];
- const enumOptions = rawEnumOptions.filter((option) => option.value !== "");
+ const fieldSchema = getFieldSchema(props);
+ const enumNames = getEnumNames(fieldSchema);
+ const uiTitle = props.uiSchema?.["ui:title"];
+ const resolvedLabel =
+ typeof uiTitle === "string"
+ ? uiTitle
+ : typeof fieldSchema.title === "string"
+ ? fieldSchema.title
+ : label;
+ const schemaPlaceholder =
+ typeof fieldSchema.placeholder === "string"
+ ? fieldSchema.placeholder
+ : undefined;
+ const labelledEnumOptions = rawEnumOptions.map((option, index) =>
+ Array.isArray(enumNames) && typeof enumNames[index] === "string"
+ ? { ...option, label: enumNames[index] }
+ : option,
+ );
+ const enumOptions = labelledEnumOptions.filter(
+ (option) => option.value !== "",
+ );
const droppedEmptyOptionCount = rawEnumOptions.length - enumOptions.length;
if (process.env.NODE_ENV === "development" && droppedEmptyOptionCount > 0) {
console.warn(
@@ -110,11 +154,12 @@ export function SelectWidget(props: WidgetProps) {
return (
<Select
- label=""
+ label={resolvedLabel}
+ placeholder={placeholder || schemaPlaceholder || "Select an option"}
id={id}
hideLabel={true}
disabled={disabled || readonly}
- size={selectSize as any}
+ size={selectSize}
value={selectedValue}
onValueChange={(newValue) =>
onChange(
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/__tests__/SelectWidget.test.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/__tests__/SelectWidget.test.tsx
index de8afc86f5..272e62eb55 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/__tests__/SelectWidget.test.tsx
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/__tests__/SelectWidget.test.tsx
@@ -5,8 +5,10 @@ import { render, screen } from "@/tests/integrations/test-utils";
import { SelectWidget } from "../SelectWidget";
interface SelectMockProps {
+ label?: string;
onValueChange?: (value: string) => void;
options?: unknown;
+ placeholder?: string;
value?: string;
}
@@ -123,6 +125,68 @@ describe("SelectWidget", () => {
});
});
+ it("forwards an accessible label and placeholder", () => {
+ render(
+ <SelectWidget
+ {...createProps({
+ label: "Transport",
+ placeholder: "Select a transport",
+ })}
+ />,
+ );
+
+ expect(selectSpy.mock.calls[0][0]).toMatchObject({
+ label: "Transport",
+ placeholder: "Select a transport",
+ });
+ });
+
+ it("uses top-level metadata for a nullable enum field", () => {
+ const enumSchema: WidgetProps["schema"] = {
+ type: "string",
+ enum: ["platform", "codex_app_server"],
+ enumNames: ["AutoGPT Platform", "ChatGPT"],
+ title: "AutoPilotTransport",
+ };
+ const transportSchema: WidgetProps["schema"] = {
+ anyOf: [enumSchema, { type: "null" }],
+ placeholder: "Select a transport",
+ title: "Transport",
+ };
+
+ render(
+ <SelectWidget
+ {...createProps({
+ name: "transport",
+ label: "AutoPilotTransport",
+ schema: enumSchema,
+ registry: {
+ ...createProps().registry,
+ rootSchema: {
+ type: "object",
+ properties: { transport: transportSchema },
+ },
+ },
+ options: {
+ enumOptions: [
+ { value: "platform", label: "platform" },
+ { value: "codex_app_server", label: "codex_app_server" },
+ ],
+ },
+ })}
+ />,
+ );
+
+ expect(selectSpy.mock.calls[0][0]).toMatchObject({
+ label: "Transport",
+ placeholder: "Select a transport",
+ options: [
+ { value: "0", label: "AutoGPT Platform" },
+ { value: "1", label: "ChatGPT" },
+ ],
+ });
+ });
+
it("preserves falsy non-empty values like 0", () => {
render(
<SelectWidget
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.tsx
index dd6de881a0..34edd1f50d 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
@@ -11,6 +11,7 @@ import { useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { CredentialFieldTitle } from "./components/CredentialFieldTitle";
import { useCredentialAvailability } from "./useCredentialAvailability";
+import { credentialNotApplicable } from "./helpers";
export const CredentialsField = (props: FieldProps) => {
const { formData, onChange, schema, registry, fieldPathId, required } = props;
@@ -38,7 +39,7 @@ export const CredentialsField = (props: FieldProps) => {
return typeof value === "boolean" ? value : false;
}, [node?.data?.metadata?.credentials_optional]);
- const handleChange = (newValue: any) => {
+ const handleChange = (newValue: unknown) => {
onChange(newValue, fieldPathId?.path);
};
@@ -78,9 +79,21 @@ export const CredentialsField = (props: FieldProps) => {
? !credentialsOptional && required
: required;
+ // Nothing to ask for: the selected discriminator value maps to no provider
+ // (AutoPilot's `platform` transport), so the row is not merely unavailable —
+ // it does not apply at all.
+ const notApplicable =
+ !required &&
+ credentialNotApplicable(
+ hardcodedValues,
+ schema as BlockIOCredentialsSubSchema,
+ selectedCredentials?.provider,
+ );
+
const availability = useCredentialAvailability(
schema as BlockIOCredentialsSubSchema,
hardcodedValues,
+ selectedCredentials?.provider,
);
const isUnavailable = availability === "unavailable";
@@ -92,6 +105,10 @@ export const CredentialsField = (props: FieldProps) => {
// node-level toggle also feeds that value, so turning "Optional" on for a
// required gated field would hide the row and the toggle along with it,
// leaving no way to turn it back off.
+ if (notApplicable) {
+ return null;
+ }
+
if (isUnavailable && !required) {
return null;
}
@@ -117,6 +134,7 @@ export const CredentialsField = (props: FieldProps) => {
uiOptions={uiOptions}
schema={schema}
required={isRequired}
+ selectedProvider={selectedCredentials?.provider}
/>
{availability === "unavailable" && (
<Text
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..d08434e61e
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/__tests__/helpers.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+import type { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";
+import {
+ credentialNotApplicable,
+ getCredentialProviderFromSchema,
+} from "../helpers";
+
+// AutoPilot's shape: one provider, but a discriminator whose `platform` value
+// is deliberately unmapped because that transport needs no credential.
+const autopilotSchema: BlockIOCredentialsSubSchema = {
+ type: "object",
+ properties: {},
+ credentials_provider: ["codex"],
+ credentials_types: ["oauth2"],
+ discriminator: "transport",
+ discriminator_mapping: { codex_app_server: "codex" },
+};
+
+// A plain single-provider field with no discriminator at all.
+const githubSchema: BlockIOCredentialsSubSchema = {
+ type: "object",
+ properties: {},
+ credentials_provider: ["github"],
+ credentials_types: ["api_key"],
+};
+
+describe("getCredentialProviderFromSchema", () => {
+ it("hides the input when a single-provider field's value is unmapped", () => {
+ // Regression: this returned "codex" regardless of the transport, so
+ // selecting `platform` still rendered — and auto-selected — a ChatGPT
+ // connection that the platform transport never uses.
+ expect(
+ getCredentialProviderFromSchema(
+ { transport: "platform" },
+ autopilotSchema,
+ ),
+ ).toBeNull();
+ });
+
+ it("resolves the provider when the value is mapped", () => {
+ expect(
+ getCredentialProviderFromSchema(
+ { transport: "codex_app_server" },
+ autopilotSchema,
+ ),
+ ).toBe("codex");
+ });
+
+ it("resolves a saved legacy credential when the discriminator is unset", () => {
+ expect(getCredentialProviderFromSchema({}, autopilotSchema, "codex")).toBe(
+ "codex",
+ );
+ });
+
+ it("still returns the lone provider when no discriminator is declared", () => {
+ expect(getCredentialProviderFromSchema({}, githubSchema)).toBe("github");
+ });
+});
+
+describe("credentialNotApplicable", () => {
+ it("is true when the selection maps to no provider", () => {
+ // AutoPilot's `platform`: needs no credential, so the row should not
+ // render at all — distinct from "unavailable" and from "still loading",
+ // which a bare null could not express.
+ expect(
+ credentialNotApplicable({ transport: "platform" }, autopilotSchema),
+ ).toBe(true);
+ });
+
+ it("is false when the selection maps to a provider", () => {
+ expect(
+ credentialNotApplicable(
+ { transport: "codex_app_server" },
+ autopilotSchema,
+ ),
+ ).toBe(false);
+ });
+
+ it("is true when neither a selection nor a legacy credential exists", () => {
+ expect(credentialNotApplicable({}, autopilotSchema)).toBe(true);
+ });
+
+ it("is false when a legacy node has a saved credential", () => {
+ expect(credentialNotApplicable({}, autopilotSchema, "codex")).toBe(false);
+ });
+
+ it("is false for a field with no discriminator at all", () => {
+ expect(credentialNotApplicable({}, githubSchema)).toBe(false);
+ });
+});
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.tsx
index b2f71b14ed..f9be6deab0 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
@@ -19,8 +19,16 @@ export const CredentialFieldTitle = (props: {
schema: RJSFSchema;
fieldPathId: FieldPathId;
required?: boolean;
+ selectedProvider?: string;
}) => {
- const { registry, uiOptions, schema, fieldPathId, required = false } = props;
+ const {
+ registry,
+ uiOptions,
+ schema,
+ fieldPathId,
+ required = false,
+ selectedProvider,
+ } = props;
const { nodeId } = registry.formContext;
const TitleFieldTemplate = getTemplate(
@@ -38,6 +46,7 @@ export const CredentialFieldTitle = (props: {
const provider = getCredentialProviderFromSchema(
useNodeStore.getState().getHardCodedValues(nodeId),
schema as BlockIOCredentialsSubSchema,
+ selectedProvider,
);
const credentialProvider = provider
? `${toDisplayName(provider)} credential`
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/gateDiscriminatorOptions.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/gateDiscriminatorOptions.ts
index cc7b546fc8..fb46382f70 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/gateDiscriminatorOptions.ts
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/gateDiscriminatorOptions.ts
@@ -40,27 +40,28 @@ export function gateDiscriminatorOptions(
for (const [fieldName, blocked] of blockedByField) {
const fieldSchema = properties[fieldName];
- if (!isRecord(fieldSchema) || !Array.isArray(fieldSchema.enum)) continue;
+ if (!isRecord(fieldSchema)) continue;
const saved = currentValues[fieldName];
const fallback = fieldSchema.default;
- const kept = fieldSchema.enum.filter(
- (option) =>
+ const keep = (option: unknown) => {
+ // Never drop the value a graph is already saved with; hiding it would
+ // silently rewrite the node on the next change. Nor the schema's own
+ // default, which RJSF falls back to when the node has no saved value —
+ // filtering it out leaves a select whose selection is not in its
+ // options. Compared as strings to match `blocked`, so a numeric enum
+ // and a string-typed saved value still line up.
+ return (
!blocked.has(String(option)) ||
- // Never drop the value a graph is already saved with; hiding it would
- // silently rewrite the node on the next change. Nor the schema's own
- // default, which RJSF falls back to when the node has no saved value —
- // filtering it out leaves a select whose selection is not in its
- // options. Compared as strings to match `blocked`, so a numeric enum
- // and a string-typed saved value still line up.
(saved !== undefined && String(option) === String(saved)) ||
- (fallback !== undefined && String(option) === String(fallback)),
- );
- if (kept.length === fieldSchema.enum.length) continue;
- // An empty dropdown is worse than an unusable option.
- if (kept.length === 0) continue;
+ (fallback !== undefined && String(option) === String(fallback))
+ );
+ };
- gatedProperties[fieldName] = { ...fieldSchema, enum: kept };
+ const gated = gateEnumNode(fieldSchema, keep);
+ if (!gated) continue;
+
+ gatedProperties[fieldName] = gated;
changed = true;
}
@@ -92,6 +93,52 @@ function collectBlockedValues(
return blockedByField;
}
+/**
+ * Filter a field's enum, returning null when nothing changed.
+ *
+ * An optional enum serialises as `anyOf: [{enum: [...]}, {type: "null"}]` with
+ * no top-level `enum` — making a field optional would otherwise silently switch
+ * the gate off, leaving a gated option on offer.
+ */
+function gateEnumNode(
+ fieldSchema: Record<string, unknown>,
+ keep: (option: unknown) => boolean,
+): Record<string, unknown> | null {
+ const enumValues = fieldSchema.enum;
+ if (Array.isArray(enumValues)) {
+ const keptIndexes = enumValues.flatMap((option, index) =>
+ keep(option) ? [index] : [],
+ );
+ if (keptIndexes.length === enumValues.length) return null;
+ // An empty dropdown is worse than an unusable option.
+ if (keptIndexes.length === 0) return null;
+
+ const originalEnumNames = fieldSchema.enumNames;
+ const enumNames = Array.isArray(originalEnumNames)
+ ? keptIndexes.map((index) => originalEnumNames[index])
+ : undefined;
+ return {
+ ...fieldSchema,
+ enum: keptIndexes.map((index) => enumValues[index]),
+ ...(enumNames ? { enumNames } : {}),
+ };
+ }
+
+ if (Array.isArray(fieldSchema.anyOf)) {
+ let branchChanged = false;
+ const branches = fieldSchema.anyOf.map((branch) => {
+ if (!isRecord(branch)) return branch;
+ const gated = gateEnumNode(branch, keep);
+ if (!gated) return branch;
+ branchChanged = true;
+ return gated;
+ });
+ return branchChanged ? { ...fieldSchema, anyOf: branches } : null;
+ }
+
+ return null;
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts
index 090959953e..08a3ca0dc0 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/helpers.ts
@@ -83,7 +83,7 @@ export function toDisplayName(provider: string): string {
.join(" ");
}
-export function isCredentialFieldSchema(schema: any): boolean {
+export function isCredentialFieldSchema(schema: unknown): boolean {
return (
typeof schema === "object" &&
schema !== null &&
@@ -134,21 +134,24 @@ export const providerIcons: Partial<Record<string, IconSvgElement>> = {
};
export const getDiscriminatorValue = (
- formData: Record<string, any>,
+ formData: Record<string, unknown>,
schema: BlockIOCredentialsSubSchema,
): string | undefined => {
const discriminator = schema.discriminator;
const discriminatorValues = schema.discriminator_values;
- return [
+ const value = [
discriminator ? formData[discriminator] : null,
...(discriminatorValues || []),
].find(Boolean);
+
+ return value === undefined || value === null ? undefined : String(value);
};
export const getCredentialProviderFromSchema = (
- formData: Record<string, any>,
+ formData: Record<string, unknown>,
schema: BlockIOCredentialsSubSchema,
+ selectedProvider?: string,
) => {
const discriminator = schema.discriminator;
const discriminatorMapping = schema.discriminator_mapping;
@@ -160,6 +163,15 @@ export const getCredentialProviderFromSchema = (
? discriminatorMapping[discriminatorValue ?? ""]
: null;
+ const legacySelectedProvider = providers.find(
+ (provider) =>
+ discriminator &&
+ discriminatorMapping &&
+ discriminatorValue === undefined &&
+ provider === selectedProvider,
+ );
+ if (legacySelectedProvider) return legacySelectedProvider;
+
if (providers.length > 1) {
if (!discriminator) {
throw new Error(
@@ -174,7 +186,36 @@ export const getCredentialProviderFromSchema = (
return null;
}
return discriminatedProvider;
- } else {
- return providers[0];
}
+
+ // Single-provider fields used to return their one provider unconditionally,
+ // ignoring the discriminator. That is wrong when a field declares a mapping:
+ // an unmapped value means "this choice needs no credential" — AutoPilot's
+ // `platform` transport, which is deliberately absent from the mapping — and
+ // the input must hide rather than ask for a credential nothing will use.
+ if (discriminator && discriminatorMapping) {
+ return discriminatedProvider ?? null;
+ }
+
+ return providers[0];
+};
+
+/**
+ * True when the field has no usable credential route for the current state.
+ *
+ * An unmapped value needs no credential. An unset discriminator also has no
+ * actionable control unless a saved provider identifies a legacy selection.
+ */
+export const credentialNotApplicable = (
+ formData: Record<string, unknown>,
+ schema: BlockIOCredentialsSubSchema,
+ selectedProvider?: string,
+): boolean => {
+ const mapping = schema.discriminator_mapping;
+ if (!schema.discriminator || !mapping) return false;
+
+ const value = getDiscriminatorValue(formData, schema);
+ if (value === undefined || value === null) return !selectedProvider;
+
+ return !Object.hasOwn(mapping, String(value));
};
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/useCredentialAvailability.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/useCredentialAvailability.ts
index 191941d2ff..2cdd995508 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/useCredentialAvailability.ts
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/useCredentialAvailability.ts
@@ -18,9 +18,14 @@ type Availability = "loading" | "available" | "unavailable";
export function useCredentialAvailability(
schema: BlockIOCredentialsSubSchema,
formData: Record<string, unknown>,
+ selectedProvider?: string,
): Availability {
const providers = useContext(CredentialsProvidersContext);
- const provider = getCredentialProviderFromSchema(formData, schema);
+ const provider = getCredentialProviderFromSchema(
+ formData,
+ schema,
+ selectedProvider,
+ );
if (providers === null) return "loading";
// A multi-provider field with no discriminator value yet resolves to null;
diff --git a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts
index 557e4b866a..0a8181de54 100644
--- a/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts
+++ b/autogpt_platform/frontend/src/hooks/__tests__/useCredentials.test.ts
@@ -98,6 +98,42 @@ describe("deriveAuthMethods", () => {
});
describe("useCredentials provider list", () => {
+ it("resolves a saved credential on a legacy node with no discriminator", () => {
+ const savedCredential = {
+ id: "codex-1",
+ provider: "codex",
+ type: "oauth2" as const,
+ title: "ChatGPT for Codex",
+ };
+ const provider = {
+ provider: "codex",
+ providerName: "Codex",
+ savedCredentials: [savedCredential],
+ isSystemProvider: false,
+ oAuthCallback: vi.fn(),
+ mcpOAuthCallback: vi.fn(),
+ createAPIKeyCredentials: vi.fn(),
+ createUserPasswordCredentials: vi.fn(),
+ createHostScopedCredentials: vi.fn(),
+ deleteCredentials: vi.fn(),
+ } satisfies CredentialsProviderData;
+
+ const { result } = renderHook(
+ () => useCredentials(schema, {}, savedCredential.provider),
+ {
+ wrapper: ({ children }: { children: React.ReactNode }) =>
+ React.createElement(
+ CredentialsProvidersContext.Provider,
+ { value: { codex: provider } },
+ children,
+ ),
+ },
+ );
+
+ expect(result.current?.provider).toBe("codex");
+ expect(result.current?.savedCredentials).toEqual([savedCredential]);
+ });
+
it("exposes the unfiltered provider credentials alongside the filtered ones", async () => {
const oauthOnly = {
id: "codex-1",
diff --git a/autogpt_platform/frontend/src/hooks/useCredentials.ts b/autogpt_platform/frontend/src/hooks/useCredentials.ts
index a41b26410e..7886568ea7 100644
--- a/autogpt_platform/frontend/src/hooks/useCredentials.ts
+++ b/autogpt_platform/frontend/src/hooks/useCredentials.ts
@@ -1,5 +1,4 @@
import { useContext } from "react";
-import { getValue } from "@/lib/utils";
import {
CredentialsProviderData,
@@ -8,10 +7,13 @@ import {
import {
BlockIOCredentialsSubSchema,
CredentialsMetaResponse,
- CredentialsProviderName,
CredentialsType,
} from "@/lib/autogpt-server-api";
import { getHostFromUrl } from "@/lib/utils/url";
+import {
+ getCredentialProviderFromSchema,
+ getDiscriminatorValue,
+} from "@/components/renderers/InputRenderer/custom/CredentialField/helpers";
export function classifyCredentials(
allSaved: readonly CredentialsMetaResponse[],
@@ -122,46 +124,21 @@ export function getConnectableCredentialTypes(
export default function useCredentials(
credsInputSchema: BlockIOCredentialsSubSchema,
- nodeInputValues?: Record<string, any>,
+ nodeInputValues?: Record<string, unknown>,
+ selectedProvider?: string,
): CredentialsData | null {
const allProviders = useContext(CredentialsProvidersContext);
- const discriminatorValue = [
- credsInputSchema.discriminator
- ? getValue(credsInputSchema.discriminator, nodeInputValues)
- : null,
- ...(credsInputSchema.discriminator_values || []),
- ].find(Boolean);
-
- const discriminatedProvider = credsInputSchema.discriminator_mapping
- ? credsInputSchema.discriminator_mapping[discriminatorValue]
- : null;
-
- let providerName: CredentialsProviderName;
- if (credsInputSchema.credentials_provider.length > 1) {
- if (!credsInputSchema.discriminator) {
- throw new Error(
- "Multi-provider credential input requires discriminator!",
- );
- }
- if (!discriminatedProvider) {
- console.warn(
- `Missing discriminator value from '${credsInputSchema.discriminator}': ` +
- "hiding credentials input until it is set.",
- );
- return null;
- }
- providerName = discriminatedProvider;
- } else {
- providerName = credsInputSchema.credentials_provider[0];
- }
+ const inputs = nodeInputValues ?? {};
+ const discriminatorValue = getDiscriminatorValue(inputs, credsInputSchema);
+ const providerName = getCredentialProviderFromSchema(
+ inputs,
+ credsInputSchema,
+ selectedProvider,
+ );
+ if (!providerName) return null;
const provider = allProviders ? allProviders[providerName] : null;
- // If block input schema doesn't have credentials, return null
- if (!credsInputSchema) {
- return null;
- }
-
const supportedTypes = getSupportedCredentialTypes(
credsInputSchema,
discriminatorValue,
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index 31a90f0804..138eb16470 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -56,6 +56,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
|-------|-------------|------|----------|
| prompt | The task or instruction for the autopilot to execute. The autopilot has access to platform tools like agent management, workspace files, web fetch, block execution, and more. | str | Yes |
| 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 |
+| transport | Run on platform credits, or on your connected ChatGPT subscription if supported by your plan. | "platform" \| "codex_app_server" | 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" \| "ask_question" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "enter_agent_building_mode" \| "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_chat_platform_channels" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "post_to_chat_platform" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |