Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform): let a user pick the connection every new chat starts on (#14078)

Nicholas Tindle448a85c9b584
diff --git a/.github/workflows/repo-workflow-checker.yml b/.github/workflows/repo-workflow-checker.yml
index aa94622d31..74b4c41e55 100644
--- a/.github/workflows/repo-workflow-checker.yml
+++ b/.github/workflows/repo-workflow-checker.yml
@@ -22,6 +22,8 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install requests
+ - name: Test status checker
+ run: python -m unittest discover -s .github/workflows/scripts -p "test_*.py"
- name: Check PR Status
run: |
echo "Current directory before running Python script:"
diff --git a/.github/workflows/scripts/check_actions_status.py b/.github/workflows/scripts/check_actions_status.py
index 37f83da452..0e618a13ec 100644
--- a/.github/workflows/scripts/check_actions_status.py
+++ b/.github/workflows/scripts/check_actions_status.py
@@ -3,9 +3,10 @@ import os
import requests
import sys
import time
-from typing import Dict, List, Tuple
+from typing import Dict, List, Optional, Tuple
CHECK_INTERVAL = 30
+PASSING_CONCLUSIONS = {"success", "skipped", "neutral"}
def get_environment_variables() -> Tuple[str, str, str, str, str]:
@@ -32,20 +33,93 @@ def get_environment_variables() -> Tuple[str, str, str, str, str]:
sys.exit(1)
-def make_api_request(url: str, headers: Dict[str, str]) -> Dict:
- """Make an API request and return the JSON response."""
+def make_api_request(
+ url: str, headers: Dict[str, str]
+) -> Tuple[Dict, Optional[str]]:
+ """Make an API request and return its JSON and next-page URL."""
try:
print("Making API request to:", url)
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
- return response.json()
+ next_url = response.links.get("next", {}).get("url")
+ return response.json(), next_url
except requests.RequestException as e:
print(f"Error: API request failed. {e}")
sys.exit(1)
-def process_check_runs(check_runs: List[Dict]) -> Tuple[bool, bool]:
+def get_paginated_items(
+ url: str, headers: Dict[str, str], item_key: str
+) -> List[Dict]:
+ """Retrieve all pages from a GitHub list endpoint."""
+ items = []
+
+ while url:
+ data, url = make_api_request(url, headers)
+ items.extend(data[item_key])
+
+ return items
+
+
+def get_action_run_id(check_run: Dict) -> Optional[int]:
+ """Extract a GitHub Actions run ID from a check run details URL."""
+ details_url = str(check_run.get("details_url", ""))
+ marker = "/actions/runs/"
+ if marker not in details_url:
+ return None
+
+ run_id = details_url.split(marker, 1)[1].split("/", 1)[0]
+ try:
+ return int(run_id)
+ except ValueError:
+ return None
+
+
+def action_run_order(run: Dict) -> Tuple[int, int, int]:
+ """Return an ordering key that also handles rerun attempts."""
+ return (
+ int(run.get("run_number", 0)),
+ int(run.get("run_attempt", 0)),
+ int(run.get("id", 0)),
+ )
+
+
+def is_superseded_cancellation(
+ check_run: Dict, workflow_runs: List[Dict]
+) -> bool:
+ """Return whether a canceled check belongs to a superseded workflow run."""
+ action_run_id = get_action_run_id(check_run)
+ if action_run_id is None:
+ return False
+
+ runs_by_id = {int(run["id"]): run for run in workflow_runs}
+ source_run = runs_by_id.get(action_run_id)
+ if source_run is None:
+ return False
+
+ for candidate in workflow_runs:
+ if candidate.get("workflow_id") != source_run.get("workflow_id"):
+ continue
+ if candidate.get("head_sha") != source_run.get("head_sha"):
+ continue
+ if candidate.get("event") != source_run.get("event"):
+ continue
+ if action_run_order(candidate) <= action_run_order(source_run):
+ continue
+ if (
+ candidate.get("status") == "completed"
+ and candidate.get("conclusion") in PASSING_CONCLUSIONS
+ ):
+ return True
+
+ return False
+
+
+def process_check_runs(
+ check_runs: List[Dict], workflow_runs: Optional[List[Dict]] = None
+) -> Tuple[bool, bool]:
"""Process check runs and return their status."""
+ workflow_runs = workflow_runs or []
runs_in_progress = False
all_others_passed = True
@@ -55,7 +129,16 @@ def process_check_runs(check_runs: List[Dict]) -> Tuple[bool, bool]:
conclusion = run["conclusion"]
if status == "completed":
- if conclusion not in ["success", "skipped", "neutral"]:
+ if conclusion not in PASSING_CONCLUSIONS:
+ if conclusion == "cancelled" and is_superseded_cancellation(
+ run, workflow_runs
+ ):
+ print(
+ f"Ignoring canceled check run {run['name']} "
+ f"(ID: {run['id']}) because a newer run of the "
+ "same workflow passed."
+ )
+ continue
all_others_passed = False
print(
f"Check run {run['name']} (ID: {run['id']}) has conclusion: {conclusion}"
@@ -75,7 +158,12 @@ def process_check_runs(check_runs: List[Dict]) -> Tuple[bool, bool]:
def main():
api_url, repo, sha, github_token, current_run_id = get_environment_variables()
- endpoint = f"{api_url}/repos/{repo}/commits/{sha}/check-runs"
+ check_runs_endpoint = (
+ f"{api_url}/repos/{repo}/commits/{sha}/check-runs?per_page=100"
+ )
+ workflow_runs_endpoint = (
+ f"{api_url}/repos/{repo}/actions/runs?head_sha={sha}&per_page=100"
+ )
headers = {
"Accept": "application/vnd.github.v3+json",
}
@@ -85,17 +173,24 @@ def main():
print(f"Current run ID: {current_run_id}")
while True:
- data = make_api_request(endpoint, headers)
-
- check_runs = data["check_runs"]
-
- print("Processing check runs...")
-
- print(check_runs)
+ check_runs = get_paginated_items(
+ check_runs_endpoint, headers, "check_runs"
+ )
+ print(f"Processing {len(check_runs)} check runs...")
- runs_in_progress, all_others_passed = process_check_runs(check_runs)
+ runs_in_progress = any(
+ str(run["name"]) != "Check PR Status"
+ and run["status"] != "completed"
+ for run in check_runs
+ )
if not runs_in_progress:
+ workflow_runs = get_paginated_items(
+ workflow_runs_endpoint, headers, "workflow_runs"
+ )
+ _, all_others_passed = process_check_runs(
+ check_runs, workflow_runs
+ )
break
print(
diff --git a/.github/workflows/scripts/test_check_actions_status.py b/.github/workflows/scripts/test_check_actions_status.py
new file mode 100644
index 0000000000..c78181b65e
--- /dev/null
+++ b/.github/workflows/scripts/test_check_actions_status.py
@@ -0,0 +1,113 @@
+import unittest
+from unittest.mock import MagicMock, patch
+
+from check_actions_status import get_paginated_items, process_check_runs
+
+
+PASSING_RUN = {
+ "id": 102,
+ "workflow_id": 7,
+ "head_sha": "abc123",
+ "event": "pull_request",
+ "run_number": 12,
+ "run_attempt": 1,
+ "status": "completed",
+ "conclusion": "success",
+}
+
+CANCELED_RUN = {
+ "id": 101,
+ "workflow_id": 7,
+ "head_sha": "abc123",
+ "event": "pull_request",
+ "run_number": 11,
+ "run_attempt": 1,
+ "status": "completed",
+ "conclusion": "cancelled",
+}
+
+CANCELED_CHECK = {
+ "id": 1001,
+ "name": "Build",
+ "status": "completed",
+ "conclusion": "cancelled",
+ "details_url": "https://github.com/example/repo/actions/runs/101/job/1001",
+}
+
+
+class ProcessCheckRunsTests(unittest.TestCase):
+ def test_accepts_skipped_check(self):
+ skipped_check = {
+ **CANCELED_CHECK,
+ "conclusion": "skipped",
+ }
+
+ self.assertEqual(process_check_runs([skipped_check]), (False, True))
+
+ def test_accepts_cancellation_superseded_by_passing_workflow_run(self):
+ result = process_check_runs(
+ [CANCELED_CHECK], [CANCELED_RUN, PASSING_RUN]
+ )
+
+ self.assertEqual(result, (False, True))
+
+ def test_rejects_cancellation_without_replacement(self):
+ result = process_check_runs([CANCELED_CHECK], [CANCELED_RUN])
+
+ self.assertEqual(result, (False, False))
+
+ def test_rejects_cancellation_replaced_by_failed_workflow_run(self):
+ failed_run = {**PASSING_RUN, "conclusion": "failure"}
+
+ result = process_check_runs(
+ [CANCELED_CHECK], [CANCELED_RUN, failed_run]
+ )
+
+ self.assertEqual(result, (False, False))
+
+ def test_rejects_cancellation_replaced_by_different_workflow(self):
+ unrelated_run = {**PASSING_RUN, "workflow_id": 8}
+
+ result = process_check_runs(
+ [CANCELED_CHECK], [CANCELED_RUN, unrelated_run]
+ )
+
+ self.assertEqual(result, (False, False))
+
+ def test_rejects_external_cancellation(self):
+ external_check = {
+ **CANCELED_CHECK,
+ "details_url": "https://checks.example.com/result/1001",
+ }
+
+ result = process_check_runs(
+ [external_check], [CANCELED_RUN, PASSING_RUN]
+ )
+
+ self.assertEqual(result, (False, False))
+
+ def test_rejects_real_failure(self):
+ failed_check = {**CANCELED_CHECK, "conclusion": "failure"}
+
+ self.assertEqual(process_check_runs([failed_check]), (False, False))
+
+
+class PaginationTests(unittest.TestCase):
+ @patch("check_actions_status.requests.get")
+ def test_gets_every_page(self, get: MagicMock):
+ first_response = MagicMock()
+ first_response.json.return_value = {"check_runs": [{"id": 1}]}
+ first_response.links = {"next": {"url": "page-2"}}
+ second_response = MagicMock()
+ second_response.json.return_value = {"check_runs": [{"id": 2}]}
+ second_response.links = {}
+ get.side_effect = [first_response, second_response]
+
+ result = get_paginated_items("page-1", {}, "check_runs")
+
+ self.assertEqual(result, [{"id": 1}, {"id": 2}])
+ self.assertEqual(get.call_count, 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 99325197de..9affe240c6 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -126,28 +126,28 @@ from backend.copilot.tools.models import (
TodoWriteResponse,
UnderstandingUpdatedResponse,
)
+from backend.copilot.transports import (
+ ChatTransportsResponse,
+ DefaultChatRoute,
+ InvalidDefaultChatRoute,
+ get_chat_transports,
+ is_deployment_chat_available,
+ save_default_chat_route,
+)
from backend.data.credit import UsageTransactionMetadata, get_user_credit_model
-from backend.data.model import Credentials
from backend.data.redis_client import get_redis_async
from backend.data.understanding import get_business_understanding
from backend.data.workspace import build_files_block, resolve_workspace_files
-from backend.integrations.codex.access import (
- enforce_codex_access_http,
- has_codex_access_for_discovery,
-)
-from backend.integrations.codex.auth_bundle import CodexAuthBundleError
-from backend.integrations.codex.credential_codec import bundle_from_credentials
-from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.integrations.codex.access import enforce_codex_access_http
from backend.util.background import spawn_background_task
from backend.util.exceptions import InsufficientBalanceError, NotFoundError
-from backend.util.settings import BehaveAs, Settings
+from backend.util.settings import Settings
settings = Settings()
logger = logging.getLogger(__name__)
config = ChatConfig()
-credentials_manager = IntegrationCredentialsManager()
async def _validate_and_get_session(
@@ -371,18 +371,6 @@ class CreateSessionResponse(BaseModel):
expert_id: str | None = None
-class ChatTransportResponse(BaseModel):
- auth_provider: CopilotLlmAuthProvider
- credential_id: str | None
- label: str
- available: bool
- default: bool
-
-
-class ChatTransportsResponse(BaseModel):
- transports: list[ChatTransportResponse]
-
-
class ActiveStreamInfo(BaseModel):
"""Information about an active stream for reconnection."""
@@ -551,71 +539,68 @@ async def list_sessions(
)
-def _is_valid_codex_credentials(credentials: Credentials | None) -> bool:
- if credentials is None or credentials.type != "oauth2":
- return False
- try:
- bundle_from_credentials(credentials)
- except CodexAuthBundleError:
- return False
- return True
+ "/transports",
+ dependencies=[Security(auth.requires_user)],
+)
+async def list_chat_transports(
+ user_id: Annotated[str, Security(auth.get_user_id)],
+) -> ChatTransportsResponse:
+ """Every transport the user can chat over.
+ Exactly one carries ``default: true`` — the connection this user chose in
+ Settings, or the server's own pick when they haven't chosen one.
+ """
+ return ChatTransportsResponse(transports=await get_chat_transports(user_id))
-def _is_deployment_chat_available() -> bool:
- if settings.config.behave_as == BehaveAs.CLOUD:
- return True
- api_key, _ = config.main_client_credentials
- return bool(config.test_mode or config.use_claude_code_subscription or api_key)
+class SetDefaultTransportRequest(BaseModel):
+ """The connection new chats should start on.
-async def _get_chat_transports(user_id: str) -> list[ChatTransportResponse]:
- deployment_available = _is_deployment_chat_available()
- transports = [
- ChatTransportResponse(
- auth_provider="platform",
- credential_id=None,
- label=(
- "AutoGPT Platform"
- if settings.config.behave_as == BehaveAs.CLOUD
- else "Self-hosted chat"
- ),
- available=deployment_available,
- default=deployment_available,
- )
- ]
+ ``auth_provider: null`` clears the choice and hands the decision back to
+ the server. Sending ``codex`` requires naming the credential, so the
+ default keeps pointing at one account rather than "whichever ChatGPT".
+ """
- codex_credentials = (
- await credentials_manager.store.get_creds_by_provider(user_id, "codex")
- if await has_codex_access_for_discovery(user_id)
- else []
- )
- valid_codex_credentials = [
- credentials
- for credentials in codex_credentials
- if _is_valid_codex_credentials(credentials)
- ]
- codex_is_default = not deployment_available and len(valid_codex_credentials) == 1
- transports.extend(
- ChatTransportResponse(
- auth_provider="codex",
- credential_id=credentials.id,
- label="ChatGPT",
- available=True,
- default=codex_is_default,
- )
- for credentials in valid_codex_credentials
- )
- return transports
+ model_config = ConfigDict(extra="forbid")
+ auth_provider: CopilotLlmAuthProvider | None = None
+ credential_id: str | None = Field(default=None, max_length=128)
- "/transports",
+
+ "/transports/default",
dependencies=[Security(auth.requires_user)],
+ responses={
+ 404: {"description": "The credential or user profile was not found"},
+ },
)
-async def list_chat_transports(
+async def set_default_chat_transport(
user_id: Annotated[str, Security(auth.get_user_id)],
+ request: SetDefaultTransportRequest,
) -> ChatTransportsResponse:
- return ChatTransportsResponse(transports=await _get_chat_transports(user_id))
+ """Save the connection every new chat starts on.
+
+ Applies to chats nobody routed explicitly — a fresh session in the web
+ app, and every conversation that arrives without a request to read a route
+ from: bot links, schedules, briefings, dream passes. It does not touch a
+ conversation that already exists; sessions keep the route they were
+ created with.
+ """
+ try:
+ transports = await save_default_chat_route(
+ user_id,
+ DefaultChatRoute(
+ auth_provider=request.auth_provider,
+ credential_id=request.credential_id,
+ ),
+ )
+ except InvalidDefaultChatRoute as e:
+ raise HTTPException(
+ status_code=404 if e.detail == "codex_credential_not_found" else 422,
+ detail=e.detail,
+ ) from e
+ return ChatTransportsResponse(transports=transports)
async def _resolve_new_session_llm_route(
@@ -634,14 +619,14 @@ async def _resolve_new_session_llm_route(
status_code=422,
detail="codex_builder_session_unsupported",
)
- if not _is_deployment_chat_available():
+ if not is_deployment_chat_available():
raise HTTPException(
status_code=503,
detail="chat_transport_not_configured",
)
return "platform", None
- transports = await _get_chat_transports(user_id)
+ transports = await get_chat_transports(user_id)
if request is not None:
route_was_explicit = bool(
{"llm_auth_provider", "llm_credential_id"} & request.model_fields_set
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 536f324ef8..27889b6ed6 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -12,6 +12,7 @@ from pydantic import SecretStr
from backend.api.features.chat import routes as chat_routes
from backend.api.features.chat.routes import _strip_injected_context
+from backend.copilot import transports as chat_transports
from backend.copilot.config import CopilotLlmAuthProvider
from backend.copilot.rate_limit import SubscriptionTier
from backend.copilot.tools.models import ExpertSoulUpdatedResponse
@@ -64,12 +65,12 @@ def setup_app_auth(mock_jwt_user, mocker: pytest_mock.MockerFixture):
app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
app.dependency_overrides[get_request_context] = mock_jwt_user["get_request_context"]
mocker.patch.object(
- chat_routes.credentials_manager.store,
+ chat_transports.credentials_manager.store,
"get_creds_by_provider",
new=AsyncMock(return_value=[]),
)
mocker.patch.object(
- chat_routes,
+ chat_transports,
"has_codex_access_for_discovery",
new=AsyncMock(return_value=True),
)
@@ -78,7 +79,18 @@ def setup_app_auth(mock_jwt_user, mocker: pytest_mock.MockerFixture):
"enforce_codex_access_http",
new=AsyncMock(),
)
+ mocker.patch.object(
+ chat_transports,
+ "get_user_default_chat_route",
+ new=AsyncMock(return_value=(None, None)),
+ )
+ mocker.patch.object(
+ chat_transports,
+ "set_user_default_chat_route",
+ new=AsyncMock(),
+ )
mocker.patch.object(chat_routes.settings.config, "behave_as", BehaveAs.CLOUD)
+ mocker.patch.object(chat_transports.settings.config, "behave_as", BehaveAs.CLOUD)
yield
app.dependency_overrides.clear()
@@ -1127,7 +1139,7 @@ def _set_self_hosted_chat_config(
*,
configured: bool,
) -> None:
- mocker.patch.object(chat_routes.settings.config, "behave_as", BehaveAs.LOCAL)
+ mocker.patch.object(chat_transports.settings.config, "behave_as", BehaveAs.LOCAL)
self_hosted_config = MagicMock()
self_hosted_config.test_mode = False
self_hosted_config.use_claude_code_subscription = False
@@ -1136,7 +1148,7 @@ def _set_self_hosted_chat_config(
if configured
else (None, "https://api.anthropic.com/v1/")
)
- mocker.patch.object(chat_routes, "config", self_hosted_config)
+ mocker.patch.object(chat_transports, "config", self_hosted_config)
def test_list_chat_transports_hosted_platform_only(
@@ -1161,7 +1173,7 @@ def test_list_chat_transports_hosted_platform_only(
def test_list_chat_transports_hosted_defaults_to_platform_with_codex(
test_user_id: str,
) -> None:
- chat_routes.credentials_manager.store.get_creds_by_provider.return_value = [
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
_codex_credentials()
]
@@ -1193,11 +1205,11 @@ def test_list_chat_transports_hosted_omits_codex_without_required_plan(
test_user_id: str,
) -> None:
access = mocker.patch.object(
- chat_routes,
+ chat_transports,
"has_codex_access_for_discovery",
new=AsyncMock(return_value=False),
)
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
lookup.return_value = [_codex_credentials()]
response = client.get("/transports")
@@ -1221,7 +1233,7 @@ def test_list_chat_transports_hosted_omits_codex_without_required_plan(
def test_list_chat_transports_omits_invalid_codex_credentials(
test_user_id: str,
) -> None:
- chat_routes.credentials_manager.store.get_creds_by_provider.return_value = [
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
_codex_credentials(provider_state=None)
]
@@ -1262,7 +1274,7 @@ def test_list_chat_transports_self_hosted_codex_is_default_without_deployment(
test_user_id: str,
) -> None:
_set_self_hosted_chat_config(mocker, configured=False)
- chat_routes.credentials_manager.store.get_creds_by_provider.return_value = [
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
_codex_credentials()
]
@@ -1292,7 +1304,7 @@ def test_list_chat_transports_self_hosted_deployment_stays_default_with_codex(
test_user_id: str,
) -> None:
_set_self_hosted_chat_config(mocker, configured=True)
- chat_routes.credentials_manager.store.get_creds_by_provider.return_value = [
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
_codex_credentials()
]
@@ -1316,6 +1328,174 @@ def test_list_chat_transports_self_hosted_deployment_stays_default_with_codex(
}
+# ─── the default connection for new chats ──────────────────────────────
+
+
+def test_list_chat_transports_marks_the_saved_default(
+ test_user_id: str,
+) -> None:
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
+ _codex_credentials()
+ ]
+ chat_transports.get_user_default_chat_route.return_value = ("codex", "cred-codex")
+
+ response = client.get("/transports")
+
+ assert response.status_code == 200
+ platform, codex = response.json()["transports"]
+ assert platform["default"] is False
+ assert codex["default"] is True
+
+
+def test_set_default_transport_saves_the_choice(
+ test_user_id: str,
+) -> None:
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
+ _codex_credentials()
+ ]
+
+ response = client.put(
+ "/transports/default",
+ json={"auth_provider": "codex", "credential_id": "cred-codex"},
+ )
+
+ assert response.status_code == 200
+ chat_transports.set_user_default_chat_route.assert_awaited_once_with(
+ test_user_id, "codex", "cred-codex"
+ )
+ platform, codex = response.json()["transports"]
+ assert platform["default"] is False
+ assert codex["default"] is True
+
+
+def test_set_default_transport_clears_the_choice(
+ test_user_id: str,
+) -> None:
+ chat_transports.get_user_default_chat_route.return_value = ("codex", "cred-codex")
+
+ response = client.put("/transports/default", json={})
+
+ assert response.status_code == 200
+ chat_transports.set_user_default_chat_route.assert_awaited_once_with(
+ test_user_id, None, None
+ )
+
+
+def test_set_default_transport_requires_an_account_for_chatgpt() -> None:
+ response = client.put("/transports/default", json={"auth_provider": "codex"})
+
+ assert response.status_code == 422
+ assert response.json()["detail"] == "codex_credential_required"
+ chat_transports.set_user_default_chat_route.assert_not_awaited()
+
+
+def test_set_default_transport_rejects_an_unknown_account() -> None:
+ response = client.put(
+ "/transports/default",
+ json={"auth_provider": "codex", "credential_id": "cred-nope"},
+ )
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "codex_credential_not_found"
+ chat_transports.set_user_default_chat_route.assert_not_awaited()
+
+
+def test_set_default_transport_reports_a_missing_user_profile() -> None:
+ chat_transports.set_user_default_chat_route.side_effect = NotFoundError(
+ "User user-1 not found"
+ )
+
+ response = client.put(
+ "/transports/default",
+ json={"auth_provider": "platform"},
+ )
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "User user-1 not found"
+
+
+def test_set_default_transport_documents_not_found_responses() -> None:
+ operation = client.get("/openapi.json").json()["paths"]["/transports/default"][
+ "put"
+ ]
+
+ assert operation["responses"]["404"]["description"] == (
+ "The credential or user profile was not found"
+ )
+
+
+def test_set_default_transport_rejects_unknown_fields() -> None:
+ response = client.put(
+ "/transports/default",
+ json={"auth_provider": "platform", "make_it_sticky": True},
+ )
+
+ assert response.status_code == 422
+
+
+def test_create_session_uses_the_saved_default(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ """A new chat with no route in the request starts on the saved default."""
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
+ _codex_credentials()
+ ]
+ chat_transports.get_user_default_chat_route.return_value = ("codex", "cred-codex")
+ mock_create = _mock_create_chat_session(mocker)
+ mock_paywall = mocker.patch(
+ "backend.api.features.chat.routes.enforce_payment_paywall",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post("/sessions", json={})
+
+ assert response.status_code == 200
+ assert mock_create.call_args.kwargs["llm_auth_provider"] == "codex"
+ assert mock_create.call_args.kwargs["llm_credential_id"] == "cred-codex"
+ # The platform paywall is for platform-backed turns; this one isn't.
+ mock_paywall.assert_not_awaited()
+
+
+def test_an_explicit_route_still_beats_the_saved_default(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
+ _codex_credentials()
+ ]
+ chat_transports.get_user_default_chat_route.return_value = ("codex", "cred-codex")
+ mock_create = _mock_create_chat_session(mocker)
+ mocker.patch(
+ "backend.api.features.chat.routes.enforce_payment_paywall",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post("/sessions", json={"llm_auth_provider": "platform"})
+
+ assert response.status_code == 200
+ assert mock_create.call_args.kwargs["llm_auth_provider"] == "platform"
+ assert mock_create.call_args.kwargs["llm_credential_id"] is None
+
+
+def test_a_saved_default_that_vanished_falls_back_instead_of_failing(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ """The saved ChatGPT account was disconnected since it was chosen."""
+ chat_transports.get_user_default_chat_route.return_value = ("codex", "cred-gone")
+ mock_create = _mock_create_chat_session(mocker)
+ mocker.patch(
+ "backend.api.features.chat.routes.enforce_payment_paywall",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post("/sessions", json={})
+
+ assert response.status_code == 200
+ assert mock_create.call_args.kwargs["llm_auth_provider"] == "platform"
+
+
def test_create_session_dry_run_true(
mocker: pytest_mock.MockerFixture,
test_user_id: str,
@@ -1379,7 +1559,7 @@ def test_create_session_requires_credential_for_codex_route() -> None:
def test_create_session_codex_route_rejects_unowned_credential(
test_user_id: str,
) -> None:
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
response = client.post(
"/sessions",
@@ -1405,7 +1585,7 @@ def test_create_session_codex_route_rejects_user_without_required_plan(
)
),
)
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
mock_create = mocker.patch.object(
chat_routes,
"create_chat_session",
@@ -1439,7 +1619,7 @@ def test_create_session_codex_route_persists_owned_credential(
),
)
credential = _codex_credentials("cred-1")
- chat_routes.credentials_manager.store.get_creds_by_provider.return_value = [
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
credential
]
@@ -1461,7 +1641,7 @@ def test_create_session_hosted_defaults_to_platform_with_codex_connected(
test_user_id: str,
) -> None:
credential = _codex_credentials()
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
lookup.return_value = [credential]
mock_create = _mock_create_chat_session(mocker)
mock_paywall = mocker.patch(
@@ -1486,7 +1666,7 @@ def test_create_session_self_hosted_defaults_to_codex_when_unconfigured(
) -> None:
_set_self_hosted_chat_config(mocker, configured=False)
credential = _codex_credentials()
- chat_routes.credentials_manager.store.get_creds_by_provider.return_value = [
+ chat_transports.credentials_manager.store.get_creds_by_provider.return_value = [
credential
]
mock_create = _mock_create_chat_session(mocker)
@@ -1548,7 +1728,7 @@ def test_create_session_self_hosted_rejects_invalid_codex_as_unconfigured(
provider_state_version: int,
) -> None:
_set_self_hosted_chat_config(mocker, configured=False)
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
lookup.return_value = [
_codex_credentials(
provider_state=provider_state,
@@ -1573,7 +1753,7 @@ def test_create_session_self_hosted_requires_selection_for_multiple_codex_routes
mocker: pytest_mock.MockerFixture,
) -> None:
_set_self_hosted_chat_config(mocker, configured=False)
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
lookup.return_value = [
_codex_credentials("cred-one"),
_codex_credentials("cred-two"),
@@ -1595,7 +1775,7 @@ def test_create_session_self_hosted_requires_selection_for_multiple_codex_routes
def test_create_session_respects_explicit_platform_route(
mocker: pytest_mock.MockerFixture,
) -> None:
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
mock_create = _mock_create_chat_session(mocker)
mocker.patch(
"backend.api.features.chat.routes.enforce_payment_paywall",
@@ -3506,7 +3686,7 @@ def test_create_session_with_builder_graph_id_uses_get_or_create(
new_callable=AsyncMock,
side_effect=_fake_get_or_create,
)
- lookup = chat_routes.credentials_manager.store.get_creds_by_provider
+ lookup = chat_transports.credentials_manager.store.get_creds_by_provider
lookup.return_value = [_codex_credentials()]
response = client.post("/sessions", json={"builder_graph_id": "graph-1"})
diff --git a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
index fd3f7d0c06..81d64a5161 100644
--- a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
+++ b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
@@ -1569,6 +1569,8 @@ class TestRegressionUserSettings:
mock_user.notifyOnStoreVerdict = True
mock_user.maxEmailsPerDay = 3
mock_user.subscriptionTier = "NO_TIER"
+ mock_user.defaultChatAuthProvider = None
+ mock_user.defaultChatCredentialId = None
self.mock_user_actions.update = AsyncMock(return_value=mock_user)
from backend.data.user import update_user_timezone
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index 9ab34378c6..f984d16714 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -33,6 +33,7 @@ from .model import (
cache_chat_session,
)
from .model import get_chat_session as get_chat_session_cached
+from .transports import resolve_default_chat_route
logger = logging.getLogger(__name__)
@@ -1334,6 +1335,28 @@ async def update_chat_session_status(
return updated > 0
+async def _default_route_metadata(
+ user_id: str, *, origin: str | None = None
+) -> ChatSessionMetadata:
+ """Session metadata carrying the user's default connection.
+
+ These sessions exist to hold an outbound message, but the user replies in
+ them — so they start on the same connection a chat the user opened
+ themselves would, instead of silently falling back to the platform route.
+
+ ``origin`` is passed through for the sessions a user is meant to type into,
+ which have to declare themselves interactive.
+ """
+ llm_auth_provider, llm_credential_id = await resolve_default_chat_route(user_id)
+ fields: dict[str, object] = {
+ "llm_auth_provider": llm_auth_provider,
+ "llm_credential_id": llm_credential_id,
+ }
+ if origin is not None:
+ fields["origin"] = origin
+ return ChatSessionMetadata(**fields)
+
+
async def append_expert_run_message(
user_id: str,
expert_id: str,
@@ -1362,7 +1385,10 @@ async def append_expert_run_message(
session_id = session.id
else:
created = await create_chat_session(
- session_id=str(uuid.uuid4()), user_id=user_id, expert_id=expert_id
+ session_id=str(uuid.uuid4()),
+ user_id=user_id,
+ expert_id=expert_id,
+ metadata=await _default_route_metadata(user_id),
)
session_id = created.session_id
@@ -1437,7 +1463,7 @@ async def append_plain_session_message(
created = await create_chat_session(
session_id=str(uuid.uuid4()),
user_id=user_id,
- metadata=ChatSessionMetadata(origin="interactive"),
+ metadata=await _default_route_metadata(user_id, origin="interactive"),
)
session_id = created.session_id
diff --git a/autogpt_platform/backend/backend/copilot/dream/apply.py b/autogpt_platform/backend/backend/copilot/dream/apply.py
index e3d1bba938..1e57f1b36f 100644
--- a/autogpt_platform/backend/backend/copilot/dream/apply.py
+++ b/autogpt_platform/backend/backend/copilot/dream/apply.py
@@ -42,6 +42,7 @@ from backend.copilot.tools.graphiti_forget import (
invalidate_entity_direct_neighbors,
mark_edges_superseded,
)
+from backend.copilot.transports import resolve_default_chat_route
from backend.util.feature_flag import Flag, is_feature_enabled
from .batch_submit import read_input_bundle
@@ -439,7 +440,16 @@ async def _create_dream_session(
org_id, team_id = None, None
session_id = str(uuidlib.uuid4())
- metadata = ChatSessionMetadata(kind="dream", dream_pass_id=pass_id)
+ # A dream is unattended, but the user reads and replies to it, and on a
+ # self-hosted install the platform route may not exist at all — so it
+ # starts on the same connection the user chose for everything else.
+ llm_auth_provider, llm_credential_id = await resolve_default_chat_route(user_id)
+ metadata = ChatSessionMetadata(
+ kind="dream",
+ dream_pass_id=pass_id,
+ llm_auth_provider=llm_auth_provider,
+ llm_credential_id=llm_credential_id,
+ )
await chat_db().create_chat_session(
session_id=session_id,
user_id=user_id,
diff --git a/autogpt_platform/backend/backend/copilot/integration_creds_test.py b/autogpt_platform/backend/backend/copilot/integration_creds_test.py
index 58da171548..8f442b4e20 100644
--- a/autogpt_platform/backend/backend/copilot/integration_creds_test.py
+++ b/autogpt_platform/backend/backend/copilot/integration_creds_test.py
@@ -297,6 +297,7 @@ class TestRefreshUnlockedPath:
mock_handler = MagicMock()
mock_handler.needs_refresh = MagicMock(return_value=False)
+ mock_handler.ROTATES_REFRESH_TOKEN = False
with patch(
"backend.integrations.creds_manager._get_provider_oauth_handler",
diff --git a/autogpt_platform/backend/backend/copilot/transports.py b/autogpt_platform/backend/backend/copilot/transports.py
new file mode 100644
index 0000000000..f7c1c0357a
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/transports.py
@@ -0,0 +1,249 @@
+"""Chat transport discovery, and the connection a user made their default.
+
+Transport enumeration used to live in ``api.features.chat.routes``, which
+worked while the only caller was an HTTP request. It no longer is: bot links,
+schedules, briefings and dream passes all open chats with no request to read a
+route from, and none of them can import the API layer. So the enumeration lives
+here and the routes module presents it.
+
+The default is stored as a provider *and* a credential id. Provider alone stops
+being an answer the moment a user can link more than one ChatGPT account, and
+this contract is the one the UI will keep.
+"""
+
+import logging
+from typing import Optional, get_args
+
+from pydantic import BaseModel
+
+from backend.copilot.config import ChatConfig, CopilotLlmAuthProvider
+from backend.data.model import Credentials
+from backend.data.user import get_user_default_chat_route, set_user_default_chat_route
+from backend.integrations.codex.access import has_codex_access_for_discovery
+from backend.integrations.codex.auth_bundle import CodexAuthBundleError
+from backend.integrations.codex.credential_codec import bundle_from_credentials
+from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.util.settings import BehaveAs, Settings
+
+logger = logging.getLogger(__name__)
+
+settings = Settings()
+config = ChatConfig()
+credentials_manager = IntegrationCredentialsManager()
+
+KNOWN_AUTH_PROVIDERS: frozenset[str] = frozenset(get_args(CopilotLlmAuthProvider))
+
+
+class ChatTransportResponse(BaseModel):
+ auth_provider: CopilotLlmAuthProvider
+ credential_id: str | None
+ label: str
+ available: bool
+ default: bool
+
+
+class ChatTransportsResponse(BaseModel):
+ transports: list[ChatTransportResponse]
+
+
+class DefaultChatRoute(BaseModel):
+ """A saved default. ``auth_provider=None`` means automatic."""
+
+ auth_provider: CopilotLlmAuthProvider | None = None
+ credential_id: str | None = None
+
+
+class InvalidDefaultChatRoute(ValueError):
+ """A default that can't be saved.
+
+ ``detail`` reuses the codes ``POST /sessions`` already returns for the same
+ mistakes, so a client only has to understand one vocabulary.
+ """
+
+ def __init__(self, detail: str) -> None:
+ super().__init__(detail)
+ self.detail = detail
+
+
+def is_deployment_chat_available() -> bool:
+ if settings.config.behave_as == BehaveAs.CLOUD:
+ return True
+ api_key, _ = config.main_client_credentials
+ return bool(config.test_mode or config.use_claude_code_subscription or api_key)
+
+
+async def get_chat_transports(user_id: str) -> list[ChatTransportResponse]:
+ """Every transport this user can chat over, one of them marked default."""
+ transports = [
+ ChatTransportResponse(
+ auth_provider="platform",
+ credential_id=None,
+ label=(
+ "AutoGPT Platform"
+ if settings.config.behave_as == BehaveAs.CLOUD
+ else "Self-hosted chat"
+ ),
+ available=is_deployment_chat_available(),
+ default=False,
+ )
+ ]
+ transports.extend(
+ ChatTransportResponse(
+ auth_provider="codex",
+ credential_id=credentials.id,
+ label="ChatGPT",
+ available=True,
+ default=False,
+ )
+ for credentials in await _valid_codex_credentials(user_id)
+ )
+
+ saved_provider, saved_credential_id = await get_user_default_chat_route(user_id)
+ _mark_default(transports, saved_provider, saved_credential_id)
+ return transports
+
+
+async def resolve_default_chat_route(
+ user_id: str,
+) -> tuple[CopilotLlmAuthProvider, str | None]:
+ """The route for a chat nobody routed — bot links, schedules, briefings.
+
+ Never raises and never asks. Where the HTTP path can answer "pick one"
+ with a 409, these callers have no user in front of them, so an
+ unresolvable default falls back to ``platform`` — which is exactly what
+ every one of them passed before this setting existed.
+ """
+ try:
+ transports = await get_chat_transports(user_id)
+ except Exception:
+ logger.warning(
+ "Could not resolve the default chat route for user ...%s; using platform",
+ user_id[-8:],
+ exc_info=True,
+ )
+ return "platform", None
+
+ default = next((transport for transport in transports if transport.default), None)
+ if default is None:
+ return "platform", None
+ return default.auth_provider, default.credential_id
+
+
+async def save_default_chat_route(
+ user_id: str, route: DefaultChatRoute
+) -> list[ChatTransportResponse]:
+ """Validate and persist a default, returning the refreshed transport list."""
+ if route.auth_provider is None:
+ if route.credential_id is not None:
+ raise InvalidDefaultChatRoute("codex_credential_not_allowed")
+ await set_user_default_chat_route(user_id, None, None)
+ return await get_chat_transports(user_id)
+
+ if route.auth_provider == "platform" and route.credential_id is not None:
+ raise InvalidDefaultChatRoute("codex_credential_not_allowed")
+ if route.auth_provider == "codex" and route.credential_id is None:
+ raise InvalidDefaultChatRoute("codex_credential_required")
+
+ transports = await get_chat_transports(user_id)
+ if _find_transport(transports, route.auth_provider, route.credential_id) is None:
+ # A codex credential the user doesn't own, or can't use on their plan,
+ # is indistinguishable from one that doesn't exist — deliberately, so
+ # this never confirms another user's credential id.
+ raise InvalidDefaultChatRoute(
+ "codex_credential_not_found"
+ if route.auth_provider == "codex"
+ else "chat_transport_not_configured"
+ )
+
+ await set_user_default_chat_route(user_id, route.auth_provider, route.credential_id)
+ _mark_default(transports, route.auth_provider, route.credential_id)
+ return transports
+
+
+def _mark_default(
+ transports: list[ChatTransportResponse],
+ saved_provider: Optional[str],
+ saved_credential_id: Optional[str],
+) -> None:
+ chosen = _saved_default(
+ transports, saved_provider, saved_credential_id
+ ) or _automatic_default(transports)
+ for transport in transports:
+ transport.default = transport is chosen
+
+
+def _saved_default(
+ transports: list[ChatTransportResponse],
+ saved_provider: Optional[str],
+ saved_credential_id: Optional[str],
+) -> ChatTransportResponse | None:
+ """The saved choice, or None when it can no longer be honoured.
+
+ Falling through to the automatic default is the heal: a disconnected
+ account or a lapsed plan quietly stops being the default rather than
+ failing a Discord message with a reason nobody can see. The row is left
+ in place, so reconnecting restores the choice.
+ """
+ if saved_provider is None:
+ return None
+ if saved_provider not in KNOWN_AUTH_PROVIDERS:
+ # A value written by a newer server. Treat it as automatic rather than
+ # letting it break an older one mid-rollout.
+ logger.warning("Ignoring unknown saved chat transport %r", saved_provider)
+ return None
+ return _find_transport(transports, saved_provider, saved_credential_id)
+
+
+def _automatic_default(
+ transports: list[ChatTransportResponse],
+) -> ChatTransportResponse | None:
+ """What the server picked before anyone could save a preference."""
+ available = [transport for transport in transports if transport.available]
+ platform = next(
+ (transport for transport in available if transport.auth_provider == "platform"),
+ None,
+ )
+ if platform is not None:
+ return platform
+ codex = [transport for transport in available if transport.auth_provider == "codex"]
+ return codex[0] if len(codex) == 1 else None
+
+
+def _find_transport(
+ transports: list[ChatTransportResponse],
+ auth_provider: str,
+ credential_id: str | None,
+) -> ChatTransportResponse | None:
+ return next(
+ (
+ transport
+ for transport in transports
+ if transport.available
+ and transport.auth_provider == auth_provider
+ and transport.credential_id == credential_id
+ ),
+ None,
+ )
+
+
+async def _valid_codex_credentials(user_id: str) -> list[Credentials]:
+ if not await has_codex_access_for_discovery(user_id):
+ return []
+ credentials = await credentials_manager.store.get_creds_by_provider(
+ user_id, "codex"
+ )
+ return [
+ credential
+ for credential in credentials
+ if _is_valid_codex_credentials(credential)
+ ]
+
+
+def _is_valid_codex_credentials(credentials: Credentials | None) -> bool:
+ if credentials is None or credentials.type != "oauth2":
+ return False
+ try:
+ bundle_from_credentials(credentials)
+ except CodexAuthBundleError:
+ return False
+ return True
diff --git a/autogpt_platform/backend/backend/copilot/transports_test.py b/autogpt_platform/backend/backend/copilot/transports_test.py
new file mode 100644
index 0000000000..30c359a51e
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/transports_test.py
@@ -0,0 +1,336 @@
+"""Chat transport discovery and the connection a user made their default."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+import pytest_mock
+from pydantic import SecretStr
+
+from backend.copilot import transports
+from backend.copilot.transports import (
+ DefaultChatRoute,
+ InvalidDefaultChatRoute,
+ get_chat_transports,
+ resolve_default_chat_route,
+ save_default_chat_route,
+)
+from backend.data.model import OAuth2Credentials
+from backend.integrations.codex.auth_bundle import (
+ CodexAuthBundleV1,
+ CodexAuthTokensV1,
+ encode_provider_state,
+)
+from backend.util.settings import BehaveAs
+
+USER_ID = "3e53486c-cf57-477e-ba2a-cb02dc828e1a"
+VALID_CODEX_PROVIDER_STATE = encode_provider_state(
+ CodexAuthBundleV1(
+ tokens=CodexAuthTokensV1(
+ id_token=SecretStr("id-token"),
+ access_token=SecretStr("access-token"),
+ refresh_token=SecretStr("refresh-token"),
+ ),
+ codex_runtime_version="0.144.4",
+ )
+)
+
+
+def _codex_credentials(credential_id: str = "cred-codex") -> OAuth2Credentials:
+ return OAuth2Credentials(
+ id=credential_id,
+ provider="codex",
+ access_token=SecretStr("access"),
+ refresh_token=SecretStr("refresh"),
+ scopes=[],
+ refresh_strategy="provider_runtime",
+ provider_state=SecretStr(VALID_CODEX_PROVIDER_STATE),
+ provider_state_version=1,
+ )
+
+
[email protected](autouse=True)
+def transport_env(mocker: pytest_mock.MockerFixture):
+ """Hosted deployment, entitled user, no connections, nothing saved."""
+ mocker.patch.object(transports.settings.config, "behave_as", BehaveAs.CLOUD)
+ mocker.patch.object(
+ transports,
+ "has_codex_access_for_discovery",
+ new=AsyncMock(return_value=True),
+ )
+ mocker.patch.object(
+ transports.credentials_manager.store,
+ "get_creds_by_provider",
+ new=AsyncMock(return_value=[]),
+ )
+ mocker.patch.object(
+ transports,
+ "get_user_default_chat_route",
+ new=AsyncMock(return_value=(None, None)),
+ )
+ mocker.patch.object(transports, "set_user_default_chat_route", new=AsyncMock())
+
+
+def _connect(*credential_ids: str) -> None:
+ transports.credentials_manager.store.get_creds_by_provider.return_value = [
+ _codex_credentials(credential_id) for credential_id in credential_ids
+ ]
+
+
+def _saved(auth_provider: str | None, credential_id: str | None = None) -> None:
+ transports.get_user_default_chat_route.return_value = (
+ auth_provider,
+ credential_id,
+ )
+
+
+def _self_hosted_without_deployment(mocker: pytest_mock.MockerFixture) -> None:
+ mocker.patch.object(transports.settings.config, "behave_as", BehaveAs.LOCAL)
+ chat_config = MagicMock()
+ chat_config.test_mode = False
+ chat_config.use_claude_code_subscription = False
+ chat_config.main_client_credentials = (None, "https://api.anthropic.com/v1/")
+ mocker.patch.object(transports, "config", chat_config)
+
+
+def _default_of(transport_list) -> tuple[str, str | None] | None:
+ default = next((t for t in transport_list if t.default), None)
+ return None if default is None else (default.auth_provider, default.credential_id)
+
+
+# ─── which transport comes back marked default ─────────────────────────
+
+
+async def test_nothing_saved_keeps_the_server_pick() -> None:
+ _connect("cred-codex")
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("platform", None)
+
+
+async def test_saved_choice_beats_the_server_pick() -> None:
+ _connect("cred-codex")
+ _saved("codex", "cred-codex")
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("codex", "cred-codex")
+
+
+async def test_exactly_one_transport_is_ever_default() -> None:
+ _connect("cred-a", "cred-b")
+ _saved("codex", "cred-b")
+
+ transport_list = await get_chat_transports(USER_ID)
+
+ assert [t.default for t in transport_list].count(True) == 1
+
+
+async def test_saved_choice_names_the_account_not_just_the_provider() -> None:
+ _connect("cred-a", "cred-b")
+ _saved("codex", "cred-b")
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("codex", "cred-b")
+
+
+# ─── healing, when the saved choice can't be honoured ──────────────────
+
+
+async def test_disconnected_account_heals_to_the_server_pick() -> None:
+ _connect("cred-other")
+ _saved("codex", "cred-gone")
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("platform", None)
+
+
+async def test_lost_entitlement_heals_to_the_server_pick() -> None:
+ _connect("cred-codex")
+ _saved("codex", "cred-codex")
+ transports.has_codex_access_for_discovery.return_value = False
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("platform", None)
+
+
+async def test_healing_lands_on_the_remaining_connection_when_there_is_no_platform(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """Self-host has no platform route to fall back to.
+
+ Healing to ``platform`` would strand exactly the users who have no
+ platform credentials — so it heals to whatever the server would have
+ picked on its own, which here is the one connection that still exists.
+ """
+ _self_hosted_without_deployment(mocker)
+ _connect("cred-other")
+ _saved("codex", "cred-gone")
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("codex", "cred-other")
+
+
+async def test_the_saved_row_survives_a_heal() -> None:
+ _connect()
+ _saved("codex", "cred-gone")
+
+ await get_chat_transports(USER_ID)
+
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
+async def test_a_provider_this_version_does_not_know_reads_as_automatic() -> None:
+ _connect("cred-codex")
+ _saved("github_copilot", "cred-gh")
+
+ assert _default_of(await get_chat_transports(USER_ID)) == ("platform", None)
+
+
+# ─── resolve_default_chat_route: the unrouted callers ──────────────────
+
+
+async def test_unrouted_callers_get_the_saved_choice() -> None:
+ _connect("cred-codex")
+ _saved("codex", "cred-codex")
+
+ assert await resolve_default_chat_route(USER_ID) == ("codex", "cred-codex")
+
+
+async def test_unrouted_callers_fall_back_to_platform_when_nothing_resolves(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """Two connections and no platform route is a question, not an answer.
+
+ The HTTP path answers it with a 409 and asks the user. A Discord message
+ has nobody to ask, so it keeps the behaviour it had before the setting
+ existed rather than failing.
+ """
+ _self_hosted_without_deployment(mocker)
+ _connect("cred-a", "cred-b")
+
+ assert await resolve_default_chat_route(USER_ID) == ("platform", None)
+
+
+async def test_unrouted_callers_survive_a_broken_lookup(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mocker.patch.object(
+ transports,
+ "get_chat_transports",
+ new=AsyncMock(side_effect=RuntimeError("credential store down")),
+ )
+
+ assert await resolve_default_chat_route(USER_ID) == ("platform", None)
+
+
+# ─── saving ────────────────────────────────────────────────────────────
+
+
+async def test_saving_persists_and_returns_the_new_default() -> None:
+ _connect("cred-codex")
+
+ transport_list = await save_default_chat_route(
+ USER_ID, DefaultChatRoute(auth_provider="codex", credential_id="cred-codex")
+ )
+
+ transports.set_user_default_chat_route.assert_awaited_once_with(
+ USER_ID, "codex", "cred-codex"
+ )
+ assert _default_of(transport_list) == ("codex", "cred-codex")
+
+
+async def test_clearing_hands_the_decision_back_to_the_server() -> None:
+ _connect("cred-codex")
+ _saved("codex", "cred-codex")
+
+ transport_list = await save_default_chat_route(USER_ID, DefaultChatRoute())
+
+ transports.set_user_default_chat_route.assert_awaited_once_with(USER_ID, None, None)
+ # The stub still reports the old saved value, so asserting the refreshed
+ # list would only prove the stub. The write is the contract here.
+ assert transport_list is not None
+
+
+async def test_chatgpt_without_an_account_is_rejected() -> None:
+ _connect("cred-codex")
+
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(USER_ID, DefaultChatRoute(auth_provider="codex"))
+
+ assert error.value.detail == "codex_credential_required"
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
+async def test_platform_with_an_account_is_rejected() -> None:
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(
+ USER_ID,
+ DefaultChatRoute(auth_provider="platform", credential_id="cred-codex"),
+ )
+
+ assert error.value.detail == "codex_credential_not_allowed"
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
+async def test_clearing_while_naming_an_account_is_rejected() -> None:
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(
+ USER_ID, DefaultChatRoute(credential_id="cred-codex")
+ )
+
+ assert error.value.detail == "codex_credential_not_allowed"
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
+async def test_an_account_the_user_does_not_own_is_rejected() -> None:
+ _connect("cred-mine")
+
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(
+ USER_ID,
+ DefaultChatRoute(auth_provider="codex", credential_id="cred-someone-else"),
+ )
+
+ assert error.value.detail == "codex_credential_not_found"
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
+async def test_chatgpt_is_not_saveable_without_the_entitlement() -> None:
+ _connect("cred-codex")
+ transports.has_codex_access_for_discovery.return_value = False
+
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(
+ USER_ID,
+ DefaultChatRoute(auth_provider="codex", credential_id="cred-codex"),
+ )
+
+ assert error.value.detail == "codex_credential_not_found"
+ transports.set_user_default_chat_route.assert_not_awaited()
+
+
+async def test_platform_is_not_saveable_where_it_is_unavailable(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ _self_hosted_without_deployment(mocker)
+
+ with pytest.raises(InvalidDefaultChatRoute) as error:
+ await save_default_chat_route(
+ USER_ID, DefaultChatRoute(auth_provider="platform")
+ )
+
+ assert error.value.detail == "chat_transport_not_configured"
+ transports.set_user_default_chat_route.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index 8ea0869039..ecf96dcb87 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -97,6 +97,17 @@ class User(BaseModel):
description="User timezone (IANA timezone identifier or 'not-set')",
)
+ # Default AutoPilot connection for chats nobody routed explicitly. Kept as
+ # plain strings here: the data layer stores the choice, the copilot layer
+ # decides what a given value means (and treats one it doesn't recognise as
+ # "automatic", so a value written by a newer server can't break an older one).
+ default_chat_auth_provider: Optional[str] = Field(
+ None, description="Saved default chat transport, or None for automatic"
+ )
+ default_chat_credential_id: Optional[str] = Field(
+ None, description="Credential backing the saved default chat transport"
+ )
+
@classmethod
def from_db(cls, prisma_user: "PrismaUser") -> "User":
"""Convert a database User object to application User model."""
@@ -145,6 +156,8 @@ class User(BaseModel):
alerts_enabled=prisma_user.alertsEnabled,
notify_on_store_verdict=prisma_user.notifyOnStoreVerdict,
timezone=prisma_user.timezone or USER_TIMEZONE_NOT_SET,
+ default_chat_auth_provider=prisma_user.defaultChatAuthProvider,
+ default_chat_credential_id=prisma_user.defaultChatCredentialId,
)
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index 80a3951fdf..a6b38a65d1 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -36,7 +36,7 @@ from backend.data.notifications import NotificationPreference, NotificationPrefe
from backend.data.org_migration import ensure_personal_org
from backend.util.cache import cached
from backend.util.encryption import JSONCryptor
-from backend.util.exceptions import DatabaseError
+from backend.util.exceptions import DatabaseError, NotFoundError
from backend.util.json import SafeJson
from backend.util.settings import Settings
@@ -1012,3 +1012,69 @@ def _sign_preference_choice(user_id: str, choice: str) -> str:
return base64.urlsafe_b64encode(
f"{user_id}:{signature.hex()}".encode("utf-8")
).decode("utf-8")
+
+
+async def get_user_default_chat_route(
+ user_id: str,
+) -> tuple[Optional[str], Optional[str]]:
+ """Read the saved default chat transport exactly as stored.
+
+ Returned verbatim rather than validated here: what a provider string
+ means belongs to the copilot layer, and the data layer must not import
+ it (``copilot.rate_limit`` already imports ``data.user``).
+
+ A user who has authenticated but has no platform row yet — the row is
+ created by ``POST /auth/user``, which the frontend calls separately after
+ sign-in — reads as "nothing saved". Raising here would take transport
+ discovery and session creation down for that window, neither of which
+ touched the user table before this setting existed.
+ """
+ try:
+ user = await get_user_by_id(user_id)
+ except ValueError:
+ return None, None
+ # Shared-cache entries can outlive a rolling deploy. An object pickled by
+ # the previous version has no attributes for fields introduced here, so
+ # read them defensively until that cache entry expires.
+ return (
+ getattr(user, "default_chat_auth_provider", None),
+ getattr(user, "default_chat_credential_id", None),
+ )
+
+
+async def set_user_default_chat_route(
+ user_id: str,
+ auth_provider: Optional[str],
+ credential_id: Optional[str],
+) -> None:
+ """Save (or, with ``auth_provider=None``, clear) the default chat transport."""
+ try:
+ prisma_user = PrismaUser.prisma()
+ user = await prisma_user.find_unique(where={"id": user_id})
+ if user is None:
+ raise NotFoundError(f"User {user_id} not found")
+
+ updated_count = await prisma_user.update_many(
+ where={"id": user_id},
+ data={
+ "defaultChatAuthProvider": auth_provider,
+ "defaultChatCredentialId": (
+ credential_id if auth_provider is not None else None
+ ),
+ },
+ )
+ if updated_count == 0:
+ raise NotFoundError(f"User {user_id} not found")
+
+ # Same cache invalidation as update_user_timezone — the route is read
+ # through the cached full-user lookup on every unrouted session create.
+ get_user_by_id.cache_delete(user_id)
+ if user.email:
+ get_user_by_email.cache_delete(user.email)
+ get_or_create_user.cache_clear()
+ except NotFoundError:
+ raise
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to update default chat route for user {user_id}: {e}"
+ ) from e
diff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.py
index 89112cfe47..765589df3b 100644
--- a/autogpt_platform/backend/backend/data/user_test.py
+++ b/autogpt_platform/backend/backend/data/user_test.py
@@ -9,7 +9,7 @@ import pytest
from backend.data import user as user_module
from backend.data.user import update_user_timezone
-from backend.util.exceptions import DatabaseError
+from backend.util.exceptions import DatabaseError, NotFoundError
def _application_user(user_id: str, email: str) -> user_module.User:
@@ -614,3 +614,89 @@ class TestGetAuthUserFlagFields:
fields = await user_module.get_auth_user_flag_fields("ghost")
assert fields is None
+
+
+class TestGetUserDefaultChatRoute:
+ @pytest.mark.asyncio
+ async def test_returns_the_saved_route(self):
+ user = _application_user("user-1", "[email protected]")
+ user.default_chat_auth_provider = "codex"
+ user.default_chat_credential_id = "cred-1"
+
+ with patch.object(user_module, "get_user_by_id", AsyncMock(return_value=user)):
+ route = await user_module.get_user_default_chat_route("user-1")
+
+ assert route == ("codex", "cred-1")
+
+ @pytest.mark.asyncio
+ async def test_a_user_with_no_platform_row_yet_reads_as_nothing_saved(self):
+ """Sign-up leaves a window before ``POST /auth/user`` creates the row.
+
+ Transport discovery and session creation both read this on paths that
+ never touched the user table before the setting existed, so raising
+ here would take them down for a freshly signed-up account.
+ """
+ with patch.object(
+ user_module,
+ "get_user_by_id",
+ AsyncMock(side_effect=ValueError("User not found with ID: user-1")),
+ ):
+ route = await user_module.get_user_default_chat_route("user-1")
+
+ assert route == (None, None)
+
+ @pytest.mark.asyncio
+ async def test_an_old_cached_user_without_route_fields_reads_as_nothing_saved(self):
+ user = _application_user("user-1", "[email protected]")
+ user.__dict__.pop("default_chat_auth_provider", None)
+ user.__dict__.pop("default_chat_credential_id", None)
+
+ with patch.object(user_module, "get_user_by_id", AsyncMock(return_value=user)):
+ route = await user_module.get_user_default_chat_route("user-1")
+
+ assert route == (None, None)
+
+
+class TestSetUserDefaultChatRoute:
+ @pytest.mark.asyncio
+ async def test_missing_user_is_reported_as_not_found(self):
+ with patch.object(user_module, "PrismaUser") as mock_prisma_user:
+ prisma_user = mock_prisma_user.prisma.return_value
+ prisma_user.find_unique = AsyncMock(return_value=None)
+ prisma_user.update_many = AsyncMock()
+
+ with pytest.raises(NotFoundError, match="User user-1 not found"):
+ await user_module.set_user_default_chat_route(
+ "user-1", "platform", None
+ )
+
+ prisma_user.update_many.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_clearing_provider_also_clears_stale_credential_id(self):
+ prisma_user = MagicMock(id="user-1", email="[email protected]")
+
+ with (
+ patch.object(user_module, "PrismaUser") as mock_prisma_user,
+ patch.object(user_module.get_user_by_id, "cache_delete") as by_id_del,
+ patch.object(user_module.get_user_by_email, "cache_delete") as by_email_del,
+ patch.object(user_module.get_or_create_user, "cache_clear") as goc_clear,
+ ):
+ prisma = mock_prisma_user.prisma.return_value
+ prisma.find_unique = AsyncMock(return_value=prisma_user)
+ prisma.update_many = AsyncMock(return_value=1)
+
+ await user_module.set_user_default_chat_route(
+ "user-1", None, "stale-credential"
+ )
+
+ prisma.update_many.assert_awaited_once_with(
+ where={"id": "user-1"},
+ data={
+ "defaultChatAuthProvider": None,
+ "defaultChatCredentialId": None,
+ },
+ )
+ by_id_del.assert_called_once_with("user-1")
+ by_email_del.assert_called_once_with("[email protected]")
+ goc_clear.assert_called_once_with()
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index b3cd099197..e3646bec16 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -38,6 +38,7 @@ from backend.copilot.executor.utils import schedule_turn
from backend.copilot.graphiti.communities import rebuild_communities_for_user
from backend.copilot.model import create_chat_session, get_chat_session
from backend.copilot.optimize_blocks import optimize_block_descriptions
+from backend.copilot.transports import resolve_default_chat_route
from backend.data.db_accessors import experts_db
from backend.data.execution import GraphExecutionWithNodes
from backend.data.model import CredentialsMetaInput, GraphInput
@@ -350,6 +351,9 @@ async def _execute_copilot_turn(**kwargs):
if expert_status != "active":
await _skip_inactive_expert_scope(args, expert_status)
return
+ llm_auth_provider, llm_credential_id = await resolve_default_chat_route(
+ args.user_id
+ )
new_session = await create_chat_session(
args.user_id,
dry_run=False,
@@ -361,6 +365,11 @@ async def _execute_copilot_turn(**kwargs):
# defaults to "interactive" and schedule_followup becomes a
# way to reach the staffing tools with nobody watching.
origin="automation",
+ # Model-authored or not, it still runs on the connection the
+ # user chose — a scheduled turn should not quietly bill to a
+ # different one than the chat it follows up on.
+ llm_auth_provider=llm_auth_provider,
+ llm_credential_id=llm_credential_id,
)
if args.expert_id and new_session.expert_id is None:
# The scope check above passed, so the expert was archived or
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index b8e18c1db3..8170f2bab2 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -301,6 +301,8 @@ async def test_execute_copilot_turn_creates_fresh_session_when_session_id_is_non
team_id="team-sched",
expert_id=None,
origin="automation",
+ llm_auth_provider="platform",
+ llm_credential_id=None,
)
mock_get_session.assert_not_awaited() # we created a new one, no lookup
mock_schedule_turn.assert_awaited_once()
@@ -342,6 +344,8 @@ async def test_execute_copilot_turn_creates_fresh_expert_session_in_same_scope()
team_id="team-sched",
expert_id="expert-1",
origin="automation",
+ llm_auth_provider="platform",
+ llm_credential_id=None,
)
assert mock_schedule_turn.call_args.kwargs["session_id"] == "new-expert-session"
@@ -562,6 +566,8 @@ async def test_execute_copilot_turn_preserves_legacy_fresh_autopilot_job():
team_id=None,
expert_id=None,
origin="automation",
+ llm_auth_provider="platform",
+ llm_credential_id=None,
)
assert mock_schedule_turn.call_args.kwargs["session_id"] == "new-legacy-session"
mock_self_delete.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/platform_linking/chat.py b/autogpt_platform/backend/backend/platform_linking/chat.py
index 76ee30934e..a3f1aad6f7 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat.py
@@ -22,6 +22,7 @@ from backend.copilot.rate_limit import (
get_global_rate_limits,
is_user_paywalled,
)
+from backend.copilot.transports import resolve_default_chat_route
from backend.data.db_accessors import orgs_db, platform_linking_db, workspace_db
from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
from backend.util.settings import Settings
@@ -261,12 +262,17 @@ async def _resolve_or_create_session(
session = None
if session is None:
org_id, team_id = await orgs_db().get_user_default_team(owner_user_id)
+ llm_auth_provider, llm_credential_id = await resolve_default_chat_route(
+ owner_user_id
+ )
session = await create_chat_session(
owner_user_id,
dry_run=False,
organization_id=org_id,
team_id=team_id,
source_platform=source_platform,
+ llm_auth_provider=llm_auth_provider,
+ llm_credential_id=llm_credential_id,
)
return session
diff --git a/autogpt_platform/backend/migrations/20260819120000_add_user_default_chat_route/migration.sql b/autogpt_platform/backend/migrations/20260819120000_add_user_default_chat_route/migration.sql
new file mode 100644
index 0000000000..caa4bf545b
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260819120000_add_user_default_chat_route/migration.sql
@@ -0,0 +1,3 @@
+-- AlterTable
+ALTER TABLE "User" ADD COLUMN "defaultChatAuthProvider" TEXT,
+ADD COLUMN "defaultChatCredentialId" TEXT;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 4edd84e83c..2bfcdd2ca3 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -129,6 +129,14 @@ model User {
timezone String @default("not-set")
+ // Default AutoPilot connection for chats the caller didn't route explicitly
+ // (bot links, schedules, a fresh /copilot session). NULL means "automatic" —
+ // the server picks, exactly as it did before this setting existed. The
+ // credential is stored alongside the provider so the choice keeps pointing at
+ // one ChatGPT account once a user can link several.
+ defaultChatAuthProvider String?
+ defaultChatCredentialId String?
+
subscriptionTier SubscriptionTier @default(NO_TIER)
// Relations
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts
index 69b3c2319d..d7944c3816 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/store.test.ts
@@ -436,11 +436,8 @@ describe("useCopilotUIStore", () => {
});
describe("copilotLlmAuth", () => {
- it("defaults to the platform route", () => {
- expect(useCopilotUIStore.getState().copilotLlmAuth).toEqual({
- authProvider: "platform",
- credentialId: null,
- });
+ it("starts unset so the saved default can decide", () => {
+ expect(useCopilotUIStore.getState().copilotLlmAuth).toBeNull();
});
it("stores a Codex credential without changing the selected mode or model", () => {
@@ -481,10 +478,7 @@ describe("useCopilotUIStore", () => {
expect(state.isSearchOpen).toBe(false);
expect(state.copilotChatMode).toBe("extended_thinking");
expect(state.copilotLlmModel).toBe("standard");
- expect(state.copilotLlmAuth).toEqual({
- authProvider: "platform",
- credentialId: null,
- });
+ expect(state.copilotLlmAuth).toBeNull();
expect(state.isNotificationsEnabled).toBe(false);
expect(state.isSoundEnabled).toBe(true);
expect(state.completedSessionIDs.size).toBe(0);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsx
index 4a831504c8..4c9290fd4b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/LlmRouteSelector.tsx
@@ -58,29 +58,33 @@ export function LLMRouteSelector() {
transports,
copilotLLMAuth,
);
+ // Before anything is chosen the trigger still names the connection the chat
+ // will actually start on, rather than flashing "Choose connection" for the
+ // one render before the effect below adopts the default.
const selectedTransport = findSelectedLLMTransport(
availableTransports,
- copilotLLMAuth,
+ copilotLLMAuth ?? resolvedSelection,
);
const selectedConnectionMissing =
transports !== undefined &&
availableTransports.length > 0 &&
+ copilotLLMAuth !== null &&
copilotLLMAuth.authProvider !== "platform" &&
!selectedTransport;
useEffect(() => {
if (!resolvedSelection) return;
if (
- resolvedSelection.authProvider === copilotLLMAuth.authProvider &&
- resolvedSelection.credentialId === copilotLLMAuth.credentialId
+ resolvedSelection.authProvider === copilotLLMAuth?.authProvider &&
+ resolvedSelection.credentialId === copilotLLMAuth?.credentialId
) {
return;
}
setCopilotLLMAuth(resolvedSelection);
}, [
- copilotLLMAuth.authProvider,
- copilotLLMAuth.credentialId,
+ copilotLLMAuth?.authProvider,
+ copilotLLMAuth?.credentialId,
resolvedSelection?.authProvider,
resolvedSelection?.credentialId,
setCopilotLLMAuth,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/copilotLlmAuth.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/copilotLlmAuth.test.ts
new file mode 100644
index 0000000000..86900cc89d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/copilotLlmAuth.test.ts
@@ -0,0 +1,89 @@
+import type { ChatTransportResponse } from "@/app/api/__generated__/models/chatTransportResponse";
+import { describe, expect, it } from "vitest";
+import { resolveCopilotLLMAuthSelection } from "../copilotLlmAuth";
+
+function platform(isDefault: boolean): ChatTransportResponse {
+ return {
+ auth_provider: "platform",
+ credential_id: null,
+ label: "AutoGPT Platform",
+ available: true,
+ default: isDefault,
+ };
+}
+
+function chatgpt(
+ credentialId: string,
+ isDefault: boolean,
+): ChatTransportResponse {
+ return {
+ auth_provider: "codex",
+ credential_id: credentialId,
+ label: "ChatGPT",
+ available: true,
+ default: isDefault,
+ };
+}
+
+describe("resolveCopilotLLMAuthSelection", () => {
+ it("adopts the saved default when nothing has been chosen yet", () => {
+ const resolved = resolveCopilotLLMAuthSelection(
+ [platform(false), chatgpt("cred-1", true)],
+ null,
+ );
+
+ expect(resolved).toEqual({
+ authProvider: "codex",
+ credentialId: "cred-1",
+ });
+ });
+
+ it("leaves a usable choice alone, so a chat in progress keeps its connection", () => {
+ const resolved = resolveCopilotLLMAuthSelection(
+ [platform(false), chatgpt("cred-1", true)],
+ { authProvider: "platform", credentialId: null },
+ );
+
+ expect(resolved).toEqual({
+ authProvider: "platform",
+ credentialId: null,
+ });
+ });
+
+ it("keeps the saved default pointed at one account", () => {
+ const resolved = resolveCopilotLLMAuthSelection(
+ [chatgpt("cred-1", false), chatgpt("cred-2", true)],
+ null,
+ );
+
+ expect(resolved).toEqual({
+ authProvider: "codex",
+ credentialId: "cred-2",
+ });
+ });
+
+ it("falls back to the only connection there is", () => {
+ const resolved = resolveCopilotLLMAuthSelection(
+ [chatgpt("cred-1", false)],
+ null,
+ );
+
+ expect(resolved).toEqual({
+ authProvider: "codex",
+ credentialId: "cred-1",
+ });
+ });
+
+ it("asks rather than guesses when several connections and no default", () => {
+ const resolved = resolveCopilotLLMAuthSelection(
+ [chatgpt("cred-1", false), chatgpt("cred-2", false)],
+ null,
+ );
+
+ expect(resolved).toBeNull();
+ });
+
+ it("waits for the transport list before choosing anything", () => {
+ expect(resolveCopilotLLMAuthSelection(undefined, null)).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts
index 82c8f1bebd..0f4490d952 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/copilotLlmAuth.ts
@@ -27,8 +27,9 @@ export function getChatTransportSelection(
export function findSelectedLLMTransport(
transports: ChatTransportResponse[] | null | undefined,
- selection: CopilotLlmAuthSelection,
+ selection: CopilotLlmAuthSelection | null,
): ChatTransportResponse | undefined {
+ if (!selection) return undefined;
return getAvailableLLMTransports(transports).find(
(transport) =>
transport.auth_provider === selection.authProvider &&
@@ -39,11 +40,15 @@ export function findSelectedLLMTransport(
export function resolveCopilotLLMAuthSelection(
transports: ChatTransportResponse[] | null | undefined,
- currentSelection: CopilotLlmAuthSelection,
+ currentSelection: CopilotLlmAuthSelection | null,
): CopilotLlmAuthSelection | null {
if (transports == null) return null;
const availableTransports = getAvailableLLMTransports(transports);
+
+ // A selection the user can still use is never overridden — including by
+ // the saved default, which decides where a chat *starts*, not where one
+ // already in progress continues.
const selectedTransport = findSelectedLLMTransport(
availableTransports,
currentSelection,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
index 0e9d717bbd..2d592840fa 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/store.ts
@@ -217,8 +217,12 @@ interface CopilotUIState {
copilotLlmModel: CopilotLlmModel;
setCopilotLlmModel: (model: CopilotLlmModel) => void;
- /** Authentication route locked into the next session when it is created. */
- copilotLlmAuth: CopilotLlmAuthSelection;
+ /**
+ * Authentication route locked into the next session when it is created.
+ * `null` until something chooses — the user via the picker, or the default
+ * they set in Settings, which the server marks on the transport list.
+ */
+ copilotLlmAuth: CopilotLlmAuthSelection | null;
setCopilotLlmAuth: (selection: CopilotLlmAuthSelection) => void;
/** Developer dry-run mode: sessions created with dry_run=true. */
@@ -541,7 +545,7 @@ export const useCopilotUIStore = create<CopilotUIState>((set, get) => ({
set({ copilotLlmModel: model });
},
- copilotLlmAuth: { authProvider: "platform", credentialId: null },
+ copilotLlmAuth: null,
setCopilotLlmAuth: (selection) => {
set({ copilotLlmAuth: selection });
},
@@ -589,7 +593,7 @@ export const useCopilotUIStore = create<CopilotUIState>((set, get) => ({
},
copilotChatMode: "extended_thinking",
copilotLlmModel: "standard",
- copilotLlmAuth: { authProvider: "platform", credentialId: null },
+ copilotLlmAuth: null,
isDryRun: false,
});
if (isClient) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index 691ce51278..de92b811c6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -260,6 +260,7 @@ export function useChatSession({
);
}
if (
+ copilotLlmAuth !== null &&
copilotLlmAuth.authProvider !== "platform" &&
resolvedLLMAuth.authProvider === "platform"
) {
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 0902ac1c96..f9271165fc 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -4554,6 +4554,7 @@
"get": {
"tags": ["v2", "chat", "chat"],
"summary": "List Chat Transports",
+ "description": "Every transport the user can chat over.\n\nExactly one carries ``default: true`` — the connection this user chose in\nSettings, or the server's own pick when they haven't chosen one.",
"operationId": "getV2ListChatTransports",
"responses": {
"200": {
@@ -4573,6 +4574,51 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/chat/transports/default": {
+ "put": {
+ "tags": ["v2", "chat", "chat"],
+ "summary": "Set Default Chat Transport",
+ "description": "Save the connection every new chat starts on.\n\nApplies to chats nobody routed explicitly — a fresh session in the web\napp, and every conversation that arrives without a request to read a route\nfrom: bot links, schedules, briefings, dream passes. It does not touch a\nconversation that already exists; sessions keep the route they were\ncreated with.",
+ "operationId": "putV2SetDefaultChatTransport",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetDefaultTransportRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ChatTransportsResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": {
+ "description": "The credential or user profile was not found"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ },
+ "security": [{ "HTTPBearerJWT": [] }]
+ }
+ },
"/api/chat/usage": {
"get": {
"tags": ["v2", "chat", "chat"],
@@ -25396,6 +25442,28 @@
"title": "SetActiveGraphVersionResponse",
"description": "Response for activating an existing graph version.\n\nCarries any webhook presets that were left pinned to their old version\nbecause the newly activated version's trigger block is incompatible and\nneeds to be reconfigured."
},
+ "SetDefaultTransportRequest": {
+ "properties": {
+ "auth_provider": {
+ "anyOf": [
+ { "type": "string", "enum": ["platform", "codex"] },
+ { "type": "null" }
+ ],
+ "title": "Auth Provider"
+ },
+ "credential_id": {
+ "anyOf": [
+ { "type": "string", "maxLength": 128 },
+ { "type": "null" }
+ ],
+ "title": "Credential Id"
+ }
+ },
+ "additionalProperties": false,
+ "type": "object",
+ "title": "SetDefaultTransportRequest",
+ "description": "The connection new chats should start on.\n\n``auth_provider: null`` clears the choice and hands the decision back to\nthe server. Sending ``codex`` requires naming the credential, so the\ndefault keeps pointing at one account rather than \"whichever ChatGPT\"."
+ },
"SetGraphActiveVersion": {
"properties": {
"active_graph_version": {