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): let a chat continue elsewhere when a plan runs out (#14150)
Nicholas Tindle6dff0e240cce
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex b6112035d3..aca20acd93 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -44,10 +44,16 @@ from backend.copilot.model import (get_or_create_builder_session,get_or_create_expert_kickoff_session,get_user_sessions,+ update_session_llm_route,update_session_pinned,update_session_title,)-from backend.copilot.offers import AIConnectionOffersResponse, get_connection_offers+from backend.copilot.offers import (+ AIConnectionOffersResponse,+ EntitlementUnavailable,+ advanced_tier_entitled,+ get_connection_offers,+)from backend.copilot.pending_message_helpers import (QueuePendingMessageResponse,StreamRegistryUnavailable,@@ -58,6 +64,10 @@ from backend.copilot.pending_messages import (clear_pending_messages_unsafe,peek_pending_messages,)+from backend.copilot.provider_tiers import (+ ProviderTiersResponse,+ describe_provider_tiers,+)from backend.copilot.rate_limit import (CoPilotUsagePublic,RateLimitExceeded,@@ -562,6 +572,28 @@ async def list_chat_connections(return AIConnectionOffersResponse(offers=await get_connection_offers(user_id))+ "/model-tiers",+ dependencies=[Security(auth.requires_user)],+)+async def list_provider_model_tiers(+ user_id: Annotated[str, Security(auth.get_user_id)],+) -> ProviderTiersResponse:+ """What each provider's quality tiers resolve to, whoever you are.++ ``GET /connections`` answers "what can you pick", and deliberately omits+ a connection nobody can select. That makes it the wrong source for the+ surfaces that describe a provider *before* the user has one -- the+ connect dialog, and the plan cards selling a plan they have not bought.+ Those need "ChatGPT's Advanced tier is 5.6 Sol", which is a fact about+ the catalog rather than about this user's entitlements.++ User-scoped only because the engine is: which model a tier maps to+ depends on the path a turn will run on. Says nothing about access.+ """+ return ProviderTiersResponse(providers=await describe_provider_tiers(user_id))++class SetDefaultTransportRequest(BaseModel):"""The connection new chats should start on.@@ -880,6 +912,77 @@ async def disconnect_session_stream(return Response(status_code=204)+class ChangeSessionConnectionRequest(BaseModel):+ """The connection the rest of this chat should run on."""++ llm_auth_provider: CopilotLlmAuthProvider+ llm_credential_id: str | None = Field(default=None, max_length=128)+++ "/sessions/{session_id}/connection",+ summary="Change the connection an existing chat runs on",+ dependencies=[Security(auth.requires_user)],+ status_code=200,+ responses={404: {"description": "Session not found or access denied"}},+)+async def change_session_connection_route(+ session_id: str,+ request: ChangeSessionConnectionRequest,+ user_id: Annotated[str, Security(auth.get_user_id)],+) -> dict:+ """Move a chat onto another connection, from the next turn onward.++ A chat is latched to the connection it started on so that a turn cannot+ silently change who pays for it halfway through. This is the deliberate+ exception: when a provider stops accepting turns -- a spent quota, an+ expired login -- the alternative to switching is the chat simply ending.++ It never happens on its own. The caller is a button the user pressed, and+ the run continues on the connection they picked rather than on whichever+ one happens to work.++ History is not rewritten. Turns already stamped keep the connection they+ ran on, so a chat that hit a limit and carried on elsewhere reads as+ exactly that.+ """+ auth_provider = request.llm_auth_provider+ credential_id = request.llm_credential_id++ if auth_provider == "platform" and credential_id is not None:+ raise HTTPException(status_code=422, detail="codex_credential_not_allowed")+ if auth_provider == "codex" and credential_id is None:+ raise HTTPException(status_code=422, detail="codex_credential_required")++ transports = await get_chat_transports(user_id)+ target = next(+ (+ transport+ for transport in transports+ if transport.auth_provider == auth_provider+ and transport.credential_id == credential_id+ and transport.available+ ),+ None,+ )+ if target is None:+ # Same shapes the session-creation path uses, so a client that already+ # handles them does not need a second vocabulary for the same refusals.+ if auth_provider == "codex":+ raise HTTPException(status_code=404, detail="codex_credential_not_found")+ raise HTTPException(status_code=503, detail="chat_transport_not_configured")++ changed = await update_session_llm_route(+ session_id, user_id, auth_provider, credential_id+ )+ if not changed:+ raise HTTPException(+ status_code=404,+ detail=f"Session {session_id} not found or access denied",+ )+ return {"status": "ok"}++@router.patch("/sessions/{session_id}/title",summary="Update session title",@@ -1438,6 +1541,23 @@ async def stream_chat_post(request: Request body with message, is_user_message, and optional context.user_id: Authenticated user ID."""+ # The Advanced tier is a paid capability, and it was only enforced where+ # the picker decides what to grey out. A client that skips the picker and+ # posts model="advanced" was served it, on our credits. Checked first,+ # before the session is touched or the message stored: a turn we are going+ # to refuse should leave nothing behind.+ if request.model == "advanced":+ try:+ entitled = await advanced_tier_entitled(user_id)+ except EntitlementUnavailable:+ # Not knowing is not permission. The picker stays generous when+ # the lookup is down; spending does not.+ raise HTTPException(+ status_code=503, detail="advanced_tier_unavailable"+ ) from None+ if not entitled:+ raise HTTPException(status_code=403, detail="advanced_tier_not_entitled")+import timestream_start_time = time.perf_counter()diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 646691ba70..186ad1cfd1 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -14,6 +14,7 @@ from backend.api.features.chat import routes as chat_routesfrom backend.api.features.chat.routes import _strip_injected_contextfrom backend.copilot import transports as chat_transportsfrom backend.copilot.config import CopilotLlmAuthProvider+from backend.copilot.offers import EntitlementUnavailablefrom backend.copilot.rate_limit import SubscriptionTierfrom backend.copilot.tools.models import ExpertSoulUpdatedResponsefrom backend.data.model import OAuth2Credentials@@ -3816,3 +3817,225 @@ def test_resolve_session_permissions_blocks_out_of_scope_tools() -> None:# enforce scope per-tool via the builder_graph_id guard.assert "edit_agent" not in perms.toolsassert "run_agent" not in perms.tools+++# ─── Change the connection an existing chat runs on ────────────────────+++def _transport(auth_provider: str, credential_id: str | None, available: bool = True):+ from backend.copilot.transports import ChatTransportResponse++ return ChatTransportResponse(+ auth_provider=auth_provider, # type: ignore[arg-type]+ credential_id=credential_id,+ label="Test",+ available=available,+ default=False,+ )+++def _mock_route_change(+ mocker: pytest_mock.MockerFixture,+ *,+ transports: list,+ success: bool = True,+):+ mocker.patch(+ "backend.api.features.chat.routes.get_chat_transports",+ new_callable=AsyncMock,+ return_value=transports,+ )+ return mocker.patch(+ "backend.api.features.chat.routes.update_session_llm_route",+ new_callable=AsyncMock,+ return_value=success,+ )+++def test_change_connection_moves_the_chat(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ """The continue-path after a provider stops accepting turns: the run keeps+ going on a connection the user picked, rather than ending."""+ mock_update = _mock_route_change(mocker, transports=[_transport("platform", None)])++ response = client.put(+ "/sessions/sess-1/connection",+ json={"llm_auth_provider": "platform"},+ )++ assert response.status_code == 200+ mock_update.assert_called_once_with("sess-1", test_user_id, "platform", None)+++def test_change_connection_refuses_a_route_the_user_does_not_have(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """Otherwise this endpoint would be a way to route a turn down a+ connection the entitlement checks already refused."""+ mock_update = _mock_route_change(mocker, transports=[_transport("platform", None)])++ response = client.put(+ "/sessions/sess-1/connection",+ json={"llm_auth_provider": "codex", "llm_credential_id": "cred-nope"},+ )++ assert response.status_code == 404+ assert response.json()["detail"] == "codex_credential_not_found"+ mock_update.assert_not_called()+++def test_change_connection_refuses_an_unavailable_transport(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_update = _mock_route_change(+ mocker, transports=[_transport("platform", None, available=False)]+ )++ response = client.put(+ "/sessions/sess-1/connection",+ json={"llm_auth_provider": "platform"},+ )++ assert response.status_code == 503+ mock_update.assert_not_called()+++def test_change_connection_rejects_a_credential_on_the_platform_route(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_update = _mock_route_change(mocker, transports=[_transport("platform", None)])++ response = client.put(+ "/sessions/sess-1/connection",+ json={"llm_auth_provider": "platform", "llm_credential_id": "cred-1"},+ )++ assert response.status_code == 422+ mock_update.assert_not_called()+++def test_change_connection_requires_a_credential_for_codex(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_update = _mock_route_change(mocker, transports=[_transport("codex", "cred-1")])++ response = client.put(+ "/sessions/sess-1/connection",+ json={"llm_auth_provider": "codex"},+ )++ assert response.status_code == 422+ mock_update.assert_not_called()+++def test_change_connection_on_someone_elses_session_is_a_404(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """update_session_llm_route filters on the owning user, so a session that+ is not theirs reports as missing rather than as forbidden."""+ _mock_route_change(mocker, transports=[_transport("platform", None)], success=False)++ response = client.put(+ "/sessions/not-mine/connection",+ json={"llm_auth_provider": "platform"},+ )++ assert response.status_code == 404+++# ─── Advanced tier is enforced where a turn starts, not just in the picker ──+++def test_advanced_tier_is_refused_without_the_entitlement(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """Found by a blue-team review of this stack: the Advanced tier was+ declared Max-only but checked only where the picker decides what to grey+ out, so posting model="advanced" directly was served on platform credits."""+ mocker.patch(+ "backend.api.features.chat.routes.advanced_tier_entitled",+ new_callable=AsyncMock,+ return_value=False,+ )+ validate = mocker.patch(+ "backend.api.features.chat.routes._validate_and_get_writable_session",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "hello", "model": "advanced"},+ )++ assert response.status_code == 403+ assert response.json()["detail"] == "advanced_tier_not_entitled"+ # Refused before the session is even loaded, so nothing is left behind.+ validate.assert_not_called()+++def test_advanced_tier_is_refused_when_entitlement_cannot_be_resolved(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """Not knowing is not permission.++ The picker deliberately stays generous when the entitlement service is+ down, because a billing hiccup should not make someone's model vanish+ from the menu. Spending is the other way round: a second blue-team pass+ found the endpoint reusing that generous helper, so an outage handed+ Advanced to anyone who asked. It refuses now, and says so as a 503 rather+ than a 403 -- the account may well be entitled; we simply cannot tell.+ """+ mocker.patch(+ "backend.api.features.chat.routes.advanced_tier_entitled",+ new_callable=AsyncMock,+ side_effect=EntitlementUnavailable("billing down"),+ )+ validate = mocker.patch(+ "backend.api.features.chat.routes._validate_and_get_writable_session",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "hello", "model": "advanced"},+ )++ assert response.status_code == 503+ detail = response.json()["detail"]+ assert detail == "advanced_tier_unavailable"+ # The underlying failure is not handed to the client.+ assert "billing down" not in str(detail)+ validate.assert_not_called()+++def test_standard_tier_is_not_gated(+ mocker: pytest_mock.MockerFixture,+) -> None:+ """The gate is on the paid tier only — Balanced must stay open to everyone+ even when the entitlement lookup says no."""+ allowed = mocker.patch(+ "backend.api.features.chat.routes.advanced_tier_entitled",+ new_callable=AsyncMock,+ return_value=False,+ )+ mocker.patch(+ "backend.api.features.chat.routes._validate_and_get_writable_session",+ new_callable=AsyncMock,+ # Stops the handler right after the gate with something the test+ # client turns into a response rather than re-raising.+ side_effect=fastapi.HTTPException(status_code=418, detail="stop here"),+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "hello", "model": "standard"},+ )++ assert response.status_code == 418++ # Short-circuits on the tier, so the entitlement is never consulted for+ # Balanced. The request goes on to fail for unrelated reasons in this+ # harness; what matters is that it was not refused for entitlement.+ allowed.assert_not_called()diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex 521b980273..2aa1493551 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -501,6 +501,40 @@ async def update_chat_session_pinned(return result > 0+async def update_chat_session_llm_route(+ session_id: str,+ user_id: str,+ llm_auth_provider: str,+ llm_credential_id: str | None,+) -> bool:+ """Point an existing session at a different connection, from now on.++ Atomically merges only the two route keys into stored metadata: everything+ else in there -- including a pending question written concurrently --+ belongs to other features and must survive a connection change.++ Always filters by (session_id, user_id) so callers cannot re-route another+ user's chat even knowing the id. Past turns keep the stamps they were+ written with; this only decides where the next one runs.++ Returns True if a row was updated, False otherwise (not found, wrong user).+ """+ result = await db.execute_raw_with_schema(+ 'UPDATE {schema_prefix}"ChatSession" SET "metadata" = '+ "COALESCE(\"metadata\", '{{}}'::jsonb) || "+ "jsonb_build_object("+ "'llm_auth_provider', $3::text, "+ "'llm_credential_id', $4::text"+ '), "updatedAt" = NOW() '+ 'WHERE "id" = $1 AND "userId" = $2',+ session_id,+ user_id,+ llm_auth_provider,+ llm_credential_id,+ )+ return result > 0++async def add_chat_message(session_id: str,role: str,diff --git a/autogpt_platform/backend/backend/copilot/db_test.py b/autogpt_platform/backend/backend/copilot/db_test.pyindex 8081340433..35b562a596 100644--- a/autogpt_platform/backend/backend/copilot/db_test.py+++ b/autogpt_platform/backend/backend/copilot/db_test.py@@ -18,6 +18,7 @@ from backend.copilot.db import (get_user_chat_sessions,set_turn_duration,update_chat_message_tool_calls,+ update_chat_session_llm_route,update_chat_session_pinned,update_message_content_by_sequence,)@@ -80,6 +81,26 @@ def _make_session(return session[email protected](("affected", "expected"), [(1, True), (0, False)])+async def test_update_chat_session_llm_route_merges_metadata_atomically(+ affected: int, expected: bool+) -> None:+ execute = AsyncMock(return_value=affected)++ with patch("backend.copilot.db.db.execute_raw_with_schema", execute):+ result = await update_chat_session_llm_route(+ "sess-1", "user-1", "codex", "cred-1"+ )++ assert result is expected+ sql, *params = execute.await_args.args+ assert "COALESCE" in sql+ assert "jsonb_build_object" in sql+ assert '"updatedAt" = NOW()' in sql+ assert params == ["sess-1", "user-1", "codex", "cred-1"]++@pytest.mark.asyncioasync def test_chat_message_has_assistant_reply_distinguishes_delivery_state():kickoff = _make_msg(3, role="user", content="kickoff")diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex 73eae9392d..fcfcf829a7 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -990,18 +990,35 @@ async def upsert_chat_session(# Ordinary upserts keep best-effort cache-on-DB-error behavior;# tenancy changes return above after eviction instead.- # Title (update_session_title) and pin state (update_session_pinned)- # are mutated *outside* this lock — they only touch their single field,- # not messages — so a concurrent rename, auto-title, or pin/unpin may- # have written a newer value to Redis while this upsert was in progress.- # Always prefer the cached title/pin to avoid reverting it with the- # stale in-memory copy.+ # Title and pin state are mutated outside this lock. Connection route+ # updates use this same lock, but a route update that completed before+ # this upsert acquired it may still be newer than this turn's in-memory+ # session. Prefer those cached fields so the stale turn cannot revert+ # a rename, pin, or connection switch.try:existing_cached = await _get_session_from_cache(session.session_id)if existing_cached:updates: dict[str, Any] = {"is_pinned": existing_cached.is_pinned}if existing_cached.title:updates["title"] = existing_cached.title+ # The route decides who pays for the next turn. A long turn+ # finishing after the user switched connection would otherwise+ # put the old one back in Redis while the database holds the+ # new one, and bill the next turn to the connection they just+ # left. Only the two route keys are taken from the cache; the+ # rest of this session's metadata is this turn's own.+ cached_route = existing_cached.metadata+ if (+ cached_route.llm_auth_provider != session.metadata.llm_auth_provider+ or cached_route.llm_credential_id+ != session.metadata.llm_credential_id+ ):+ updates["metadata"] = session.metadata.model_copy(+ update={+ "llm_auth_provider": cached_route.llm_auth_provider,+ "llm_credential_id": cached_route.llm_credential_id,+ }+ )session = session.model_copy(update=updates)await cache_chat_session(session)except Exception as e:@@ -1680,6 +1697,53 @@ async def update_session_title(return False+async def update_session_llm_route(+ session_id: str,+ user_id: str,+ llm_auth_provider: CopilotLlmAuthProvider,+ llm_credential_id: str | None,+) -> bool:+ """Move an existing chat onto a different connection, from the next turn.++ The session's metadata is segment zero -- where the chat started, and the+ answer for any turn that carries no stamp of its own. Changing it does not+ rewrite history: turns already stamped keep the connection they ran on, so+ a chat that hit a limit and continued elsewhere reads as what it was.++ Written through the same cache the title update uses, because a stale+ cached session would send the next turn back to the connection the user+ just moved off.+ """+ # This is a read-modify-write of the cached session. Serialize it with+ # full-session upserts so a route change cannot write an older cache+ # snapshot over messages that a turn just persisted (or vice versa).+ async with _get_session_lock(session_id) as lock_acquired:+ if not lock_acquired:+ raise RedisError(+ f"Could not serialize route update for session {session_id}"+ )++ updated = await chat_db().update_chat_session_llm_route(+ session_id, user_id, llm_auth_provider, llm_credential_id+ )+ if not updated:+ return False++ # Cache refresh is best-effort -- the DB write already succeeded.+ try:+ cached = await _get_session_from_cache(session_id)+ if cached:+ cached.metadata.llm_auth_provider = llm_auth_provider+ cached.metadata.llm_credential_id = llm_credential_id+ await cache_chat_session(cached)+ except Exception as e:+ logger.warning(+ f"Cache route update failed for session {session_id} "+ f"(non-critical): {e}"+ )+ return True++async def update_session_pinned(session_id: str,user_id: str,diff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.pyindex b3a2974fa1..f59daf0c28 100644--- a/autogpt_platform/backend/backend/copilot/model_test.py+++ b/autogpt_platform/backend/backend/copilot/model_test.py@@ -1,3 +1,4 @@+from contextlib import asynccontextmanagerfrom typing import castimport pytest@@ -15,7 +16,7 @@ from prisma.models import Expertfrom pytest_mock import MockerFixturefrom backend.data.redis_client import get_redis_async-from backend.util.exceptions import NotFoundError+from backend.util.exceptions import NotFoundError, RedisErrorfrom .model import (ChatMessage,@@ -28,6 +29,7 @@ from .model import (get_or_create_builder_session,is_message_duplicate,maybe_append_user_message,+ update_session_llm_route,upsert_chat_session,)@@ -55,6 +57,92 @@ messages = []+async def test_update_session_llm_route_propagates_database_failures(+ mocker: MockerFixture,+) -> None:+ @asynccontextmanager+ async def acquired_lock(_session_id: str):+ yield True++ db = mocker.MagicMock()+ db.update_chat_session_llm_route = mocker.AsyncMock(+ side_effect=RuntimeError("database unavailable")+ )+ mocker.patch("backend.copilot.model.chat_db", return_value=db)+ mocker.patch("backend.copilot.model._get_session_lock", new=acquired_lock)++ with pytest.raises(RuntimeError, match="database unavailable"):+ await update_session_llm_route("session-1", "user-1", "platform", None)+++async def test_update_session_llm_route_serializes_database_and_cache(+ mocker: MockerFixture,+) -> None:+ lock_held = False++ @asynccontextmanager+ async def acquired_lock(_session_id: str):+ nonlocal lock_held+ lock_held = True+ try:+ yield True+ finally:+ lock_held = False++ async def update_route(*_args):+ assert lock_held+ return True++ cached = ChatSession.new(user_id="user-1", dry_run=False)+ cached.session_id = "session-1"+ cached.messages.append(ChatMessage(role="assistant", content="keep me"))++ async def cache_session(session: ChatSession):+ assert lock_held+ assert session.messages[-1].content == "keep me"++ db = mocker.MagicMock()+ db.update_chat_session_llm_route = mocker.AsyncMock(side_effect=update_route)+ mocker.patch("backend.copilot.model.chat_db", return_value=db)+ mocker.patch("backend.copilot.model._get_session_lock", new=acquired_lock)+ mocker.patch(+ "backend.copilot.model._get_session_from_cache",+ new=mocker.AsyncMock(return_value=cached),+ )+ write_cache = mocker.patch(+ "backend.copilot.model.cache_chat_session",+ new=mocker.AsyncMock(side_effect=cache_session),+ )++ assert await update_session_llm_route(+ "session-1", "user-1", "codex", "credential-1"+ )+ assert cached.metadata.llm_auth_provider == "codex"+ assert cached.metadata.llm_credential_id == "credential-1"+ write_cache.assert_awaited_once_with(cached)+ assert not lock_held+++async def test_update_session_llm_route_fails_before_writing_without_lock(+ mocker: MockerFixture,+) -> None:+ @asynccontextmanager+ async def unavailable_lock(_session_id: str):+ yield False++ db = mocker.MagicMock()+ db.update_chat_session_llm_route = mocker.AsyncMock(return_value=True)+ mocker.patch("backend.copilot.model.chat_db", return_value=db)+ mocker.patch("backend.copilot.model._get_session_lock", new=unavailable_lock)++ with pytest.raises(RedisError, match="Could not serialize route update"):+ await update_session_llm_route("session-1", "user-1", "codex", "credential-1")+ db.update_chat_session_llm_route.assert_not_awaited()++@pytest.mark.asyncio(loop_scope="session")async def test_chatsession_serialization_deserialization():s = ChatSession.new(user_id="abc123", dry_run=False)diff --git a/autogpt_platform/backend/backend/copilot/offers.py b/autogpt_platform/backend/backend/copilot/offers.pyindex deba6c8d2e..84d43ed24e 100644--- a/autogpt_platform/backend/backend/copilot/offers.py+++ b/autogpt_platform/backend/backend/copilot/offers.py@@ -15,12 +15,11 @@ import loggingfrom pydantic import BaseModelfrom backend.copilot.config import ChatConfig, CopilotLlmAuthProvider, CopilotLLMModel-from backend.copilot.engine import resolve_use_sdk-from backend.copilot.model_router import (- ROUTE_SURFACE_CODEX,- ModelMode,- catalog_lookup,- resolve_model_route,+from backend.copilot.provider_tiers import (+ TIER_LABELS,+ codex_tier_models,+ platform_tier_models,+ resolve_engine_mode,)from backend.copilot.transports import (ChatTransportResponse,@@ -28,7 +27,6 @@ from backend.copilot.transports import (is_deployment_chat_available,settings,)-from backend.data import llm_registryfrom backend.integrations.codex.access import CODEX_MINIMUM_PLAN_ERROR, has_codex_accessfrom backend.util.entitlements import Entitlement, has_entitlementfrom backend.util.feature_flag import Flag, is_feature_enabled@@ -36,13 +34,6 @@ from backend.util.settings import BehaveAslogger = logging.getLogger(__name__)-# Product vocabulary. "Fast" and "Thinking" are execution paths, not tiers a-# user picks between; the two labels below are what the product exposes.-TIER_LABELS: dict[CopilotLLMModel, str] = {- "standard": "Balanced",- "advanced": "Advanced",-}-class ConnectionTier(BaseModel):"""One quality level on a connection.@@ -98,18 +89,10 @@ async def get_connection_offers(user_id: str) -> list[AIConnectionOffer]:pick."""config = ChatConfig()- # One engine decision for the whole response: it is a property of the- # deployment and the user, not of which connection they pick.- 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"- models = await _platform_tier_models(mode, user_id, config)- codex_models = _codex_tier_models(mode)- advanced_allowed = await _advanced_tier_allowed(user_id)+ mode = await resolve_engine_mode(user_id, config)+ models = await platform_tier_models(mode, user_id, config)+ codex_models = codex_tier_models(mode)+ advanced_allowed = await advanced_tier_allowed(user_id)offers = [_offer(transport, models, codex_models, advanced_allowed)for transport in await get_chat_transports(user_id)@@ -190,32 +173,6 @@ async def _locked_codex_offer()-async def _platform_tier_models(- mode: ModelMode, 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.- """- resolved: dict[CopilotLLMModel, str | None] = {}- for tier in TIER_LABELS:- try:- route = await resolve_model_route(mode, tier, user_id, config=config)- resolved[tier] = _display_name(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 resolved--def offer_id_for(transport: ChatTransportResponse) -> str:"""Stable across requests, and unique per account.@@ -228,61 +185,47 @@ def offer_id_for(transport: ChatTransportResponse) -> str:ADVANCED_TIER_LOCK_REASON = "A Max plan or higher is required for Advanced."-async def _advanced_tier_allowed(user_id: str) -> bool:- """Whether this user may pick the Advanced tier.+class EntitlementUnavailable(Exception):+ """The entitlement service could not answer.- A failure to resolve the entitlement leaves the tier open rather than- locked: a billing hiccup should not silently downgrade someone's model.+ Raised only on the enforcement path, where "we do not know" has to be+ refused rather than guessed at."""- try:- return await has_entitlement(user_id, Entitlement.ADVANCED_MODEL_TIER)- except Exception:- logger.warning(- "Could not resolve the Advanced tier entitlement; leaving it open",- exc_info=True,- )- return True--def _display_name(slug: str | None) -> str | None:- """What the catalog calls this model, rather than its slug.- The PRD labels tiers "Balanced · 5.6 Terra", not- "Balanced · gpt-5.6-terra": the slug is a routing key and reads as one.+async def advanced_tier_entitled(user_id: str) -> bool:+ """Whether this user actually holds the Advanced entitlement.- Goes through the router's lookup rather than the catalog directly,- because the slug arrives in whatever spelling configured it. The default- configuration routes through OpenRouter, whose provider-prefixed forms- (``anthropic/claude-sonnet-5``) the catalog does not use as keys -- so a- direct read misses on exactly the setup most deployments run.-- Falls back to the slug when nothing resolves, which is better than- showing nothing for a model the catalog has never heard of -- minus the- vendor prefix, which is how the transport addresses the model and carries- nothing for the reader. Keeping it costs ten characters in a control that- has to fit two of these side by side, and spends them on the one part of- the string that cannot tell anyone anything.+ This is the enforcement answer, so it never invents one: a lookup that+ fails raises rather than returning a verdict. The presentation answer+ lives in ``advanced_tier_allowed`` and is deliberately more forgiving --+ the two must not be the same function, because a billing hiccup that+ should merely leave a control enabled must not also authorize spend."""- if not slug:- return None- model = catalog_lookup(slug)- if model:- return model.display_name- return slug.split("/", 1)[1] if "/" in slug else slug+ try:+ return await has_entitlement(user_id, Entitlement.ADVANCED_MODEL_TIER)+ except Exception as exc:+ raise EntitlementUnavailable(str(exc)) from exc-def _codex_tier_models(mode: str) -> dict[CopilotLLMModel, str | None]:- """The models the catalog pins for the Codex cells of this engine.+async def advanced_tier_allowed(user_id: str) -> bool:+ """Whether to offer this user the Advanced tier in the picker.- A registry read, so it costs nothing and needs no credential. The router- validates the pinned slug against what the account actually advertises- when the turn runs, and falls back if it is gone -- so this names the- routed model, not a promise about the account.+ Presentation only. A failure to resolve the entitlement leaves the tier+ on offer rather than locked: a billing hiccup should not make someone's+ model quietly disappear from the menu. The turn itself is still checked+ by ``advanced_tier_entitled``, which refuses when it cannot tell -- so+ being generous here costs nothing."""- return {- tier: _display_name(llm_registry.get_route(ROUTE_SURFACE_CODEX, mode, tier))- for tier in TIER_LABELS- }+ try:+ return await advanced_tier_entitled(user_id)+ except EntitlementUnavailable:+ logger.warning(+ "Could not resolve the Advanced tier entitlement; leaving it on "+ "offer. The turn is still enforced separately.",+ exc_info=True,+ )+ return Truedef _offer(diff --git a/autogpt_platform/backend/backend/copilot/offers_test.py b/autogpt_platform/backend/backend/copilot/offers_test.pyindex e682ed726d..bc88f459c6 100644--- a/autogpt_platform/backend/backend/copilot/offers_test.py+++ b/autogpt_platform/backend/backend/copilot/offers_test.py@@ -6,8 +6,14 @@ from unittest.mock import AsyncMock, MagicMockimport pytestimport pytest_mock-from backend.copilot import offers, transports-from backend.copilot.offers import get_connection_offers, offer_id_for+from backend.copilot import offers, provider_tiers, transports+from backend.copilot.offers import (+ EntitlementUnavailable,+ advanced_tier_allowed,+ advanced_tier_entitled,+ get_connection_offers,+ offer_id_for,+)from backend.copilot.transports import ChatTransportResponsefrom backend.data.llm_registry import registryfrom backend.util.settings import BehaveAs@@ -43,9 +49,11 @@ def advanced_allowed(mocker: pytest_mock.MockerFixture):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,+ provider_tiers, "resolve_use_sdk", new=AsyncMock(return_value=False)+ )+ mocker.patch.object(+ provider_tiers,"resolve_model_route",new=AsyncMock(side_effect=lambda mode, tier, user_id, *, config: SimpleNamespace(@@ -130,7 +138,7 @@ async def test_a_chatgpt_tier_names_the_model_the_catalog_pins(# A registry read, not a call to the account: the router validates the# pinned slug against what the account advertises when the turn runs.mocker.patch.object(- offers.llm_registry,+ provider_tiers.llm_registry,"get_route",side_effect=lambda surface, mode, tier: f"{surface}:{mode}:{tier}",)@@ -154,7 +162,7 @@ async def test_a_chatgpt_tier_names_the_model_the_catalog_pins(async def test_a_chatgpt_tier_the_catalog_pins_nothing_for_stays_unnamed(mocker: pytest_mock.MockerFixture,) -> None:- mocker.patch.object(offers.llm_registry, "get_route", return_value=None)+ mocker.patch.object(provider_tiers.llm_registry, "get_route", return_value=None)_mock_transports(mocker, [_transport("platform", None), _transport("codex", "cred-1")])@@ -188,7 +196,9 @@ async def test_tiers_follow_the_engine_the_user_will_actually_run_on(mocker: pytest_mock.MockerFixture,) -> None:"""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))+ mocker.patch.object(+ provider_tiers, "resolve_use_sdk", new=AsyncMock(return_value=True)+ )_mock_transports(mocker, [_transport(default=True)])(offer,) = await get_connection_offers(USER_ID)@@ -217,7 +227,7 @@ async def test_an_unresolvable_tier_is_described_without_a_name(mocker: pytest_mock.MockerFixture,) -> None:mocker.patch.object(- offers,+ provider_tiers,"resolve_model_route",new=AsyncMock(side_effect=RuntimeError("registry down")),)@@ -435,9 +445,9 @@ async def test_a_locked_chatgpt_offer_still_names_the_models(# "What you get" is the argument for connecting; a locked row that# cannot name the models asks the user to take it on faith.mocker.patch.object(- offers.llm_registry, "get_route", side_effect=lambda s, m, t: f"{m}-{t}"+ provider_tiers.llm_registry, "get_route", side_effect=lambda s, m, t: f"{m}-{t}")- mocker.patch.object(offers.llm_registry, "get_model", return_value=None)+ mocker.patch.object(provider_tiers.llm_registry, "get_model", return_value=None)_mock_transports(mocker, [_transport("platform", None)])_upsell(mocker)@@ -485,7 +495,7 @@ async def test_a_platform_tier_names_a_model_configured_in_transport_spelling(default."""_mock_transports(mocker, [_transport(default=True)])mocker.patch.object(- offers,+ provider_tiers,"resolve_model_route",new=AsyncMock(side_effect=lambda mode, tier, user_id, *, config: SimpleNamespace(@@ -512,7 +522,7 @@ async def test_a_model_the_catalog_does_not_know_is_named_by_its_slug(prefix, which is addressing rather than identity."""_mock_transports(mocker, [_transport(default=True)])mocker.patch.object(- offers,+ provider_tiers,"resolve_model_route",new=AsyncMock(side_effect=lambda mode, tier, user_id, *, config: SimpleNamespace(@@ -524,3 +534,44 @@ async def test_a_model_the_catalog_does_not_know_is_named_by_its_slug(offer = (await get_connection_offers(USER_ID))[0]assert offer.tiers[0].display_model == "a-model-nobody-has-heard-of"+++class TestAdvancedTierEntitlement:+ """The picker and the turn ask the same question and need opposite answers+ when the entitlement service is down: show the tier, refuse the spend."""++ async def test_entitled_reports_what_the_service_said(+ self, mocker: pytest_mock.MockFixture+ ) -> None:+ mocker.patch.object(offers, "has_entitlement", new=AsyncMock(return_value=True))+ assert await advanced_tier_entitled(USER_ID) is True++ mocker.patch.object(+ offers, "has_entitlement", new=AsyncMock(return_value=False)+ )+ assert await advanced_tier_entitled(USER_ID) is False++ async def test_enforcement_refuses_to_guess_when_lookup_fails(+ self, mocker: pytest_mock.MockFixture+ ) -> None:+ # Returning True here is what let an unentitled account spend on+ # Advanced during a billing outage. Not knowing is not permission.+ mocker.patch.object(+ offers,+ "has_entitlement",+ new=AsyncMock(side_effect=RuntimeError("billing down")),+ )+ with pytest.raises(EntitlementUnavailable):+ await advanced_tier_entitled(USER_ID)++ async def test_the_picker_stays_generous_when_lookup_fails(+ self, mocker: pytest_mock.MockFixture+ ) -> None:+ # The control staying on offer costs nothing, because the turn is+ # enforced separately.+ mocker.patch.object(+ offers,+ "has_entitlement",+ new=AsyncMock(side_effect=RuntimeError("billing down")),+ )+ assert await advanced_tier_allowed(USER_ID) is Truediff --git a/autogpt_platform/backend/backend/copilot/provider_tiers.py b/autogpt_platform/backend/backend/copilot/provider_tiers.pynew file mode 100644index 0000000000..e7d123bc38--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/provider_tiers.py@@ -0,0 +1,176 @@+"""What each quality tier resolves to, per provider, independent of access.++``offers`` answers "which connections can this user pick, and what are they".+That is the right question for the composer and for settings, and the wrong+one for every surface that has to *describe* a provider before the user has+one: the connect dialog, and the plan cards that sell a plan the user has not+bought yet.++Those surfaces need "ChatGPT's Advanced tier is 5.6 Sol" — a statement about+the catalog, not about the user's entitlements. Asking ``offers`` for it does+not work, because a connection nobody can select is deliberately absent from+that list, and hardcoding it in the client reintroduces exactly the drift the+offers endpoint exists to remove.++So this module owns tier resolution, and ``offers`` consumes it.+"""++import logging++from pydantic import BaseModel++from backend.copilot.config import ChatConfig, CopilotLLMModel+from backend.copilot.engine import resolve_use_sdk+from backend.copilot.model_router import (+ ROUTE_SURFACE_CODEX,+ ModelMode,+ catalog_lookup,+ resolve_model_route,+)+from backend.data import llm_registry++logger = logging.getLogger(__name__)++# Product vocabulary. "Fast" and "Thinking" are execution paths, not tiers a+# user picks between; the two labels below are what the product exposes.+TIER_LABELS: dict[CopilotLLMModel, str] = {+ "standard": "Balanced",+ "advanced": "Advanced",+}+++class ProviderTier(BaseModel):+ """A tier and the model it resolves to, with no claim about access.++ Deliberately not ``ConnectionTier``: that type carries ``selectable`` and+ ``lock_reason``, which are answers about a user. This one is a statement+ about the catalog and is true whether or not anyone can pick it.+ """++ tier: CopilotLLMModel+ label: str+ display_model: str | None = None+++class ProviderTiers(BaseModel):+ provider_family: str+ display_name: str+ tiers: list[ProviderTier]+++class ProviderTiersResponse(BaseModel):+ providers: list[ProviderTiers]+++async def describe_provider_tiers(user_id: str) -> list[ProviderTiers]:+ """What every provider's tiers resolve to for this user's engine.++ User-scoped only because the engine is: which models a tier maps to+ depends on whether the turn will run on the SDK path. It says nothing+ about whether the user may use either provider.+ """+ config = ChatConfig()+ mode = await resolve_engine_mode(user_id, config)+ platform = await platform_tier_models(mode, user_id, config)+ codex = codex_tier_models(mode)+ return [+ ProviderTiers(+ provider_family="autogpt",+ display_name="AutoGPT Platform",+ tiers=_as_tiers(platform),+ ),+ ProviderTiers(+ provider_family="openai",+ display_name="ChatGPT",+ tiers=_as_tiers(codex),+ ),+ ]+++async def resolve_engine_mode(user_id: str, config: ChatConfig) -> ModelMode:+ """One engine decision per response.++ It is a property of the deployment and the user, not of which connection+ they pick, so it is resolved once rather than per provider.+ """+ 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,+ )+ return "thinking" if use_sdk else "fast"+++async def platform_tier_models(+ mode: ModelMode, 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.+ """+ resolved: dict[CopilotLLMModel, str | None] = {}+ for tier in TIER_LABELS:+ try:+ route = await resolve_model_route(mode, tier, user_id, config=config)+ resolved[tier] = display_name(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 resolved+++def codex_tier_models(mode: ModelMode) -> dict[CopilotLLMModel, str | None]:+ """The models the catalog pins for the Codex cells of this engine.++ A registry read, so it costs nothing and needs no credential. The router+ validates the pinned slug against what the account actually advertises+ when the turn runs, and falls back if it is gone -- so this names the+ routed model, not a promise about the account.+ """+ return {+ tier: display_name(llm_registry.get_route(ROUTE_SURFACE_CODEX, mode, tier))+ for tier in TIER_LABELS+ }+++def display_name(slug: str | None) -> str | None:+ """What the catalog calls this model, rather than its slug.++ The PRD labels tiers "Balanced · 5.6 Terra", not+ "Balanced · gpt-5.6-terra": the slug is a routing key and reads as one.++ Goes through the router's lookup rather than the catalog directly,+ because the slug arrives in whatever spelling configured it. The default+ configuration routes through OpenRouter, whose provider-prefixed forms+ (``anthropic/claude-sonnet-5``) the catalog does not use as keys -- so a+ direct read misses on exactly the setup most deployments run.++ Falls back to the slug when nothing resolves, which is better than+ showing nothing for a model the catalog has never heard of -- minus the+ vendor prefix, which is how the transport addresses the model and carries+ nothing for the reader. Keeping it costs ten characters in a control that+ has to fit two of these side by side, and spends them on the one part of+ the string that cannot tell anyone anything.+ """+ if not slug:+ return None+ model = catalog_lookup(slug)+ if model:+ return model.display_name+ return slug.split("/", 1)[1] if "/" in slug else slug+++def _as_tiers(models: dict[CopilotLLMModel, str | None]) -> list[ProviderTier]:+ return [+ ProviderTier(tier=tier, label=label, display_model=models.get(tier))+ for tier, label in TIER_LABELS.items()+ ]diff --git a/autogpt_platform/backend/backend/copilot/provider_tiers_test.py b/autogpt_platform/backend/backend/copilot/provider_tiers_test.pynew file mode 100644index 0000000000..22055075ba--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/provider_tiers_test.py@@ -0,0 +1,110 @@+"""Describing a provider's tiers without asking whether the user may use it."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+import pytest_mock++from backend.copilot import provider_tiers+from backend.copilot.provider_tiers import describe_provider_tiers, display_name+from backend.data.llm_registry import registry++USER_ID = "3e53486c-cf57-477e-ba2a-cb02dc828e1a"+++def real_catalog():+ """Resolution is only observable with the catalog actually loaded, and it+ is process state, so it is put back afterwards."""+ old = (+ registry._dynamic_models,+ registry._date_stripped_models,+ registry._routes,+ registry._loaded,+ )+ registry.load_catalog()+ yield+ (+ registry._dynamic_models,+ registry._date_stripped_models,+ registry._routes,+ registry._loaded,+ ) = old++[email protected](autouse=True)+def engine(mocker: pytest_mock.MockerFixture):+ mocker.patch.object(+ provider_tiers, "resolve_use_sdk", new=AsyncMock(return_value=False)+ )+ mocker.patch.object(+ provider_tiers,+ "resolve_model_route",+ new=AsyncMock(+ side_effect=lambda mode, tier, user_id, *, config: SimpleNamespace(+ model=f"{mode}-{tier}-model", source="config"+ )+ ),+ )+++async def test_describes_chatgpt_without_the_user_having_it(+ real_catalog,+ mocker: pytest_mock.MockerFixture,+) -> None:+ """The whole reason this exists: the connect dialog and the plan cards+ describe ChatGPT to someone who has not connected it, and the offers list+ deliberately omits a connection nobody can select."""+ mocker.patch.object(+ provider_tiers.llm_registry,+ "get_route",+ side_effect=lambda surface, mode, tier: {+ "standard": "gpt-5.6-terra",+ "advanced": "gpt-5.6-sol",+ }[tier],+ )++ providers = await describe_provider_tiers(USER_ID)++ chatgpt = next(p for p in providers if p.provider_family == "openai")+ # Named, not slugged: the catalog knows both, which is the point.+ assert [(t.label, t.display_model) for t in chatgpt.tiers] == [+ ("Balanced", "GPT-5.6 Terra"),+ ("Advanced", "GPT-5.6 Sol"),+ ]+++async def test_describes_the_platform_too(real_catalog) -> None:+ providers = await describe_provider_tiers(USER_ID)++ platform = next(p for p in providers if p.provider_family == "autogpt")+ assert [t.label for t in platform.tiers] == ["Balanced", "Advanced"]+ assert [t.tier for t in platform.tiers] == ["standard", "advanced"]+++async def test_says_nothing_about_access(real_catalog) -> None:+ """A tier here carries no ``selectable`` and no ``lock_reason`` -- those+ are answers about a user, and this is a statement about the catalog."""+ providers = await describe_provider_tiers(USER_ID)++ tier = providers[0].tiers[0]+ assert not hasattr(tier, "selectable")+ assert not hasattr(tier, "lock_reason")+++def test_names_a_model_configured_in_transport_spelling(real_catalog) -> None:+ assert display_name("anthropic/claude-sonnet-5") == "Claude Sonnet 5"+++def test_falls_back_to_the_slug_tail_for_an_unlisted_model(real_catalog) -> None:+ assert display_name("acme/a-model-nobody-has-heard-of") == (+ "a-model-nobody-has-heard-of"+ )+++def test_has_no_name_for_no_model(real_catalog) -> None:+ assert display_name(None) is Nonediff --git a/autogpt_platform/backend/backend/copilot/turn_queue.py b/autogpt_platform/backend/backend/copilot/turn_queue.pyindex 2bc0852056..3bab7b701f 100644--- a/autogpt_platform/backend/backend/copilot/turn_queue.py+++ b/autogpt_platform/backend/backend/copilot/turn_queue.py@@ -45,6 +45,7 @@ from backend.copilot.model import (_get_session_lock,invalidate_session_cache,)+from backend.copilot.offers import EntitlementUnavailable, advanced_tier_entitledfrom backend.copilot.rate_limit import (RateLimitExceeded,RateLimitUnavailable,@@ -267,7 +268,8 @@ async def dispatch_next_for_user(user_id: str) -> bool:return Falsehead = queued[0]- if head.metadata.llm_auth_provider == "codex":+ route_provider = head.metadata.llm_auth_provider+ if route_provider == "codex":if not await has_codex_access(user_id):logger.info("dispatch_next_for_user: user=%s lacks Codex entitlement, "@@ -276,7 +278,7 @@ async def dispatch_next_for_user(user_id: str) -> bool:head.session_id,)return False- else:+ elif route_provider == "platform":if await is_user_paywalled(user_id):logger.info("dispatch_next_for_user: user=%s paywalled, leaving session=%s queued",@@ -340,6 +342,35 @@ async def dispatch_next_for_user(user_id: str) -> bool:return Falsemetadata = pending.metadata or {}++ # A turn can sit in the queue long enough for the plan that bought it to+ # lapse. The tier was checked when the turn was accepted, but promoting it+ # is a second, later decision to spend, so it gets its own check --+ # otherwise a downgrade between the two buys a free Advanced run. The turn+ # goes back to queued rather than quietly re-running on Standard: nothing+ # in this feature changes what a turn runs on without being asked. It+ # promotes itself once entitlement returns, and can be cancelled meanwhile.+ if route_provider == "platform" and metadata.get("model") == "advanced":+ try:+ entitled = await advanced_tier_entitled(user_id)+ except EntitlementUnavailable:+ entitled = False+ logger.warning(+ "dispatch_next_for_user: could not resolve the Advanced "+ "entitlement for user=%s; leaving session=%s queued",+ user_id,+ head.session_id,+ exc_info=True,+ )+ if not entitled:+ await chat_db().update_chat_session_status(+ session_id=head.session_id,+ expect_status=CHAT_STATUS_RUNNING,+ status=CHAT_STATUS_QUEUED,+ )+ await invalidate_session_cache(head.session_id)+ return False+turn_id = str(uuid.uuid4())try:# The user's message is already persisted AND the session isdiff --git a/autogpt_platform/backend/backend/copilot/turn_queue_test.py b/autogpt_platform/backend/backend/copilot/turn_queue_test.pyindex da1f2241a0..fa40f051f2 100644--- a/autogpt_platform/backend/backend/copilot/turn_queue_test.py+++ b/autogpt_platform/backend/backend/copilot/turn_queue_test.py@@ -50,6 +50,7 @@ def _mock_session(session_id: str = "s1", title: str | None = "T") -> MagicMock:s.session_id = session_ids.title = titles.updated_at = datetime.now(timezone.utc)+ s.metadata.llm_auth_provider = "platform"return s@@ -301,6 +302,167 @@ async def test_codex_dispatch_skips_platform_billing_gates() -> None:assert dispatch_turn_mock.call_args.kwargs["llm_credential_id"] == "cred-1"+async def test_promotion_rechecks_the_advanced_tier_before_spending() -> None:+ """A queued Advanced turn is a decision to spend, taken later.++ Found by a blue-team pass: promotion already re-checked the paywall, the+ rate limit and Codex access, because a turn can wait long enough for any+ of them to change -- but not the tier. A user who queued Advanced turns+ and then downgraded had them dispatched anyway.+ """+ head = _mock_session()+ head.metadata.llm_auth_provider = "platform"+ pending = _pyd_message(metadata={"model": "advanced"})+ db = MagicMock()+ db.update_chat_session_status = AsyncMock(return_value=True)+ db.get_latest_user_message_in_session = AsyncMock(return_value=pending)+ dispatch_turn_mock = AsyncMock()+ entitled = AsyncMock(return_value=False)++ with (+ _patch_queued_list([head]),+ patch.object(turn_queue, "chat_db", return_value=db),+ patch(+ "backend.copilot.turn_queue.is_user_paywalled",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "backend.copilot.turn_queue.get_global_rate_limits",+ new=AsyncMock(return_value=(1, 1, None)),+ ),+ patch("backend.copilot.turn_queue.check_rate_limit", new=AsyncMock()),+ patch.object(+ turn_queue, "claim_queued_session", new=AsyncMock(return_value=True)+ ),+ patch.object(turn_queue, "advanced_tier_entitled", new=entitled),+ patch.object(turn_queue, "invalidate_session_cache", new=AsyncMock()),+ patch("backend.copilot.executor.utils.dispatch_turn", new=dispatch_turn_mock),+ ):+ promoted = await turn_queue.dispatch_next_for_user("u1")++ assert promoted is False+ entitled.assert_awaited_once_with("u1")+ dispatch_turn_mock.assert_not_awaited()+ # Back to queued rather than quietly re-run on Standard: nothing here+ # changes what a turn runs on without being asked.+ assert db.update_chat_session_status.await_args.kwargs["status"] == "queued"+++async def test_promotion_refuses_when_the_entitlement_cannot_be_resolved() -> None:+ """An outage is not permission to spend, and not a reason to lose the turn."""+ head = _mock_session()+ head.metadata.llm_auth_provider = "platform"+ pending = _pyd_message(metadata={"model": "advanced"})+ db = MagicMock()+ db.update_chat_session_status = AsyncMock(return_value=True)+ db.get_latest_user_message_in_session = AsyncMock(return_value=pending)+ dispatch_turn_mock = AsyncMock()++ with (+ _patch_queued_list([head]),+ patch.object(turn_queue, "chat_db", return_value=db),+ patch(+ "backend.copilot.turn_queue.is_user_paywalled",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "backend.copilot.turn_queue.get_global_rate_limits",+ new=AsyncMock(return_value=(1, 1, None)),+ ),+ patch("backend.copilot.turn_queue.check_rate_limit", new=AsyncMock()),+ patch.object(+ turn_queue, "claim_queued_session", new=AsyncMock(return_value=True)+ ),+ patch.object(+ turn_queue,+ "advanced_tier_entitled",+ new=AsyncMock(side_effect=turn_queue.EntitlementUnavailable("down")),+ ),+ patch.object(turn_queue, "invalidate_session_cache", new=AsyncMock()),+ patch("backend.copilot.executor.utils.dispatch_turn", new=dispatch_turn_mock),+ ):+ promoted = await turn_queue.dispatch_next_for_user("u1")++ assert promoted is False+ dispatch_turn_mock.assert_not_awaited()+ assert db.update_chat_session_status.await_args.kwargs["status"] == "queued"+++async def test_promotion_does_not_recheck_the_tier_for_a_standard_turn() -> None:+ """The gate is on the paid tier only; Balanced promotes as before."""+ head = _mock_session()+ head.metadata.llm_auth_provider = "platform"+ pending = _pyd_message(metadata={"model": "standard"})+ db = MagicMock()+ db.update_chat_session_status = AsyncMock(return_value=True)+ db.get_latest_user_message_in_session = AsyncMock(return_value=pending)+ entitled = AsyncMock(side_effect=AssertionError("tier checked for Balanced"))++ with (+ _patch_queued_list([head]),+ patch.object(turn_queue, "chat_db", return_value=db),+ patch(+ "backend.copilot.turn_queue.is_user_paywalled",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "backend.copilot.turn_queue.get_global_rate_limits",+ new=AsyncMock(return_value=(1, 1, None)),+ ),+ patch("backend.copilot.turn_queue.check_rate_limit", new=AsyncMock()),+ patch.object(+ turn_queue, "claim_queued_session", new=AsyncMock(return_value=True)+ ),+ patch.object(turn_queue, "advanced_tier_entitled", new=entitled),+ patch.object(turn_queue, "invalidate_session_cache", new=AsyncMock()),+ patch("backend.copilot.executor.utils.dispatch_turn", new=AsyncMock()),+ ):+ promoted = await turn_queue.dispatch_next_for_user("u1")++ assert promoted is True+ entitled.assert_not_awaited()+++async def test_promotion_uses_current_codex_route_not_stale_platform_tier() -> None:+ """Switching a queued turn to ChatGPT removes platform billing gates.++ The pending message keeps the tier selected when it was enqueued, but the+ session route is deliberately mutable so a blocked turn can continue on a+ subscription-backed connection.+ """+ head = _mock_session()+ head.metadata.llm_auth_provider = "codex"+ head.metadata.llm_credential_id = "cred-1"+ pending = _pyd_message(metadata={"model": "advanced"})+ db = MagicMock()+ db.update_chat_session_status = AsyncMock(return_value=True)+ db.get_latest_user_message_in_session = AsyncMock(return_value=pending)+ dispatch_turn_mock = AsyncMock()+ entitled = AsyncMock(side_effect=AssertionError("platform tier checked for Codex"))++ with (+ _patch_queued_list([head]),+ patch.object(turn_queue, "chat_db", return_value=db),+ patch.object(turn_queue, "has_codex_access", new=AsyncMock(return_value=True)),+ patch.object(+ turn_queue, "claim_queued_session", new=AsyncMock(return_value=True)+ ),+ patch.object(turn_queue, "advanced_tier_entitled", new=entitled),+ patch.object(turn_queue, "invalidate_session_cache", new=AsyncMock()),+ patch("backend.copilot.executor.utils.dispatch_turn", new=dispatch_turn_mock),+ ):+ promoted = await turn_queue.dispatch_next_for_user("u1")++ assert promoted is True+ entitled.assert_not_awaited()+ assert dispatch_turn_mock.await_args.kwargs["llm_auth_provider"] == "codex"+ assert dispatch_turn_mock.await_args.kwargs["model"] == "advanced"++@pytest.mark.asyncioasync def test_codex_dispatch_leaves_queued_when_user_lacks_access() -> None:head = _mock_session()diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex e10927bf54..d7bb57b628 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -558,6 +558,7 @@ class DatabaseManager(AppService):update_chat_message_stamps = _(chat_db.update_chat_message_stamps)update_chat_message_tool_calls = _(chat_db.update_chat_message_tool_calls)update_chat_session_title = _(chat_db.update_chat_session_title)+ update_chat_session_llm_route = _(chat_db.update_chat_session_llm_route)update_chat_session_pinned = _(chat_db.update_chat_session_pinned)set_turn_duration = _(chat_db.set_turn_duration)# ChatSession lifecycle primitives. Three functions cover the@@ -933,6 +934,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):update_chat_message_stamps = d.update_chat_message_stampsupdate_chat_message_tool_calls = d.update_chat_message_tool_callsupdate_chat_session_title = d.update_chat_session_title+ update_chat_session_llm_route = d.update_chat_session_llm_routeupdate_chat_session_pinned = d.update_chat_session_pinnedset_turn_duration = d.set_turn_durationcount_chat_sessions_by_status = d.count_chat_sessions_by_statusdiff --git a/autogpt_platform/backend/backend/data/db_manager_test.py b/autogpt_platform/backend/backend/data/db_manager_test.pyindex 71c7429cd1..377b9b4ed7 100644--- a/autogpt_platform/backend/backend/data/db_manager_test.py+++ b/autogpt_platform/backend/backend/data/db_manager_test.py@@ -4,6 +4,8 @@ from .db_manager import DatabaseManager, DatabaseManagerAsyncClientdef test_async_client_exposes_chat_methods() -> None:assert hasattr(DatabaseManagerAsyncClient, "delete_chat_session")assert hasattr(DatabaseManagerAsyncClient, "set_turn_duration")+ assert hasattr(DatabaseManager, "update_chat_session_llm_route")+ assert hasattr(DatabaseManagerAsyncClient, "update_chat_session_llm_route")def test_bot_analytics_methods_registered() -> None:diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsxindex 1d25b4f81a..9b2fc4959d 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/brain-dump.test.tsx@@ -85,6 +85,19 @@ vi.mock("../steps/BrainDumpStep/recordingStore", () => ({},}));+// These tests navigate by NO_PAYWALL_STEPS, which is the layout for a+// deployment with neither a paywall nor a self-host connect step. isLocal()+// is true for anything not explicitly CLOUD, including the test environment,+// so it is pinned here rather than left to the default.+vi.mock("@/services/environment", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@/services/environment")>();+ return {+ ...actual,+ environment: { ...actual.environment, isLocal: () => false },+ };+});+vi.mock("posthog-js", () => ({default: { capture: vi.fn() },}));diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsxindex 30699fabeb..658e1bcc63 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/__tests__/page.test.tsx@@ -24,6 +24,10 @@ vi.mock("../steps/RoleStep", () => ({vi.mock("../steps/PainPointsStep", () => ({PainPointsStep: () => <div data-testid="step-painpoints" />,}));+vi.mock("../steps/ConnectStep/ConnectStep", () => ({+ ConnectStep: () => <div data-testid="step-connect" />,+}));+vi.mock("../steps/SubscriptionStep/SubscriptionStep", () => ({SubscriptionStep: () => <div data-testid="step-subscription" />,}));@@ -116,6 +120,15 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({flag === "ENABLE_PLATFORM_PAYMENT" ? mockFlagValue : false,}));+vi.mock("@/services/environment", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@/services/environment")>();+ return {+ ...actual,+ environment: { ...actual.environment, isLocal: () => mockIsLocal },+ };+});+vi.mock("launchdarkly-react-client-sdk", () => ({useLDClient: () => ({waitForInitialization: () => Promise.resolve(),@@ -123,10 +136,12 @@ vi.mock("launchdarkly-react-client-sdk", () => ({}));const STEP_STORAGE_KEY = "autogpt:onboarding-highest-step";+let mockIsLocal = false;beforeEach(() => {currentSearchParams = new URLSearchParams();mockFlagValue = false;+ mockIsLocal = false;mockSubscriptionTier = "NO_TIER";mockAuthState = { isLoggedIn: true, isUserLoading: false };authUserPutBodies.length = 0;@@ -442,3 +457,43 @@ describe("OnboardingPage — flag-gated SubscriptionStep", () => {expect(state.painPoints).toEqual(["slow builds"]);});});++describe("OnboardingPage — self-host leads with the connection", () => {+ it("renders ConnectStep first on a self-host install", async () => {+ // A fresh self-host install cannot answer a single message until it has+ // a model, so asking for one comes before personalising the chat.+ mockIsLocal = true;+ currentSearchParams = new URLSearchParams("step=1");+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-connect")).toBeDefined();+ expect(screen.queryByTestId("step-welcome")).toBeNull();+ });++ it("puts Welcome after it, the way the paywall does on cloud", async () => {+ mockIsLocal = true;+ window.sessionStorage.setItem(STEP_STORAGE_KEY, "2");+ currentSearchParams = new URLSearchParams("step=2");+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-welcome")).toBeDefined();+ expect(screen.queryByTestId("step-connect")).toBeNull();+ });++ it("does not insert it on cloud", async () => {+ mockIsLocal = false;+ currentSearchParams = new URLSearchParams("step=1");+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-welcome")).toBeDefined();+ expect(screen.queryByTestId("step-connect")).toBeNull();+ });++ it("yields to the paywall rather than showing both first steps", async () => {+ // Payments and self-host are mutually exclusive in practice; if a+ // deployment ever had both, only one step can be first.+ mockIsLocal = true;+ mockFlagValue = true;+ currentSearchParams = new URLSearchParams("step=1");+ render(<OnboardingPage />);+ expect(await screen.findByTestId("step-subscription")).toBeDefined();+ expect(screen.queryByTestId("step-connect")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsxindex 54c79db46e..815f5d3659 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/page.tsx@@ -6,9 +6,14 @@ import { BrainDumpStep } from "./steps/BrainDumpStep/BrainDumpStep";import { PainPointsStep } from "./steps/PainPointsStep";import { PreparingStep } from "./steps/PreparingStep";import { RoleStep } from "./steps/RoleStep";+import { ConnectStep } from "./steps/ConnectStep/ConnectStep";import { SubscriptionStep } from "./steps/SubscriptionStep/SubscriptionStep";import { WelcomeStep } from "./steps/WelcomeStep";-import { PAYWALL_FIRST_STEPS, useOnboardingWizardStore } from "./store";+import {+ PAYWALL_FIRST_STEPS,+ SELF_HOST_STEPS,+ useOnboardingWizardStore,+} from "./store";import { useOnboardingPage } from "./useOnboardingPage";import { ArrowLeft01Icon, Logout03Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -19,6 +24,7 @@ export default function OnboardingPage() {isLoading,handlePreparingComplete,isPaymentEnabled,+ isSelfHostConnectEnabled,isBrainDumpEnabled,steps,preparingStep,@@ -64,6 +70,8 @@ export default function OnboardingPage() {currentStep === PAYWALL_FIRST_STEPS.subscription && (<SubscriptionStep />)}+ {isSelfHostConnectEnabled &&+ currentStep === SELF_HOST_STEPS.connect && <ConnectStep />}{currentStep === steps.welcome && <WelcomeStep />}{currentStep === steps.role && <RoleStep />}{currentStep === steps.painPoints &&diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsxnew file mode 100644index 0000000000..d48063badb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/ConnectStep.tsx@@ -0,0 +1,101 @@+"use client";++import { LinkSquare01Icon } from "@hugeicons/core-free-icons";+import Link from "next/link";++import { AutoGPTLogo } from "@/components/atoms/AutoGPTLogo/AutoGPTLogo";+import { Button } from "@/components/atoms/Button/Button";+import { FadeIn } from "@/components/atoms/FadeIn/FadeIn";+import { Icon } from "@/components/atoms/Icon/Icon";+import { Text } from "@/components/atoms/Text/Text";++import { useConnectStep } from "./useConnectStep";++/**+ * The first thing a self-host install asks for: a model to run on.+ *+ * A fresh install has no way to answer a single message until someone+ * configures a provider, and the honest shape of that ask is not "paste an+ * API key" — most people setting this up already pay for a subscription that+ * can do the work. So the zero-config path leads and API keys become the+ * advanced one.+ *+ * Deliberately skippable. A user who wants API keys, or who has already+ * configured them, should not have to link an account to get past a wizard.+ */+export function ConnectStep() {+ const { connect, isConnecting, skip, isAlreadyLinked, models } =+ useConnectStep();++ return (+ <FadeIn>+ <div className="flex w-full max-w-lg flex-col items-center gap-8 px-4">+ <div className="flex flex-col items-center gap-3 text-center">+ <AutoGPTLogo+ className="relative right-[3rem] h-24 w-[12rem]"+ hideText+ />+ <Text variant="h3">Power your agents in one sign-in</Text>+ <Text variant="lead" as="span" className="!text-zinc-500">+ {isAlreadyLinked+ ? "Your ChatGPT plan is connected. Agents will run on it instead of spending AutoGPT credits."+ : "Connect the ChatGPT plan you already have and AutoGPT runs with no API keys and no billing setup."}+ {models && !isAlreadyLinked ? ` You get ${models}.` : ""}+ </Text>+ </div>++ <div className="flex w-full flex-col items-center gap-4">+ {isAlreadyLinked ? (+ <Button variant="primary" size="large" onClick={skip}>+ Continue+ </Button>+ ) : (+ <Button+ variant="primary"+ size="large"+ onClick={connect}+ loading={isConnecting}+ rightIcon={<Icon icon={LinkSquare01Icon} size={18} />}+ >+ Sign in with ChatGPT+ </Button>+ )}++ {!isAlreadyLinked && (+ <>+ <Text+ variant="small"+ as="span"+ className="uppercase tracking-[0.08em] !text-zinc-400"+ >+ or configure manually+ </Text>+ <Button variant="secondary" size="large" onClick={skip}>+ Skip for now+ </Button>+ <Text variant="small" as="span" className="!text-zinc-400">+ You can add API keys in Settings → Integrations at any+ time.+ </Text>+ </>+ )}+ </div>++ {/* Named here rather than discovered later: someone arriving with a+ Claude subscription will look for it, and the answer is a policy+ they cannot change, not a missing feature. */}+ <Text variant="small" as="span" className="text-center !text-zinc-400">+ Claude subscriptions can't be linked — Anthropic blocks+ third-party subscription access. Anthropic models work via{" "}+ <Link+ href="/settings/integrations"+ className="underline underline-offset-2"+ >+ API key+ </Link>+ .+ </Text>+ </div>+ </FadeIn>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsxnew file mode 100644index 0000000000..4f0b5b4153--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/__tests__/ConnectStep.test.tsx@@ -0,0 +1,187 @@+import {+ getGetV2ListChatConnectionsMockHandler200,+ getGetV2ListProviderModelTiersMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import type { ProviderTiers } from "@/app/api/__generated__/models/providerTiers";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { useOnboardingWizardStore } from "../../../store";+import { ConnectStep } from "../ConnectStep";+import { hasLinkedSubscription, linkedModelsSentence } from "../helpers";++const connect = vi.fn();+vi.mock(+ "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect",+ () => ({+ useOAuthConnect: () => ({ connect, isPending: false }),+ }),+);++function offer(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {+ return {+ offer_id: "platform:deployment",+ provider_family: "autogpt",+ display_name: "Self-hosted chat",+ auth_method: "deployment",+ credential_id: null,+ backed_by_label: "This server's chat provider",+ description: "New chats are backed by the chat provider on this server.",+ state: "ready",+ selectable: true,+ is_default: true,+ tiers: [],+ limitations: [],+ lock_reason: null,+ unlock_href: null,+ ...over,+ } as AIConnectionOffer;+}++function chatgpt(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {+ return offer({+ offer_id: "codex:cred-1",+ provider_family: "openai",+ display_name: "ChatGPT",+ auth_method: "chatgpt_oauth",+ credential_id: "cred-1",+ is_default: false,+ tiers: [+ {+ tier: "standard",+ label: "Balanced",+ selectable: true,+ display_model: "GPT-5.6 Terra",+ },+ {+ tier: "advanced",+ label: "Advanced",+ selectable: true,+ display_model: "GPT-5.6 Sol",+ },+ ],+ ...over,+ });+}++function chatgptTiers(): ProviderTiers {+ return {+ provider_family: "openai",+ display_name: "ChatGPT",+ tiers: [+ { tier: "standard", label: "Balanced", display_model: "GPT-5.6 Terra" },+ { tier: "advanced", label: "Advanced", display_model: "GPT-5.6 Sol" },+ ],+ } as ProviderTiers;+}++function mockOffers(+ offers: AIConnectionOffer[],+ providers: ProviderTiers[] = [],+) {+ server.use(+ getGetV2ListChatConnectionsMockHandler200({ offers }),+ getGetV2ListProviderModelTiersMockHandler200({ providers }),+ );+}++describe("ConnectStep", () => {+ beforeEach(() => {+ connect.mockClear();+ useOnboardingWizardStore.setState({ currentStep: 1 });+ });++ it("leads with the zero-config path", async () => {+ mockOffers([offer()]);++ render(<ConnectStep />);++ expect(+ await screen.findByRole("button", { name: /Sign in with ChatGPT/ }),+ ).toBeDefined();+ expect(screen.getByRole("button", { name: /Skip for now/ })).toBeDefined();+ });++ it("can be skipped, because API keys are a legitimate answer", async () => {+ // A wizard that cannot be passed without linking an account would make+ // the advanced path a dead end rather than an alternative. The control+ // is named for what it does -- it skips the step; it cannot add a key --+ // and the line beside it says where keys actually live.+ mockOffers([offer()]);++ render(<ConnectStep />);+ await userEvent.click(+ await screen.findByRole("button", { name: /Skip for now/ }),+ );++ expect(useOnboardingWizardStore.getState().currentStep).toBe(2);+ expect(connect).not.toHaveBeenCalled();+ });++ it("stops asking once a subscription is linked", async () => {+ mockOffers([offer(), chatgpt()]);++ render(<ConnectStep />);++ expect(+ await screen.findByText(/Your ChatGPT plan is connected/),+ ).toBeDefined();+ expect(screen.queryByRole("button", { name: /Sign in with ChatGPT/ })).toBe(+ null,+ );+ });++ it("says a Claude subscription cannot be linked, rather than leaving it to be discovered", async () => {+ mockOffers([offer()]);++ render(<ConnectStep />);++ expect(+ await screen.findByText(/Claude subscriptions can't be linked/),+ ).toBeDefined();+ });++ it("names what you get, from the catalog", async () => {+ mockOffers([offer()], [chatgptTiers()]);++ render(<ConnectStep />);++ expect(+ await screen.findByText(+ /GPT-5\.6 Terra \(Balanced\) and GPT-5\.6 Sol \(Advanced\)/,+ ),+ ).toBeDefined();+ });+});++describe("ConnectStep helpers", () => {+ it("does not count the deployment's own provider as a linked subscription", () => {+ // It is a connection, but it is the one that exists because someone put+ // an API key in a file -- which is what this step offers a way around.+ expect(hasLinkedSubscription([offer()])).toBe(false);+ expect(hasLinkedSubscription([offer(), chatgpt()])).toBe(true);+ });++ it("names the models from the catalog rather than hardcoding them", () => {+ expect(linkedModelsSentence([chatgptTiers()])).toBe(+ "GPT-5.6 Terra (Balanced) and GPT-5.6 Sol (Advanced)",+ );+ });++ it("reads them from provider tiers, not from the user's connections", () => {+ // The whole point of this screen is that the user has not connected yet,+ // so ChatGPT is absent from their offers and this sentence would always+ // have come out empty if it read them.+ expect(linkedModelsSentence([])).toBe("");+ });++ it("says nothing when the server named no models", () => {+ expect(+ linkedModelsSentence([{ ...chatgptTiers(), tiers: [] } as ProviderTiers]),+ ).toBe("");+ expect(linkedModelsSentence(undefined)).toBe("");+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.tsnew file mode 100644index 0000000000..b8c868caba--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/helpers.ts@@ -0,0 +1,45 @@+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import type { ProviderTiers } from "@/app/api/__generated__/models/providerTiers";++/**+ * Whether the user has already linked a subscription of their own.+ *+ * The deployment's own chat provider does not count. It is a connection, but+ * it is the one that exists because someone put an API key in a file — which+ * is the thing this step offers a way around.+ */+export function hasLinkedSubscription(+ offers: AIConnectionOffer[] | undefined,+): boolean {+ return (offers ?? []).some(+ (offer) =>+ offer.auth_method !== "deployment" && Boolean(offer.credential_id),+ );+}++/**+ * "5.6 Terra (Balanced) and 5.6 Sol (Advanced)", from the catalog.+ *+ * Read from the provider-tiers endpoint rather than from the user's+ * connections, because the whole point of this screen is that the user does+ * not have this connection yet -- so it is absent from the offers list, and+ * the sentence would always come out empty.+ *+ * Empty when the server named nothing, so the sentence that would have+ * carried it is dropped rather than rendered half-written. Never hardcoded+ * here: which model a tier resolves to is the server's to say, and this+ * screen is the one making the promise.+ */+export function linkedModelsSentence(+ providers: ProviderTiers[] | undefined,+): string {+ const chatgpt = (providers ?? []).find(+ (provider) => provider.provider_family === "openai",+ );+ const named = (chatgpt?.tiers ?? [])+ .filter((tier) => tier.display_model)+ .map((tier) => `${tier.display_model} (${tier.label})`);+ if (named.length === 0) return "";+ if (named.length === 1) return named[0];+ return `${named.slice(0, -1).join(", ")} and ${named[named.length - 1]}`;+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.tsnew file mode 100644index 0000000000..98a83ce50b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/steps/ConnectStep/useConnectStep.ts@@ -0,0 +1,56 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";++import {+ getGetV2ListChatConnectionsQueryKey,+ useGetV2ListChatConnections,+ useGetV2ListProviderModelTiers,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { useOAuthConnect } from "@/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/useOAuthConnect";++import { useOnboardingWizardStore } from "../../store";+import { hasLinkedSubscription, linkedModelsSentence } from "./helpers";++export function useConnectStep() {+ const queryClient = useQueryClient();+ const nextStep = useOnboardingWizardStore((s) => s.nextStep);++ const connectionsQuery = useGetV2ListChatConnections({+ query: { refetchOnWindowFocus: false },+ });+ const offers =+ connectionsQuery.data?.status === 200+ ? connectionsQuery.data.data.offers+ : undefined;++ // What ChatGPT's tiers resolve to, which the connections list cannot answer+ // for a connection the user has not made yet.+ const tiersQuery = useGetV2ListProviderModelTiers({+ query: { refetchOnWindowFocus: false },+ });+ const providers =+ tiersQuery.data?.status === 200+ ? tiersQuery.data.data.providers+ : undefined;++ const { connect, isPending } = useOAuthConnect({+ provider: "codex",+ onSuccess: () => {+ // The next step's copy depends on what is connected, and so does the+ // decision to show this step at all on a later visit.+ queryClient.invalidateQueries({+ queryKey: getGetV2ListChatConnectionsQueryKey(),+ });+ nextStep();+ },+ });++ return {+ connect,+ isConnecting: isPending,+ skip: nextStep,+ isAlreadyLinked: hasLinkedSubscription(offers),+ models: linkedModelsSentence(providers),+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.tsindex 182e125e46..2310104a1d 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/store.ts@@ -23,6 +23,18 @@ export const NO_PAYWALL_STEPS = {preparing: 4,} as const;+// Self-host has no paywall, but it has the same question in a different+// currency: a chat needs a model behind it before personalising the chat is+// worth anything. On cloud the user pays us first; on self-host they connect+// a plan they already pay for. Same slot, same reason.+export const SELF_HOST_STEPS = {+ connect: 1,+ welcome: 2,+ role: 3,+ painPoints: 4,+ preparing: 5,+} as const;+interface OnboardingWizardState {currentStep: Step;name: string;diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.tsindex 56bb1eba45..5b4d19ec33 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts+++ b/autogpt_platform/frontend/src/app/(no-navbar)/onboarding/useOnboardingPage.ts@@ -17,6 +17,7 @@ import { normalizeOnboardingProfile } from "./helpers";import {NO_PAYWALL_STEPS,PAYWALL_FIRST_STEPS,+ SELF_HOST_STEPS,Step,useOnboardingWizardStore,} from "./store";@@ -119,9 +120,18 @@ export function useOnboardingPage() {const isPaymentEnabled =(paymentEnabledSnapshot.current ?? false) && !userHasActivePlan;- const steps = isPaymentEnabled ? PAYWALL_FIRST_STEPS : NO_PAYWALL_STEPS;+ // A self-host install has no paywall and no model until someone gives it+ // one, so it leads with the connection instead. Payments and self-host are+ // mutually exclusive in practice; the check is ordered anyway so a+ // deployment that somehow had both still only inserts one first step.+ const isSelfHostConnectEnabled = !isPaymentEnabled && environment.isLocal();+ const steps = isPaymentEnabled+ ? PAYWALL_FIRST_STEPS+ : isSelfHostConnectEnabled+ ? SELF_HOST_STEPS+ : NO_PAYWALL_STEPS;const preparingStep: Step = steps.preparing;- const totalSteps = isPaymentEnabled ? 4 : 3;+ const totalSteps = isPaymentEnabled || isSelfHostConnectEnabled ? 4 : 3;// Wait for auth too — without !isUserLoading, LD can resolve while// isLoggedIn is transiently false, the tier query stays disabled@@ -268,6 +278,7 @@ export function useOnboardingPage() {isLoading: isOnboardingStateLoading || !isReady,handlePreparingComplete,isPaymentEnabled,+ isSelfHostConnectEnabled,isBrainDumpEnabled,steps,preparingStep,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex 2d6bb762ef..8c7df0b473 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -1,5 +1,6 @@"use client";import { ChatContainer } from "./components/ChatContainer/ChatContainer";+import { ProviderLimitDialog } from "./components/ProviderLimitDialog/ProviderLimitDialog";import { RateLimitGate } from "./components/RateLimitResetDialog/RateLimitGate";import { useCopilotPage } from "./useCopilotPage";import { FlaskConicalIcon } from "@hugeicons/core-free-icons";@@ -48,6 +49,8 @@ export function CopilotChatHost({turnStats,rateLimitMessage,dismissRateLimit,+ providerLimit,+ dismissProviderLimit,sessionDryRun,sessionChatStatus,expertIdentity,@@ -105,6 +108,11 @@ export function CopilotChatHost({rateLimitMessage={rateLimitMessage}onDismiss={dismissRateLimit}/>+ <ProviderLimitDialog+ failure={providerLimit}+ sessionId={sessionId}+ onDismiss={dismissProviderLimit}+ /></>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsxindex 04940ffe0a..9566accb3a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/CopilotPage.test.tsx@@ -74,6 +74,15 @@ vi.mock("@/app/api/__generated__/endpoints/chat/chat", () => ({}return { data: undefined, isSuccess: false, isError: false };},+ // The provider-limit dialog reads connections to find somewhere to+ // continue. It only renders on a failure, which this page test never+ // provokes, so an empty result is the honest stand-in.+ useGetV2ListChatConnections: () => ({ data: undefined }),+ getGetV2ListChatConnectionsQueryKey: () => ["chat", "connections"],+ usePutV2ChangeTheConnectionAnExistingChatRunsOn: () => ({+ mutateAsync: vi.fn(),+ isPending: false,+ }),}));vi.mock("@/hooks/useCredits", () => ({default: () => ({ credits: null, fetchCredits: vi.fn() }),diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.tsindex 2e40c5d7d3..8f1713ddc5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamErrorHandlers.test.ts@@ -195,3 +195,57 @@ describe("handleStreamError", () => {expect(mockToast).not.toHaveBeenCalled();});});++describe("handleStreamError — telling the two usage limits apart", () => {+ function limit(authProvider: string | null) {+ return {+ kind: "usage_limit" as const,+ message: "Limit reached.",+ authProvider,+ credentialId: authProvider === "codex" ? "cred-1" : null,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ };+ }++ beforeEach(() => {+ mockToast.mockClear();+ });++ it("hands a linked plan's limit to the caller with the failure attached", () => {+ // The caller needs it to open the continue path rather than the plan+ // dialog: asking someone to upgrade with us because OpenAI said no is+ // the wrong answer to the wrong question.+ const onRateLimit = vi.fn();++ handleStreamError({+ error: new Error("boom"),+ providerFailure: limit("codex"),+ onRateLimit,+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });++ expect(onRateLimit).toHaveBeenCalledTimes(1);+ expect(onRateLimit.mock.calls[0][1]).toEqual(+ expect.objectContaining({ kind: "usage_limit", authProvider: "codex" }),+ );+ });++ it("still routes our own limit the same way, so the composer text survives", () => {+ const onRateLimit = vi.fn();++ handleStreamError({+ error: new Error("boom"),+ providerFailure: limit("platform"),+ onRateLimit,+ onReconnect: vi.fn(),+ isUserStoppingRef: makeRef(false),+ });++ expect(onRateLimit).toHaveBeenCalledTimes(1);+ expect(onRateLimit.mock.calls[0][1]?.authProvider).toBe("platform");+ expect(mockToast).not.toHaveBeenCalled();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.tsindex 064696a966..41d6737b9a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/providerFailure.test.ts@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";import {describeProviderFailure,+ latestProviderFailure,parseProviderFailurePart,+ PROVIDER_FAILURE_KEY,+ providerFailureFingerprint,type ProviderFailure,} from "../providerFailure";@@ -109,3 +112,121 @@ describe("describeProviderFailure", () => {expect(copy.description).toContain("safety policy");});});++describe("latestProviderFailure", () => {+ const envelope = {+ kind: "usage_limit",+ message: "Your ChatGPT plan is out of turns.",+ authProvider: "codex",+ credentialId: "cred-1",+ resetsAt: 1767225600,+ retryable: false,+ reconnectFixesIt: false,+ };++ it("recovers the failure a reopened chat is still sitting on", () => {+ // The backend persists the envelope onto the marker row precisely so a+ // reload can still offer the way out. Reading it only from the live+ // stream meant a refresh silently removed the switch-connection control+ // and left the chat latched to the connection that had just refused it.+ const failure = latestProviderFailure([+ { role: "user", content: "hi", metadata: null },+ {+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] out of turns",+ metadata: { [PROVIDER_FAILURE_KEY]: envelope },+ },+ ]);+ expect(failure?.kind).toBe("usage_limit");+ expect(failure?.credentialId).toBe("cred-1");+ });++ it("takes the newest one, so a recovered-from failure stays history", () => {+ const older = { ...envelope, credentialId: "old" };+ const newer = { ...envelope, credentialId: "new" };+ const failure = latestProviderFailure([+ {+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] old",+ metadata: { [PROVIDER_FAILURE_KEY]: older },+ },+ {+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] new",+ metadata: { [PROVIDER_FAILURE_KEY]: newer },+ },+ ]);+ expect(failure?.credentialId).toBe("new");+ });++ it("does not resurrect a failure the chat has since recovered from", () => {+ // A successful turn after the failure means the chat moved on. Walking+ // past it would re-offer "continue on ..." for a limit that no longer+ // applies -- on a reload, indistinguishable from failing again.+ expect(+ latestProviderFailure([+ {+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] out of turns",+ metadata: { [PROVIDER_FAILURE_KEY]: envelope },+ },+ { role: "user", content: "try again please", metadata: null },+ { role: "assistant", content: "Done.", metadata: null },+ ]),+ ).toBeNull();+ });++ it("does not resurrect a failure after the chat switched connections", () => {+ expect(+ latestProviderFailure(+ [+ {+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] out of turns",+ metadata: { [PROVIDER_FAILURE_KEY]: envelope },+ },+ ],+ { authProvider: "platform", credentialId: null },+ ),+ ).toBeNull();+ });++ it("keeps a failure when the chat is still on that connection", () => {+ expect(+ latestProviderFailure(+ [+ {+ role: "assistant",+ content: "[__COPILOT_ERROR_f7a1__] out of turns",+ metadata: { [PROVIDER_FAILURE_KEY]: envelope },+ },+ ],+ { authProvider: "codex", credentialId: "cred-1" },+ )?.kind,+ ).toBe("usage_limit");+ });++ it("is null for a chat that never failed", () => {+ expect(+ latestProviderFailure([+ { role: "user", content: "hi", metadata: null },+ {+ role: "assistant",+ content: "sure",+ metadata: { kind: "expert_run" },+ },+ ]),+ ).toBeNull();+ });+});++describe("providerFailureFingerprint", () => {+ it("changes when a new connection or reset window fails", () => {+ expect(providerFailureFingerprint(failure())).not.toBe(+ providerFailureFingerprint(failure({ credentialId: "cred-2" })),+ );+ expect(providerFailureFingerprint(failure())).not.toBe(+ providerFailureFingerprint(failure({ resetsAt: 123 })),+ );+ });+});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.tsxindex d2ce51edbf..3f3c1cc900 100644--- 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.tsx@@ -22,6 +22,13 @@ interface Props {badge?: string;/** Why this cannot be chosen, and where to go to change that. */lock?: { reason: string; href: string | null };+ /** Identifies the row to the group's arrow-key handler. */+ offerId?: string;+ /**+ * A radio group is one tab stop; only the active row takes it. Supplied by+ * the group so Tab skips past the whole set rather than through it.+ */+ tabIndex?: number;}export function ChoiceRow({@@ -33,6 +40,8 @@ export function ChoiceRow({label,lock,badge,+ offerId,+ tabIndex,}: Props) {if (lock) {return (@@ -46,6 +55,8 @@ export function ChoiceRow({role="radio"aria-checked={isSelected}aria-label={label}+ data-offer={offerId}+ tabIndex={tabIndex}onClick={onSelect}className={cn("flex w-full items-start gap-2.5 px-3 py-2 text-left transition-colors",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.tsxindex e5f8041353..122a76a787 100644--- 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.tsx@@ -1,10 +1,10 @@"use client";import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuTrigger,-} from "@/components/molecules/DropdownMenu/DropdownMenu";+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/molecules/Popover/Popover";import {AlertCircleIcon,ArrowDown01Icon,@@ -18,12 +18,14 @@ import { cn } from "@/lib/utils";import { ChoiceRow } from "./ChoiceRow";import {isLinkedAccount,+ isSelectable,offerSubtitle,tierLabel,tierName,tierLock,tierSummary,} from "./helpers";+import { nextRovingValue, rovingTabIndex } from "./radioKeys";import { TierToggle } from "./TierToggle";import { useConnectionPicker } from "./useConnectionPicker";@@ -98,6 +100,10 @@ export function ConnectionPicker({ connectionLocked = false }: Props) {return null;}+ const connectionOptions = offers.map((offer) => ({+ value: offer.offer_id,+ disabled: !isSelectable(offer),+ }));const runsOnOwnPlan = active ? isLinkedAccount(active) : false;const showsTier = connectionLocked && Boolean(active);const label = showsTier@@ -110,8 +116,8 @@ export function ConnectionPicker({ connectionLocked = false }: Props) {runsOnOwnPlan && !showsTier ? `${label} · your plan` : label;return (- <DropdownMenu>- <DropdownMenuTrigger asChild>+ <Popover>+ <PopoverTrigger asChild><buttontype="button"aria-label={@@ -134,19 +140,42 @@ export function ConnectionPicker({ connectionLocked = false }: Props) {className="text-muted-foreground"/></button>- </DropdownMenuTrigger>+ </PopoverTrigger>- <DropdownMenuContent+ <PopoverContentalign="start"- className="w-[26rem] max-w-[calc(100vw-2rem)] p-0"+ className="w-[26rem] max-w-[calc(100vw-2rem)] border-border bg-popover p-0 text-popover-foreground">{(!connectionLocked || onlyOfferIsLocked) && (<><SectionLabel>Runs on</SectionLabel>- <div role="radiogroup" aria-label="Connection this chat runs on">+ <div+ role="radiogroup"+ aria-label="Connection this chat runs on"+ onKeyDown={(event) => {+ const to = nextRovingValue(+ connectionOptions,+ active?.offer_id ?? "",+ event.key,+ );+ if (to === null) return;+ event.preventDefault();+ const target = offers.find((o) => o.offer_id === to);+ if (target) chooseConnection(target);+ event.currentTarget+ .querySelector<HTMLElement>(`[data-offer="${to}"]`)+ ?.focus();+ }}+ >{offers.map((offer) => (<ChoiceRowkey={offer.offer_id}+ offerId={offer.offer_id}+ tabIndex={rovingTabIndex(+ connectionOptions,+ { value: offer.offer_id },+ active?.offer_id ?? "",+ )}title={offer.display_name}subtitle={offerSubtitle(offer)}badge={isLinkedAccount(offer) ? "Connected" : undefined}@@ -183,8 +212,8 @@ export function ConnectionPicker({ connectionLocked = false }: Props) {/></>)}- </DropdownMenuContent>- </DropdownMenu>+ </PopoverContent>+ </Popover>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsxindex a3dd26a6bc..2d663e4ea6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/TierToggle.tsx@@ -7,6 +7,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";import { cn } from "@/lib/utils";import type { CopilotLlmModel } from "../../../../store";+import { nextRovingValue, rovingTabIndex } from "./radioKeys";interface Segment {tier: CopilotLlmModel;@@ -34,12 +35,29 @@ interface Props {*/export function TierToggle({ segments, value, onSelect }: Props) {const locked = segments.filter((segment) => segment.lock);+ const options = segments.map((segment) => ({+ value: segment.tier,+ disabled: Boolean(segment.lock),+ }));++ function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {+ const to = nextRovingValue(options, value, event.key);+ if (to === null) return;+ event.preventDefault();+ onSelect(to);+ // Selection follows focus in a radio group, so the newly chosen segment+ // is also where focus belongs.+ const group = event.currentTarget;+ const next = group.querySelector<HTMLElement>(`[data-tier="${to}"]`);+ next?.focus();+ }return (<div className="mb-3 mt-1 flex flex-col gap-1.5 px-3"><divrole="radiogroup"aria-label="Model tier"+ onKeyDown={handleKeyDown}className="flex items-stretch gap-1 rounded-full bg-muted/70 p-1">{segments.map((segment) =>@@ -51,6 +69,8 @@ export function TierToggle({ segments, value, onSelect }: Props) {type="button"role="radio"aria-checked={segment.tier === value}+ data-tier={segment.tier}+ tabIndex={rovingTabIndex(options, { value: segment.tier }, value)}onClick={() => onSelect(segment.tier)}className={cn("min-w-0 flex-1 truncate rounded-full px-3 py-1.5 text-[11px] font-medium transition-colors",diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/radioKeys.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/radioKeys.tsnew file mode 100644index 0000000000..bfce4032d1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/ConnectionPicker/radioKeys.ts@@ -0,0 +1,63 @@+/**+ * Keyboard behaviour for a radio group, which is not the same as a list of+ * buttons that happen to say `role="radio"`.+ *+ * A radio group is one tab stop: Tab moves past the whole group, and the+ * arrow keys move *and select* within it. Without that, a keyboard user tabs+ * through every option one at a time and a screen reader announces a group+ * whose operating instructions do not match how it behaves.+ *+ * Locked options are skipped rather than focused. They exist to explain a+ * barrier, and stopping on something that cannot be chosen is a dead end.+ */++const NEXT_KEYS = new Set(["ArrowRight", "ArrowDown"]);+const PREV_KEYS = new Set(["ArrowLeft", "ArrowUp"]);++export interface RovingOption<T> {+ value: T;+ disabled?: boolean;+}++/** The single tab stop: the selected option, or the first selectable one. */+export function rovingTabIndex<T>(+ options: RovingOption<T>[],+ option: RovingOption<T>,+ selected: T,+): 0 | -1 {+ const selectable = options.filter((candidate) => !candidate.disabled);+ const active =+ selectable.find((candidate) => candidate.value === selected) ??+ selectable[0];+ return active && active.value === option.value ? 0 : -1;+}++/**+ * Returns the option the key moves to, or null when the key is not one this+ * group handles — in which case the caller must not preventDefault, or it+ * would swallow Tab and Escape.+ */+export function nextRovingValue<T>(+ options: RovingOption<T>[],+ current: T,+ key: string,+): T | null {+ const selectable = options.filter((option) => !option.disabled);+ if (selectable.length === 0) return null;++ if (key === "Home") return selectable[0].value;+ if (key === "End") return selectable[selectable.length - 1].value;++ const step = NEXT_KEYS.has(key) ? 1 : PREV_KEYS.has(key) ? -1 : 0;+ if (step === 0) return null;++ const at = selectable.findIndex((option) => option.value === current);+ // An unselected group starts from whichever end the user arrowed toward.+ if (at === -1) {+ return step === 1+ ? selectable[0].value+ : selectable[selectable.length - 1].value;+ }+ const to = (at + step + selectable.length) % selectable.length;+ return selectable[to].value;+}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.tsxindex a29854debe..3bbf532e2c 100644--- 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.tsx@@ -207,6 +207,37 @@ describe("ConnectionPicker", () => {);});+ it("is one tab stop, and the arrow keys move and select within it", async () => {+ // A radio group is not a list of buttons that say role="radio". Tab moves+ // past the whole group; the arrows move within it and select as they go.+ // Previously every option was its own tab stop and the arrows did nothing,+ // so a keyboard user could not operate the control the way its role+ // promised.+ mockOffers([offer()]);+ render(<ConnectionPicker connectionLocked />);++ await userEvent.click(+ await screen.findByRole("button", { name: /Model tier/ }),+ );+ const tiers = await screen.findByRole("radiogroup", { name: "Model tier" });+ const balanced = within(tiers).getByRole("radio", {+ name: "Balanced · sonnet-5",+ });+ const advanced = within(tiers).getByRole("radio", {+ name: "Advanced · opus-5",+ });++ expect(balanced.getAttribute("tabindex")).toBe("0");+ expect(advanced.getAttribute("tabindex")).toBe("-1");++ balanced.focus();+ await userEvent.keyboard("{ArrowRight}");++ await waitFor(() =>+ expect(useCopilotUIStore.getState().copilotLlmModel).toBe("advanced"),+ );+ });+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.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/ProviderLimitDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/ProviderLimitDialog.tsxnew file mode 100644index 0000000000..798eb7f47e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/ProviderLimitDialog.tsx@@ -0,0 +1,114 @@+"use client";++import { Button } from "@/components/atoms/Button/Button";+import { Text } from "@/components/atoms/Text/Text";+import { Dialog } from "@/components/molecules/Dialog/Dialog";++import type { ProviderFailure } from "../../providerFailure";+import { useProviderLimitDialog } from "./useProviderLimitDialog";++interface Props {+ failure: ProviderFailure | null;+ sessionId: string | null;+ onDismiss: () => void;+}++/**+ * A linked subscription stopped accepting turns. Offer to keep going.+ *+ * The PRD's out-of-limit path: the run pauses and offers to continue+ * somewhere else, and never moves the bill on its own. A dialog rather than a+ * toast because the choice has a cost — the rest of this chat spends AutoGPT+ * credits instead of a plan the user already pays for — and that is not a+ * thing to slip past someone in the corner of the screen.+ *+ * Waiting stays a real option. When the provider told us when the limit+ * resets that is said here; an invented time would be worse than none,+ * because people plan around it.+ */+export function ProviderLimitDialog({ failure, sessionId, onDismiss }: Props) {+ const {+ alternative,+ continueHere,+ isSwitching,+ resetHint,+ isLoadingOffers,+ failedToLoadOffers,+ retryOffers,+ } = useProviderLimitDialog({ failure, sessionId, onDismiss });++ return (+ <Dialog+ title="You've hit this connection's limit"+ styling={{ maxWidth: "30rem", minWidth: "auto" }}+ controlled={{+ isOpen: Boolean(failure),+ set: (open) => {+ if (!open) onDismiss();+ },+ }}+ >+ <Dialog.Content>+ <Text variant="body" className="text-zinc-600">+ {failure?.message?.trim() ||+ "The connection this chat runs on stopped accepting turns."}+ {resetHint ? ` ${resetHint}` : ""}+ </Text>++ {isLoadingOffers ? (+ <Text variant="small" className="mt-3 !text-zinc-500">+ Checking what else this chat can run on…+ </Text>+ ) : failedToLoadOffers ? (+ <>+ <Text variant="small" className="mt-3 !text-zinc-500">+ We couldn't check your other connections just now.+ </Text>+ <Dialog.Footer>+ <Button variant="secondary" onClick={onDismiss}>+ Close+ </Button>+ <Button variant="primary" onClick={retryOffers}>+ Try again+ </Button>+ </Dialog.Footer>+ </>+ ) : alternative ? (+ <>+ <Text variant="small" className="mt-3 !text-zinc-500">+ Continuing moves the rest of this chat to{" "}+ {alternative.display_name}. Everything already said stays as it+ is, on the connection it ran on.+ </Text>+ <Dialog.Footer>+ <Button variant="secondary" onClick={onDismiss}>+ Wait for it to reset+ </Button>+ <Button+ variant="primary"+ onClick={continueHere}+ loading={isSwitching}+ >+ Continue on {alternative.display_name}+ </Button>+ </Dialog.Footer>+ </>+ ) : (+ <>+ {/* Nothing to offer: saying so is better than a button that+ cannot do anything. */}+ <Text variant="small" className="mt-3 !text-zinc-500">+ There is no other connection set up to continue on. You can add+ one in Settings, or wait for this one to reset.+ </Text>+ <Dialog.Footer>+ <Button variant="primary" onClick={onDismiss}>+ Close+ </Button>+ </Dialog.Footer>+ </>+ )}+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.tsnew file mode 100644index 0000000000..8d93ba739d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/__tests__/helpers.test.ts@@ -0,0 +1,134 @@+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import { describe, expect, it } from "vitest";++import type { ProviderFailure } from "../../../providerFailure";+import { alternativeConnection, formatResetHint } from "../helpers";++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: "Runs on your AutoGPT plan.",+ state: "ready",+ selectable: true,+ is_default: true,+ tiers: [],+ limitations: [],+ lock_reason: null,+ unlock_href: null,+ ...over,+ } as AIConnectionOffer;+}++function chatgpt(over: Partial<AIConnectionOffer> = {}): AIConnectionOffer {+ return offer({+ offer_id: "codex:cred-1",+ provider_family: "openai",+ display_name: "ChatGPT",+ auth_method: "chatgpt_oauth",+ credential_id: "cred-1",+ is_default: false,+ ...over,+ });+}++function limitOn(+ authProvider: string | null,+ credentialId: string | null = null,+): ProviderFailure {+ return {+ kind: "usage_limit",+ message: "Your plan's limit was reached.",+ authProvider,+ credentialId,+ resetsAt: null,+ retryable: false,+ reconnectFixesIt: false,+ };+}++describe("alternativeConnection", () => {+ it("offers the platform when a linked plan runs out", () => {+ const found = alternativeConnection(+ [offer(), chatgpt()],+ limitOn("codex", "cred-1"),+ );++ expect(found?.display_name).toBe("AutoGPT Platform");+ expect(found?.auth_provider).toBe("platform");+ expect(found?.credential_id).toBeNull();+ });++ it("never offers the connection that just refused the turn", () => {+ // It would fail again immediately, which is worse than saying there is+ // nothing to switch to.+ const found = alternativeConnection(+ [chatgpt()],+ limitOn("codex", "cred-1"),+ );++ expect(found).toBeNull();+ });++ it("keeps a second account of the same provider, which has its own quota", () => {+ const found = alternativeConnection(+ [+ chatgpt(),+ chatgpt({ offer_id: "codex:cred-2", credential_id: "cred-2" }),+ ],+ limitOn("codex", "cred-1"),+ );++ expect(found?.credential_id).toBe("cred-2");+ });++ it("excludes the whole provider when the failure named no account", () => {+ const found = alternativeConnection([offer()], limitOn("platform", null));++ expect(found).toBeNull();+ });++ it("ignores a connection the user cannot select", () => {+ const found = alternativeConnection(+ [offer({ selectable: false }), chatgpt()],+ limitOn("codex", "cred-1"),+ );++ expect(found).toBeNull();+ });++ it("has nothing to offer when there are no other connections", () => {+ expect(alternativeConnection([], limitOn("codex", "cred-1"))).toBeNull();+ expect(+ alternativeConnection(undefined, limitOn("codex", "cred-1")),+ ).toBeNull();+ });+});++describe("formatResetHint", () => {+ it("says nothing when the provider reported no reset time", () => {+ // An invented "try again in an hour" is worse than silence, because+ // people plan around it.+ expect(formatResetHint(null)).toBeNull();+ });++ it("says nothing for a reset that has already passed", () => {+ expect(formatResetHint(Math.floor(Date.now() / 1000) - 60)).toBeNull();+ });++ it("rounds to something a person would say", () => {+ const now = Math.floor(Date.now() / 1000);+ expect(formatResetHint(now + 30)).toBe("It resets in under a minute.");+ expect(formatResetHint(now + 20 * 60)).toBe(+ "It resets in about 20 minutes.",+ );+ expect(formatResetHint(now + 60 * 60)).toBe("It resets in about an hour.");+ expect(formatResetHint(now + 3 * 60 * 60)).toBe(+ "It resets in about 3 hours.",+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.tsnew file mode 100644index 0000000000..9770e3f374--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/helpers.ts@@ -0,0 +1,76 @@+import type { AIConnectionOffer } from "@/app/api/__generated__/models/aIConnectionOffer";+import type { ChangeSessionConnectionRequestLlmAuthProvider } from "@/app/api/__generated__/models/changeSessionConnectionRequestLlmAuthProvider";++import type { ProviderFailure } from "../../providerFailure";++export interface Alternative {+ display_name: string;+ auth_provider: ChangeSessionConnectionRequestLlmAuthProvider;+ credential_id: string | null;+}++/**+ * A connection this chat could continue on, or nothing.+ *+ * The PRD's priority order starts with the platform, because it is the one+ * connection a user is guaranteed to be able to fall back to. Anything else+ * that is selectable will do after that; the one thing excluded is the+ * connection that just refused the turn, which would fail again immediately.+ */+export function alternativeConnection(+ offers: AIConnectionOffer[] | undefined,+ failure: ProviderFailure | null,+): Alternative | null {+ if (!failure) return null;++ const usable = (offers ?? []).filter(+ (offer) =>+ offer.selectable &&+ !isTheOneThatFailed(offer, failure) &&+ (offer.auth_method === "deployment" || offer.credential_id !== null),+ );+ if (usable.length === 0) return null;++ const platform =+ usable.find((offer) => offer.auth_method === "deployment") ?? usable[0];++ return {+ display_name: platform.display_name,+ auth_provider: platform.offer_id.split(+ ":",+ )[0] as ChangeSessionConnectionRequestLlmAuthProvider,+ credential_id: platform.credential_id ?? null,+ };+}++function isTheOneThatFailed(+ offer: AIConnectionOffer,+ failure: ProviderFailure,+): boolean {+ const provider = offer.offer_id.split(":")[0];+ if (provider !== failure.authProvider) return false;+ // A provider with no credential is a single connection, so the provider+ // matching is enough. With one, only the account that failed is excluded --+ // a second ChatGPT account has its own quota.+ if (failure.credentialId === null) return true;+ return offer.credential_id === failure.credentialId;+}++/**+ * "Resets in about 3 hours", or nothing.+ *+ * Only when the provider actually reported a reset time. An invented one is+ * worse than silence, because people plan around it.+ */+export function formatResetHint(resetsAt: number | null): string | null {+ if (resetsAt === null) return null;+ const seconds = resetsAt - Math.floor(Date.now() / 1000);+ if (seconds <= 0) return null;+ if (seconds < 90) return "It resets in under a minute.";+ const minutes = Math.round(seconds / 60);+ if (minutes < 60) return `It resets in about ${minutes} minutes.`;+ const hours = Math.round(minutes / 60);+ return hours === 1+ ? "It resets in about an hour."+ : `It resets in about ${hours} hours.`;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.tsnew file mode 100644index 0000000000..749b61a9ad--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ProviderLimitDialog/useProviderLimitDialog.ts@@ -0,0 +1,102 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";++import {+ getGetV2GetSessionQueryKey,+ getGetV2ListChatConnectionsQueryKey,+ useGetV2ListChatConnections,+ usePutV2ChangeTheConnectionAnExistingChatRunsOn,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { toast } from "@/components/molecules/Toast/use-toast";++import type { ProviderFailure } from "../../providerFailure";+import { alternativeConnection, formatResetHint } from "./helpers";++interface Args {+ failure: ProviderFailure | null;+ sessionId: string | null;+ onDismiss: () => void;+}++export function useProviderLimitDialog({+ failure,+ sessionId,+ onDismiss,+}: Args) {+ const queryClient = useQueryClient();++ const connectionsQuery = useGetV2ListChatConnections({+ query: { enabled: Boolean(failure) },+ });+ const offers =+ connectionsQuery.data?.status === 200+ ? connectionsQuery.data.data.offers+ : undefined;++ // "There is no other connection" is a claim about the account, and while the+ // list is still loading -- or failed to load -- we do not know that. Saying+ // it anyway tells a user with a perfectly good second connection that they+ // have none, at the moment they most need it.+ const isLoadingOffers = connectionsQuery.isLoading;+ const failedToLoadOffers =+ connectionsQuery.isError ||+ (connectionsQuery.data !== undefined &&+ connectionsQuery.data.status !== 200);+ const alternative = alternativeConnection(offers, failure);++ const { mutateAsync: changeConnection, isPending: isSwitching } =+ usePutV2ChangeTheConnectionAnExistingChatRunsOn({+ mutation: {+ onSuccess: async () => {+ // The composer already holds the message the provider refused, so+ // the user resends when they are ready. Never automatic: the whole+ // point is that moving the bill is their call.+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: getGetV2ListChatConnectionsQueryKey(),+ }),+ queryClient.invalidateQueries({+ queryKey: getGetV2GetSessionQueryKey(sessionId ?? undefined),+ }),+ ]);+ onDismiss();+ },+ onError: () => {+ toast({+ variant: "destructive",+ title: "Could not switch connection",+ description:+ "This chat is still on the connection it was. Try again, or pick one in Settings.",+ });+ },+ },+ });++ async function continueHere() {+ if (!sessionId || !alternative) return;+ try {+ await changeConnection({+ sessionId,+ data: {+ llm_auth_provider: alternative.auth_provider,+ llm_credential_id: alternative.credential_id,+ },+ });+ } catch {+ // React Query's onError handler above owns the user-facing failure.+ // Consume mutateAsync's rejection so a button click does not become an+ // unhandled promise rejection as well.+ }+ }++ return {+ alternative,+ isLoadingOffers,+ failedToLoadOffers,+ retryOffers: () => void connectionsQuery.refetch(),+ continueHere,+ isSwitching,+ resetHint: formatResetHint(failure?.resetsAt ?? null),+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.tsindex ecacddef2c..c36203fd53 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamErrorHandlers.ts@@ -99,7 +99,7 @@ function extractErrorDetail(error: Error): string {interface HandleStreamErrorArgs {error: Error;- onRateLimit: (message: string) => void;+ onRateLimit: (message: string, providerFailure?: ProviderFailure) => void;onReconnect: () => void;isUserStoppingRef: React.MutableRefObject<boolean>;/**@@ -141,7 +141,14 @@ export function handleStreamError({// Still routed through the rate-limit path: it restores the composer// text for a message the backend refused before persisting, which a// toast alone would lose.- onRateLimit(`${copy.title}. ${copy.description}`);+ //+ // The failure travels with it so the caller can tell the two limits+ // apart. They are not the same event: our own credits running out is+ // answered by upgrading a plan with us, and a linked subscription+ // running out is answered by continuing on a different connection.+ // Offering the first for the second asks someone to pay us because+ // OpenAI said no.+ onRateLimit(`${copy.title}. ${copy.description}`, providerFailure);return;}toast({diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.tsindex 5a9c253365..4f9191f990 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/providerFailure.ts@@ -32,6 +32,11 @@ export interface ProviderFailure {reconnectFixesIt: boolean;}+export interface ProviderRoute {+ authProvider: string;+ credentialId: string | null;+}+const KINDS = new Set<string>(["auth_expired","invalid_credential",@@ -42,12 +47,16 @@ const KINDS = new Set<string>(["transient",]);-export function parseProviderFailurePart(dataPart: {- type: string;- data?: unknown;-}): ProviderFailure | null {- if (dataPart.type !== "data-provider-failure") return null;- const data = dataPart.data as Partial<ProviderFailure> | undefined;+/**+ * The envelope, from wherever it came from.+ *+ * The same object rides the live stream and is persisted onto the error+ * marker row, so reopening a chat tomorrow can offer the same recovery the+ * user was offered when it failed. One parser for both, because a second one+ * would be free to disagree about the shape.+ */+export function parseProviderFailure(value: unknown): ProviderFailure | null {+ const data = value as Partial<ProviderFailure> | undefined;if (!data || typeof data.kind !== "string" || !KINDS.has(data.kind)) {return null;}@@ -62,6 +71,87 @@ export function parseProviderFailurePart(dataPart: {};}+export function parseProviderFailurePart(dataPart: {+ type: string;+ data?: unknown;+}): ProviderFailure | null {+ if (dataPart.type !== "data-provider-failure") return null;+ return parseProviderFailure(dataPart.data);+}++/** The key the backend stores the envelope under on a marker row. */+export const PROVIDER_FAILURE_KEY = "provider_failure";++// Server-written prefixes that mark a row as a failure card rather than a+// reply. Kept in step with COPILOT_ERROR_PREFIX in the backend's constants.+const ERROR_MARKER_PREFIXES = [+ "[__COPILOT_ERROR_f7a1__]",+ "[__COPILOT_RETRYABLE_ERROR_f7a1__]",+];++function isErrorMarker(row: { role?: unknown; content?: unknown }): boolean {+ const content = row.content;+ if (row.role !== "assistant" || typeof content !== "string") return false;+ return ERROR_MARKER_PREFIXES.some((prefix) => content.startsWith(prefix));+}++/**+ * The failure this chat is *currently* sitting on, if any.+ *+ * Scans newest-first and stops at the first thing that answers the question.+ * A marker carrying an envelope is the answer. So is a newer turn: if the user+ * has spoken again, or the assistant has replied for real, since the failure,+ * then the chat moved on and the old failure is history. Without that second+ * stop the scan walks straight past a recovered turn and resurrects a "continue+ * on ..." offer for a failure that no longer applies -- which on a reload is+ * indistinguishable, to the user, from failing again.+ */+export function latestProviderFailure(+ messages: readonly unknown[],+ activeRoute: ProviderRoute | null = null,+): ProviderFailure | null {+ for (let i = messages.length - 1; i >= 0; i--) {+ const row = messages[i];+ if (!row || typeof row !== "object") continue;+ const typed = row as {+ role?: unknown;+ content?: unknown;+ metadata?: unknown;+ };++ if (isErrorMarker(typed)) {+ const meta = typed.metadata;+ if (!meta || typeof meta !== "object") return null;+ const raw = (meta as Record<string, unknown>)[PROVIDER_FAILURE_KEY];+ const failure = raw === undefined ? null : parseProviderFailure(raw);+ if (!failure || !activeRoute || failure.authProvider === null) {+ return failure;+ }+ return failure.authProvider === activeRoute.authProvider &&+ failure.credentialId === activeRoute.credentialId+ ? failure+ : null;+ }++ // A real turn after the failure means the chat recovered.+ if (typed.role === "user") return null;+ if (typed.role === "assistant" && typeof typed.content === "string") {+ return null;+ }+ }+ return null;+}++export function providerFailureFingerprint(failure: ProviderFailure): string {+ return JSON.stringify([+ failure.kind,+ failure.message,+ failure.authProvider,+ failure.credentialId,+ failure.resetsAt,+ ]);+}+interface FailureCopy {title: string;description: string;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex a3956aba7f..3469711cb4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -359,6 +359,10 @@ export function useChatSession({? "codex": "platform": null;+ const sessionLlmCredentialId =+ sessionId && sessionQuery.data?.status === 200+ ? (sessionQuery.data.data.metadata?.llm_credential_id ?? null)+ : null;// The expert this session actually belongs to, straight off the session// response rather than the URL — the ?expertId= param only describes what@@ -374,6 +378,7 @@ export function useChatSession({sessionId,setSessionId,sessionLlmAuthProvider,+ sessionLlmCredentialId,sessionExpertId,isAdoptingExpertSession,hydratedMessages,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex b0d30d8bbc..c275764643 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -122,6 +122,8 @@ export function useCopilotPage() {const {sessionId,setSessionId,+ sessionLlmAuthProvider,+ sessionLlmCredentialId,sessionExpertId,isAdoptingExpertSession,hydratedMessages,@@ -172,10 +174,15 @@ export function useCopilotPage() {isUserStopping,rateLimitMessage,dismissRateLimit,+ providerLimit,+ dismissProviderLimit,} = useCopilotStream({userId: user?.id ?? null,sessionId,hydratedMessages,+ rawSessionMessages,+ sessionAuthProvider: sessionLlmAuthProvider,+ sessionCredentialId: sessionLlmCredentialId,activeTurnStartMessageId,hasActiveStream,refetchSession,@@ -412,6 +419,8 @@ export function useCopilotPage() {turnStats,rateLimitMessage,dismissRateLimit,+ providerLimit,+ dismissProviderLimit,// sessionDryRun is the CURRENT session's immutable dry_run flag from API,// used to render the banner. The global `isDryRun` preference (for new// sessions) lives in the store and is consumed by the toggle button.diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex a5dffbc61e..09dc155197 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -35,7 +35,9 @@ import {import { extractDbSequence } from "./helpers/convertChatSessionToUiMessages";import { getLatestAssistantStatusMessage } from "./messageParts";import {+ latestProviderFailure,parseProviderFailurePart,+ providerFailureFingerprint,type ProviderFailure,} from "./providerFailure";import { useCopilotUIStore } from "./store";@@ -75,6 +77,18 @@ interface UseCopilotStreamArgs {userId?: string | null;sessionId: string | null;hydratedMessages: UIMessage[] | undefined;+ /**+ * The session's messages as the API sent them.+ *+ * Conversion to UIMessages merges rows and drops their metadata, so the+ * persisted failure envelope does not survive it. This is the same data+ * before that happens.+ */+ rawSessionMessages?: unknown[];+ /** The route currently persisted for this session. Historical provider+ * failures from a route the chat already left are resolved, not live. */+ sessionAuthProvider?: string | null;+ sessionCredentialId?: string | null;/** Id of the first hydrated message of the turn the backend is still* running — the point the GET-resume replay starts from. */activeTurnStartMessageId?: string | null;@@ -88,6 +102,9 @@ export function useCopilotStream({userId = null,sessionId,hydratedMessages,+ rawSessionMessages,+ sessionAuthProvider = null,+ sessionCredentialId = null,activeTurnStartMessageId = null,hasActiveStream,refetchSession,@@ -96,6 +113,15 @@ export function useCopilotStream({const queryClient = useQueryClient();const setInitialPrompt = useCopilotUIStore((s) => s.setInitialPrompt);const [rateLimitMessage, setRateLimitMessage] = useState<string | null>(null);+ // A linked subscription that stopped accepting turns, as opposed to our own+ // credits running out. Held separately because the answer is different.+ const [providerLimit, setProviderLimit] = useState<ProviderFailure | null>(+ null,+ );+ const dismissedProviderFailureRef = useRef<{+ sessionId: string;+ fingerprint: string;+ } | null>(null);function dismissRateLimit() {setRateLimitMessage(null);}@@ -224,7 +250,7 @@ export function useCopilotStream({handleStreamError({error,providerFailure: failureForThisTurn,- onRateLimit: (message) => {+ onRateLimit: (message, limitFailure) => {// Backend raises 429 BEFORE persisting the user message, so the// optimistic user bubble added by useChat is a lie. Restore the text// into the composer (via the same store slot URL pre-fills use) and@@ -270,7 +296,26 @@ export function useCopilotStream({return next;});}- setRateLimitMessage(message);+ // A provider's own limit is not answered by upgrading with us, so+ // it opens the continue path instead of the plan dialog.+ //+ // Which limit it is turns on whether the server sent a failure+ // envelope, not on which connection the turn ran on. Our own daily+ // budget is refused at admission and arrives with no envelope; an+ // upstream 429 always carries one. Reading the connection instead+ // meant a self-host -- where the route is "platform" because the+ // deployment holds the key -- was told "Daily AutoPilot limit+ // reached, upgrade your plan" when its own OpenRouter or local+ // gateway had rate-limited it. That is a claim about an account we+ // do not bill, offering a plan that would not help.+ if (limitFailure) {+ // A later turn can fail in exactly the same way as an earlier one+ // the user dismissed. Live stream evidence is a new occurrence.+ dismissedProviderFailureRef.current = null;+ setProviderLimit(limitFailure);+ } else {+ setRateLimitMessage(message);+ }},onReconnect: () => handleReconnectRef.current(),isUserStoppingRef,@@ -488,6 +533,40 @@ export function useCopilotStream({useCopilotStreamStore.getState().setMessageSnapshot(sessionId, messages);}, [sessionId, messages]);+ // A failure the chat is still sitting on survives a reload, because the+ // backend persisted the envelope onto the marker row for exactly this. It+ // was only ever read from the live stream before, so refreshing, opening the+ // chat in another tab, or closing the laptop took away the one control that+ // offered a way out -- leaving the chat latched to the connection that had+ // just refused it, with no way to say "continue on the other one".+ useEffect(() => {+ setProviderLimit(null);+ dismissedProviderFailureRef.current = null;+ }, [sessionId]);++ useEffect(() => {+ if (!sessionId || !rawSessionMessages?.length) return;+ const historical = latestProviderFailure(+ rawSessionMessages,+ sessionAuthProvider+ ? {+ authProvider: sessionAuthProvider,+ credentialId: sessionCredentialId,+ }+ : null,+ );+ const dismissed = dismissedProviderFailureRef.current;+ if (+ historical &&+ dismissed?.sessionId === sessionId &&+ dismissed.fingerprint === providerFailureFingerprint(historical)+ ) {+ return;+ }+ // A live failure is the fresher truth; never let history overwrite it.+ setProviderLimit((current) => current ?? historical);+ }, [rawSessionMessages, sessionAuthProvider, sessionCredentialId, sessionId]);+useEffect(() => {if (!sessionId || !hydratedMessages) return;const coord = useCopilotStreamStore.getState().getCoord(sessionId);@@ -761,6 +840,16 @@ export function useCopilotStream({isUserStoppingRef,isUserStopping,rateLimitMessage,+ providerLimit,+ dismissProviderLimit: () => {+ if (sessionId && providerLimit) {+ dismissedProviderFailureRef.current = {+ sessionId,+ fingerprint: providerFailureFingerprint(providerLimit),+ };+ }+ setProviderLimit(null);+ },dismissRateLimit,};}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex b0e236793e..607d4e1a77 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -3745,6 +3745,30 @@}}},+ "/api/chat/model-tiers": {+ "get": {+ "tags": ["v2", "chat", "chat"],+ "summary": "List Provider Model Tiers",+ "description": "What each provider's quality tiers resolve to, whoever you are.\n\n``GET /connections`` answers \"what can you pick\", and deliberately omits\na connection nobody can select. That makes it the wrong source for the\nsurfaces that describe a provider *before* the user has one -- the\nconnect dialog, and the plan cards selling a plan they have not bought.\nThose need \"ChatGPT's Advanced tier is 5.6 Sol\", which is a fact about\nthe catalog rather than about this user's entitlements.\n\nUser-scoped only because the engine is: which model a tier maps to\ndepends on the path a turn will run on. Says nothing about access.",+ "operationId": "getV2ListProviderModelTiers",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ProviderTiersResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },"/api/chat/schema/tool-responses": {"get": {"tags": ["v2", "chat", "chat"],@@ -4116,6 +4140,59 @@}}},+ "/api/chat/sessions/{session_id}/connection": {+ "put": {+ "tags": ["v2", "chat", "chat"],+ "summary": "Change the connection an existing chat runs on",+ "description": "Move a chat onto another connection, from the next turn onward.\n\nA chat is latched to the connection it started on so that a turn cannot\nsilently change who pays for it halfway through. This is the deliberate\nexception: when a provider stops accepting turns -- a spent quota, an\nexpired login -- the alternative to switching is the chat simply ending.\n\nIt never happens on its own. The caller is a button the user pressed, and\nthe run continues on the connection they picked rather than on whichever\none happens to work.\n\nHistory is not rewritten. Turns already stamped keep the connection they\nran on, so a chat that hit a limit and carried on elsewhere reads as\nexactly that.",+ "operationId": "putV2Change the connection an existing chat runs on",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Session Id" }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChangeSessionConnectionRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "additionalProperties": true,+ "title": "Response Putv2Change The Connection An Existing Chat Runs On"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "404": { "description": "Session not found or access denied" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/chat/sessions/{session_id}/messages/pending": {"get": {"tags": ["v2", "chat", "chat"],@@ -16997,6 +17074,26 @@"title": "CancelSessionResponse","description": "Response model for the cancel session endpoint."},+ "ChangeSessionConnectionRequest": {+ "properties": {+ "llm_auth_provider": {+ "type": "string",+ "enum": ["platform", "codex"],+ "title": "Llm Auth Provider"+ },+ "llm_credential_id": {+ "anyOf": [+ { "type": "string", "maxLength": 128 },+ { "type": "null" }+ ],+ "title": "Llm Credential Id"+ }+ },+ "type": "object",+ "required": ["llm_auth_provider"],+ "title": "ChangeSessionConnectionRequest",+ "description": "The connection the rest of this chat should run on."+ },"ChangelogEntry": {"properties": {"version": { "type": "string", "title": "Version" },@@ -24433,6 +24530,50 @@"required": ["providers", "pagination"],"title": "ProviderResponse"},+ "ProviderTier": {+ "properties": {+ "tier": {+ "type": "string",+ "enum": ["standard", "advanced"],+ "title": "Tier"+ },+ "label": { "type": "string", "title": "Label" },+ "display_model": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Display Model"+ }+ },+ "type": "object",+ "required": ["tier", "label"],+ "title": "ProviderTier",+ "description": "A tier and the model it resolves to, with no claim about access.\n\nDeliberately not ``ConnectionTier``: that type carries ``selectable`` and\n``lock_reason``, which are answers about a user. This one is a statement\nabout the catalog and is true whether or not anyone can pick it."+ },+ "ProviderTiers": {+ "properties": {+ "provider_family": { "type": "string", "title": "Provider Family" },+ "display_name": { "type": "string", "title": "Display Name" },+ "tiers": {+ "items": { "$ref": "#/components/schemas/ProviderTier" },+ "type": "array",+ "title": "Tiers"+ }+ },+ "type": "object",+ "required": ["provider_family", "display_name", "tiers"],+ "title": "ProviderTiers"+ },+ "ProviderTiersResponse": {+ "properties": {+ "providers": {+ "items": { "$ref": "#/components/schemas/ProviderTiers" },+ "type": "array",+ "title": "Providers"+ }+ },+ "type": "object",+ "required": ["providers"],+ "title": "ProviderTiersResponse"+ },"PushSubscribeRequest": {"properties": {"endpoint": {diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsxindex 2df94c2c50..01d2efff4b 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/AIConnectionsSection/AIConnectionsSection.tsx@@ -33,9 +33,13 @@ export function AIConnectionsSection() {if (isError) return null;// One connection is not a choice. The rows still say what powers a chat,- // they just stop presenting a decision that doesn't exist. A locked upsell- // row is visible context, not a route the user can select.- const hasChoice = connections.filter(isSelectable).length > 1;+ // they just stop presenting a decision that doesn't exist.+ //+ // Counted over what can actually be picked: a locked upsell row is listed+ // so the user can see the connection exists, but offering it as a choice+ // produces a click the server can only refuse.+ const selectableCount = connections.filter(isSelectable).length;+ const hasChoice = selectableCount > 1;return (<section aria-labelledby="ai-connections-heading" className="pb-8 pl-4">diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ChatGPTConnectExplainer.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ChatGPTConnectExplainer.tsxindex c47be136a3..5e81edc6fe 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ChatGPTConnectExplainer.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/ChatGPTConnectExplainer.tsx@@ -8,13 +8,17 @@ import {} from "@hugeicons/core-free-icons";import type { IconSvgElement } from "@hugeicons/react";+import { useGetV2ListProviderModelTiers } from "@/app/api/__generated__/endpoints/chat/chat";import { Icon } from "@/components/atoms/Icon/Icon";import { Text } from "@/components/atoms/Text/Text";+import { chatgptModelsSentence } from "./helpers";+interface Point {icon: IconSvgElement;title: string;body: string;+ withModels?: (models: string) => string;}/**@@ -22,9 +26,13 @@ interface Point {* that implies get answered on screen before the OAuth window opens rather* than after the user has committed.*- * Deliberately claims nothing about specific models or about pausing and- * resuming a run at a provider limit: the model catalog is server-owned, and- * same-chat recovery is not built yet. Both land with their own work.+ * Says nothing about pausing and resuming a run at a provider limit, because+ * same-chat recovery is not built yet.+ *+ * It does name the models, from the catalog rather than from a literal here.+ * The connections list cannot answer that at this point -- the user has not+ * made this connection, so it is absent from their offers -- which is what+ * the provider-tiers endpoint exists for.*/const POINTS: Point[] = [{@@ -41,6 +49,8 @@ const POINTS: Point[] = [icon: SparklesIcon,title: "What you get.",body: "The models your ChatGPT plan already includes, at no extra cost from AutoGPT.",+ /** Replaced with the named models when the catalog can supply them. */+ withModels: (models: string) => `${models}, at no extra cost from AutoGPT.`,},{icon: ShieldKeyIcon,@@ -50,6 +60,12 @@ const POINTS: Point[] = [];export function ChatGPTConnectExplainer() {+ const { data } = useGetV2ListProviderModelTiers({+ query: { refetchOnWindowFocus: false },+ });+ const models =+ data?.status === 200 ? chatgptModelsSentence(data.data.providers) : "";+return (<div className="divide-y divide-[#DADADC] rounded-2xl border border-[#DADADC] bg-[#FBFBFC]">{POINTS.map((point) => (@@ -62,7 +78,7 @@ export function ChatGPTConnectExplainer() {</span><Text variant="small" className="text-[#505057]"><span className="font-medium text-black">{point.title}</span>{" "}- {point.body}+ {models && point.withModels ? point.withModels(models) : point.body}</Text></div>))}diff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/MethodPanel.test.tsx b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/MethodPanel.test.tsxindex 55bab9594d..c3045a1b95 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/MethodPanel.test.tsx+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/__tests__/MethodPanel.test.tsx@@ -1,3 +1,6 @@+import { getGetV2ListProviderModelTiersMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { ProviderTiers } from "@/app/api/__generated__/models/providerTiers";+import { server } from "@/mocks/mock-server";import { render, screen } from "@/tests/integrations/test-utils";import { describe, expect, test, vi } from "vitest";@@ -17,7 +20,61 @@ const openaiProvider: ConnectableProvider = {authProviderByType: { [AuthType.oauth2]: "codex" },};+function mockProviderTiers(providers: ProviderTiers[]) {+ server.use(getGetV2ListProviderModelTiersMockHandler200({ providers }));+}+describe("MethodPanel", () => {+ test("names the models the plan gets you, from the catalog", async () => {+ // Mock 2 spells these out. They cannot come from the connections list --+ // the user has not connected yet, so ChatGPT is absent from it -- and+ // hardcoding them here would drift from the catalog that routes the turn.+ mockProviderTiers([+ {+ provider_family: "openai",+ display_name: "ChatGPT",+ tiers: [+ {+ tier: "standard",+ label: "Balanced",+ display_model: "GPT-5.6 Terra",+ },+ { tier: "advanced", label: "Advanced", display_model: "GPT-5.6 Sol" },+ ],+ } as ProviderTiers,+ ]);++ render(+ <MethodPanel+ method={AuthType.oauth2}+ provider={openaiProvider}+ onSuccess={vi.fn()}+ />,+ );++ expect(+ await screen.findByText(+ /GPT-5\.6 Terra \(Balanced\) and GPT-5\.6 Sol \(Advanced\)/,+ ),+ ).toBeDefined();+ });++ test("falls back to the general promise when the catalog names nothing", async () => {+ mockProviderTiers([]);++ render(+ <MethodPanel+ method={AuthType.oauth2}+ provider={openaiProvider}+ onSuccess={vi.fn()}+ />,+ );++ expect(+ await screen.findByText(/models your ChatGPT plan already includes/),+ ).toBeDefined();+ });+test("uses ChatGPT branding while sending OAuth to the Codex backend provider", () => {render(<MethodPaneldiff --git a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.tsindex 6898af46c9..9c92d788e3 100644--- a/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts+++ b/autogpt_platform/frontend/src/components/contextual/IntegrationsPanel/components/ConnectServiceDialog/components/DetailView/helpers.ts@@ -1,3 +1,5 @@+import type { ProviderTiers } from "@/app/api/__generated__/models/providerTiers";+type ValidationDetailItem = { msg?: unknown };function readDetail(value: unknown): string | null {@@ -52,3 +54,23 @@ export function getOAuthErrorMessage(error: unknown): string {return "Something went wrong. Please try again.";}++/**+ * "5.6 Terra (Balanced) and 5.6 Sol (Advanced)", from the catalog.+ *+ * Empty when the server named nothing, so the sentence falls back to the+ * general one rather than rendering half of a promise.+ */+export function chatgptModelsSentence(+ providers: ProviderTiers[] | undefined,+): string {+ const chatgpt = (providers ?? []).find(+ (provider) => provider.provider_family === "openai",+ );+ const named = (chatgpt?.tiers ?? [])+ .filter((tier) => tier.display_model)+ .map((tier) => `${tier.display_model} (${tier.label})`);+ if (named.length === 0) return "";+ if (named.length === 1) return named[0];+ return `${named.slice(0, -1).join(", ")} and ${named[named.length - 1]}`;+}diff --git a/autogpt_platform/frontend/src/playwright/auth-happy-path.spec.ts b/autogpt_platform/frontend/src/playwright/auth-happy-path.spec.tsindex 85b6e7fec5..29a8338680 100644--- a/autogpt_platform/frontend/src/playwright/auth-happy-path.spec.ts+++ b/autogpt_platform/frontend/src/playwright/auth-happy-path.spec.ts@@ -4,6 +4,7 @@ import { BuildPage } from "./pages/build.page";import { LoginPage } from "./pages/login.page";import {completeOnboardingWizard,+ dismissConnectStepIfPresent,skipOnboardingIfPresent,} from "./utils/onboarding";import { signupTestUser } from "./utils/signup";@@ -15,6 +16,8 @@ test("auth happy path: user can sign up with a fresh account", async ({await signupTestUser(page, undefined, undefined, false);await expect(page).toHaveURL(/\/onboarding/);+ // A self-host build opens on the connect step; Welcome is behind it.+ await dismissConnectStepIfPresent(page);await expect(page.getByText("Welcome to AutoGPT")).toBeVisible();});@@ -25,6 +28,8 @@ test("auth happy path: user can sign up, enter the app, and log out", async ({await signupTestUser(page, undefined, undefined, false);await expect(page).toHaveURL(/\/onboarding/);+ // A self-host build opens on the connect step; Welcome is behind it.+ await dismissConnectStepIfPresent(page);await expect(page.getByText("Welcome to AutoGPT")).toBeVisible();await skipOnboardingIfPresent(page, "/marketplace");diff --git a/autogpt_platform/frontend/src/playwright/utils/onboarding.ts b/autogpt_platform/frontend/src/playwright/utils/onboarding.tsindex d5402a8665..9c31b6ca76 100644--- a/autogpt_platform/frontend/src/playwright/utils/onboarding.ts+++ b/autogpt_platform/frontend/src/playwright/utils/onboarding.ts@@ -44,6 +44,48 @@ export async function skipOnboardingIfPresent(await page.waitForLoadState("domcontentloaded", { timeout: 10000 });}+/**+ * Dismiss the self-host connect step if this build shows it.+ *+ * It is the first onboarding screen when payment is off and the deployment is+ * local -- which is exactly how the e2e stack is built -- so on those runs it+ * sits in front of the Welcome step every other assertion starts from. It is+ * genuinely optional: skipping leaves the account on the platform connection,+ * which is what the rest of the wizard expects.+ *+ * Races the two headers rather than waiting on a timeout, so the helper works+ * in both configurations without flaking on a slow render.+ */+export async function dismissConnectStepIfPresent(page: Page) {+ const connectHeader = page.getByText("Power your agents in one sign-in");+ const welcomeHeader = page.getByText("Welcome to AutoGPT");++ const shown = await Promise.race([+ connectHeader+ .waitFor({ state: "visible", timeout: 10000 })+ .then(() => "connect" as const),+ welcomeHeader+ .waitFor({ state: "visible", timeout: 10000 })+ .then(() => "welcome" as const),+ ]);++ if (shown !== "connect") return;++ // Several different buttons advance past this step. Which one renders+ // depends on whether the account already has a linked plan ("Continue" when+ // it does), and on where in this stack the suite is running -- a later PR+ // renames the opt-out from "Add API keys instead" to "Skip for now". Match+ // by what the button does rather than what this commit happens to call it,+ // so the helper holds at every point in the stack instead of only at the+ // tip.+ const skipButton = page.getByRole("button", {+ name: /^(Skip for now|Add API keys instead|Continue)$/,+ });+ await skipButton.first().waitFor({ state: "visible", timeout: 15000 });+ await skipButton.first().click();+ await expect(welcomeHeader).toBeVisible({ timeout: 10000 });+}+/*** Walk through the onboarding wizard in the browser. The Subscription step* is gated behind ENABLE_PLATFORM_PAYMENT and only walked when present.@@ -63,6 +105,9 @@ export async function completeOnboardingWizard(const painPoints = options?.painPoints ?? ["Research", "Reports & data"];const plan = options?.plan ?? "pro";+ // Step 0: the self-host connect step, when this build shows it.+ await dismissConnectStepIfPresent(page);+// Step 1: Welcome — enter nameawait expect(page.getByText("Welcome to AutoGPT")).toBeVisible({timeout: 10000,