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(platform): show the ChatGPT connection a plan excludes, locked (#14086)
Nicholas Tindle562c84385303
diff --git a/autogpt_platform/backend/backend/copilot/engine.py b/autogpt_platform/backend/backend/copilot/engine.pynew file mode 100644index 0000000000..7c45eddbc5--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/engine.py@@ -0,0 +1,41 @@+"""Which execution engine runs a turn.++Lives apart from the processor so the answer can be read without importing+the engines themselves: the processor pulls in both services at module+level, and the API layer needs this decision to describe a connection+before any turn exists.+"""++import logging++from backend.util.feature_flag import Flag, is_feature_enabled++logger = logging.getLogger(__name__)+++async def resolve_use_sdk(+ user_id: str | None,+ *,+ use_claude_code_subscription: bool,+ config_default: bool,+ thinking_available: bool = True,+) -> bool:+ """Pick the SDK vs baseline engine.++ Entirely the server's call: the Claude Code subscription override, then+ the ``COPILOT_SDK`` LaunchDarkly flag, then the config default. Callers+ used to be able to name an engine per request; nothing can now, so this+ is one decision rather than a request overriding it — which is also what+ makes it answerable ahead of a turn.++ ``thinking_available`` is the kill-switch for deployments where the SDK+ transport simply cannot run (today: ``CHAT_USE_LOCAL=true`` — Ollama+ doesn't speak Anthropic's wire protocol).+ """+ if not thinking_available:+ return False+ return use_claude_code_subscription or await is_feature_enabled(+ Flag.COPILOT_SDK,+ user_id or "anonymous",+ default=config_default,+ )diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.pyindex bb8a328292..521bc38136 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py@@ -16,6 +16,7 @@ from typing import TYPE_CHECKING, Callable, castfrom backend.copilot import stream_registryfrom backend.copilot.baseline import stream_chat_completion_baselinefrom backend.copilot.config import ChatConfig+from backend.copilot.engine import resolve_use_sdkfrom backend.copilot.expert_context import (EXPERT_SESSION_MISSING_MESSAGE,EXPERT_SESSION_TEMPORARY_MESSAGE,@@ -32,7 +33,6 @@ from backend.util.exceptions import (ExpertNotFoundError,ExpertPrivateTenancyNotFoundError,)-from backend.util.feature_flag import Flag, is_feature_enabledfrom backend.util.logging import TruncatedLogger, configure_loggingfrom backend.util.process import set_service_namefrom backend.util.retry import func_retry@@ -135,33 +135,6 @@ def sync_fail_close_session(# ============ Mode Routing ============ #-async def resolve_use_sdk(- user_id: str | None,- *,- use_claude_code_subscription: bool,- config_default: bool,- thinking_available: bool = True,-) -> bool:- """Pick the SDK vs baseline engine for a single turn.-- The engine is entirely the server's call: the Claude Code subscription- override, then the ``COPILOT_SDK`` LaunchDarkly flag, then the config- default. Callers used to be able to name an engine per request; nothing- can now, so there is one decision here instead of a request overriding it.-- ``thinking_available`` is the kill-switch for deployments where the SDK- transport simply cannot run (today: ``CHAT_USE_LOCAL=true`` — Ollama- doesn't speak Anthropic's wire protocol).- """- if not thinking_available:- return False- return use_claude_code_subscription or await is_feature_enabled(- Flag.COPILOT_SDK,- user_id or "anonymous",- default=config_default,- )--# ============ Module Entry Points ============ ## Thread-local storage for processor instancesdiff --git a/autogpt_platform/backend/backend/copilot/executor/processor_test.py b/autogpt_platform/backend/backend/copilot/executor/processor_test.pyindex 8fd562a34f..076fcf2f37 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor_test.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor_test.py@@ -17,11 +17,11 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from backend.copilot.engine import resolve_use_sdkfrom backend.copilot.executor.processor import (_CODEX_CREDENTIAL_ACQUIRE_TIMEOUT_SECONDS,CoPilotProcessor,_normalize_private_expert_session_tenancy,- resolve_use_sdk,sync_fail_close_session,)from backend.copilot.executor.utils import CoPilotExecutionEntry, CoPilotLogMetadata@@ -49,7 +49,7 @@ class TestResolveUseSdk:@pytest.mark.asyncioasync def test_subscription_override_routes_to_sdk(self):with patch(- "backend.copilot.executor.processor.is_feature_enabled",+ "backend.copilot.engine.is_feature_enabled",new=AsyncMock(return_value=False),):assert (@@ -64,7 +64,7 @@ class TestResolveUseSdk:@pytest.mark.asyncioasync def test_feature_flag_routes_to_sdk(self):with patch(- "backend.copilot.executor.processor.is_feature_enabled",+ "backend.copilot.engine.is_feature_enabled",new=AsyncMock(return_value=True),):assert (@@ -84,7 +84,7 @@ class TestResolveUseSdk:captured["default"] = defaultreturn default- with patch("backend.copilot.executor.processor.is_feature_enabled", new=_flag):+ with patch("backend.copilot.engine.is_feature_enabled", new=_flag):assert (await resolve_use_sdk("user-1",@@ -98,7 +98,7 @@ class TestResolveUseSdk:@pytest.mark.asyncioasync def test_everything_disabled_routes_to_baseline(self):with patch(- "backend.copilot.executor.processor.is_feature_enabled",+ "backend.copilot.engine.is_feature_enabled",new=AsyncMock(return_value=False),):assert (@@ -119,7 +119,7 @@ class TestResolveUseSdk:wire protocol."""with patch(- "backend.copilot.executor.processor.is_feature_enabled",+ "backend.copilot.engine.is_feature_enabled",new=AsyncMock(return_value=True),):assert (@@ -135,7 +135,7 @@ class TestResolveUseSdk:@pytest.mark.asyncioasync def test_anonymous_user_is_routable(self):with patch(- "backend.copilot.executor.processor.is_feature_enabled",+ "backend.copilot.engine.is_feature_enabled",new=AsyncMock(return_value=False),):assert (diff --git a/autogpt_platform/backend/backend/copilot/offers.py b/autogpt_platform/backend/backend/copilot/offers.pyindex 5f89c94822..dda5bb8638 100644--- a/autogpt_platform/backend/backend/copilot/offers.py+++ b/autogpt_platform/backend/backend/copilot/offers.py@@ -14,13 +14,17 @@ import loggingfrom pydantic import BaseModel-from backend.copilot.config import CopilotLlmAuthProvider, CopilotLLMModel+from backend.copilot.config import ChatConfig, CopilotLlmAuthProvider, CopilotLLMModel+from backend.copilot.engine import resolve_use_sdk+from backend.copilot.model_router import resolve_model_routefrom backend.copilot.transports import (ChatTransportResponse,get_chat_transports,is_deployment_chat_available,settings,)+from backend.integrations.codex.access import CODEX_MINIMUM_PLAN_ERROR, has_codex_access+from backend.util.feature_flag import Flag, is_feature_enabledfrom backend.util.settings import BehaveAslogger = logging.getLogger(__name__)@@ -36,15 +40,20 @@ TIER_LABELS: dict[CopilotLLMModel, str] = {class ConnectionTier(BaseModel):"""One quality level on a connection.- ``display_model`` is deliberately absent. Naming the model a tier will- resolve to needs the execution path, which is decided per turn by which- service handles it — and on ChatGPT it needs a live call against the- account. A name that is right half the time is worse here than no name.+ ``display_model`` is the model this tier resolves to, run through the+ same router the turn will use — LaunchDarkly cell, then registry, then+ config — so it cannot drift from what actually answers.++ It is ``None`` on a ChatGPT connection. Naming that model means asking+ the account what it advertises, which takes a runtime lease against the+ provider; doing that once per credential to render a list is the cost+ this endpoint exists to avoid."""tier: CopilotLLMModellabel: strselectable: bool+ display_model: str | None = Noneclass AIConnectionOffer(BaseModel):@@ -60,6 +69,8 @@ class AIConnectionOffer(BaseModel):is_default: booltiers: list[ConnectionTier]limitations: list[str]+ lock_reason: str | None = None+ unlock_href: str | None = Noneclass AIConnectionOffersResponse(BaseModel):@@ -67,7 +78,110 @@ class AIConnectionOffersResponse(BaseModel):async def get_connection_offers(user_id: str) -> list[AIConnectionOffer]:- return [_offer(transport) for transport in await get_chat_transports(user_id)]+ """Describe every connection, naming the models where they are knowable.++ The engine is resolved once for the user rather than per offer: it is a+ property of the deployment and the user, not of which connection they+ pick.+ """+ config = ChatConfig()+ models = await _platform_tier_models(user_id, config)+ offers = [+ _offer(transport, models) for transport in await get_chat_transports(user_id)+ ]+ locked = await _locked_codex_offer(user_id, offers)+ return offers + ([locked] if locked else [])+++async def _locked_codex_offer(+ user_id: str, offers: list[AIConnectionOffer]+) -> AIConnectionOffer | None:+ """The ChatGPT connection a plan does not include, shown rather than hidden.++ ``get_chat_transports`` answers what may run, and it is right to omit a+ transport the entitlement forbids -- anything that routes a turn reads+ that list, and an unroutable entry there would be a bug waiting to+ happen. What it cannot say is *why* the connection is missing, so a user+ below the plan sees no ChatGPT at all and no way to learn one exists.++ This offer says so, in the one place that exists to describe rather than+ route. It is never selectable and carries no credential, so nothing can+ accidentally send a turn down it.+ """+ if any(offer.provider_family == "openai" for offer in offers):+ return None+ if not _is_hosted():+ # Self-host grants the entitlement outright; there is nothing to sell.+ return None+ try:+ entitled = await has_codex_access(user_id)+ except Exception:+ # A missing upsell is harmless; falsely telling an already-entitled+ # user to buy a plan during an entitlement outage is not.+ logger.warning(+ "Unable to resolve Codex entitlement for user %s; hiding upsell",+ user_id,+ exc_info=True,+ )+ return None+ if entitled:+ # Entitled but unconnected: the settings page owns that invitation.+ return None+ if not await is_feature_enabled(Flag.CHAT_CONNECTION_UPSELL, user_id):+ return None++ return AIConnectionOffer(+ offer_id="codex:locked",+ provider_family="openai",+ display_name="ChatGPT",+ auth_method="chatgpt_oauth",+ credential_id=None,+ backed_by_label="Your ChatGPT plan",+ description=(+ "Run chats on a ChatGPT plan you already pay for, spending no "+ "AutoGPT credits."+ ),+ state="locked",+ selectable=False,+ is_default=False,+ tiers=[],+ limitations=[],+ lock_reason=CODEX_MINIMUM_PLAN_ERROR,+ unlock_href="/settings/billing",+ )+++async def _platform_tier_models(+ user_id: str, config: ChatConfig+) -> dict[CopilotLLMModel, str | None]:+ """Resolve each tier against the engine this user's turns will run on.++ Answerable at all only because nothing can name an engine per request+ any more — the decision is the server's, so it can be made before a turn+ exists rather than during one.+ """+ use_sdk = await resolve_use_sdk(+ user_id,+ use_claude_code_subscription=config.use_claude_code_subscription,+ config_default=config.use_claude_agent_sdk,+ thinking_available=config.thinking_available,+ )+ mode = "thinking" if use_sdk else "fast"+ resolved: dict[CopilotLLMModel, str | None] = {}+ for tier in TIER_LABELS:+ try:+ route = await resolve_model_route(mode, tier, user_id, config=config)+ resolved[tier] = route.model+ except Exception:+ # A tier that cannot be resolved is described without a name+ # rather than failing the whole list.+ logger.warning(+ "Could not resolve the %s model for the platform connection",+ tier,+ exc_info=True,+ )+ resolved[tier] = None+ return resolveddef offer_id_for(transport: ChatTransportResponse) -> str:@@ -79,7 +193,10 @@ def offer_id_for(transport: ChatTransportResponse) -> str:return f"{transport.auth_provider}:{transport.credential_id or 'deployment'}"-def _offer(transport: ChatTransportResponse) -> AIConnectionOffer:+def _offer(+ transport: ChatTransportResponse,+ platform_models: dict[CopilotLLMModel, str | None],+) -> AIConnectionOffer:return AIConnectionOffer(offer_id=offer_id_for(transport),provider_family=_provider_family(transport.auth_provider),@@ -92,7 +209,16 @@ def _offer(transport: ChatTransportResponse) -> AIConnectionOffer:selectable=transport.available,is_default=transport.default,tiers=[- ConnectionTier(tier=tier, label=label, selectable=transport.available)+ ConnectionTier(+ tier=tier,+ label=label,+ selectable=transport.available,+ display_model=(+ platform_models.get(tier)+ if transport.auth_provider == "platform"+ else None+ ),+ )for tier, label in TIER_LABELS.items()],limitations=_limitations(transport),diff --git a/autogpt_platform/backend/backend/copilot/offers_test.py b/autogpt_platform/backend/backend/copilot/offers_test.pyindex ffca12dfa9..f5be6f5384 100644--- a/autogpt_platform/backend/backend/copilot/offers_test.py+++ b/autogpt_platform/backend/backend/copilot/offers_test.py@@ -1,5 +1,6 @@"""The server-owned description of an AI connection."""+from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -33,6 +34,16 @@ def _transport(def hosted(mocker: pytest_mock.MockerFixture):mocker.patch.object(offers.settings.config, "behave_as", BehaveAs.CLOUD)mocker.patch.object(transports.settings.config, "behave_as", BehaveAs.CLOUD)+ mocker.patch.object(offers, "resolve_use_sdk", new=AsyncMock(return_value=False))+ mocker.patch.object(+ offers,+ "resolve_model_route",+ new=AsyncMock(+ side_effect=lambda mode, tier, user_id, *, config: SimpleNamespace(+ model=f"{mode}-{tier}-model", source="config"+ )+ ),+ )def _mock_transports(@@ -104,17 +115,64 @@ async def test_offer_ids_are_stable_and_per_account(@pytest.mark.asyncio-async def test_tiers_are_labelled_but_never_named_with_a_model(+async def test_tiers_name_the_model_they_resolve_to(+ mocker: pytest_mock.MockerFixture,+) -> None:+ _mock_transports(mocker, [_transport(default=True)])++ (offer,) = await get_connection_offers(USER_ID)++ assert [tier.label for tier in offer.tiers] == ["Balanced", "Advanced"]+ assert [tier.display_model for tier in offer.tiers] == [+ "fast-standard-model",+ "fast-advanced-model",+ ]+++async def test_tiers_follow_the_engine_the_user_will_actually_run_on(mocker: pytest_mock.MockerFixture,) -> None:- """Naming the model needs the execution path, decided per turn."""+ """The engine is the server's decision, so it is knowable before a turn."""+ mocker.patch.object(offers, "resolve_use_sdk", new=AsyncMock(return_value=True))_mock_transports(mocker, [_transport(default=True)])(offer,) = await get_connection_offers(USER_ID)+ assert [tier.display_model for tier in offer.tiers] == [+ "thinking-standard-model",+ "thinking-advanced-model",+ ]+++async def test_chatgpt_tiers_are_not_named(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """Naming them means leasing a runtime per credential to render a list."""+ _mock_transports(mocker, [_transport("codex", "cred-1", "ChatGPT")])++ (offer,) = await get_connection_offers(USER_ID)++ assert all(tier.display_model is None for tier in offer.tiers)assert [tier.label for tier in offer.tiers] == ["Balanced", "Advanced"]- assert [tier.tier for tier in offer.tiers] == ["standard", "advanced"]- assert not any(hasattr(tier, "display_model") for tier in offer.tiers)+++async def test_an_unresolvable_tier_is_described_without_a_name(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch.object(+ offers,+ "resolve_model_route",+ new=AsyncMock(side_effect=RuntimeError("registry down")),+ )+ _mock_transports(mocker, [_transport(default=True)])++ (offer,) = await get_connection_offers(USER_ID)++ assert all(tier.display_model is None for tier in offer.tiers)+ assert offer.state == "ready"@pytest.mark.asyncio@@ -162,3 +220,112 @@ async def test_exactly_one_offer_is_the_default(offer_list = await get_connection_offers(USER_ID)assert [offer.is_default for offer in offer_list].count(True) == 1+++def _upsell(+ mocker: pytest_mock.MockerFixture,+ *,+ entitled: bool = False,+ flag: bool = True,+) -> None:+ mocker.patch.object(+ offers,+ "has_codex_access",+ new=AsyncMock(return_value=entitled),+ )+ mocker.patch.object(offers, "is_feature_enabled", new=AsyncMock(return_value=flag))+++def _locked(offer_list: list) -> list:+ return [offer for offer in offer_list if offer.state == "locked"]+++async def test_a_plan_that_excludes_chatgpt_says_so_instead_of_hiding_it(+ mocker: pytest_mock.MockerFixture,+) -> None:+ _mock_transports(mocker, [_transport("platform", None)])+ _upsell(mocker)++ locked = _locked(await get_connection_offers("user"))++ assert len(locked) == 1+ assert locked[0].display_name == "ChatGPT"+ assert locked[0].lock_reason+ assert locked[0].unlock_href == "/settings/billing"+++async def test_a_locked_offer_can_never_be_routed_to(+ mocker: pytest_mock.MockerFixture,+) -> None:+ # The whole risk of showing an unusable connection is that something+ # picks it. It carries no credential and refuses selection, so the+ # picker cannot select it and a turn cannot be addressed to it.+ _mock_transports(mocker, [_transport("platform", None)])+ _upsell(mocker)++ locked = _locked(await get_connection_offers("user"))[0]++ assert locked.selectable is False+ assert locked.credential_id is None+ assert locked.is_default is False+++async def test_a_connected_account_is_never_shadowed_by_an_upsell(+ mocker: pytest_mock.MockerFixture,+) -> None:+ _mock_transports(+ mocker, [_transport("platform", None), _transport("codex", "cred-1")]+ )+ _upsell(mocker, entitled=True)++ assert _locked(await get_connection_offers("user")) == []+++async def test_being_entitled_but_unconnected_is_not_an_upsell(+ mocker: pytest_mock.MockerFixture,+) -> None:+ # Nothing to sell: the plan already includes it, so the invitation to+ # connect belongs on the settings page, not in the composer.+ _mock_transports(mocker, [_transport("platform", None)])+ _upsell(mocker, entitled=True)++ assert _locked(await get_connection_offers("user")) == []+++async def test_entitlement_outage_does_not_show_a_false_upsell(+ mocker: pytest_mock.MockerFixture,+) -> None:+ _mock_transports(mocker, [_transport("platform", None)])+ mocker.patch.object(+ offers,+ "has_codex_access",+ new=AsyncMock(side_effect=RuntimeError("entitlement unavailable")),+ )++ assert _locked(await get_connection_offers("user")) == []+++async def test_the_upsell_stays_off_until_its_cohort_is_opened(+ mocker: pytest_mock.MockerFixture,+) -> None:+ _mock_transports(mocker, [_transport("platform", None)])+ _upsell(mocker, flag=False)++ assert _locked(await get_connection_offers("user")) == []+++async def test_self_host_sells_nothing_because_it_grants_everything(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocker.patch.object(offers.settings.config, "behave_as", BehaveAs.LOCAL)+ _mock_transports(mocker, [_transport("platform", None)])+ _upsell(mocker)++ assert _locked(await get_connection_offers("user")) == []diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex 152232d11f..f9a74e6a3c 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -169,6 +169,13 @@ class Flag(str, Enum):# targeted.COPILOT_MODEL_ROUTING = "copilot-model-routing"+ # Shows a connection the user's plan does not include as a locked entry+ # in the connection list, rather than omitting it. Merchandising, not+ # access: the entitlement still decides what may actually run, and a+ # locked offer is never routable. Off by default so the upsell reaches+ # a cohort before it reaches everyone.+ CHAT_CONNECTION_UPSELL = "chat-connection-upsell"+def is_configured() -> bool:"""Check if LaunchDarkly is configured with an SDK key."""diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.tsindex 6b6c092032..688e26b49c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts@@ -125,6 +125,42 @@ describe("copilotStreamTransport.prepareSendMessagesRequest", () => {expect(body1.body.message_id).toMatch(UUID_RE);});+ it("sends the tier the picker holds, so the turn runs on what was chosen", async () => {+ // Regression: the tier was gated on CHAT_MODE_OPTION on the way to the+ // request while the picker that sets it was not gated at all. With the+ // flag off the control still moved and the turn still ran on the other+ // tier -- the label said Advanced and the reply came back from the+ // Balanced model. Whatever the ref holds has to reach the body.+ const transport = createCopilotTransport({+ sessionId: "sess-tier",+ ...makeRefs(),+ copilotModelRef: { current: "advanced" as const },+ });+ const prepared = await (+ transport as unknown as {+ prepareSendMessagesRequest: (args: {+ messages: ReturnType<typeof lastMessage>;+ }) => Promise<{ body: { model?: string | null } }>;+ }+ ).prepareSendMessagesRequest({ messages: lastMessage("hi") });+ expect(prepared.body.model).toBe("advanced");+ });++ it("sends a null tier when nothing is chosen, leaving the call to the server", async () => {+ const transport = createCopilotTransport({+ sessionId: "sess-tier-default",+ ...makeRefs(),+ });+ const prepared = await (+ transport as unknown as {+ prepareSendMessagesRequest: (args: {+ messages: ReturnType<typeof lastMessage>;+ }) => Promise<{ body: { model?: string | null } }>;+ }+ ).prepareSendMessagesRequest({ messages: lastMessage("hi") });+ expect(prepared.body.model).toBeNull();+ });+it("emits a different message_id per call so distinct user clicks dedupe " +"as distinct sends server-side",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsxindex 7ddd022ff3..ce2e24722e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx@@ -233,10 +233,11 @@ describe("useExpertKickoff", () => {renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);await waitFor(() => expect(createCount).toBe(1));+ // The route is omitted, not defaulted client-side: an unmade choice+ // stays unmade so the server applies the account's own default.expect(createBody).toEqual({expert_id: EXPERT_ID,expert_kickoff: true,- llm_auth_provider: "platform",});await waitFor(() => expect(sendSpy).toHaveBeenCalledTimes(1));diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsxindex 25d092e99b..ca9d0f3988 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx@@ -263,10 +263,10 @@ describe("useChatSession — expert sessions", () => {fireEvent.click(screen.getByRole("button", { name: "create" }));await waitFor(() => {- expect(createBody).toEqual({- expert_id: "expert-maria",- llm_auth_provider: "platform",- });+ // No route travels unless the user picked one. Naming it here would+ // make the server skip its own default, which is how a connection+ // chosen for one chat leaked into every later chat.+ expect(createBody).toEqual({ expert_id: "expert-maria" });});});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsxindex 6dccd46bfa..30fe193b00 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx@@ -32,8 +32,7 @@ import { ComposerPlusMenu } from "./components/ComposerPlusMenu";import { DryRunToggleButton } from "./components/DryRunToggleButton";import { FileChips } from "./components/FileChips";import { MentionDropdown } from "./components/MentionDropdown";-import { ModelToggleButton } from "./components/ModelToggleButton";-import { LLMRouteSelector } from "./components/LlmRouteSelector";+import { ConnectionPicker } from "./components/ConnectionPicker/ConnectionPicker";import { RecordingButton } from "./components/RecordingButton";import { RecordingIndicator } from "./components/RecordingIndicator";import { WorkspaceFilePicker } from "./components/WorkspaceFilePicker/WorkspaceFilePicker";@@ -94,8 +93,7 @@ export function ChatInput({hideSubmitWhenEmpty = false,recipientPicker,}: Props) {- const { copilotLlmModel, setCopilotLlmModel, isDryRun, setIsDryRun } =- useCopilotUIStore();+ const { isDryRun, setIsDryRun } = useCopilotUIStore();// Still the CHAT_MODE_OPTION flag, which no longer names what it gates: the// Fast/Thinking control it was created for is gone. Renaming it means an// LaunchDarkly change, so it is left until the combined picker restructures@@ -107,21 +105,6 @@ export function ChatInput({const [isPickerOpen, setIsPickerOpen] = useState(false);const [isMultiline, setIsMultiline] = useState(false);- function handleToggleModel() {- const next = copilotLlmModel === "advanced" ? "standard" : "advanced";- setCopilotLlmModel(next);- toast({- title:- next === "advanced"- ? "Switched to Advanced model"- : "Switched to Balanced model",- description:- next === "advanced"- ? "Using the highest-capability model."- : "Using the balanced default model.",- });- }-function handleToggleDryRun() {const next = !isDryRun;setIsDryRun(next);@@ -238,7 +221,6 @@ export function ChatInput({// Narrows to string, so the render site needn't re-test sessionId.const devtoolSessionId = isTokenDevtoolEnabled() ? sessionId : null;-const canSend =!disabled &&(!!value.trim() || hasAttachments) &&@@ -315,7 +297,11 @@ export function ChatInput({disabled={isBusy}/>{recipientPicker}- {!hasSession && <LLMRouteSelector />}+ {/* Connection and tier are per-message settings, so they remain+ changeable between turns in an existing session. */}+ {(!hasSession || !isStreaming) && (+ <ConnectionPicker connectionLocked={hasSession} />+ )}</InputGroupAddon>{/* Must be a real flex item: `order`/`w-full` are ignored on a`display: contents` box, which is what PromptInputBody was. */}@@ -350,12 +336,6 @@ export function ChatInput({align="inline-end"className="order-none ml-auto gap-1 py-1 pr-1.5">- {showAdvancedComposerControls && !isStreaming && (- <ModelToggleButton- model={copilotLlmModel}- onToggle={handleToggleModel}- />- )}{showAdvancedComposerControls && !hasSession && (<DryRunToggleButtonisDryRun={isDryRun}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsxindex 8b5d67fe8d..3bec8d091c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/__tests__/ChatInput.test.tsx@@ -20,21 +20,44 @@ const mockCancel =vi.fn<(sessionId: string) => Promise<{ status: number; data: unknown }>>();vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({postV2CancelSessionTask: (sessionId: string) => mockCancel(sessionId),- useGetV2ListChatTransports: () => ({+ // A lone platform connection whose tiers resolve to one model: the picker+ // presents nothing, which keeps these tests about the composer itself.+ useGetV2ListChatConnections: () => ({data: {status: 200,data: {- transports: [+ offers: [{- auth_provider: "platform",+ offer_id: "platform:deployment",+ provider_family: "autogpt",+ display_name: "AutoGPT Platform",+ auth_method: "deployment",credential_id: null,- label: "AutoGPT Platform",- available: true,- default: true,+ backed_by_label: "Your AutoGPT plan",+ description: "New chats are backed by your AutoGPT plan.",+ state: "ready",+ selectable: true,+ is_default: true,+ tiers: [+ {+ tier: "standard",+ label: "Balanced",+ selectable: true,+ display_model: "one-model",+ },+ {+ tier: "advanced",+ label: "Advanced",+ selectable: true,+ display_model: "one-model",+ },+ ],+ limitations: [],},],},},+ isLoading: false,isPending: false,isError: false,}),@@ -273,27 +296,7 @@ describe("ChatInput token devtool badge", () => {});});-describe("ChatInput advanced composer controls", () => {- it("does not render advanced controls when the flag is disabled", () => {- mockFlagValue = false;- render(<ChatInput onSend={mockOnSend} />);- expect(screen.queryByLabelText(/switch to/i)).toBeNull();- });-- it("renders the model toggle when the flag is enabled", () => {- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} />);- expect(screen.getByLabelText(/switch to advanced model/i)).toBeDefined();- });-- it("shows the Codex model control backed by the model catalog", () => {- mockFlagValue = true;- mockCopilotLlmAuthProvider = "codex";- render(<ChatInput onSend={mockOnSend} />);-- expect(screen.getByLabelText(/switch to advanced model/i)).toBeTruthy();- });-+describe("ChatInput Codex route", () => {it("keeps Claude SDK file attachments available for the Codex route", () => {mockCopilotLlmAuthProvider = "codex";render(<ChatInput onSend={mockOnSend} />);@@ -323,22 +326,6 @@ describe("ChatInput advanced composer controls", () => {rerender(<ChatInput onSend={mockOnSend} hasSession />);expect(screen.queryByLabelText(/AI connection:/i)).toBeNull();});-- it("hides the model toggle when streaming", () => {- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} isStreaming />);- expect(- screen.queryByLabelText(/switch to (advanced|balanced|standard) model/i),- ).toBeNull();- });-- it("shows the model toggle between turns of an existing session", () => {- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} hasSession />);- expect(- screen.queryByLabelText(/switch to (advanced|balanced|standard) model/i),- ).not.toBeNull();- });});describe("ChatInput queue button", () => {@@ -434,95 +421,6 @@ describe("ChatInput dry-run toggle", () => {});});-describe("ChatInput model toggle", () => {- it("renders model toggle button when flag is enabled", () => {- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} />);- expect(screen.getByLabelText(/switch to advanced model/i)).toBeDefined();- });-- it("does not render model toggle when flag is disabled", () => {- mockFlagValue = false;- render(<ChatInput onSend={mockOnSend} />);- expect(- screen.queryByLabelText(/switch to (advanced|standard) model/i),- ).toBeNull();- });-- it("toggles from standard to advanced on click", () => {- mockFlagValue = true;- mockCopilotLlmModel = "standard";- render(<ChatInput onSend={mockOnSend} />);- fireEvent.click(screen.getByLabelText(/switch to advanced model/i));- expect(mockSetCopilotLlmModel).toHaveBeenCalledWith("advanced");- });-- it("toggles from advanced to standard on click", () => {- mockFlagValue = true;- mockCopilotLlmModel = "advanced";- render(<ChatInput onSend={mockOnSend} />);- fireEvent.click(screen.getByLabelText(/switch to balanced model/i));- expect(mockSetCopilotLlmModel).toHaveBeenCalledWith("standard");- });-- it("hides model toggle when streaming", () => {- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} isStreaming />);- expect(- screen.queryByLabelText(/switch to (advanced|standard) model/i),- ).toBeNull();- });-- it("shows model toggle when hasSession is true and not streaming", () => {- // Model is per-message — can be changed between turns even in an existing session.- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} hasSession />);- expect(- screen.queryByLabelText(/switch to (advanced|standard) model/i),- ).not.toBeNull();- });-- it("hides dry-run toggle when hasSession is true", () => {- // DryRun button is only for new chats — once a session exists its dry_run- // flag is immutable and shown via the CopilotPage banner, not this button.- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} hasSession />);- expect(screen.queryByTestId("dry-run-toggle")).toBeNull();- });-- it("shows dry-run toggle when no session", () => {- mockFlagValue = true;- render(<ChatInput onSend={mockOnSend} />);- expect(screen.getByTestId("dry-run-toggle")).toBeTruthy();- });-- it("shows a toast when switching to advanced", async () => {- const { toast } = await import("@/components/molecules/Toast/use-toast");- mockFlagValue = true;- mockCopilotLlmModel = "standard";- render(<ChatInput onSend={mockOnSend} />);- fireEvent.click(screen.getByLabelText(/switch to advanced model/i));- expect(toast).toHaveBeenCalledWith(- expect.objectContaining({- title: expect.stringMatching(/switched to advanced model/i),- }),- );- });-- it("shows a toast when switching to standard", async () => {- const { toast } = await import("@/components/molecules/Toast/use-toast");- mockFlagValue = true;- mockCopilotLlmModel = "advanced";- render(<ChatInput onSend={mockOnSend} />);- fireEvent.click(screen.getByLabelText(/switch to balanced model/i));- expect(toast).toHaveBeenCalledWith(- expect.objectContaining({- title: expect.stringMatching(/switched to balanced model/i),- }),- );- });-});-describe("ChatInput guided prompt prefill", () => {it("prefills the composer and focuses it when an initial prompt arrives after mount", async () => {const { rerender } = render(<ChatInput onSend={mockOnSend} />);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ChoiceRow.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ChoiceRow.tsxnew file mode 100644index 0000000000..372fa44e48--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ChoiceRow.tsx@@ -0,0 +1,122 @@+"use client";++import { cn } from "@/lib/utils";+import Link from "next/link";+import { PiLockSimple as LockIcon } from "react-icons/pi";++interface Props {+ title: string;+ subtitle?: string;+ notes?: string[];+ isSelected: boolean;+ onSelect: () => void;+ /**+ * The accessible name, when the visible title alone would not identify the+ * choice — a tier reads as "Balanced · sonnet-5" while showing the model on+ * its own line, so the name a screen reader announces stays complete.+ */+ label?: string;+ /** Why this cannot be chosen, and where to go to change that. */+ lock?: { reason: string; href: string | null };+}++export function ChoiceRow({+ title,+ subtitle,+ notes,+ isSelected,+ onSelect,+ label,+ lock,+}: Props) {+ if (lock) {+ return <LockedRow title={title} subtitle={subtitle} lock={lock} />;+ }++ return (+ <button+ type="button"+ role="radio"+ aria-checked={isSelected}+ aria-label={label}+ onClick={onSelect}+ className={cn(+ "flex w-full items-start gap-2.5 px-3 py-2 text-left transition-colors",+ "focus-visible:bg-muted focus-visible:outline-none",+ isSelected ? "bg-muted/60" : "hover:bg-muted/40",+ )}+ >+ <span+ aria-hidden+ className={cn(+ "mt-[3px] flex h-3.5 w-3.5 flex-none items-center justify-center rounded-full border",+ isSelected ? "border-primary" : "border-muted-foreground/50",+ )}+ >+ {isSelected && (+ <span className="h-1.5 w-1.5 rounded-full bg-primary" aria-hidden />+ )}+ </span>+ <span className="flex min-w-0 flex-col">+ <span className="text-xs font-medium text-foreground">{title}</span>+ {subtitle && (+ <span className="break-words text-[11px] leading-snug text-muted-foreground">+ {subtitle}+ </span>+ )}+ {notes?.map((note) => (+ <span+ key={note}+ className="mt-0.5 text-[11px] leading-snug text-muted-foreground/80"+ >+ {note}+ </span>+ ))}+ </span>+ </button>+ );+}++interface LockedProps {+ title: string;+ subtitle?: string;+ lock: { reason: string; href: string | null };+}++/**+ * Not a radio: this is not a choice, and offering it as one would invite a+ * click that cannot do anything. It states what the connection is, why it is+ * unavailable, and the one action that changes that.+ */+function LockedRow({ title, subtitle, lock }: LockedProps) {+ return (+ <div className="flex items-start gap-2.5 px-3 py-2">+ <LockIcon+ size={14}+ aria-hidden+ className="mt-[3px] flex-none text-muted-foreground/70"+ />+ <span className="flex min-w-0 flex-col">+ <span className="text-xs font-medium text-muted-foreground">+ {title}+ </span>+ {subtitle && (+ <span className="break-words text-[11px] leading-snug text-muted-foreground/80">+ {subtitle}+ </span>+ )}+ <span className="mt-0.5 text-[11px] leading-snug text-muted-foreground/80">+ {lock.reason}+ </span>+ {lock.href && (+ <Link+ href={lock.href}+ className="mt-1 w-fit text-[11px] font-medium text-primary underline underline-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"+ >+ See plans+ </Link>+ )}+ </span>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsxnew file mode 100644index 0000000000..98af38d794--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/ConnectionPicker.tsx@@ -0,0 +1,168 @@+"use client";++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from "@/components/molecules/DropdownMenu/DropdownMenu";+import Link from "next/link";+import {+ PiCaretDown as CaretDownIcon,+ PiKey as KeyIcon,+ PiWarningCircle as WarningCircleIcon,+} from "react-icons/pi";++import { ChoiceRow } from "./ChoiceRow";+import { offerSubtitle, tierLabel, tierModel, tierName } from "./helpers";+import { useConnectionPicker } from "./useConnectionPicker";++const TIERS = ["standard", "advanced"] as const;++interface Props {+ /**+ * The connection is settled and only the tier is still open.+ *+ * A session's connection is chosen when it is created and fixed for its+ * lifetime, but the tier is a per-message setting -- it can change between+ * turns of a chat already underway. Hiding the whole control once a session+ * exists would take that away.+ */+ connectionLocked?: boolean;+}++/**+ * One control for what a turn runs on: the connection, and the quality tier+ * within it. Both come from the server-owned connection offer, so the client+ * decides nothing about routing, billing copy, or which models a tier maps to.+ */+export function ConnectionPicker({ connectionLocked = false }: Props) {+ const {+ offers,+ active,+ chooseConnection,+ tier,+ setTier,+ showTiers,+ isLoading,+ isError,+ } = useConnectionPicker();++ if (isLoading && offers.length === 0) return null;++ if (isError) {+ return (+ <span+ aria-label="AI connections unavailable"+ className="ml-2 inline-flex h-9 items-center gap-1.5 rounded-full border border-destructive/20 bg-destructive/10 px-2.5 text-xs font-medium text-destructive"+ >+ <WarningCircleIcon size={14} />+ <span className="hidden sm:inline">Connections unavailable</span>+ </span>+ );+ }++ if (offers.length === 0) {+ return (+ <Link+ href="/settings/integrations"+ aria-label="Set up an AI connection"+ className="ml-2 inline-flex h-9 items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted/80"+ >+ <WarningCircleIcon size={14} />+ <span className="hidden sm:inline">Set up AI connection</span>+ </Link>+ );+ }++ // Nothing left to decide when the one offer can actually run. A locked-only+ // offer still needs this control so the user can see why it is unavailable+ // and follow its unlock link.+ const onlyOfferIsLocked =+ offers.length === 1 && Boolean(offers[0]?.lock_reason);+ if (+ !showTiers &&+ !onlyOfferIsLocked &&+ (connectionLocked || offers.length === 1)+ ) {+ return null;+ }++ const showsTier = connectionLocked && Boolean(active);+ const label = showsTier+ ? tierName(active, tier)+ : (active?.display_name ?? "Choose connection");++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={+ showsTier+ ? `Model tier ${label} — change`+ : `Runs on ${label} — change`+ }+ className="ml-2 inline-flex h-9 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-xs font-medium text-foreground shadow-sm transition-colors hover:bg-muted"+ >+ <KeyIcon size={14} />+ <span className="hidden sm:inline">{label}</span>+ <CaretDownIcon size={12} className="text-muted-foreground" />+ </button>+ </DropdownMenuTrigger>++ <DropdownMenuContent align="start" className="w-80 p-0">+ {(!connectionLocked || onlyOfferIsLocked) && (+ <>+ <SectionLabel>Runs on</SectionLabel>+ <div role="radiogroup" aria-label="Connection this chat runs on">+ {offers.map((offer) => (+ <ChoiceRow+ key={offer.offer_id}+ title={offer.display_name}+ subtitle={offerSubtitle(offer)}+ notes={offer.limitations}+ isSelected={offer.offer_id === active?.offer_id}+ onSelect={() => chooseConnection(offer)}+ lock={+ offer.lock_reason+ ? {+ reason: offer.lock_reason,+ href: offer.unlock_href ?? null,+ }+ : undefined+ }+ />+ ))}+ </div>+ </>+ )}++ {showTiers && (+ <>+ <SectionLabel>Model tier</SectionLabel>+ <div role="radiogroup" aria-label="Model tier">+ {TIERS.map((candidate) => (+ <ChoiceRow+ key={candidate}+ title={tierName(active, candidate)}+ subtitle={tierModel(active, candidate) ?? undefined}+ label={tierLabel(active, candidate)}+ isSelected={tier === candidate}+ onSelect={() => setTier(candidate)}+ />+ ))}+ </div>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function SectionLabel({ children }: { children: React.ReactNode }) {+ return (+ <p className="px-3 pb-1 pt-3 text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground">+ {children}+ </p>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.tsnew file mode 100644index 0000000000..d3f0e13d0d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/helpers.ts@@ -0,0 +1,107 @@+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import type { CopilotLlmAuthSelection } from "../../../../store";++export function offerToSelection(+ offer: AIConnectionOffer,+): CopilotLlmAuthSelection | null {+ if (offer.auth_method === "deployment") {+ return { authProvider: "platform", credentialId: null };+ }+ if (!offer.credential_id) return null;+ return { authProvider: "codex", credentialId: offer.credential_id };+}++export function matchesSelection(+ offer: AIConnectionOffer,+ selection: CopilotLlmAuthSelection | null,+): boolean {+ if (!selection) return false;+ if (selection.authProvider === "platform") {+ return offer.auth_method === "deployment";+ }+ return offer.credential_id === selection.credentialId;+}++export function isSelectable(offer: AIConnectionOffer): boolean {+ return (+ offer.selectable &&+ (offer.auth_method === "deployment" || offer.credential_id !== null)+ );+}++/**+ * Every offer worth showing, selectable or not.+ *+ * A locked offer earns its place by explaining an absence the user would+ * otherwise have to guess at, so it is listed; {@link isSelectable} is what+ * decides whether it can be chosen. An offer that is neither selectable nor+ * able to say why is just a dead row, so it is dropped.+ */+export function visibleOffers(+ offers: AIConnectionOffer[] | undefined,+): AIConnectionOffer[] {+ return (offers ?? []).filter(+ (offer) => isSelectable(offer) || Boolean(offer.lock_reason),+ );+}++/**+ * Whether picking a tier on this connection means anything.+ *+ * A deployment can resolve both tiers to the same model — a single-model+ * self-host does exactly that — and offering a choice between two identical+ * options is a decision with no consequence. Where the server cannot name+ * the models at all, the tiers are kept: unknown is not the same as equal.+ */+export function tiersAreDistinct(+ offer: AIConnectionOffer | undefined,+): boolean {+ if (!offer || offer.tiers.length < 2) return false;+ const named = offer.tiers.filter((tier) => tier.display_model);+ if (named.length < offer.tiers.length) return true;+ return new Set(named.map((tier) => tier.display_model)).size > 1;+}++function tierOf(offer: AIConnectionOffer | undefined, tier: string) {+ return offer?.tiers.find((candidate) => candidate.tier === tier);+}++export function tierName(+ offer: AIConnectionOffer | undefined,+ tier: string,+): string {+ return (+ tierOf(offer, tier)?.label ??+ (tier === "advanced" ? "Advanced" : "Balanced")+ );+}++export function tierModel(+ offer: AIConnectionOffer | undefined,+ tier: string,+): string | null {+ return tierOf(offer, tier)?.display_model ?? null;+}++/** The whole choice in one string, for an accessible name. */+export function tierLabel(+ offer: AIConnectionOffer | undefined,+ tier: string,+): string {+ const model = tierModel(offer, tier);+ const name = tierName(offer, tier);+ return model ? `${name} · ${model}` : name;+}++/**+ * The line under a connection's name.+ *+ * An available connection says what pays for it. A locked one says what the+ * user would get, because "Your ChatGPT plan" presumes a plan they may not+ * have -- and sitting directly above "a Max plan or higher is required" it+ * reads as two different plans. A row the user cannot act on has to justify+ * the space it takes.+ */+export function offerSubtitle(offer: AIConnectionOffer): string {+ return offer.lock_reason ? offer.description : offer.backed_by_label;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/useConnectionPicker.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/useConnectionPicker.tsnew file mode 100644index 0000000000..baaa2b5fe9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/useConnectionPicker.ts@@ -0,0 +1,67 @@+"use client";++import { useGetV2ListChatConnections } from "@/app/api/__generated__/endpoints/chat/chat";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";++import { useCopilotUIStore } from "../../../../store";+import {+ isSelectable,+ matchesSelection,+ offerToSelection,+ tiersAreDistinct,+ visibleOffers,+} from "./helpers";++export function useConnectionPicker() {+ const query = useGetV2ListChatConnections({+ query: { refetchOnWindowFocus: true, staleTime: 0 },+ });+ const {+ copilotLlmAuth,+ setCopilotLlmAuth,+ copilotLlmModel,+ setCopilotLlmModel,+ } = useCopilotUIStore();++ const offers = visibleOffers(+ query.data?.status === 200 ? query.data.data.offers : undefined,+ );+ // Only ever consider what can actually run: a locked offer is listed to+ // explain itself, never to be landed on.+ const choosable = offers.filter(isSelectable);+ const selected = choosable.find((offer) =>+ matchesSelection(offer, copilotLlmAuth),+ );++ // Nothing chosen yet, or the chosen connection is gone: show the one the+ // server marks default. Showing it is all this does -- writing it into the+ // store would turn "follow the server" into a standing choice, and the+ // store has no way back to null: a connection picked for one chat would+ // silently become the default for every later chat, a new default set in+ // Settings could never take over, and the create call would always name a+ // route, which makes the server skip its own default. Deciding where a chat+ // starts is the server's job, so an unmade choice stays unmade.+ const fallback = choosable.find((offer) => offer.is_default) ?? choosable[0];++ const active = selected ?? fallback;++ function chooseConnection(offer: AIConnectionOffer) {+ if (!isSelectable(offer)) return;+ const selection = offerToSelection(offer);+ if (selection) setCopilotLlmAuth(selection);+ }++ return {+ offers,+ active,+ chooseConnection,+ tier: copilotLlmModel,+ setTier: setCopilotLlmModel,+ showTiers: tiersAreDistinct(active),+ isLoading: query.isLoading,+ // React Query can retain the last successful offers while a background+ // refetch fails. Keep that usable snapshot visible; the error state is+ // only terminal when there is nothing to render.+ isError: query.isError && offers.length === 0,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsxdeleted file mode 100644index 4c9290fd4b..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsx+++ /dev/null@@ -1,194 +0,0 @@-"use client";--import { useGetV2ListChatTransports } from "@/app/api/__generated__/endpoints/chat/chat";-import type { ChatTransportResponse } from "@/app/api/__generated__/models/chatTransportResponse";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/molecules/DropdownMenu/DropdownMenu";-import { toast } from "@/components/molecules/Toast/use-toast";-import { cn } from "@/lib/utils";-import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";-import Link from "next/link";-import { useContext, useEffect } from "react";-import {- PiCaretDown as CaretDownIcon,- PiKey as KeyIcon,- PiWarningCircle as WarningCircleIcon,-} from "react-icons/pi";-import {- findSelectedLLMTransport,- getAvailableLLMTransports,- getChatTransportSelection,- resolveCopilotLLMAuthSelection,-} from "../../../helpers/copilotLlmAuth";-import { useCopilotUIStore } from "../../../store";--function getTransportDescription(- transport: ChatTransportResponse,- credentialTitle: string | undefined,-): string {- if (transport.auth_provider === "codex") {- return credentialTitle- ? `${credentialTitle} · Uses your ChatGPT plan`- : "Uses your ChatGPT plan";- }- return transport.label === "AutoGPT Platform"- ? "Uses your AutoGPT plan"- : "Uses this server's configured chat provider";-}--export function LLMRouteSelector() {- const providers = useContext(CredentialsProvidersContext);- const transportQuery = useGetV2ListChatTransports({- query: { refetchOnWindowFocus: true, staleTime: 0 },- });- const transports =- transportQuery.data?.status === 200- ? transportQuery.data.data.transports- : undefined;- const availableTransports = getAvailableLLMTransports(transports);- const {- copilotLlmAuth: copilotLLMAuth,- setCopilotLlmAuth: setCopilotLLMAuth,- } = useCopilotUIStore();- const resolvedSelection = resolveCopilotLLMAuthSelection(- transports,- copilotLLMAuth,- );- // Before anything is chosen the trigger still names the connection the chat- // will actually start on, rather than flashing "Choose connection" for the- // one render before the effect below adopts the default.- const selectedTransport = findSelectedLLMTransport(- availableTransports,- copilotLLMAuth ?? resolvedSelection,- );- const selectedConnectionMissing =- transports !== undefined &&- availableTransports.length > 0 &&- copilotLLMAuth !== null &&- copilotLLMAuth.authProvider !== "platform" &&- !selectedTransport;-- useEffect(() => {- if (!resolvedSelection) return;- if (- resolvedSelection.authProvider === copilotLLMAuth?.authProvider &&- resolvedSelection.credentialId === copilotLLMAuth?.credentialId- ) {- return;- }-- setCopilotLLMAuth(resolvedSelection);- }, [- copilotLLMAuth?.authProvider,- copilotLLMAuth?.credentialId,- resolvedSelection?.authProvider,- resolvedSelection?.credentialId,- setCopilotLLMAuth,- ]);-- useEffect(() => {- if (!selectedConnectionMissing) return;-- toast({- title: "AI connections changed",- description:- "The selected connection is unavailable. The next AutoPilot task will use the available default.",- });- }, [selectedConnectionMissing]);-- if (transportQuery.isPending && transports === undefined) return null;-- if (transports === undefined) {- return (- <span- aria-label="AI connections unavailable"- className="ml-2 inline-flex h-9 items-center gap-1.5 rounded-full border border-destructive/20 bg-destructive/10 px-2.5 text-xs font-medium text-destructive"- >- <WarningCircleIcon size={14} />- <span className="hidden sm:inline">Connections unavailable</span>- </span>- );- }-- if (availableTransports.length === 0) {- return (- <Link- href="/settings/integrations"- aria-label="Set up an AI connection"- className="ml-2 inline-flex h-9 items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted/80"- >- <WarningCircleIcon size={14} />- <span className="hidden sm:inline">Set up AI connection</span>- </Link>- );- }-- if (availableTransports.length === 1) return null;-- const selectionLabel = selectedConnectionMissing- ? "Connection unavailable"- : (selectedTransport?.label ?? "Choose connection");-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- aria-label={`AI connection: ${selectionLabel} — change connection`}- className={cn(- "ml-2 inline-flex h-9 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-xs font-medium shadow-sm transition-colors hover:bg-muted",- selectedConnectionMissing ? "text-destructive" : "text-foreground",- )}- >- {selectedConnectionMissing ? (- <WarningCircleIcon size={14} />- ) : (- <KeyIcon size={14} />- )}- <span className="hidden sm:inline">{selectionLabel}</span>- <CaretDownIcon size={12} className="text-muted-foreground" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-72">- {selectedConnectionMissing && (- <DropdownMenuItem disabled className="gap-2 text-destructive">- <WarningCircleIcon size={16} />- Selected connection is unavailable- </DropdownMenuItem>- )}- {availableTransports.map((transport) => {- const selection = getChatTransportSelection(transport);- if (!selection) return null;- const credential =- transport.auth_provider === "codex"- ? providers?.codex?.savedCredentials.find(- (candidate) => candidate.id === transport.credential_id,- )- : undefined;- const isSelected =- selectedTransport?.auth_provider === transport.auth_provider &&- selectedTransport.credential_id === transport.credential_id;- return (- <DropdownMenuItem- key={`${transport.auth_provider}:${transport.credential_id ?? "deployment"}`}- onClick={() => setCopilotLLMAuth(selection)}- className={cn("gap-2", isSelected && "bg-muted")}- >- <KeyIcon size={16} />- <div className="min-w-0">- <div>{transport.label}</div>- <div className="truncate text-xs text-muted-foreground">- {getTransportDescription(transport, credential?.title)}- </div>- </div>- </DropdownMenuItem>- );- })}- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsxdeleted file mode 100644index 6283081b22..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ModelToggleButton.tsx+++ /dev/null@@ -1,50 +0,0 @@-"use client";--import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from "@/components/ui/tooltip";-import { Icon } from "@/components/atoms/Icon/Icon";-import { cn } from "@/lib/utils";-import { CpuIcon } from "@hugeicons/core-free-icons";-import type { CopilotLlmModel } from "../../../store";--interface Props {- model: CopilotLlmModel;- onToggle: () => void;-}--export function ModelToggleButton({ model, onToggle }: Props) {- const isAdvanced = model === "advanced";- const tooltip = isAdvanced- ? "Using the highest-capability model (click to switch to Balanced)."- : "Using the balanced default model (click to switch to Advanced).";- const ariaLabel = isAdvanced- ? "Switch to Balanced model"- : "Switch to Advanced model";-- return (- <Tooltip>- <TooltipTrigger asChild>- <button- type="button"- aria-pressed={isAdvanced}- onClick={onToggle}- className={cn(- "inline-flex h-8 w-8 items-center justify-center rounded-full transition-colors hover:bg-zinc-100",- // Model tier drives cost and quality, and a tooltip never opens on- // touch — so the raised tier has to be visible on the icon itself.- isAdvanced- ? "text-emerald-600 hover:text-emerald-700"- : "text-zinc-500 hover:text-zinc-700",- )}- aria-label={ariaLabel}- >- <Icon icon={CpuIcon} size={16} />- </button>- </TooltipTrigger>- <TooltipContent>{tooltip}</TooltipContent>- </Tooltip>- );-}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsxnew file mode 100644index 0000000000..d36456ce5d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ConnectionPicker.test.tsx@@ -0,0 +1,439 @@+import {+ getGetV2ListChatConnectionsMockHandler200,+ getGetV2ListChatConnectionsMockHandler401,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import type { ConnectionTier } from "@/app/api/__generated__/models/connectionTier";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it } from "vitest";++import { useCopilotUIStore } from "../../../../store";+import { ConnectionPicker } from "../ConnectionPicker/ConnectionPicker";++function tier(+ name: ConnectionTier["tier"],+ label: string,+ model: string | null,+): ConnectionTier {+ return { tier: name, label, selectable: true, display_model: model };+}++function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {+ return {+ offer_id: "platform:deployment",+ provider_family: "autogpt",+ display_name: "AutoGPT Platform",+ auth_method: "deployment",+ credential_id: null,+ backed_by_label: "Your AutoGPT plan",+ description: "New chats are backed by your AutoGPT plan.",+ state: "ready",+ selectable: true,+ is_default: true,+ tiers: [+ tier("standard", "Balanced", "sonnet-5"),+ tier("advanced", "Advanced", "opus-5"),+ ],+ limitations: [],+ ...over,+ } as AIConnectionOffer;+}++const chatgpt = (over: Partial<AIConnectionOffer> = {}) =>+ offer({+ offer_id: "codex:cred-1",+ provider_family: "openai",+ display_name: "ChatGPT",+ auth_method: "chatgpt_oauth",+ credential_id: "cred-1",+ backed_by_label: "Your ChatGPT plan",+ is_default: false,+ tiers: [+ tier("standard", "Balanced", null),+ tier("advanced", "Advanced", null),+ ],+ limitations: ["The agent builder's chat panel always runs on AutoGPT."],+ ...over,+ });++const locked = (over: Partial<AIConnectionOffer> = {}) =>+ offer({+ offer_id: "codex:locked",+ provider_family: "openai",+ display_name: "ChatGPT",+ auth_method: "chatgpt_oauth",+ credential_id: null,+ backed_by_label: "Your ChatGPT plan",+ state: "locked",+ selectable: false,+ is_default: false,+ tiers: [],+ limitations: [],+ description:+ "Run chats on a ChatGPT plan you already pay for, spending no AutoGPT credits.",+ lock_reason: "A Max plan or higher is required to use ChatGPT.",+ unlock_href: "/settings/billing",+ ...over,+ });++function mockOffers(offers: AIConnectionOffer[]) {+ server.use(getGetV2ListChatConnectionsMockHandler200({ offers }));+}++beforeEach(() => {+ useCopilotUIStore.setState({+ copilotLlmAuth: null,+ copilotLlmModel: "standard",+ });+});++describe("ConnectionPicker", () => {+ it("says what backs a run on each connection", async () => {+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(await screen.findByText("Your AutoGPT plan")).toBeDefined();+ expect(screen.getByText("Your ChatGPT plan")).toBeDefined();+ });++ it("falls in behind the connection the server marks default", async () => {+ mockOffers([offer({ is_default: false }), chatgpt({ is_default: true })]);++ render(<ConnectionPicker />);++ expect(+ await screen.findByRole("button", { name: /Runs on ChatGPT/ }),+ ).toBeDefined();+ });++ it("names the model behind each tier where the server knows it", async () => {+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(+ await screen.findByRole("radio", { name: "Balanced · sonnet-5" }),+ ).toBeDefined();+ expect(+ screen.getByRole("radio", { name: "Advanced · opus-5" }),+ ).toBeDefined();+ });++ it("gives the model its own line so a long name stays readable", async () => {+ // The model is the reason the tier row exists; sharing one line with the+ // label truncates it away on any realistic model id.+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(await screen.findByText("sonnet-5")).toBeDefined();+ expect(screen.getByText("opus-5")).toBeDefined();+ });++ it("puts the chosen tier in the store", async () => {+ // The picker is the only place a tier is chosen, and the store is the only+ // thing the send path reads. A regression once gated the value -- but not+ // this control -- on CHAT_MODE_OPTION, so the segment moved to Advanced+ // and the turn still ran Balanced. Landing the choice here is the contract+ // the send path depends on.+ mockOffers([offer()]);+ render(<ConnectionPicker connectionLocked />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Model tier/ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: "Advanced · opus-5" }),+ );++ await waitFor(() =>+ expect(useCopilotUIStore.getState().copilotLlmModel).toBe("advanced"),+ );+ });++ it("shows the server default without claiming it as a choice", async () => {+ // The store is what the create call treats as an override, and it has no+ // way back to null. Writing the default into it on render made every+ // later chat inherit whatever this one displayed, and made a default+ // changed in Settings unable to take over. Displaying is not choosing.+ mockOffers([offer(), chatgpt()]);+ render(<ConnectionPicker />);++ expect(+ await screen.findByRole("button", { name: /AutoGPT Platform/ }),+ ).toBeDefined();+ expect(useCopilotUIStore.getState().copilotLlmAuth).toBeNull();+ });++ it("records the connection once the user actually picks one", async () => {+ mockOffers([offer(), chatgpt()]);+ render(<ConnectionPicker />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /ChatGPT/ }),+ );++ await waitFor(() =>+ expect(useCopilotUIStore.getState().copilotLlmAuth).toMatchObject({+ authProvider: "codex",+ }),+ );+ });++ it("offers no tier choice when both tiers are the same model", async () => {+ // A single-model self-host resolves both tiers identically; choosing+ // between two identical options is a decision with no consequence.+ mockOffers([+ offer({+ tiers: [+ tier("standard", "Balanced", "ornith-1.5-9b"),+ tier("advanced", "Advanced", "ornith-1.5-9b"),+ ],+ }),+ chatgpt(),+ ]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ await waitFor(() =>+ expect(+ screen.queryByRole("radiogroup", { name: "Model tier" }),+ ).toBeNull(),+ );+ });++ it("keeps the tiers when the models are merely unknown", async () => {+ // Unknown is not the same as equal — a ChatGPT connection cannot name its+ // models without a provider call, which is not a reason to hide the choice.+ mockOffers([chatgpt({ is_default: true })]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(+ await screen.findByRole("radio", { name: "Balanced" }),+ ).toBeDefined();+ });++ it("switches the connection a chat will run on", async () => {+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );+ await userEvent.click(+ await screen.findByRole("radio", { name: /ChatGPT/ }),+ );++ await waitFor(() =>+ expect(useCopilotUIStore.getState().copilotLlmAuth).toEqual({+ authProvider: "codex",+ credentialId: "cred-1",+ }),+ );+ });++ it("surfaces a limitation the user can actually hit", async () => {+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(+ await screen.findByText(/builder's chat panel always runs on AutoGPT/),+ ).toBeDefined();+ });++ it("stays out of the way when there is nothing to choose", async () => {+ mockOffers([+ offer({+ tiers: [+ tier("standard", "Balanced", "one-model"),+ tier("advanced", "Advanced", "one-model"),+ ],+ }),+ ]);++ render(<ConnectionPicker />);++ await waitFor(() =>+ expect(screen.queryByRole("button", { name: /Runs on/ })).toBeNull(),+ );+ });++ it("still lets an underway chat change its model tier", async () => {+ // The connection is fixed when a session is created, but the tier is a+ // per-message setting -- it was changeable between turns before the two+ // controls were merged, and must stay so.+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker connectionLocked />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Model tier/ }),+ );++ expect(+ await screen.findByRole("radio", { name: "Advanced · opus-5" }),+ ).toBeDefined();+ });++ it("does not offer to move an underway chat to another connection", async () => {+ mockOffers([offer(), chatgpt()]);++ render(<ConnectionPicker connectionLocked />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Model tier/ }),+ );++ await waitFor(() =>+ expect(+ screen.queryByRole("radiogroup", {+ name: "Connection this chat runs on",+ }),+ ).toBeNull(),+ );+ });++ it("stays out of an underway chat that has no tier to choose", async () => {+ mockOffers([+ offer({+ tiers: [+ tier("standard", "Balanced", "one-model"),+ tier("advanced", "Advanced", "one-model"),+ ],+ }),+ chatgpt(),+ ]);++ render(<ConnectionPicker connectionLocked />);++ await waitFor(() =>+ expect(screen.queryByRole("button", { name: /Model tier/ })).toBeNull(),+ );+ });++ it("says why a connection the plan excludes is unavailable", async () => {+ mockOffers([offer(), locked()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(await screen.findByText("ChatGPT")).toBeDefined();+ expect(+ screen.getByText("A Max plan or higher is required to use ChatGPT."),+ ).toBeDefined();+ expect(screen.getByRole("link", { name: "See plans" })).toBeDefined();+ });++ it("keeps a locked-only offer visible", async () => {+ mockOffers([locked()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on Choose connection/ }),+ );++ expect(+ await screen.findByText(+ "A Max plan or higher is required to use ChatGPT.",+ ),+ ).toBeDefined();+ expect(screen.getByRole("link", { name: "See plans" })).toBeDefined();+ });++ it("keeps a locked-only offer visible after an underway chat loses access", async () => {+ mockOffers([locked()]);++ render(<ConnectionPicker connectionLocked />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on Choose connection/ }),+ );++ expect(+ await screen.findByText(+ "A Max plan or higher is required to use ChatGPT.",+ ),+ ).toBeDefined();+ expect(screen.getByRole("link", { name: "See plans" })).toBeDefined();+ });++ it("spends a locked row on the benefit, not on a plan the user may lack", async () => {+ mockOffers([offer(), locked()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );++ expect(+ await screen.findByText(/spending no AutoGPT credits/),+ ).toBeDefined();+ // "Your ChatGPT plan" above "a Max plan is required" reads as two+ // different plans, and presumes one they may not have.+ expect(screen.queryByText("Your ChatGPT plan")).toBeNull();+ });++ it("does not offer a locked connection as something to pick", async () => {+ // Rendering it as a radio would invite a click that cannot take effect.+ mockOffers([offer(), locked()]);++ render(<ConnectionPicker />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Runs on/ }),+ );+ await screen.findByText("A Max plan or higher is required to use ChatGPT.");++ expect(screen.queryByRole("radio", { name: /ChatGPT/ })).toBeNull();+ });++ it("never falls back onto a locked connection", async () => {+ // is_default should never point at a locked offer, but the client is not+ // the place to find out the hard way.+ mockOffers([offer({ is_default: false }), locked({ is_default: true })]);++ render(<ConnectionPicker />);++ expect(+ await screen.findByRole("button", { name: /Runs on AutoGPT Platform/ }),+ ).toBeDefined();+ // What it lands on is what it shows: a locked offer is never the one the+ // chip names. Nothing is written into the store either, because showing a+ // default is not the user choosing it.+ expect(useCopilotUIStore.getState().copilotLlmAuth).toBeNull();+ });++ it("reports a failure rather than inventing a connection", async () => {+ server.use(getGetV2ListChatConnectionsMockHandler401());++ render(<ConnectionPicker />);++ expect(+ await screen.findByLabelText("AI connections unavailable"),+ ).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/LlmRouteSelector.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/LlmRouteSelector.test.tsxdeleted file mode 100644index 90f4e9d633..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/LlmRouteSelector.test.tsx+++ /dev/null@@ -1,239 +0,0 @@-import type { ChatTransportResponse } from "@/app/api/__generated__/models/chatTransportResponse";-import type { CredentialsMetaResponse } from "@/lib/autogpt-server-api";-import {- CredentialsProvidersContext,- type CredentialsProviderData,-} from "@/providers/agent-credentials/credentials-provider";-import {- cleanup,- render,- screen,- waitFor,-} from "@/tests/integrations/test-utils";-import userEvent from "@testing-library/user-event";-import { afterEach, describe, expect, it, vi } from "vitest";-import { useCopilotUIStore } from "../../../../store";-import { LLMRouteSelector } from "../LlmRouteSelector";--const testState = vi.hoisted(() => ({- transports: [] as ChatTransportResponse[] | null,- isError: false,- queryOptions: vi.fn(),- toast: vi.fn(),-}));--vi.mock(- "@/app/api/__generated__/endpoints/chat/chat",- async (importOriginal) => {- const actual =- await importOriginal<- typeof import("@/app/api/__generated__/endpoints/chat/chat")- >();- return {- ...actual,- useGetV2ListChatTransports: (options: unknown) => {- testState.queryOptions(options);- return {- data:- testState.transports === null- ? undefined- : { status: 200, data: { transports: testState.transports } },- isPending: testState.transports === null && !testState.isError,- isError: testState.isError,- };- },- };- },-);--vi.mock("@/components/molecules/Toast/use-toast", () => ({- toast: (...args: unknown[]) => testState.toast(...args),- useToast: () => ({ toast: testState.toast, dismiss: vi.fn() }),-}));--const codexCredential: CredentialsMetaResponse = {- id: "codex-credential-1",- provider: "codex",- type: "oauth2",- title: "Personal ChatGPT",- username: "[email protected]",- scopes: [],-};--const hostedPlatform: ChatTransportResponse = {- auth_provider: "platform",- credential_id: null,- label: "AutoGPT Platform",- available: true,- default: true,-};--const configuredSelfHosted: ChatTransportResponse = {- auth_provider: "platform",- credential_id: null,- label: "Self-hosted chat",- available: true,- default: true,-};--const unconfiguredSelfHosted: ChatTransportResponse = {- ...configuredSelfHosted,- available: false,- default: false,-};--const codexTransport: ChatTransportResponse = {- auth_provider: "codex",- credential_id: codexCredential.id,- label: "ChatGPT",- available: true,- default: false,-};--function makeCodexProvider(): CredentialsProviderData {- return {- provider: "codex",- providerName: "Codex",- savedCredentials: [codexCredential],- isSystemProvider: false,- oAuthCallback: async () => codexCredential,- mcpOAuthCallback: async () => codexCredential,- createAPIKeyCredentials: async () => codexCredential,- createUserPasswordCredentials: async () => codexCredential,- createHostScopedCredentials: async () => codexCredential,- deleteCredentials: async () => ({ deleted: true, revoked: null }),- };-}--function SelectorHarness() {- return (- <CredentialsProvidersContext.Provider- value={{ codex: makeCodexProvider() }}- >- <LLMRouteSelector />- </CredentialsProvidersContext.Provider>- );-}--afterEach(() => {- cleanup();- testState.transports = [];- testState.isError = false;- testState.queryOptions.mockClear();- testState.toast.mockClear();- useCopilotUIStore.getState().setCopilotLlmAuth({- authProvider: "platform",- credentialId: null,- });-});--describe("LLMRouteSelector", () => {- it("hides when the hosted platform is the only available route", () => {- testState.transports = [hostedPlatform];-- render(<SelectorHarness />);-- expect(screen.queryByLabelText(/AI connection/i)).toBeNull();- expect(useCopilotUIStore.getState().copilotLlmAuth).toEqual({- authProvider: "platform",- credentialId: null,- });- });-- it("offers hosted platform and Codex while defaulting to hosted", async () => {- testState.transports = [hostedPlatform, codexTransport];- const user = userEvent.setup();-- render(<SelectorHarness />);-- await user.click(screen.getByLabelText(/AI connection: AutoGPT Platform/i));- expect(screen.getAllByText("AutoGPT Platform").length).toBeGreaterThan(0);- expect(screen.getByText("ChatGPT")).toBeTruthy();- expect(screen.getByText(/Personal ChatGPT/)).toBeTruthy();-- await user.click(screen.getByText("ChatGPT"));- expect(useCopilotUIStore.getState().copilotLlmAuth).toEqual({- authProvider: "codex",- credentialId: codexCredential.id,- });- });-- it("refreshes a changed transport inventory immediately after pairing", () => {- testState.transports = [hostedPlatform];- const { rerender } = render(<SelectorHarness />);-- expect(screen.queryByLabelText(/AI connection/i)).toBeNull();- expect(testState.queryOptions).toHaveBeenLastCalledWith(- expect.objectContaining({- query: expect.objectContaining({- refetchOnWindowFocus: true,- staleTime: 0,- }),- }),- );-- testState.transports = [hostedPlatform, codexTransport];- rerender(<SelectorHarness />);- expect(- screen.getByLabelText(/AI connection: AutoGPT Platform/i),- ).toBeTruthy();-- testState.transports = [hostedPlatform];- rerender(<SelectorHarness />);- expect(screen.queryByLabelText(/AI connection/i)).toBeNull();- });-- it("hides when configured self-hosted chat is the only route", () => {- testState.transports = [configuredSelfHosted];-- render(<SelectorHarness />);-- expect(screen.queryByLabelText(/AI connection/i)).toBeNull();- });-- it("offers configured self-hosted chat alongside Codex", async () => {- testState.transports = [configuredSelfHosted, codexTransport];- const user = userEvent.setup();-- render(<SelectorHarness />);-- await user.click(screen.getByLabelText(/AI connection: Self-hosted chat/i));- expect(screen.getAllByText("Self-hosted chat").length).toBeGreaterThan(0);- expect(screen.getByText("ChatGPT")).toBeTruthy();- });-- it("automatically selects sole Codex on a keyless self-host", async () => {- testState.transports = [- unconfiguredSelfHosted,- { ...codexTransport, default: true },- ];-- render(<SelectorHarness />);-- await waitFor(() => {- expect(useCopilotUIStore.getState().copilotLlmAuth).toEqual({- authProvider: "codex",- credentialId: codexCredential.id,- });- });- expect(screen.queryByLabelText(/AI connection/i)).toBeNull();- });-- it("links a keyless self-host with no Codex connection to setup", () => {- testState.transports = [unconfiguredSelfHosted];-- render(<SelectorHarness />);-- const setupLink = screen.getByLabelText("Set up an AI connection");- expect(setupLink.getAttribute("href")).toBe("/settings/integrations");- });-- it("shows inventory failures without inventing a route", () => {- testState.transports = null;- testState.isError = true;-- render(<SelectorHarness />);-- expect(screen.getByLabelText("AI connections unavailable")).toBeTruthy();- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsxdeleted file mode 100644index 9f4997d0bb..0000000000--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/__tests__/ModelToggleButton.test.tsx+++ /dev/null@@ -1,55 +0,0 @@-import {- render as rtlRender,- screen,- fireEvent,- cleanup,-} from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";-import type { ReactElement } from "react";-import { TooltipProvider } from "@/components/ui/tooltip";-import { ModelToggleButton } from "../ModelToggleButton";--afterEach(cleanup);--function render(ui: ReactElement) {- return rtlRender(<TooltipProvider>{ui}</TooltipProvider>);-}--describe("ModelToggleButton", () => {- it("carries no text label — the composer row is icon-only", () => {- render(<ModelToggleButton model="standard" onToggle={vi.fn()} />);- expect(screen.queryByText("Standard")).toBeNull();- expect(screen.queryByText("Advanced")).toBeNull();- });-- // Model tier drives cost and quality, and a tooltip never opens on touch,- // so the raised tier has to be legible on the glyph itself.- it("tints the glyph so the advanced tier is visible without a tooltip", () => {- render(<ModelToggleButton model="advanced" onToggle={vi.fn()} />);- const advanced = screen.getByRole("button").className;- expect(advanced).toContain("emerald");- cleanup();-- render(<ModelToggleButton model="standard" onToggle={vi.fn()} />);- expect(screen.getByRole("button").className).not.toContain("emerald");- });-- it("calls onToggle when clicked", () => {- const onToggle = vi.fn();- render(<ModelToggleButton model="standard" onToggle={onToggle} />);- fireEvent.click(screen.getByRole("button"));- expect(onToggle).toHaveBeenCalledTimes(1);- });-- it("sets aria-pressed=false for standard", () => {- render(<ModelToggleButton model="standard" onToggle={vi.fn()} />);- const btn = screen.getByLabelText("Switch to Advanced model");- expect(btn.getAttribute("aria-pressed")).toBe("false");- });-- it("sets aria-pressed=true for advanced", () => {- render(<ModelToggleButton model="advanced" onToggle={vi.fn()} />);- const btn = screen.getByLabelText("Switch to Balanced model");- expect(btn.getAttribute("aria-pressed")).toBe("true");- });-});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex de92b811c6..a3956aba7f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -272,11 +272,18 @@ export function useChatSession({}try {- const sessionData: CreateSessionRequest = {- llm_auth_provider: resolvedLLMAuth.authProvider,- };- if (resolvedLLMAuth.authProvider === "codex") {- sessionData.llm_credential_id = resolvedLLMAuth.credentialId;+ const sessionData: CreateSessionRequest = {};+ // Only an explicit choice travels. Naming the route unconditionally+ // makes every new chat an override, which is how a connection picked+ // once quietly became the account's default and how a default changed+ // in Settings stopped taking effect: the server skips its own default+ // whenever the client names one. `copilotLlmAuth` is null until the+ // user actually picks, and null means "use whatever the server says".+ if (copilotLlmAuth !== null) {+ sessionData.llm_auth_provider = resolvedLLMAuth.authProvider;+ if (resolvedLLMAuth.authProvider === "codex") {+ sessionData.llm_credential_id = resolvedLLMAuth.credentialId;+ }}if (dryRun) sessionData.dry_run = true;if (expertId) sessionData.expert_id = expertId;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex 9ef0eefcdb..b0d30d8bbc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -64,7 +64,6 @@ function getLatestKickoffAttemptToken(messages: UIMessage[]) {export function useCopilotPage() {const { user, isUserLoading, isLoggedIn } = useAuth();- const showAdvancedComposerControls = useGetFlag(Flag.CHAT_MODE_OPTION);const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);const [expertIdParam] = useQueryState("expertId", parseAsString);@@ -180,7 +179,11 @@ export function useCopilotPage() {activeTurnStartMessageId,hasActiveStream,refetchSession,- copilotModel: showAdvancedComposerControls ? copilotLlmModel : undefined,+ // Sent whenever the picker can set it. The tier control is not behind+ // CHAT_MODE_OPTION -- it renders from the server's connection offer --+ // so gating the value on that flag silently ran the turn on the tier the+ // user had not chosen. Entitlement is the server's call, not the flag's.+ copilotModel: copilotLlmModel,});const kickoffAttemptToken = getLatestKickoffAttemptToken(currentMessages);diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex fdb0d3e2d6..eded303186 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -15065,6 +15065,14 @@"items": { "type": "string" },"type": "array","title": "Limitations"+ },+ "lock_reason": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Lock Reason"+ },+ "unlock_href": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Unlock Href"}},"type": "object",@@ -17487,12 +17495,16 @@"title": "Tier"},"label": { "type": "string", "title": "Label" },- "selectable": { "type": "boolean", "title": "Selectable" }+ "selectable": { "type": "boolean", "title": "Selectable" },+ "display_model": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Display Model"+ }},"type": "object","required": ["tier", "label", "selectable"],"title": "ConnectionTier",- "description": "One quality level on a connection.\n\n``display_model`` is deliberately absent. Naming the model a tier will\nresolve to needs the execution path, which is decided per turn by which\nservice handles it — and on ChatGPT it needs a live call against the\naccount. A name that is right half the time is worse here than no name."+ "description": "One quality level on a connection.\n\n``display_model`` is the model this tier resolves to, run through the\nsame router the turn will use — LaunchDarkly cell, then registry, then\nconfig — so it cannot drift from what actually answers.\n\nIt is ``None`` on a ChatGPT connection. Naming that model means asking\nthe account what it advertises, which takes a runtime lease against the\nprovider; doing that once per credential to render a list is the cost\nthis endpoint exists to avoid."},"ContentType": {"type": "string",