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.
fix(platform): stop codex transport reaching non-entitled users (#14058)
Nicholas Tindle4409613ecf36
diff --git a/autogpt_platform/backend/backend/blocks/codex.py b/autogpt_platform/backend/backend/blocks/codex.pyindex cd7f064362..4630e1a7f0 100644--- a/autogpt_platform/backend/backend/blocks/codex.py+++ b/autogpt_platform/backend/backend/blocks/codex.py@@ -147,8 +147,8 @@ class CodeGenerationBlock(Block):title="Transport",default=CodexExecutionTransport.OPENAI_API,description=(- "Use an OpenAI API key or your connected ChatGPT plan through "- "Codex App Server."+ "Use an OpenAI API key, or your connected ChatGPT subscription "+ "through Codex App Server if supported by your plan."),advanced=False,)diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex c13e520625..e3c3aa7225 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -389,6 +389,33 @@ class GraphMeta(GraphBaseMeta):)+def _mappable_discriminator_default(+ input_schema: "AnyBlockSchema",+ field_info: CredentialsFieldInfo,+) -> Any:+ """The discriminator's schema default, or None if it can't discriminate.++ Read from the serialized schema rather than the model field so the value is+ a plain JSON scalar matching `discriminator_mapping` keys instead of a+ Python enum member. Returns None unless the default is actually present in+ the mapping, because `discriminate()` raises on unknown values and this+ runs inside a computed_field where raising would break schema generation.+ """+ discriminator = field_info.discriminator+ mapping = field_info.discriminator_mapping+ if not discriminator or not mapping:+ return None++ # `.get`, not indexing: a schema with no properties at all would raise+ # here, and this runs inside a computed_field where that breaks schema+ # generation for the whole graph — the failure mode this helper's+ # None-returning contract exists to avoid.+ properties = input_schema.jsonschema().get("properties", {})+ field_schema = properties.get(discriminator, {})+ default = field_schema.get("default")+ return default if default in mapping else None++class GraphModel(Graph, GraphMeta):"""Full graph model representing an existing graph from the database.@@ -552,6 +579,11 @@ class GraphModel(Graph, GraphMeta):node_required_map: dict[str, bool] = {} # node_id -> is_requiredfor graph in [self] + self.sub_graphs:+ linked_inputs = {+ (link.sink_id, sanitize_pin_name(link.sink_name))+ for link in graph.links+ }+for node in graph.nodes:# A node's credentials are optional if either:# 1. The node metadata says so (credentials_optional=True), or@@ -574,7 +606,38 @@ class GraphModel(Graph, GraphMeta):node_credential_data.append((field_info, (node.id, field_name)))continue- discriminator_value = node.input_default.get(discriminator)+ discriminator_is_linked = (+ node.id,+ sanitize_pin_name(discriminator),+ ) in linked_inputs+ # An upstream link overrides the saved/default value at+ # runtime, so its value is unknown during aggregation.+ discriminator_value = (+ None+ if discriminator_is_linked+ else node.input_default.get(discriminator)+ )+ if (+ discriminator_value is None+ and field_info.discriminator_type_mapping+ and not discriminator_is_linked+ ):+ # The node hasn't pinned the discriminator, but the+ # executor will: it builds `input_schema(**input_default)`,+ # so pydantic fills the schema default. Resolve it the+ # same way here.+ #+ # Only when the credential TYPE depends on the+ # discriminator. There the un-discriminated union is a+ # cross-product that asserts pairs which don't exist+ # (e.g. codex+api_key, openai+oauth2). For mapping-only+ # discriminators the type set is a singleton, so the+ # union is faithful and is left alone — its slot key is+ # what persisted preset/schedule credentials are keyed by.+ discriminator_value = _mappable_discriminator_default(+ node.block.input_schema, field_info+ )+if discriminator_value is None:node_credential_data.append((field_info, (node.id, field_name)))continuediff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.pyindex 9c303564fc..0bee8331c4 100644--- a/autogpt_platform/backend/backend/data/graph_test.py+++ b/autogpt_platform/backend/backend/data/graph_test.py@@ -2373,3 +2373,246 @@ async def test_get_graph_without_org_keeps_strict_ownership(mocker):where = mock_client.find_first.call_args.kwargs["where"]assert where["userId"] == "u-1"assert "AND" not in where+++# ============================================================================+# Tests for discriminated credentials aggregation (codex transport hotfix)+#+# A node that has not pinned its discriminator still resolves it at execution+# time: blocks/_base.py builds `self.input_schema(**input_default)`, so pydantic+# fills the schema default. Aggregation must resolve it the same way, or the+# graph advertises credentials the node can never actually use.+#+# The fallback is scoped to fields whose credential TYPE depends on the+# discriminator (discriminator_type_mapping). For those, the un-discriminated+# union is a cross-product that asserts invalid pairs — e.g. (codex, api_key)+# and (openai, oauth2) — neither of which exists. For mapping-only+# discriminators the type set is a singleton, so the union is faithful and is+# deliberately left alone: its aggregated slot key is load-bearing for+# persisted preset and schedule credentials.+# ============================================================================++CODEX_CODEGEN_BLOCK_ID = "86a2a099-30df-47b4-b7e4-34ae5f83e0d5"+AUTOPILOT_BLOCK_ID = "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6"+++def _graph_with(nodes: list[NodeModel]) -> GraphModel:+ from datetime import datetime, timezone++ return GraphModel(+ id="agg-graph",+ version=1,+ name="Aggregation",+ description="",+ user_id="u-1",+ created_at=datetime.now(timezone.utc),+ nodes=nodes,+ links=[],+ )+++def _node(node_id: str, block_id: str, input_default: dict[str, Any]) -> NodeModel:+ return NodeModel(+ id=node_id,+ block_id=block_id,+ input_default=input_default,+ graph_id="agg-graph",+ graph_version=1,+ )+++def _slots(graph: GraphModel) -> dict[str, tuple[set[str], set[str], bool]]:+ schema = graph.credentials_input_schema+ required = set(schema["required"])+ return {+ key: (+ {getattr(p, "value", p) for p in prop["credentials_provider"]},+ set(prop["credentials_types"]),+ key in required,+ )+ for key, prop in schema["properties"].items()+ }+++def test_codegen_without_transport_resolves_to_schema_default():+ """The discriminator defaults to openai_api, so the slot must be OpenAI+ only. Advertising codex here let a non-entitled user see a required+ credential for a plan-gated provider they cannot connect."""+ graph = _graph_with([_node("n1", CODEX_CODEGEN_BLOCK_ID, {"prompt": "hi"})])++ assert _slots(graph) == {+ "openai_api_key_credentials": ({"openai"}, {"api_key"}, True)+ }+++def test_codegen_with_linked_transport_does_not_assume_schema_default():+ graph = _graph_with([_node("n1", CODEX_CODEGEN_BLOCK_ID, {"prompt": "hi"})])+ graph.links = [+ Link(+ source_id="source",+ sink_id="n1",+ source_name="value",+ sink_name="transport",+ )+ ]++ assert _slots(graph) == {+ "codex-openai_api_key-oauth2_credentials": (+ {"codex", "openai"},+ {"api_key", "oauth2"},+ True,+ )+ }+++def test_codegen_with_explicit_openai_transport_matches_default_case():+ graph = _graph_with(+ [+ _node(+ "n1",+ CODEX_CODEGEN_BLOCK_ID,+ {"prompt": "hi", "transport": "openai_api"},+ )+ ]+ )++ assert _slots(graph) == {+ "openai_api_key_credentials": ({"openai"}, {"api_key"}, True)+ }+++def test_codegen_with_codex_transport_yields_codex_slot():+ graph = _graph_with(+ [+ _node(+ "n1",+ CODEX_CODEGEN_BLOCK_ID,+ {"prompt": "hi", "transport": "codex_app_server"},+ )+ ]+ )++ assert _slots(graph) == {"codex_oauth2_credentials": ({"codex"}, {"oauth2"}, True)}+++def test_autopilot_codex_credentials_slot_is_not_required():+ """AutoPilot's codex_credentials declares default=None, so the graph must+ not demand it — the block falls back to the platform transport."""+ graph = _graph_with([_node("n1", AUTOPILOT_BLOCK_ID, {"prompt": "hi"})])++ assert _slots(graph) == {"codex_oauth2_credentials": ({"codex"}, {"oauth2"}, False)}+++def test_codex_transport_node_merges_with_autopilot_codex_slot():+ """Both resolve to (codex, oauth2), so they share one slot instead of+ presenting the user two separate codex rows."""+ graph = _graph_with(+ [+ _node("n1", AUTOPILOT_BLOCK_ID, {"prompt": "hi"}),+ _node(+ "n2",+ CODEX_CODEGEN_BLOCK_ID,+ {"prompt": "hi", "transport": "codex_app_server"},+ ),+ ]+ )++ slots = _slots(graph)+ assert list(slots) == ["codex_oauth2_credentials"]+ # Required because the CodeGen node requires it, even though AutoPilot's is optional.+ assert slots["codex_oauth2_credentials"] == ({"codex"}, {"oauth2"}, True)+++def test_llm_block_union_is_left_intact_without_model():+ """Regression guard: mapping-only discriminators keep their union slot key.+ Persisted preset/schedule credentials are keyed by this name, so collapsing+ it would silently orphan them."""+ from backend.blocks.llm import AITextGeneratorBlock++ graph = _graph_with([_node("n1", AITextGeneratorBlock().id, {"prompt": "hi"})])++ slots = _slots(graph)+ assert list(slots) == [+ "aiml_api-anthropic-groq-llama_api-ollama-open_router-openai-v0_api_key_credentials"+ ]+ providers, types, required = slots[list(slots)[0]]+ assert len(providers) == 8+ assert types == {"api_key"}+ assert required is True+++def test_llm_block_with_model_discriminates_normally():+ from backend.blocks.llm import AITextGeneratorBlock++ graph = _graph_with(+ [_node("n1", AITextGeneratorBlock().id, {"prompt": "hi", "model": "gpt-4o"})]+ )++ assert _slots(graph) == {+ "openai_api_key_credentials": ({"openai"}, {"api_key"}, True)+ }+++def test_only_known_blocks_use_discriminator_type_mapping():+ """Guard on the fallback's trigger condition. If a new block adds+ discriminator_type_mapping, it silently inherits schema-default+ discrimination — this test forces that to be a conscious decision."""+ from backend.blocks import load_all_blocks++ users = set()+ construction_failures: list[str] = []+ for block_cls in load_all_blocks().values():+ try:+ block = block_cls()+ except Exception as e:+ # Never skip silently: an excluded block is one this guard did not+ # actually check, so the assertion below could pass while a new+ # block quietly adopts schema-default discrimination.+ construction_failures.append(f"{block_cls.__name__}: {e!r}")+ continue+ rendered = block.input_schema.get_credentials_fields()+ for name, info in block.input_schema.get_credentials_fields_info().items():+ if name in rendered and info.discriminator_type_mapping:+ users.add((block.name, name))++ assert not construction_failures, (+ "blocks failed to construct, so they were not covered by this guard: "+ + "; ".join(construction_failures)+ )+ assert users == {("CodeGenerationBlock", "credentials")}+++def test_graph_credential_slots_agree_with_executor_defaults():+ """The graph schema must not advertise a provider the executor cannot+ select. For every discriminated credentials field, the providers offered+ for an unpinned node must be reachable from the block's own default."""+ from backend.blocks import load_all_blocks++ construction_failures: list[str] = []+ for block_cls in load_all_blocks().values():+ try:+ block = block_cls()+ except Exception as e:+ construction_failures.append(f"{block_cls.__name__}: {e!r}")+ continue+ rendered = block.input_schema.get_credentials_fields()+ info = block.input_schema.get_credentials_fields_info()+ for name in rendered:+ field = info[name]+ if not field.discriminator_type_mapping:+ continue+ default = block.input_schema.jsonschema()["properties"][+ field.discriminator+ ].get("default")+ expected = field.discriminate(default)+ graph = _graph_with([_node("n1", block.id, {})])+ for providers, types, _ in _slots(graph).values():+ assert providers == {+ getattr(p, "value", p) for p in expected.provider+ }, f"{block.name}.{name} advertises unreachable providers"+ assert types == set(expected.supported_types)++ assert not construction_failures, (+ "blocks failed to construct, so they were not covered by this guard: "+ + "; ".join(construction_failures)+ )diff --git a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.pyindex 6a59b73b89..67b2b8f27f 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py@@ -69,9 +69,14 @@ async def _before_graph_activate(graph: "BaseGraph | GraphModel", user_id: str):refs: list[tuple["Node | NodeModel", str, dict, BlockSchema]] = []for new_node in graph.nodes:block_input_schema = cast(BlockSchema, new_node.block.input_schema)- for creds_field_name in block_input_schema.get_credentials_fields().keys():+ for creds_field_name in block_input_schema.get_credentials_fields():creds_meta = new_node.input_default.get(creds_field_name)- if not creds_meta:+ # A meta without `id` means no credential was selected. The form+ # can emit provider/type on their own, so this shape is reachable+ # without any user action; treat it as unset instead of indexing+ # it. Required-but-unset is caught by execution-time validation,+ # which can name the block and field.+ if not creds_meta or not creds_meta.get("id"):continuerefs.append((new_node, creds_field_name, creds_meta, block_input_schema))@@ -198,15 +203,28 @@ async def on_graph_deactivate(graph: "GraphModel", user_id: str):for node in graph.nodes:block_input_schema = cast(BlockSchema, node.block.input_schema)+ # First resolved credential wins. Assigning unconditionally per field+ # meant a block with several credential fields passed only the last+ # one, and a failed lookup on that last field discarded a credential+ # an earlier field had resolved successfully.node_credentials = None- for creds_field_name in block_input_schema.get_credentials_fields().keys():- if (creds_meta := node.input_default.get(creds_field_name)) and not (- node_credentials := await get_credentials(creds_meta["id"])- ):+ for creds_field_name in block_input_schema.get_credentials_fields():+ # Same shape guard as activation: a meta without `id` means no+ # credential was selected, and indexing it would raise KeyError.+ # Persisted graphs can carry this id-less shape, so deactivation+ # has to tolerate it.+ creds_meta = node.input_default.get(creds_field_name)+ if not creds_meta or not (creds_id := creds_meta.get("id")):+ continue+ resolved = await get_credentials(creds_id)+ if not resolved:logger.warning(f"Node #{node.id} input '{creds_field_name}' referenced "- f"non-existent credentials #{creds_meta['id']}"+ f"non-existent credentials #{creds_id}")+ continue+ if node_credentials is None:+ node_credentials = resolvedupdated_node = await on_node_deactivate(user_id, node, credentials=node_credentialsdiff --git a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.pyindex dd289f1ef0..1b91e2328d 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py@@ -5,6 +5,7 @@ import pytestfrom backend.integrations.webhooks.graph_lifecycle_hooks import (GraphActivationError,_before_graph_activate,+ on_graph_deactivate,)@@ -120,3 +121,78 @@ async def test_before_graph_activate_succeeds_when_credentials_resolve():await _before_graph_activate(graph, "user-1")assert node.input_default["credentials"]["id"] == "cred-1"+++async def test_before_graph_activate_ignores_credential_meta_without_id():+ """A credentials value that is truthy but carries no `id` means "nothing+ selected", not "resolve this". It must be skipped like an absent field+ rather than indexed — indexing raised KeyError('id'), surfacing to the user+ as a bare 500 on POST /api/graphs that named neither block nor field."""+ node = _make_node(creds_field="codex_credentials", required=False)+ node.input_default = {"codex_credentials": {"provider": "codex", "type": "oauth2"}}+ graph = MagicMock(nodes=[node])++ getter = AsyncMock(return_value=MagicMock())+ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = getter+ await _before_graph_activate(graph, "user-1")++ getter.assert_not_awaited()+++async def test_on_graph_deactivate_ignores_credential_meta_without_id():+ """Deactivation had the same `creds_meta["id"]` indexing as activation.+ Graphs persisted with the id-less shape hit it on delete, so the guard+ needs its own regression test rather than relying on the activation one."""+ node = _make_node(creds_field="codex_credentials", required=False)+ node.input_default = {"codex_credentials": {"provider": "codex", "type": "oauth2"}}+ node.block.webhook_config = None+ graph = MagicMock(nodes=[node])++ getter = AsyncMock(return_value=MagicMock())+ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = getter+ await on_graph_deactivate(graph, "user-1")++ getter.assert_not_awaited()+++async def test_on_graph_deactivate_keeps_first_resolved_credential():+ """A failed lookup on a later field must not discard a credential an+ earlier field already resolved."""+ node = _make_node(required=False)+ node.input_default = {+ "credentials": {"id": "good", "provider": "github", "type": "api_key"},+ "other_credentials": {"id": "gone", "provider": "github", "type": "api_key"},+ }+ node.block.webhook_config = None+ schema = node.block.input_schema+ schema.get_credentials_fields.return_value = {+ "credentials": object(),+ "other_credentials": object(),+ }++ resolved = MagicMock()++ async def getter(creds_id):+ return resolved if creds_id == "good" else None++ graph = MagicMock(nodes=[node])+ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.cached_getter.return_value = getter+ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.on_node_deactivate",+ new=AsyncMock(return_value=node),+ ) as deactivate:+ await on_graph_deactivate(graph, "user-1")++ assert deactivate.await_args.kwargs["credentials"] is resolveddiff --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.tsxindex 77b21dda92..a26a8d992e 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@@ -1,9 +1,21 @@import { RJSFSchema } from "@rjsf/utils";-import React from "react";+import type { IChangeEvent } from "@rjsf/core";+import React, { useContext, useMemo } from "react";import { uiSchema } from "./uiSchema";import { useNodeStore } from "../../../stores/nodeStore";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";++function isCredentialsProperty(schema: RJSFSchema, key: string): boolean {+ const property = schema.properties?.[key];+ return (+ typeof property === "object" &&+ property !== null &&+ "credentials_provider" in property+ );+}interface FormCreatorProps {jsonSchema: RJSFSchema;@@ -30,11 +42,29 @@ export const FormCreator: React.FC<FormCreatorProps> = React.memo((state) => state.getHardCodedValues,);+ const credentialsProviders = useContext(CredentialsProvidersContext);+const isAgent = uiType === BlockUIType.AGENT;- const handleChange = ({ formData }: any) => {- if ("credentials" in formData && !formData.credentials?.id) {- delete formData.credentials;+ const handleChange = ({+ formData,+ }: IChangeEvent<Record<string, unknown>>) => {+ if (!formData) return;++ // RJSF seeds `const` provider/type into default form state, so an+ // untouched credential field arrives as {provider, type} with no id.+ // That half object must never reach input_default: graph activation+ // indexes creds_meta["id"] and would raise KeyError.+ //+ // Keyed off the schema, not the field name. MCP tool arguments are+ // declared by third-party servers and may legitimately be named+ // `*_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) {+ delete formData[key];+ }}let updatedValues;@@ -47,10 +77,11 @@ export const FormCreator: React.FC<FormCreatorProps> = React.memo(// Separate credentials from tool arguments — credentials are stored// at the top level of hardcodedValues, not inside tool_arguments.const { credentials, ...toolArgs } = formData;+ const selected = credentials as { id?: unknown } | undefined;updatedValues = {...getHardCodedValues(nodeId),tool_arguments: toolArgs,- ...(credentials?.id ? { credentials } : {}),+ ...(selected?.id ? { credentials } : {}),};} else {updatedValues = formData;@@ -61,20 +92,36 @@ export const FormCreator: React.FC<FormCreatorProps> = React.memo(const hardcodedValues = getHardCodedValues(nodeId);- let initialValues;- if (isAgent) {- initialValues = hardcodedValues.inputs ?? {};- } else if (isMCPWithTool) {- // Merge tool arguments with credentials for the form- initialValues = {- ...(hardcodedValues.tool_arguments ?? {}),- ...(hardcodedValues.credentials?.id- ? { credentials: hardcodedValues.credentials }- : {}),- };- } else {- initialValues = hardcodedValues;- }+ // Memoized so the object identity is stable across renders. FormRenderer+ // memoizes its schema preprocessing on these props, so a fresh object each+ // render re-ran the whole RJSF schema pipeline for every node on the canvas.+ const initialValues = useMemo(() => {+ if (isAgent) return hardcodedValues.inputs ?? {};+ if (isMCPWithTool) {+ // Merge tool arguments with credentials for the form+ return {+ ...(hardcodedValues.tool_arguments ?? {}),+ ...(hardcodedValues.credentials?.id+ ? { credentials: hardcodedValues.credentials }+ : {}),+ };+ }+ return hardcodedValues;+ }, [isAgent, isMCPWithTool, hardcodedValues]);++ // Domain gating lives here rather than in the credential field renderer+ // because the discriminator is a sibling property: only a whole-schema+ // view can map a credential field's discriminator back to the enum it+ // narrows. Run dialogs gate through backend aggregation instead.+ const gatedSchema = useMemo(+ () =>+ gateDiscriminatorOptions(+ jsonSchema,+ credentialsProviders,+ initialValues,+ ),+ [jsonSchema, credentialsProviders, initialValues],+ );return (<div@@ -82,7 +129,7 @@ export const FormCreator: React.FC<FormCreatorProps> = React.memo(data-id={`form-creator-container-${nodeId}-node`}><FormRenderer- jsonSchema={jsonSchema}+ jsonSchema={gatedSchema}handleChange={handleChange}uiSchema={uiSchema}initialValues={initialValues}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.tsxnew file mode 100644index 0000000000..975ca63a6d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/__tests__/FormCreator.credentials.test.tsx@@ -0,0 +1,519 @@+import { BlockUIType } from "@/app/(platform)/build/components/types";+import { FormCreator } from "@/app/(platform)/build/components/FlowEditor/nodes/FormCreator";+import type { CustomNode } from "@/app/(platform)/build/components/FlowEditor/nodes/CustomNode/CustomNode";+import { useEdgeStore } from "@/app/(platform)/build/stores/edgeStore";+import { useHistoryStore } from "@/app/(platform)/build/stores/historyStore";+import { useNodeStore } from "@/app/(platform)/build/stores/nodeStore";+import {+ CredentialsProvidersContext,+ type CredentialsProvidersContextType,+} from "@/providers/agent-credentials/credentials-provider";+import { render } from "@/tests/integrations/test-utils";+import { screen, waitFor } from "@testing-library/react";+import type { RJSFSchema } from "@rjsf/utils";+import React from "react";+import { beforeEach, describe, expect, it } from "vitest";++// Mirrors AutoPilotBlock.codex_credentials: optional (default null), rendered on+// the block face, and — critically — provider/type are `const` in the subschema+// while `id` is not. RJSF seeds const values into default form state, so this+// field materializes as {provider, type} with no id and no user interaction.+const autopilotSchema = {+ type: "object",+ properties: {+ prompt: { advanced: false, title: "Prompt", type: "string" },+ codex_credentials: {+ advanced: false,+ credentials_provider: ["codex"],+ credentials_types: ["oauth2"],+ default: null,+ properties: {+ id: { title: "Id", type: "string" },+ provider: { const: "codex", title: "Provider", type: "string" },+ type: { const: "oauth2", title: "Type", type: "string" },+ },+ required: ["id", "provider", "type"],+ secret: true,+ title: "ChatGPT / Codex connection",+ type: "object",+ },+ },+ required: ["prompt"],+} as unknown as RJSFSchema;++function makeNode(schema: RJSFSchema): CustomNode {+ return {+ id: "autopilot-node",+ type: "custom",+ position: { x: 0, y: 0 },+ data: {+ hardcodedValues: {},+ title: "AutoPilot",+ description: "Run an autopilot task",+ inputSchema: schema,+ outputSchema: {},+ uiType: BlockUIType.STANDARD,+ block_id: "c069dc6b-c3ed-4c12-b6e5-d47361e64ce6",+ costs: [],+ categories: [],+ },+ } as unknown as CustomNode;+}++function makeProviders(...names: string[]): CredentialsProvidersContextType {+ const entries = names.map((name) => [+ name,+ {+ provider: name,+ providerName: name,+ savedCredentials: [],+ isSystemProvider: false,+ },+ ]);+ return Object.fromEntries(entries) as CredentialsProvidersContextType;+}++function renderNode(+ providers: CredentialsProvidersContextType,+ schema: RJSFSchema = autopilotSchema,+ nodeId = "autopilot-node",+) {+ useNodeStore.setState({+ nodes: [{ ...makeNode(schema), id: nodeId } as unknown as CustomNode],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ return render(+ <CredentialsProvidersContext.Provider value={providers}>+ <FormCreator+ jsonSchema={schema}+ nodeId={nodeId}+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );+}++beforeEach(() => {+ useNodeStore.setState({ nodes: [], nodeAdvancedStates: {} });+});++describe("FormCreator credential emission", () => {+ // Regression: a non-entitled user has no `codex` provider (the backend strips+ // it from /integrations/providers), so this field can never be filled. Before+ // the fix the node still persisted {provider, type} with no id, which reached+ // input_default and made POST /api/graphs return 500 with detail "'id'" from+ // graph_lifecycle_hooks._before_graph_activate.+ it("never persists a credential field that has no id", async () => {+ renderNode({});++ await waitFor(() => {+ expect(+ useNodeStore.getState().getHardCodedValues("autopilot-node"),+ ).toBeDefined();+ });++ const stored = useNodeStore+ .getState()+ .getHardCodedValues("autopilot-node") as Record<string, unknown>;++ expect(stored).not.toHaveProperty("codex_credentials");+ });++ // 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 () => {+ useNodeStore.setState({+ nodes: [+ {+ ...makeNode(autopilotSchema),+ data: {+ ...makeNode(autopilotSchema).data,+ hardcodedValues: {+ codex_credentials: {+ id: "codex-oauth-1",+ provider: "codex",+ type: "oauth2",+ title: "ChatGPT for Codex",+ },+ },+ },+ } as unknown as CustomNode,+ ],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ render(+ <CredentialsProvidersContext.Provider value={makeProviders("codex")}>+ <FormCreator+ jsonSchema={autopilotSchema}+ nodeId="autopilot-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ await waitFor(() => {+ expect(+ useNodeStore.getState().getHardCodedValues("autopilot-node"),+ ).toBeDefined();+ });++ const stored = useNodeStore+ .getState()+ .getHardCodedValues("autopilot-node") as Record<string, unknown>;++ expect(stored.codex_credentials).toMatchObject({ id: "codex-oauth-1" });+ });+});++// MCPToolBlock is the other block with a schema-optional rendered credential+// field (default={}), so it exercises the same star path under the literal+// `credentials` name rather than a `*_credentials` one.+const mcpToolSchema = {+ type: "object",+ properties: {+ server_url: { advanced: false, title: "Server Url", type: "string" },+ credentials: {+ advanced: false,+ credentials_provider: ["mcp"],+ credentials_types: ["oauth2"],+ default: {},+ discriminator: "server_url",+ properties: {+ id: { title: "Id", type: "string" },+ provider: { const: "mcp", title: "Provider", type: "string" },+ type: { const: "oauth2", title: "Type", type: "string" },+ },+ required: ["id", "provider", "type"],+ title: "Credentials",+ type: "object",+ },+ },+ required: ["server_url"],+} as unknown as RJSFSchema;++const requiredCodexSchema = {+ type: "object",+ properties: {+ prompt: { advanced: false, title: "Prompt", type: "string" },+ credentials: {+ advanced: false,+ credentials_provider: ["codex"],+ credentials_types: ["oauth2"],+ properties: {+ id: { title: "Id", type: "string" },+ provider: { const: "codex", title: "Provider", type: "string" },+ type: { const: "oauth2", title: "Type", type: "string" },+ },+ required: ["id", "provider", "type"],+ title: "Credentials",+ type: "object",+ },+ },+ required: ["prompt", "credentials"],+} as unknown as RJSFSchema;++describe("unavailable provider", () => {+ // The backend omits providers the user isn't entitled to, so CredentialsInput+ // renders no control. An optional field then has nothing actionable in it.+ it("hides an optional credential row whose provider the user cannot use", async () => {+ renderNode(makeProviders("openai"));++ await waitFor(() => {+ expect(screen.getByText("Prompt")).toBeDefined();+ });++ expect(screen.queryByText("OpenAI credential")).toBeNull();+ });++ it("shows the row once the provider becomes available", async () => {+ renderNode(makeProviders("codex"));++ expect(await screen.findByText("OpenAI credential")).toBeDefined();+ });++ // null context means the fetches haven't settled. Treating that as+ // unavailable would hide the row from entitled users on every page load.+ it("does not hide the row while providers are still loading", async () => {+ renderNode(null as unknown as CredentialsProvidersContextType);++ expect(await screen.findByText("OpenAI credential")).toBeDefined();+ });++ // Found in manual E2E: a PRO user selecting the codex transport on Code+ // Generation saw "Not available on your account." under a field still marked+ // required. The field can't be hidden (the schema requires a credential) but+ // the star demands something the UI offers no way to supply.+ it("does not star a required field whose provider is unavailable", async () => {+ const requiredUnavailableSchema = {+ type: "object",+ properties: {+ prompt: { advanced: false, title: "Prompt", type: "string" },+ credentials: {+ advanced: false,+ credentials_provider: ["codex"],+ credentials_types: ["oauth2"],+ properties: {+ id: { title: "Id", type: "string" },+ provider: { const: "codex", title: "Provider", type: "string" },+ type: { const: "oauth2", title: "Type", type: "string" },+ },+ required: ["id", "provider", "type"],+ title: "Credentials",+ type: "object",+ },+ },+ required: ["prompt", "credentials"],+ } as unknown as RJSFSchema;++ useNodeStore.setState({+ nodes: [+ {+ ...makeNode(requiredUnavailableSchema),+ id: "req-node",+ } as unknown as CustomNode,+ ],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ render(+ <CredentialsProvidersContext.Provider value={makeProviders("openai")}>+ <FormCreator+ jsonSchema={requiredUnavailableSchema}+ nodeId="req-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ const title = await screen.findByText("OpenAI credential");++ expect(title.parentElement?.textContent).not.toContain("*");+ });++ it("still stars a required field whose provider IS available", async () => {+ const requiredAvailableSchema = {+ type: "object",+ properties: {+ credentials: {+ advanced: false,+ credentials_provider: ["github"],+ credentials_types: ["api_key"],+ properties: {+ id: { title: "Id", type: "string" },+ provider: { const: "github", title: "Provider", type: "string" },+ type: { const: "api_key", title: "Type", type: "string" },+ },+ required: ["id", "provider", "type"],+ title: "Credentials",+ type: "object",+ },+ },+ required: ["credentials"],+ } as unknown as RJSFSchema;++ useNodeStore.setState({+ nodes: [+ {+ ...makeNode(requiredAvailableSchema),+ id: "gh-avail",+ } as unknown as CustomNode,+ ],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ render(+ <CredentialsProvidersContext.Provider value={makeProviders("github")}>+ <FormCreator+ jsonSchema={requiredAvailableSchema}+ nodeId="gh-avail"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ const title = await screen.findByText("Github credential");++ expect(title.parentElement?.textContent).toContain("*");+ });+});++describe("unavailable required field", () => {+ // Regression for the toggle trap: the hide condition must key off the schema's+ // own `required`, not the toggle-adjusted value. Otherwise turning "Optional"+ // on for a required gated field hides the row AND its toggle, with no way back.+ it("keeps a required-but-unavailable row visible when marked optional", async () => {+ useNodeStore.setState({+ nodes: [+ {+ ...makeNode(requiredCodexSchema),+ id: "toggle-node",+ data: {+ ...makeNode(requiredCodexSchema).data,+ metadata: { credentials_optional: true },+ },+ } as unknown as CustomNode,+ ],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ render(+ <CredentialsProvidersContext.Provider value={makeProviders("openai")}>+ <FormCreator+ jsonSchema={requiredCodexSchema}+ nodeId="toggle-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ // The row survives so the toggle stays reachable, but carries no star.+ const title = await screen.findByText("OpenAI credential");+ expect(title.parentElement?.textContent).not.toContain("*");++ // Dropping the star removes the only visual cue that the field matters,+ // so the explanation has to be present to replace it.+ expect(screen.getByText("Not available on your account.")).toBeDefined();+ });++ it("explains why a required gated field cannot be filled", async () => {+ renderNode(makeProviders("openai"), requiredCodexSchema, "required-node");++ const note = await screen.findByText("Not available on your account.");+ // Wired to the control so assistive tech connects the two.+ expect(note.getAttribute("id")).toBeTruthy();+ });+});++describe("credential field required marker", () => {+ // The builder used to derive the marker purely from the node-level+ // credentials_optional toggle, so a schema-optional credential field was+ // still starred. codex_credentials is absent from the schema's `required`+ // array, so it must render without one.+ it("does not star a credential field the schema declares optional", async () => {+ renderNode(makeProviders("codex"));++ const title = await screen.findByText("OpenAI credential");++ expect(title.parentElement?.textContent).not.toContain("*");+ });++ it("still stars a genuinely required field", async () => {+ renderNode(makeProviders("codex"));++ const title = await screen.findByText("Prompt");++ expect(title.parentElement?.textContent).toContain("*");+ });++ it("does not star MCP Tool's schema-optional credentials either", async () => {+ useNodeStore.setState({+ nodes: [+ {+ ...makeNode(mcpToolSchema),+ id: "mcp-node",+ } as unknown as CustomNode,+ ],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ render(+ <CredentialsProvidersContext.Provider value={makeProviders("mcp")}>+ <FormCreator+ jsonSchema={mcpToolSchema}+ nodeId="mcp-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ const title = await screen.findByText("Mcp credential");++ expect(title.parentElement?.textContent).not.toContain("*");+ });++ it("keeps the node-level toggle able to relax a required credential", async () => {+ // The toggle may only relax, never tighten. A schema-required credential+ // with credentials_optional set must lose its star, which is the feature+ // the optional-credentials flag added.+ const requiredCredsSchema = {+ type: "object",+ properties: {+ credentials: {+ advanced: false,+ credentials_provider: ["github"],+ credentials_types: ["api_key"],+ properties: {+ id: { title: "Id", type: "string" },+ provider: { const: "github", title: "Provider", type: "string" },+ type: { const: "api_key", title: "Type", type: "string" },+ },+ required: ["id", "provider", "type"],+ title: "Credentials",+ type: "object",+ },+ },+ required: ["credentials"],+ } as unknown as RJSFSchema;++ useNodeStore.setState({+ nodes: [+ {+ id: "gh-node",+ type: "custom",+ position: { x: 0, y: 0 },+ data: {+ hardcodedValues: {},+ title: "GitHub",+ description: "d",+ inputSchema: requiredCredsSchema,+ outputSchema: {},+ uiType: BlockUIType.STANDARD,+ block_id: "gh",+ costs: [],+ categories: [],+ metadata: { credentials_optional: true },+ },+ } as unknown as CustomNode,+ ],+ nodeAdvancedStates: {},+ });+ useEdgeStore.setState({ edges: [] });+ useHistoryStore.setState({ past: [], future: [] });++ render(+ <CredentialsProvidersContext.Provider value={makeProviders("github")}>+ <FormCreator+ jsonSchema={requiredCredsSchema}+ nodeId="gh-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ const title = await screen.findByText("Github credential");++ expect(title.parentElement?.textContent).not.toContain("*");+ });+});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.tsxindex a024c072dd..fddbaee9ca 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@@ -207,3 +207,247 @@ describe("Code Generation transport fields", () => {});});});++function renderTransport(+ providers: Record<string, CredentialsProviderData> | null,+) {+ return render(+ <CredentialsProvidersContext.Provider value={providers}>+ <FormCreator+ jsonSchema={codeGenerationSchema}+ nodeId="code-generation-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );+}++function transportOptionLabels() {+ const select = screen.getByLabelText("agpt_%_transport");+ return Array.from(select.querySelectorAll("option")).map(+ (option) => option.textContent,+ );+}++describe("Transport options gated by provider entitlement", () => {+ it("hides the codex transport when the provider is not on the account", () => {+ renderTransport({ openai: makeProvider("openai", "OpenAI", []) });++ expect(transportOptionLabels()).toEqual(["openai_api"]);+ });++ it("offers the codex transport when the provider is on the account", () => {+ renderTransport({+ openai: makeProvider("openai", "OpenAI", []),+ codex: makeProvider("codex", "Codex", [codexCredential]),+ });++ expect(transportOptionLabels()).toEqual(["openai_api", "codex_app_server"]);+ });++ it("leaves options alone while the provider map is still loading", () => {+ renderTransport(null);++ expect(transportOptionLabels()).toEqual(["openai_api", "codex_app_server"]);+ });++ it("keeps a saved codex transport selectable after entitlement is lost", () => {+ useNodeStore.setState({+ nodes: [+ {+ ...createCodeGenerationNode(),+ data: {+ ...createCodeGenerationNode().data,+ hardcodedValues: {+ prompt: "Write a hello-world function",+ transport: "codex_app_server",+ },+ },+ },+ ],+ nodeAdvancedStates: {},+ });++ renderTransport({ openai: makeProvider("openai", "OpenAI", []) });++ expect(transportOptionLabels()).toEqual(["openai_api", "codex_app_server"]);+ });++ it("leaves the enum intact when every option would be filtered out", () => {+ // An empty dropdown is worse than an unusable option. Needs a node with+ // no saved transport and a schema with no default, otherwise those two+ // escape hatches keep an option and the guard never fires.+ const noDefault = JSON.parse(+ JSON.stringify(codeGenerationSchema),+ ) as Record<string, any>;+ delete noDefault.properties.transport.default;++ useNodeStore.setState({+ nodes: [+ {+ ...createCodeGenerationNode(),+ data: {+ ...createCodeGenerationNode().data,+ hardcodedValues: { prompt: "hi" },+ inputSchema: noDefault,+ },+ },+ ],+ nodeAdvancedStates: {},+ });++ render(+ <CredentialsProvidersContext.Provider value={{}}>+ <FormCreator+ jsonSchema={noDefault as unknown as RJSFSchema}+ nodeId="code-generation-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ expect(transportOptionLabels()).toEqual(["openai_api", "codex_app_server"]);+ });++ it("keeps the schema default even when its provider is gated", () => {+ // RJSF falls back to the schema default when the node has no saved value;+ // filtering it out would leave a select whose selection is not an option.+ useNodeStore.setState({+ nodes: [+ {+ ...createCodeGenerationNode(),+ data: {+ ...createCodeGenerationNode().data,+ hardcodedValues: { prompt: "hi" },+ inputSchema: {+ ...(codeGenerationSchema as Record<string, any>),+ properties: {+ ...(codeGenerationSchema as Record<string, any>).properties,+ transport: {+ ...(codeGenerationSchema as Record<string, any>).properties+ .transport,+ default: "codex_app_server",+ },+ },+ },+ },+ },+ ],+ nodeAdvancedStates: {},+ });++ render(+ <CredentialsProvidersContext.Provider+ value={{ openai: makeProvider("openai", "OpenAI", []) }}+ >+ <FormCreator+ jsonSchema={+ {+ ...(codeGenerationSchema as Record<string, any>),+ properties: {+ ...(codeGenerationSchema as Record<string, any>).properties,+ transport: {+ ...(codeGenerationSchema as Record<string, any>).properties+ .transport,+ default: "codex_app_server",+ },+ },+ } as unknown as RJSFSchema+ }+ nodeId="code-generation-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ expect(transportOptionLabels()).toContain("codex_app_server");+ });++ it("does not touch the model dropdown, which no credential discriminates on", () => {+ renderTransport({ openai: makeProvider("openai", "OpenAI", []) });++ const model = screen.getByLabelText("agpt_%_model");+ expect(+ Array.from(model.querySelectorAll("option")).map((o) => o.textContent),+ ).toEqual(["gpt-5.3-codex", "gpt-5.1-codex"]);+ });+});++describe("LLM blocks keep every model option", () => {+ const llmSchema = {+ type: "object",+ properties: {+ prompt: { advanced: false, title: "Prompt", type: "string" },+ model: {+ advanced: false,+ default: "gpt-4o",+ enum: ["gpt-4o", "claude-opus-4-5-20251101", "llama3.3"],+ title: "Model",+ type: "string",+ },+ credentials: {+ credentials_provider: ["openai", "anthropic", "ollama"],+ credentials_types: ["api_key"],+ discriminator: "model",+ discriminator_mapping: {+ "gpt-4o": "openai",+ "claude-opus-4-5-20251101": "anthropic",+ "llama3.3": "ollama",+ },+ properties: {+ id: { type: "string" },+ provider: {+ enum: ["openai", "anthropic", "ollama"],+ type: "string",+ },+ type: { const: "api_key", type: "string" },+ },+ required: ["id", "provider", "type"],+ title: "Credentials",+ type: "object",+ },+ },+ required: ["prompt", "credentials"],+ } as unknown as RJSFSchema;++ it("keeps all models when every LLM provider is present, as list_providers guarantees", () => {+ useNodeStore.setState({+ nodes: [+ {+ ...createCodeGenerationNode(),+ data: {+ ...createCodeGenerationNode().data,+ hardcodedValues: { prompt: "hi", model: "gpt-4o" },+ inputSchema: llmSchema,+ },+ },+ ],+ nodeAdvancedStates: {},+ });++ render(+ <CredentialsProvidersContext.Provider+ value={{+ openai: makeProvider("openai", "OpenAI", []),+ anthropic: makeProvider("anthropic", "Anthropic", []),+ ollama: makeProvider("ollama", "Ollama", []),+ }}+ >+ <FormCreator+ jsonSchema={llmSchema}+ nodeId="code-generation-node"+ uiType={BlockUIType.STANDARD}+ showHandles={false}+ />+ </CredentialsProvidersContext.Provider>,+ );++ const model = screen.getByLabelText("agpt_%_model");+ expect(+ Array.from(model.querySelectorAll("option")).map((o) => o.textContent),+ ).toEqual(["gpt-4o", "claude-opus-4-5-20251101", "llama3.3"]);+ });+});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 7e34673125..dd6de881a0 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@@ -5,10 +5,12 @@ import {BlockIOCredentialsSubSchema,CredentialsMetaInput,} from "@/lib/autogpt-server-api";+import { Text } from "@/components/atoms/Text/Text";import { FieldProps, getUiOptions } from "@rjsf/utils";import { useMemo } from "react";import { useShallow } from "zustand/react/shallow";import { CredentialFieldTitle } from "./components/CredentialFieldTitle";+import { useCredentialAvailability } from "./useCredentialAvailability";export const CredentialsField = (props: FieldProps) => {const { formData, onChange, schema, registry, fieldPathId, required } = props;@@ -67,12 +69,48 @@ 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;+ // Combines the schema's `required` array with the node-level toggle, which+ // is why it is not named for the schema alone: in the builder canvas the+ // toggle can relax a required field to optional. It must never mark a+ // schema-optional field required — blocks declaring an optional credential+ // (default=None) would otherwise render an unfillable star.+ const effectiveRequired = nodeId+ ? !credentialsOptional && required+ : required;++ const availability = useCredentialAvailability(+ schema as BlockIOCredentialsSubSchema,+ hardcodedValues,+ );+ const isUnavailable = availability === "unavailable";++ // CredentialsInput renders nothing when the provider is missing from the+ // providers map, which used to leave a bare title with no control under it.+ // An optional field then has nothing actionable in it at all, so drop the row.+ //+ // Keyed off the schema's own `required`, not `effectiveRequired` above: the+ // 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 (isUnavailable && !required) {+ return null;+ }++ // A provider this user cannot connect is not actionable, so the required+ // marker only misleads: it demands something the UI gives no way to supply.+ // The schema still requires it and execution-time validation still enforces+ // that — this only suppresses the star on a field that cannot be filled.+ const isRequired = isUnavailable ? false : effectiveRequired;+ // Ties the explanation to the control for assistive tech: dropping the+ // required marker also removes the only programmatic cue that a visible+ // field cannot be filled.+ const unavailableNoteId = `${fieldPathId?.$id ?? "credentials"}-unavailable`;return (- <div className="flex flex-col gap-2">+ <div+ className="flex flex-col gap-2"+ aria-describedby={isUnavailable ? unavailableNoteId : undefined}+ ><CredentialFieldTitlefieldPathId={fieldPathId}registry={registry}@@ -80,6 +118,16 @@ export const CredentialsField = (props: FieldProps) => {schema={schema}required={isRequired}/>+ {availability === "unavailable" && (+ <Text+ id={unavailableNoteId}+ variant="small"+ className="text-zinc-500"+ aria-live="polite"+ >+ Not available on your account.+ </Text>+ )}<CredentialsInputschema={schema as BlockIOCredentialsSubSchema}selectedCredentials={selectedCredentials}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.tsnew file mode 100644index 0000000000..cc7b546fc8--- /dev/null+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/gateDiscriminatorOptions.ts@@ -0,0 +1,97 @@+import { RJSFSchema } from "@rjsf/utils";+import { CredentialsProvidersContextType } from "@/providers/agent-credentials/credentials-provider";++/**+ * Drop discriminator enum options whose credential provider this user cannot+ * connect.+ *+ * A block like Code Generation declares `credentials.discriminator = "transport"`+ * plus a `discriminator_mapping` of enum value -> provider. Offering a value+ * whose provider is gated lets the user select a transport they can never+ * satisfy: the credential row then renders "Not available on your account" and+ * execution is rejected server-side. Removing the option says the same thing+ * up front.+ *+ * Only ever narrows options for providers absent from the user's provider map.+ * `list_providers` filters exactly one provider (codex, on non-entitled+ * accounts) and returns every other provider unconditionally, so LLM blocks —+ * which discriminate on `model` across eight always-present providers — keep+ * every option.+ */+export function gateDiscriminatorOptions(+ schema: RJSFSchema,+ providers: CredentialsProvidersContextType | null,+ currentValues: Record<string, unknown>,+): RJSFSchema {+ // null means the provider map has not loaded. Filtering against it would+ // briefly drop every option, so leave the schema alone until it arrives.+ if (!providers) return schema;++ const properties = schema.properties;+ if (!properties) return schema;++ const blockedByField = collectBlockedValues(properties, providers);+ if (blockedByField.size === 0) return schema;++ const gatedProperties: NonNullable<RJSFSchema["properties"]> = {+ ...properties,+ };+ let changed = false;++ for (const [fieldName, blocked] of blockedByField) {+ const fieldSchema = properties[fieldName];+ if (!isRecord(fieldSchema) || !Array.isArray(fieldSchema.enum)) continue;++ const saved = currentValues[fieldName];+ const fallback = fieldSchema.default;+ const kept = fieldSchema.enum.filter(+ (option) =>+ !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;++ gatedProperties[fieldName] = { ...fieldSchema, enum: kept };+ changed = true;+ }++ return changed ? { ...schema, properties: gatedProperties } : schema;+}++function collectBlockedValues(+ properties: Record<string, unknown>,+ providers: CredentialsProvidersContextType,+): Map<string, Set<string>> {+ const blockedByField = new Map<string, Set<string>>();++ for (const propSchema of Object.values(properties)) {+ if (!isRecord(propSchema)) continue;+ if (!("credentials_provider" in propSchema)) continue;++ const discriminator = propSchema.discriminator;+ const mapping = propSchema.discriminator_mapping;+ if (typeof discriminator !== "string" || !isRecord(mapping)) continue;++ for (const [value, provider] of Object.entries(mapping)) {+ if (typeof provider !== "string" || providers[provider]) continue;+ const blocked = blockedByField.get(discriminator) ?? new Set<string>();+ blocked.add(value);+ blockedByField.set(discriminator, blocked);+ }+ }++ return blockedByField;+}++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/useCredentialAvailability.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/useCredentialAvailability.tsnew file mode 100644index 0000000000..191941d2ff--- /dev/null+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/CredentialField/useCredentialAvailability.ts@@ -0,0 +1,31 @@+import { BlockIOCredentialsSubSchema } from "@/lib/autogpt-server-api";+import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";+import { useContext } from "react";+import { getCredentialProviderFromSchema } from "./helpers";++type Availability = "loading" | "available" | "unavailable";++/**+ * Whether this field's provider is usable by the current user.+ *+ * The providers map is null until the provider-name and credential fetches+ * settle, and the backend omits providers the user isn't entitled to (e.g.+ * codex below the MAX tier). Those are different states: null means "unknown+ * yet", a loaded map missing the key means "this user cannot connect it".+ * Collapsing them would flash an unavailable state at entitled users on every+ * page load.+ */+export function useCredentialAvailability(+ schema: BlockIOCredentialsSubSchema,+ formData: Record<string, unknown>,+): Availability {+ const providers = useContext(CredentialsProvidersContext);+ const provider = getCredentialProviderFromSchema(formData, schema);++ if (providers === null) return "loading";+ // A multi-provider field with no discriminator value yet resolves to null;+ // nothing is decided, so don't claim unavailability.+ if (!provider) return "loading";++ return providers[provider] ? "available" : "unavailable";+}diff --git a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsxindex 43c3dc0325..fdd4f3a1fe 100644--- a/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx+++ b/autogpt_platform/frontend/src/providers/agent-credentials/credentials-provider.tsx@@ -121,7 +121,7 @@ export default function CredentialsProvider({const [systemProviders, setSystemProviders] = useState<Set<string>>(new Set(),);- const { isLoggedIn } = useAuth();+ const { isLoggedIn, isUserLoading } = useAuth();const api = useBackendAPI();const onFailToast = useToastOnFail();const queryClient = useQueryClient();@@ -287,7 +287,22 @@ export default function CredentialsProvider({const loadCredentials = useCallback(() => {if (!isLoggedIn || providerNames.length === 0) {- if (isLoggedIn == false) setProviders({});+ // null is the sole "still loading" sentinel; an empty object means+ // "loaded, and this user has no providers". Keeping those distinct+ // matters because consumers render an unavailable state from the+ // latter, and showing that to an entitled user is wrong.+ //+ // Logged out, once auth has settled: genuinely empty. isLoggedIn is+ // false while the auth store initializes too, hence the isUserLoading+ // guard — without it a logged-in user briefly gets the empty map.+ if (!isUserLoading && !isLoggedIn) {+ setProviders({});+ return;+ }+ // Logged in but provider names haven't arrived yet. If a previous+ // logout left the empty map published, clear it back to null so this+ // reads as loading rather than "nothing is available to you".+ if (isLoggedIn) setProviders(null);return;}@@ -342,6 +357,7 @@ export default function CredentialsProvider({}, [api,isLoggedIn,+ isUserLoading,providerNames,systemProviders,createAPIKeyCredentials,diff --git a/autogpt_platform/single-container/entrypoint.sh b/autogpt_platform/single-container/entrypoint.shindex 3f48fc7be3..cd53bb577d 100755--- a/autogpt_platform/single-container/entrypoint.sh+++ b/autogpt_platform/single-container/entrypoint.sh@@ -166,7 +166,18 @@ configure_environment() {export BATCH_EXECUTOR_PORT="${AUTOGPT_BATCH_EXECUTOR_PORT}"# Keep self-hosted product behavior without enabling LOCAL-only API docs and# asyncio debug mode on the public REST process.- export APP_ENV=dev BEHAVE_AS=local ENABLE_AUTH=true+ # BEHAVE_AS defaults to local (self-hosted product behavior) but stays+ # overridable: entitlement policies with allow_local=True grant every user+ # access under `local`, so gating cannot be exercised without injecting+ # `cloud`. APP_ENV stays dev to keep LOCAL-only API docs and asyncio debug+ # mode off the public REST process.+ #+ # ⚠️ OPERATORS: `local` disables entitlement gating for EVERY user — the+ # allow_local carve-out grants plan-gated features (e.g. the ChatGPT/Codex+ # transport) regardless of subscription tier. That is correct for a+ # single-tenant self-hosted install. Any multi-tenant or hosted deployment+ # MUST set BEHAVE_AS=cloud, or every user gets every gated capability.+ export APP_ENV=dev BEHAVE_AS="${BEHAVE_AS:-local}" ENABLE_AUTH=trueexport BETTER_AUTH_URL="${AUTOGPT_PUBLIC_URL}"export BETTER_AUTH_INTERNAL_URL=http://127.0.0.1:3001diff --git a/docs/integrations/block-integrations/llm.md b/docs/integrations/block-integrations/llm.mdindex 073adfa2e7..09d5ffbd2c 100644--- a/docs/integrations/block-integrations/llm.md+++ b/docs/integrations/block-integrations/llm.md@@ -597,7 +597,7 @@ Choose `codex_app_server` to use a connected ChatGPT plan. This path requires ma|-------|-------------|------|----------|| prompt | Primary coding request passed to the Codex model. | str | Yes || system_prompt | Optional instructions passed to the selected Codex transport. | str | No |-| transport | Use an OpenAI API key or your connected ChatGPT plan through Codex App Server. | "openai_api" \| "codex_app_server" | No |+| transport | Use an OpenAI API key, or your connected ChatGPT subscription through Codex App Server if supported by your plan. | "openai_api" \| "codex_app_server" | No || model | OpenAI API transport only. Codex App Server selects the current subscription model from its live model catalog. | "gpt-5.6-sol" \| "gpt-5.6-terra" \| "gpt-5.6-luna" \| "gpt-5.3-codex" \| "gpt-5.1-codex" | No || reasoning_effort | Controls the selected transport's reasoning effort. OpenAI API does not support 'ultra'; select 'none' to omit reasoning config. | "none" \| "low" \| "medium" \| "high" \| "xhigh" \| "max" \| "ultra" | No || max_output_tokens | OpenAI API transport only: upper bound for generated tokens (hard limit 128,000). Codex App Server uses its model and plan limits. | int | No |