Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: offer only the Codex models the ChatGPT plan can actually reach (#9302)

Nilaycaa0b7925b68
diff --git a/studio/backend/core/inference/openai_codex_auth.py b/studio/backend/core/inference/openai_codex_auth.py
index 0a49da1f30c..42fec07b8fc 100644
--- a/studio/backend/core/inference/openai_codex_auth.py
+++ b/studio/backend/core/inference/openai_codex_auth.py
@@ -42,7 +42,10 @@ OPENAI_CODEX_DEVICE_REDIRECT_URI = f"{OPENAI_CODEX_ISSUER}/deviceauth/callback"
OPENAI_CODEX_ORIGINATOR = "unsloth_studio"
OPENAI_CODEX_API_BASE = "https://chatgpt.com/backend-api"
OPENAI_CODEX_RESPONSES_URL = f"{OPENAI_CODEX_API_BASE}/codex/responses"
+OPENAI_CODEX_MODELS_URL = f"{OPENAI_CODEX_API_BASE}/codex/models"
OPENAI_CODEX_USER_AGENT = "unsloth-studio/1"
+# /codex/models hides any slug whose minimal_client_version exceeds this.
+OPENAI_CODEX_CLIENT_VERSION = "0.156.0"
OPENAI_CODEX_COMPATIBILITY_INSTRUCTIONS = (
"You are operating inside Unsloth Studio. Follow the user's instructions, "
"use only tools supplied in this request, and return concise, accurate results."
@@ -227,11 +230,48 @@ def _validate_token_payload(body: Any, previous_refresh_token: str = "") -> dict
def save_oauth_bundle(provider_id: str, bundle: dict[str, Any]) -> None:
+ previous = load_oauth_bundle(provider_id)
credential_secrets.upsert_secret(
credential_secrets.OPENAI_CODEX_OAUTH_KIND,
provider_id,
json.dumps(bundle, separators = (",", ":")),
)
+ if previous and previous.get("account_id") != bundle.get("account_id"):
+ # Rebound to a different ChatGPT account, whose plan lists different slugs. No
+ # later request is guaranteed to notice: the picker only refreshes while its form
+ # is open, and the chat gate only refetches a catalog it does not already have.
+ # Imported here because the client module imports this one at load time.
+ from core.inference.openai_codex_client import (
+ forget_subscription_models,
+ mark_subscription_catalog_stale,
+ )
+ forget_subscription_models(provider_id)
+ # The emptiness here is deliberate, not a cold start: until this account's own
+ # catalog is read, the saved models still describe the previous one.
+ mark_subscription_catalog_stale(provider_id)
+
+
+async def remember_catalog_account(provider_id: str, account_id: str) -> None:
+ """Record, next to the credentials, which account the saved models were proven for.
+
+ The in-memory mark does not survive a restart or reach a cold worker, and a rebind
+ replaces the bundle wholesale, so keeping the proof here is what makes "these saved
+ models belong to some other account" outlive this process.
+
+ Written under the same guard the refresh path uses, and re-read inside it: an
+ unguarded read-modify-write here could put stale tokens back over a rotation that
+ landed in between, which would cost the connection its credentials.
+ """
+ if load_oauth_bundle(provider_id) is None:
+ return
+ async with provider_oauth_write_guard(provider_id):
+ bundle = load_oauth_bundle(provider_id)
+ if not bundle or bundle.get("account_id") != account_id:
+ return
+ if bundle.get("catalog_account_id") == account_id:
+ return
+ bundle["catalog_account_id"] = account_id
+ save_oauth_bundle(provider_id, bundle)
def load_oauth_bundle(provider_id: str) -> dict[str, Any] | None:
@@ -654,6 +694,13 @@ def delete_oauth_bundle(provider_id: str) -> None:
credential_secrets.OPENAI_CODEX_OAUTH_KIND,
provider_id,
)
+ # Disconnecting erases the account identity that a later save would be compared
+ # against, so the next authorization cannot tell it is a different account. The saved
+ # models outlive the bundle, so mark them unproven now rather than letting them read
+ # as cold-start evidence under whoever connects next.
+ from core.inference.openai_codex_client import mark_subscription_catalog_stale
+
+ mark_subscription_catalog_stale(provider_id)
def _oauth_flow_record(provider_id: str) -> dict[str, Any] | None:
@@ -852,5 +899,11 @@ async def resolve_access(
raise CodexAuthError("ChatGPT connection was disconnected during refresh.")
if current.get("refresh_token") != previous_refresh_token:
return current["access_token"], current["account_id"]
+ # A refresh rotates credentials, it does not rebind the connection, so the
+ # record of which account the saved models were proven for carries over.
+ # _validate_token_payload only knows about the token fields.
+ proof = current.get("catalog_account_id")
+ if proof is not None and refreshed.get("account_id") == current.get("account_id"):
+ refreshed["catalog_account_id"] = proof
save_oauth_bundle(provider_id, refreshed)
return refreshed["access_token"], refreshed["account_id"]
diff --git a/studio/backend/core/inference/openai_codex_client.py b/studio/backend/core/inference/openai_codex_client.py
index b4771c27c59..b67cd623d2e 100644
--- a/studio/backend/core/inference/openai_codex_client.py
+++ b/studio/backend/core/inference/openai_codex_client.py
@@ -18,8 +18,11 @@ from urllib.parse import urlparse
import httpx
+from core.inference import openai_codex_auth as codex_auth
from core.inference.openai_codex_auth import (
+ OPENAI_CODEX_CLIENT_VERSION,
OPENAI_CODEX_COMPATIBILITY_INSTRUCTIONS,
+ OPENAI_CODEX_MODELS_URL,
OPENAI_CODEX_ORIGINATOR,
OPENAI_CODEX_RESPONSES_URL,
OPENAI_CODEX_USER_AGENT,
@@ -208,6 +211,349 @@ def _validated_responses_url() -> str:
return OPENAI_CODEX_RESPONSES_URL
+def _validated_models_url() -> str:
+ parsed = urlparse(OPENAI_CODEX_MODELS_URL)
+ if (
+ parsed.scheme != "https"
+ or parsed.hostname != "chatgpt.com"
+ or parsed.port is not None
+ or parsed.path != "/backend-api/codex/models"
+ or parsed.query
+ or parsed.fragment
+ or parsed.username
+ or parsed.password
+ ):
+ raise RuntimeError("ChatGPT Codex model endpoint configuration is invalid.")
+ return OPENAI_CODEX_MODELS_URL
+
+
+_MODELS_CACHE_TTL_SECONDS = 600
+_MODELS_CACHE_MAX_ENTRIES = 32
+_models_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}
+# Outlives the cache TTL: a slug listed for this plan stays saveable afterwards.
+_offered_models: dict[str, dict[str, dict[str, Any]]] = {}
+# Which ChatGPT account each cached catalog belongs to; a reauthorization can rebind
+# a connection to a different account whose plan lists different slugs.
+_catalog_accounts: dict[str, str] = {}
+
+
+def _normalize_subscription_model(item: Any) -> dict[str, Any] | None:
+ if not isinstance(item, dict):
+ return None
+ slug = item.get("slug")
+ if not isinstance(slug, str) or not slug or len(slug) > 128:
+ return None
+ display_name = item.get("display_name")
+ context_window = item.get("context_window")
+ modalities = item.get("input_modalities")
+ # Every other field here tolerates whatever upstream sends, and this one has to as
+ # well: `or []` only covers a falsy value, so a scalar raised TypeError out of the
+ # whole call and cost the catalog every other entry too, not just this one.
+ levels = item.get("supported_reasoning_levels")
+ efforts = [
+ level["effort"]
+ for level in (levels if isinstance(levels, list) else [])
+ if isinstance(level, dict) and isinstance(level.get("effort"), str)
+ ]
+ return {
+ "id": slug,
+ "display_name": display_name if isinstance(display_name, str) and display_name else slug,
+ # bool is a subclass of int, so a JSON `true` would otherwise be reported to the
+ # picker as a context length of its own.
+ "context_length": (
+ context_window
+ if isinstance(context_window, int) and not isinstance(context_window, bool)
+ else None
+ ),
+ "vision": "image" in modalities if isinstance(modalities, list) else None,
+ "reasoning_efforts": efforts,
+ # "hide" marks a slug no picker should offer (codex-auto-review, and models that
+ # age out of the list). It is a presentation flag, not a revocation: the account
+ # can still call one it already saved, so the entry is kept and marked instead of
+ # dropped, which is what lets callers tell "not offered" from "not on this plan".
+ "listed": item.get("visibility") == "list",
+ }
+
+
+def cached_subscription_models(provider_id: str) -> list[dict[str, Any]] | None:
+ entry = _models_cache.get(provider_id)
+ if entry is None or entry[0] <= time.time():
+ return None
+ return entry[1]
+
+
+def offered_subscription_model_ids(provider_id: str) -> set[str]:
+ """Slugs the plan offers, and so the only ones a fetch alone may authorize.
+
+ Hidden entries are cached for their metadata and stay usable when they are already
+ on a connection, but a slug the picker never offered must not become invocable just
+ because a catalog fetch happened.
+ """
+ return {
+ model_id
+ for model_id, model in _offered_models.get(provider_id, {}).items()
+ if model.get("listed")
+ }
+
+
+# Connections whose catalog was dropped because the account behind them changed. The
+# absence is deliberate, so it must not read as "nothing fetched yet" and license the
+# previous account's saved slugs.
+_stale_catalogs: set[str] = set()
+
+
+# The ticket the newest catalog read for each connection is holding, so a read that was
+# overtaken (by a rebind, a disconnect, or a newer read) cannot commit its result over
+# the one that replaced it.
+_catalog_requests: dict[str, int] = {}
+# Tickets are drawn from one counter shared by every connection rather than counting up
+# per connection. Nothing reads the number itself, only whether it still matches, and a
+# value that is never reissued is what lets forget_subscription_models drop the entry
+# instead of leaving a larger one behind: a read still in flight then finds no ticket at
+# all, and the next read draws a number no earlier read can be holding.
+_catalog_request_serial = 0
+
+
+def _begin_catalog_request(provider_id: str) -> int:
+ global _catalog_request_serial
+ _catalog_request_serial += 1
+ _catalog_requests[provider_id] = _catalog_request_serial
+ return _catalog_request_serial
+
+
+def subscription_catalog_matches_account(provider_id: str, account_id: str | None) -> bool:
+ """Whether the catalog held for this connection belongs to the account named.
+
+ The OAuth bundle is shared through the installation DB but the catalog is per
+ process, so another worker can rebind a connection this one still has a catalog for.
+ """
+ known = _catalog_accounts.get(provider_id)
+ return known is None or account_id is None or known == account_id
+
+
+def mark_subscription_catalog_stale(provider_id: str) -> None:
+ _stale_catalogs.add(provider_id)
+
+
+def subscription_catalog_stale(provider_id: str) -> bool:
+ return provider_id in _stale_catalogs
+
+
+def saved_models_proven_for(provider_id: str, account_id: str | None) -> bool:
+ """Whether the row's saved models are on record as validated against this account.
+
+ Consulted when this process holds no catalog: the in-memory mark is gone after a
+ restart and never existed on a cold worker, so the record kept with the credentials
+ is the only thing that still knows a rebind happened.
+ """
+ if account_id is None:
+ return True
+ bundle = codex_auth.load_oauth_bundle(provider_id)
+ return bool(bundle) and bundle.get("catalog_account_id") == account_id
+
+
+def subscription_catalog_known(provider_id: str) -> bool:
+ """Whether this process has read a catalog for the connection at all.
+
+ Without one the saved row is the only evidence there is; with one, a slug the plan
+ does not carry has genuinely gone, which is how a reauthorization to another account
+ retires the previous account's selections.
+ """
+ return provider_id in _offered_models
+
+
+def offered_subscription_model(provider_id: str, model_id: str) -> dict[str, Any] | None:
+ """What the plan said about one slug, for models the static registry cannot describe."""
+ return _offered_models.get(provider_id, {}).get(model_id)
+
+
+def forget_subscription_models(provider_id: str) -> None:
+ # Retire any read still in flight: its result describes what was just dropped. The
+ # ticket is dropped rather than bumped, so this releases the entry instead of
+ # replacing it; see the counter above for why that is still safe.
+ _catalog_requests.pop(provider_id, None)
+ _models_cache.pop(provider_id, None)
+ _offered_models.pop(provider_id, None)
+ _catalog_accounts.pop(provider_id, None)
+ _stale_catalogs.discard(provider_id)
+
+
+async def list_subscription_models(
+ provider_id: str,
+ access_token: str,
+ account_id: str,
+ force: bool = False,
+) -> list[dict[str, Any]]:
+ """Model slugs this ChatGPT plan can reach; anything else is a 400 upstream.
+
+ ``force`` skips the cache for an explicit user reload: a plan change or a slug
+ rolled out since the last fetch is exactly what that click is asking about.
+ """
+ if _catalog_accounts.get(provider_id) not in (None, account_id):
+ # Reauthorized against a different account: the previous plan's catalog says
+ # nothing about this one, and nothing else clears it on the reconnect path.
+ forget_subscription_models(provider_id)
+ if not force:
+ cached = cached_subscription_models(provider_id)
+ if cached is not None:
+ return cached
+
+ ticket = _begin_catalog_request(provider_id)
+ url = _validated_models_url()
+
+ def _headers(token: str, account: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {token}",
+ "chatgpt-account-id": account,
+ "originator": OPENAI_CODEX_ORIGINATOR,
+ "User-Agent": OPENAI_CODEX_USER_AGENT,
+ "Accept": "application/json",
+ }
+
+ client = _create_http_client()
+ try:
+ response = await client.get(
+ url,
+ headers = _headers(access_token, account_id),
+ params = {"client_version": OPENAI_CODEX_CLIENT_VERSION},
+ )
+ if response.status_code == 401:
+ # Upstream can reject a token before its recorded expiry while the refresh
+ # credential is still good. The responses transport spends one forced refresh
+ # on that; without the same here the editor cannot load a catalog for a
+ # connection whose chats recover fine.
+ try:
+ access_token, account_id = await codex_auth.resolve_access(
+ provider_id,
+ force_refresh = True,
+ expected_access_token = access_token,
+ )
+ except CodexReauthorizationRequired as exc:
+ raise CodexReauthorizationError(
+ "ChatGPT authorization expired. Reconnect this connection.",
+ status = 401,
+ ) from exc
+ except Exception as exc:
+ # The refresh did not get an answer, which is retryable. Calling it a
+ # reauthorization would send the user to reconnect a connection whose
+ # credentials are probably fine, and the responses transport treats the
+ # same failure as transient.
+ raise CodexTransportError("Could not refresh ChatGPT authorization.") from exc
+ response = await client.get(
+ url,
+ headers = _headers(access_token, account_id),
+ params = {"client_version": OPENAI_CODEX_CLIENT_VERSION},
+ )
+ if response.status_code == 401:
+ # A freshly refreshed token was rejected too, so the connection really is
+ # done. Record it against that token the way the streaming path does, or
+ # auth_status keeps reporting connected, the editor never offers Reconnect
+ # and every later catalog load repeats this.
+ # Under the same guard the streaming error path uses: the read and the write
+ # inside are one step, so a rotation landing between them cannot be undone by
+ # writing the rejected bundle back with the marker on it.
+ async with codex_auth.provider_oauth_write_guard(provider_id):
+ codex_auth.mark_reauthorization_required(
+ provider_id, expected_access_token = access_token
+ )
+ raise CodexReauthorizationError(
+ "ChatGPT authorization expired. Reconnect this connection.",
+ status = 401,
+ )
+ if response.status_code != 200:
+ detail = await _upstream_error_detail(response)
+ suffix = f" {detail}" if detail else ""
+ raise CodexTransportError(
+ f"Could not list ChatGPT Codex models ({response.status_code}).{suffix}",
+ status = response.status_code,
+ )
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise CodexTransportError("ChatGPT returned an unreadable model list.") from exc
+ except httpx.HTTPError as exc:
+ raise CodexTransportError("Could not reach ChatGPT Codex.") from exc
+ finally:
+ await client.aclose()
+
+ raw = payload.get("models") if isinstance(payload, dict) else None
+ models: list[dict[str, Any]] = []
+ seen_slugs: set[str] = set()
+ for item in raw or []:
+ model = _normalize_subscription_model(item)
+ if model is None:
+ continue
+ if model["id"] in seen_slugs:
+ # A slug repeated in one payload describes itself twice, and the list and the
+ # by-id map built from it below disagree about which description won: the
+ # route offers what the first entry said while the chat gate judges by the
+ # last, so a duplicate whose second entry is hidden had the picker offering a
+ # model every send then refused. First wins, so both read the same entry.
+ continue
+ seen_slugs.add(model["id"])
+ models.append(model)
+ if not any(model.get("listed") for model in models):
+ # Nothing offerable came back. The route answers with the curated seed for this,
+ # so committing it as a known catalog would leave the picker offering models that
+ # validation and chat, reading that same empty catalog, would then refuse.
+ return models
+ if _catalog_requests.get(provider_id) != ticket:
+ # Overtaken while this request was out. Committing now would reinstate a catalog
+ # for an account this connection may no longer be on, and clear the mark that
+ # says so, so hand the caller the models without storing them.
+ return models
+ # That counter only sees this process. Rebinding travels through the installation DB,
+ # so ask it who owns the connection now before recording this as its catalog.
+ current_bundle = codex_auth.load_oauth_bundle(provider_id)
+ if current_bundle and current_bundle.get("account_id") != account_id:
+ return models
+ if len(_models_cache) >= _MODELS_CACHE_MAX_ENTRIES:
+ # Only the TTL response cache is bounded here. The per-account authorization
+ # evidence deliberately outlives it: dropping it would make every other
+ # connection look cold and license saved slugs their account no longer carries.
+ # It is keyed by connection and released by forget_subscription_models, so it is
+ # bounded by the connections that exist rather than by fetches.
+ _models_cache.clear()
+ _models_cache[provider_id] = (time.time() + _MODELS_CACHE_TTL_SECONDS, models)
+ _offered_models[provider_id] = {model["id"]: model for model in models}
+ _catalog_accounts[provider_id] = account_id
+ _stale_catalogs.discard(provider_id)
+ return models
+
+
+async def ensure_subscription_models(provider_id: str) -> set[str]:
+ """The plan's slugs, fetching them once when this process has none yet.
+
+ The catalog lives in memory, so a restart leaves a saved dynamic slug with
+ nothing to authorize it. Callers use this before refusing such a model; an
+ unreachable or disconnected upstream returns empty so the caller falls back
+ to the seed rather than locking the account out.
+ """
+ listed = offered_subscription_model_ids(provider_id)
+ if listed:
+ return listed
+ try:
+ access_token, account_id = await codex_auth.resolve_access(provider_id)
+ models = await list_subscription_models(provider_id, access_token, account_id)
+ except (codex_auth.CodexAuthError, CodexReauthorizationError):
+ # The connection needs reconnecting, which is a different answer from "this plan
+ # does not list that model". Callers turn this into the reauthorization error the
+ # user can act on instead of a misleading model-choice rejection.
+ raise
+ except Exception:
+ return set()
+ listed = offered_subscription_model_ids(provider_id)
+ if listed:
+ return listed
+ # A read overtaken by a newer one returns its models without storing them. That
+ # answer still came from upstream for the account resolved above, so use it rather
+ # than reporting an empty plan; only a rebind makes it the wrong account's.
+ current_bundle = codex_auth.load_oauth_bundle(provider_id)
+ if current_bundle and current_bundle.get("account_id") == account_id:
+ return {model["id"] for model in models if model.get("listed")}
+ return set()
+
+
def _quota_metadata(response: httpx.Response) -> dict[str, Any]:
values = {
"retry_after": response.headers.get("retry-after"),
@@ -229,8 +575,11 @@ async def _upstream_error_detail(response: httpx.Response) -> str | None:
message = error.get("message")
code = error.get("code") or error.get("type")
detail = message if isinstance(message, str) and message.strip() else code
+ elif isinstance(error, str):
+ detail = error
else:
- detail = error if isinstance(error, str) else None
+ # The subscription endpoint reports rejected models as a bare "detail".
+ detail = payload.get("detail") if isinstance(payload, dict) else None
if not isinstance(detail, str):
return None
return " ".join(detail.split())[:500] or None
diff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.py
index e873f69e88c..c2c09e232cd 100644
--- a/studio/backend/core/inference/providers.py
+++ b/studio/backend/core/inference/providers.py
@@ -20,8 +20,8 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"openai_codex": {
"display_name": "ChatGPT / Codex subscription",
"base_url": "https://chatgpt.com/backend-api",
+ # Only seeds the picker; /codex/models is the truth once connected.
"default_models": [
- "gpt-5.3-codex-spark",
"gpt-5.4",
"gpt-5.4-mini",
"gpt-5.5",
@@ -30,7 +30,6 @@ PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"gpt-5.6-terra",
],
"model_capabilities": {
- "gpt-5.3-codex-spark": {"vision": False, "studio_tools": True},
"gpt-5.4": {"vision": True, "studio_tools": True},
"gpt-5.4-mini": {"vision": True, "studio_tools": True},
"gpt-5.5": {"vision": True, "studio_tools": True},
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 948229db2ee..c19b936552f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -12999,6 +12999,7 @@ async def _proxy_to_external_provider(
from core.inference.openai_codex_auth import (
OPENAI_CODEX_API_BASE,
CodexAuthError,
+ load_oauth_bundle,
resolve_access,
)
from core.inference.openai_codex_client import (
@@ -13006,6 +13007,15 @@ async def _proxy_to_external_provider(
CodexTransportError,
CodexQuotaError,
CodexReauthorizationError,
+ ensure_subscription_models,
+ offered_subscription_model,
+ offered_subscription_model_ids,
+ forget_subscription_models,
+ mark_subscription_catalog_stale,
+ subscription_catalog_known,
+ saved_models_proven_for,
+ subscription_catalog_matches_account,
+ subscription_catalog_stale,
)
# Through the same helper the saved-credential exception uses, not a bare
@@ -13032,12 +13042,93 @@ async def _proxy_to_external_provider(
from core.inference.providers import get_provider_info as _get_codex_provider_info
info = _get_codex_provider_info("openai_codex") or {}
- if model not in info.get("default_models", []):
+
+ # The seed is only a seed: /codex/models is what the plan can reach, and the
+ # provider routes already accept saving a listed slug that is newer than it.
+ # Gating chat on the seed alone rejects the model the picker just offered.
+ # The OAuth bundle is shared through the installation DB, the catalog is not, so
+ # another worker can have rebound this connection since this process last read
+ # one. Drop a catalog that belongs to a different account before trusting it.
+ current_bundle = load_oauth_bundle(payload.provider_id)
+ current_account = current_bundle.get("account_id") if current_bundle else None
+ if current_account and not subscription_catalog_matches_account(
+ payload.provider_id, current_account
+ ):
+ forget_subscription_models(payload.provider_id)
+ mark_subscription_catalog_stale(payload.provider_id)
+
+ def _allowed_codex_models() -> set[str]:
+ """What this connection may call, in order of what is actually known.
+
+ The plan's catalog is the authority once it has been read: the registry seed
+ is a bootstrapping list, not evidence about this account, so it stops
+ counting there. A saved slug survives a flip to "hide", because that retires
+ a model from what is offered rather than from what the user may call, but not
+ a plan that no longer carries it at all. With no catalog read yet the seed and
+ the saved row are all there is, unless the row was left behind by a different
+ account, in which case only the seed is safe to assume.
+ """
+ saved = set(config.get("models") or [])
+ if subscription_catalog_known(payload.provider_id):
+ return offered_subscription_model_ids(payload.provider_id) | {
+ slug
+ for slug in saved
+ if offered_subscription_model(payload.provider_id, slug) is not None
+ }
+ if subscription_catalog_stale(payload.provider_id):
+ return set(info.get("default_models", []))
+ if not saved_models_proven_for(payload.provider_id, current_account):
+ # No catalog here and nothing on record saying the row was validated for
+ # this account, which is what a rebind before a restart, or on another
+ # worker, leaves behind.
+ return set(info.get("default_models", []))
+ return set(info.get("default_models", [])) | saved
+
+ allowed_models = _allowed_codex_models()
+ if model not in allowed_models:
+ # The catalog is process-local, so a restart leaves a saved plan slug with
+ # nothing to authorize it. Refresh once before refusing what the user picked.
+ try:
+ await ensure_subscription_models(payload.provider_id)
+ except (CodexAuthError, CodexReauthorizationError) as exc:
+ # Say reconnect, not "choose another model": the catalog is unreadable
+ # because the connection is, and the model may be perfectly valid.
+ raise HTTPException(status_code = 401, detail = str(exc)) from exc
+ allowed_models = _allowed_codex_models()
+ if model not in allowed_models:
raise HTTPException(status_code = 400, detail = "Choose a curated Codex model.")
- model_supports_vision = bool(
- info.get("model_capabilities", {}).get(model, {}).get("vision")
+ capabilities = info.get("model_capabilities", {})
+ image_requested = any(
+ isinstance(message.content, list)
+ and any(part.type == "image_url" for part in message.content)
+ for message in payload.messages
)
+ listed_model = (
+ None
+ if model in capabilities
+ else offered_subscription_model(payload.provider_id, model)
+ )
+ if image_requested and model not in capabilities and listed_model is None:
+ # Admitted straight off the saved row, so no catalog read happened this
+ # process and nothing here knows the modalities. Defaulting to text-only
+ # would refuse an image for a model the picker offered as capable. Only an
+ # actual image is worth the fetch; a text turn should not pay for one.
+ try:
+ await ensure_subscription_models(payload.provider_id)
+ except (CodexAuthError, CodexReauthorizationError) as exc:
+ # Same rule as the authorization refresh above: a dead connection is not
+ # a text-only model, and this branch runs before resolve_access, so
+ # swallowing it here would report the wrong failure first.
+ raise HTTPException(status_code = 401, detail = str(exc)) from exc
+ except Exception:
+ pass
+ listed_model = offered_subscription_model(payload.provider_id, model)
+ if model in capabilities:
+ model_supports_vision = bool(capabilities[model].get("vision"))
+ else:
+ # A slug the registry never listed: the plan's own entry is all we know.
+ model_supports_vision = bool(listed_model and listed_model.get("vision"))
if not model_supports_vision:
for message in payload.messages:
if isinstance(message.content, list) and any(
@@ -13051,6 +13142,19 @@ async def _proxy_to_external_provider(
access_token, account_id = await resolve_access(payload.provider_id)
except CodexAuthError as exc:
raise HTTPException(status_code = 401, detail = str(exc)) from exc
+ if (current_account and account_id != current_account) or (
+ not subscription_catalog_matches_account(payload.provider_id, account_id)
+ ):
+ # Another worker rebound the connection between the gate and here, so the
+ # model was judged against an account these credentials do not belong to.
+ # The catalog comparison alone has no opinion on a cold worker, where the row
+ # was authorized from the persisted proof rather than a catalog, so the
+ # account the gate judged by is compared too. Drop and re-judge before
+ # anything is sent under them.
+ forget_subscription_models(payload.provider_id)
+ mark_subscription_catalog_stale(payload.provider_id)
+ if model not in _allowed_codex_models():
+ raise HTTPException(status_code = 400, detail = "Choose a curated Codex model.")
chat_messages = _build_external_messages(
payload.messages,
model_supports_vision,
@@ -13100,6 +13204,19 @@ async def _proxy_to_external_provider(
force_refresh = True,
expected_access_token = current_access_token,
)
+ if (current_account and refreshed_account_id != current_account) or (
+ not subscription_catalog_matches_account(
+ payload.provider_id, refreshed_account_id
+ )
+ ):
+ # A rebind landed mid-stream, so these credentials belong to an
+ # account this model was never authorized against. Retrying here
+ # would put it upstream under them.
+ forget_subscription_models(payload.provider_id)
+ mark_subscription_catalog_stale(payload.provider_id)
+ raise CodexAuthError(
+ "This ChatGPT connection changed accounts. Send the message again."
+ )
return current_access_token, refreshed_account_id
from core.inference.openai_codex_tool_loop import (
diff --git a/studio/backend/routes/openai_codex_auth.py b/studio/backend/routes/openai_codex_auth.py
index 5f4e3d98cec..4db0a340453 100644
--- a/studio/backend/routes/openai_codex_auth.py
+++ b/studio/backend/routes/openai_codex_auth.py
@@ -6,15 +6,19 @@
import secrets
from typing import Literal
+import structlog
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from auth.authentication import authenticated_via_api_key, get_current_credential
from core.inference import openai_codex_auth as codex_auth
+from core.inference import openai_codex_client as codex_client
+from core.inference.providers import get_provider_info
from routes.provider_credentials import current_credential_write, require_ui_session
from storage import providers_db
router = APIRouter()
+logger = structlog.get_logger(__name__)
class OAuthStartRequest(BaseModel):
@@ -147,6 +151,66 @@ async def cancel_oauth(
raise _safe_error(exc) from exc
[email protected]("/{provider_id}/codex/models")
+async def list_subscription_models(
+ provider_id: str,
+ refresh: bool = False,
+ _credential: tuple = Depends(get_current_credential),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+):
+ """Models this plan can reach, falling back to the curated seed."""
+ require_ui_session(via_api_key)
+ _provider(provider_id)
+ curated = [
+ {"id": model, "display_name": model, "context_length": None}
+ for model in get_provider_info("openai_codex")["default_models"]
+ ]
+ status = codex_auth.auth_status(provider_id)
+ if status == "reauthorization_required":
+ # Something already marked this bundle, possibly another worker, after the last
+ # provider sync the browser saw. Saying only "curated" here would leave the
+ # editor presenting a dead connection as healthy.
+ return {"models": curated, "source": "reauthorization_required"}
+ if status != "connected":
+ return {"models": curated, "source": "curated"}
+ try:
+ token, account_id = await codex_auth.resolve_access(provider_id)
+ models = await codex_client.list_subscription_models(
+ provider_id, token, account_id, force = refresh
+ )
+ except (codex_auth.CodexAuthError, codex_client.CodexReauthorizationError) as exc:
+ # resolve_access has already marked the connection as needing reauthorization, so
+ # say so in the answer rather than through a 401: the client's authFetch reads
+ # every 401 as an expired Studio session, refreshes it and retries, and the retry
+ # would come back as a plain curated list with the connection looking healthy.
+ # A source the picker does not treat as authoritative carries the signal instead.
+ logger.info(
+ "openai_codex.model_list_reauthorization_required",
+ provider_id = provider_id,
+ error_type = type(exc).__name__,
+ )
+ return {"models": curated, "source": "reauthorization_required"}
+ except Exception as exc:
+ logger.warning(
+ "openai_codex.model_list_failed",
+ provider_id = provider_id,
+ error_type = type(exc).__name__,
+ )
+ return {"models": curated, "source": "curated"}
+ # Only listed slugs are offered, but every slug the plan returned is reported so the
+ # picker can tell one it should stop offering from one this account cannot reach.
+ offered = [model for model in models if model.get("listed")]
+ if not offered:
+ return {"models": curated, "source": "curated"}
+ return {
+ "models": offered,
+ # Full entries, not just ids: a hidden slug stays selectable, so the client needs
+ # its capabilities too or it will guess and offer what the chat route refuses.
+ "known": models,
+ "source": "subscription",
+ }
+
+
@router.delete("/{provider_id}/oauth", status_code = 204)
async def delete_oauth(
provider_id: str,
@@ -158,6 +222,7 @@ async def delete_oauth(
codex_auth.credential_secrets.get_or_create_credential_encryption_key()
await codex_auth.cancel_provider_flows(provider_id)
+ codex_client.forget_subscription_models(provider_id)
async with codex_auth.provider_oauth_write_guard(provider_id):
with current_credential_write(credential):
codex_auth.delete_oauth_bundle(provider_id)
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 72f6fc8a2fd..bb0459913da 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -43,7 +43,7 @@ from core.inference.providers import (
from core.inference.pricing import pricing_snapshot
from core.inference.external_provider import ExternalProviderClient
-from core.inference import openai_codex_auth
+from core.inference import openai_codex_auth, openai_codex_client
from models.providers import (
ProviderCreate,
ProviderCredentialMigration,
@@ -102,6 +102,9 @@ def _validate_provider_auth_contract(
models: list[str] | None,
updating: bool,
clear_api_key: bool = False,
+ provider_id: str | None = None,
+ persisted_models: list[str] | None = None,
+ validated_account: str | None = None,
) -> None:
if info.get("auth_kind") != "chatgpt_oauth":
return
@@ -109,7 +112,31 @@ def _validate_provider_auth_contract(
raise HTTPException(status_code = 400, detail = "ChatGPT subscriptions do not use API keys.")
if base_url is not None and (not updating or base_url != info["base_url"]):
raise HTTPException(status_code = 400, detail = "ChatGPT subscription routing is fixed.")
- if models is not None and (not models or not set(models).issubset(set(info["default_models"]))):
+ if models is None:
+ return
+ # Same order of evidence the chat route uses, so a save cannot persist a model that
+ # every send would then refuse: the plan's catalog once it is known, otherwise the
+ # seed, plus what this row already carries unless it was left by another account.
+ if provider_id and openai_codex_client.subscription_catalog_known(provider_id):
+ allowed = openai_codex_client.offered_subscription_model_ids(provider_id) | {
+ slug
+ for slug in (persisted_models or [])
+ if openai_codex_client.offered_subscription_model(provider_id, slug) is not None
+ }
+ else:
+ allowed = set(info["default_models"])
+ proven = not provider_id or openai_codex_client.saved_models_proven_for(
+ provider_id, validated_account
+ )
+ if (
+ persisted_models
+ and proven
+ and not (provider_id and openai_codex_client.subscription_catalog_stale(provider_id))
+ ):
+ # Already accepted on this row once, so an upstream outage must not make an
+ # unrelated edit such as a rename unsavable.
+ allowed |= set(persisted_models)
+ if not models or not set(models).issubset(allowed):
raise HTTPException(status_code = 400, detail = "Choose only curated Codex models.")
@@ -278,6 +305,40 @@ async def update_provider_config(
max_output_tokens_requested,
payload.max_output_tokens,
)
+ persisted_models = list(existing.get("models") or [])
+ # One reading of who owns this connection, used for every decision in this request:
+ # a second lookup later could name a different account than the one the selection was
+ # actually judged against.
+ validated_account: str | None = None
+ if existing_info.get("auth_kind") == "chatgpt_oauth":
+ # The OAuth bundle is shared through the installation DB while the catalog is per
+ # process, so another worker may have rebound this connection. The chat route
+ # makes the same check; without it here a save would persist exactly what every
+ # send then refuses.
+ current_bundle = openai_codex_auth.load_oauth_bundle(provider_id)
+ validated_account = current_bundle.get("account_id") if current_bundle else None
+ current_account = validated_account
+ if current_account and not openai_codex_client.subscription_catalog_matches_account(
+ provider_id, current_account
+ ):
+ openai_codex_client.forget_subscription_models(provider_id)
+ openai_codex_client.mark_subscription_catalog_stale(provider_id)
+ if existing_info.get("auth_kind") == "chatgpt_oauth" and payload.models:
+ # Only a slug that is neither seeded nor already saved here needs the plan
+ # catalog. Reaching upstream for the others would make an ordinary save wait out
+ # the 20s connect / 120s read timeout whenever ChatGPT is unreachable, and would
+ # fail an unrelated edit to a connection whose selection was accepted long ago.
+ unproven = (
+ set(payload.models) - set(existing_info["default_models"]) - set(persisted_models)
+ )
+ if unproven:
+ try:
+ await openai_codex_client.ensure_subscription_models(provider_id)
+ except (
+ openai_codex_auth.CodexAuthError,
+ openai_codex_client.CodexReauthorizationError,
+ ) as exc:
+ raise HTTPException(status_code = 401, detail = str(exc)) from exc
_validate_provider_auth_contract(
existing_info,
encrypted_api_key = payload.encrypted_api_key,
@@ -285,6 +346,9 @@ async def update_provider_config(
models = payload.models,
updating = True,
clear_api_key = payload.clear_api_key,
+ provider_id = provider_id,
+ persisted_models = persisted_models,
+ validated_account = validated_account,
)
if payload.clear_api_key and payload.encrypted_api_key:
@@ -322,18 +386,73 @@ async def update_provider_config(
if not replacement_api_key:
raise HTTPException(status_code = 400, detail = "API key cannot be empty")
+ metadata_updates: dict = {}
+ if metadata_requested:
+ metadata_updates = dict(
+ id = provider_id,
+ display_name = payload.display_name,
+ base_url = base_url,
+ is_enabled = payload.is_enabled,
+ models = payload.models,
+ available_models = payload.available_models,
+ )
+ if max_output_tokens_requested:
+ metadata_updates["max_output_tokens"] = payload.max_output_tokens
+
+ # The row snapshot this request found, keyed the way update_provider takes it.
+ _restorable = dict(
+ display_name = existing["display_name"],
+ base_url = existing["base_url"],
+ is_enabled = bool(existing["is_enabled"]),
+ models = existing.get("models") or [],
+ available_models = existing.get("available_models") or [],
+ max_output_tokens = existing.get("max_output_tokens"),
+ )
+
+ def _current_matches(current: dict, field: str, written) -> bool:
+ """Does the row still hold what this request wrote into that column?"""
+ if field == "is_enabled":
+ return bool(current.get("is_enabled")) == bool(written)
+ return current.get(field) == written
+
+ def _restore_metadata() -> None:
+ """Undo this request's own metadata write, while it is still the row.
+
+ update_provider commits and closes its own connection, so the row is already
+ durable by the time any later step fails; a compensating write is the only undo
+ there is. This handler suspends between that commit and the proof write, though
+ (remember_catalog_account awaits a 30s file lock, and the failure worth undoing is
+ exactly the one where that lock was contended), so a second save can land in
+ between. Restoring the whole pre-request snapshot would silently erase it. Put
+ back only the columns this request set, and only those the row still holds this
+ request's value for: a column a later save has since claimed belongs to that save.
+ """
+ if not metadata_requested:
+ return
+ current = providers_db.get_provider(provider_id)
+ if current is None:
+ return
+ undo = {}
+ for field, written in metadata_updates.items():
+ if field == "id":
+ continue
+ # None means "not sent" for every column but max_output_tokens, which is only
+ # present here when it was explicitly requested. update_provider left the
+ # unsent ones alone, so there is nothing of this request's to take back.
+ if written is None and field != "max_output_tokens":
+ continue
+ if not _current_matches(current, field, written):
+ continue
+ undo[field] = _restorable[field]
+ if not undo:
+ return
+ try:
+ providers_db.update_provider(id = provider_id, **undo)
+ except Exception:
+ logger.exception("provider.update_metadata_rollback_failed", provider_id = provider_id)
+
with current_credential_write(credential):
if metadata_requested:
- metadata_updates = dict(
- id = provider_id,
- display_name = payload.display_name,
- base_url = base_url,
- is_enabled = payload.is_enabled,
- models = payload.models,
- available_models = payload.available_models,
- )
- if max_output_tokens_requested:
- metadata_updates["max_output_tokens"] = payload.max_output_tokens
providers_db.update_provider(**metadata_updates)
try:
if replacement_api_key is not None:
@@ -341,27 +460,32 @@ async def update_provider_config(
elif payload.clear_api_key:
credential_secrets.delete_provider_api_key(provider_id)
except Exception:
- if metadata_requested:
- try:
- providers_db.update_provider(
- id = provider_id,
- display_name = existing["display_name"],
- base_url = existing["base_url"],
- is_enabled = bool(existing["is_enabled"]),
- models = existing.get("models") or [],
- available_models = existing.get("available_models") or [],
- max_output_tokens = existing.get("max_output_tokens"),
- )
- except Exception:
- logger.exception(
- "provider.update_metadata_rollback_failed", provider_id = provider_id
- )
+ _restore_metadata()
raise
if not metadata_requested and not payload.encrypted_api_key and not payload.clear_api_key:
raise HTTPException(status_code = 400, detail = "No fields to update")
row = providers_db.get_provider(provider_id)
+ if existing_info.get("auth_kind") == "chatgpt_oauth" and payload.models is not None:
+ # Record the proof here rather than when a catalog is read: reading one only
+ # shows which account answered, while this is the point where the row's models
+ # were actually judged against it and stored.
+ # The account the selection was judged against, not whatever owns the connection
+ # by now. remember_catalog_account re-reads under the guard and declines to write
+ # when the bundle has moved on, so a rebind in between records nothing.
+ # Written after the row, never before: a proof recorded ahead of a commit that
+ # then failed would license models this connection never saved. Recording it is
+ # part of the save, so a failure here undoes the row too. Leaving the new models
+ # behind without the proof is the state saved_models_proven_for exists to catch,
+ # and it outlives the process: after a restart, with the plan catalog unreadable,
+ # the row's own slugs stop authorizing chat and the next save is refused as well.
+ if validated_account:
+ try:
+ await openai_codex_auth.remember_catalog_account(provider_id, validated_account)
+ except Exception:
+ _restore_metadata()
+ raise
return _provider_response(row)
@@ -441,6 +565,15 @@ async def delete_provider_config(
"provider.delete_credential_rollback_failed", provider_id = provider_id
)
raise
+ # The plan catalog is held per connection in this process and is only
+ # released by forget_subscription_models. Disconnecting the OAuth bundle
+ # calls it, deleting the whole connection did not, so every ChatGPT
+ # connection a user removed left its catalog, its account marker and its
+ # request ticket behind for the life of the process. Ids come from uuid4 and
+ # are never reused, so nothing stale could be consulted again; it simply
+ # accumulated. Released here, after the row is gone for good, so a rolled
+ # back delete keeps the catalog it is about to need again.
+ openai_codex_client.forget_subscription_models(provider_id)
def _bind_saved_provider_target(payload):
diff --git a/studio/backend/tests/test_credential_routes.py b/studio/backend/tests/test_credential_routes.py
index 3f5cad3bbc4..0e2e3d1966c 100644
--- a/studio/backend/tests/test_credential_routes.py
+++ b/studio/backend/tests/test_credential_routes.py
@@ -8,6 +8,7 @@ from contextlib import contextmanager
import asyncio
import importlib.util
import sys
+import time
import types
from pathlib import Path
@@ -622,3 +623,695 @@ def test_hugging_face_secret_routes_reject_api_key_authentication():
via_api_key = True,
)
assert delete_error.value.status_code == 403
+
+
+def test_codex_update_refreshes_the_plan_catalog_before_validating(monkeypatch):
+ """A save must not reject a slug the plan lists just because this process forgot it.
+
+ The catalog lives in memory, so a restart between the picker's fetch and this save
+ leaves it empty; the update path refreshes it on the same terms as the chat gate.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ listed = "gpt-5.7-nova"
+ codex_client.forget_subscription_models(created.id)
+
+ async def _no_catalog(_provider_id):
+ return set()
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_client, "ensure_subscription_models", _no_catalog
+ )
+ with pytest.raises(HTTPException) as refused:
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert refused.value.status_code == 400
+
+ async def _refresh(provider_id):
+ codex_client._offered_models[provider_id] = {
+ listed: {"id": listed, "display_name": listed, "vision": None, "listed": True}
+ }
+ return {listed}
+
+ monkeypatch.setattr(providers_route.openai_codex_client, "ensure_subscription_models", _refresh)
+ try:
+ updated = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert updated.models == [listed]
+ finally:
+ codex_client.forget_subscription_models(created.id)
+
+
+def test_codex_update_of_seed_models_never_reaches_upstream(monkeypatch):
+ """A curated-only save must not wait on /codex/models when upstream is down."""
+ from core.inference import openai_codex_client as codex_client
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ codex_client.forget_subscription_models(created.id)
+ calls = []
+
+ async def _refresh(provider_id):
+ calls.append(provider_id)
+ return set()
+
+ monkeypatch.setattr(providers_route.openai_codex_client, "ensure_subscription_models", _refresh)
+ updated = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = ["gpt-5.4", "gpt-5.5"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert updated.models == ["gpt-5.4", "gpt-5.5"]
+ assert calls == []
+
+
+def test_codex_unrelated_edit_survives_an_unreachable_catalog(monkeypatch):
+ """Renaming a connection must not need ChatGPT to be reachable.
+
+ The saved selection was proven when it was first accepted, and the picker
+ deliberately preserves it through a curated fallback, so refusing the save during an
+ outage would strand the row.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ listed = "gpt-5.7-nova"
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+
+ async def _refresh(provider_id):
+ codex_client._offered_models[provider_id] = {listed: {"id": listed, "listed": True}}
+ return {listed}
+
+ monkeypatch.setattr(providers_route.openai_codex_client, "ensure_subscription_models", _refresh)
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ codex_client.forget_subscription_models(created.id)
+
+ calls = []
+
+ async def _unreachable(provider_id):
+ calls.append(provider_id)
+ return set()
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_client, "ensure_subscription_models", _unreachable
+ )
+ try:
+ renamed = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(display_name = "Work account", models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert renamed.display_name == "Work account"
+ assert renamed.models == [listed]
+ # The slug was already on the row, so nothing had to be proven upstream.
+ assert calls == []
+
+ # A slug that was never saved here still needs the catalog.
+ with pytest.raises(HTTPException) as refused:
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = [listed, "gpt-5.9-unheard-of"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert refused.value.status_code == 400
+ assert calls == [created.id]
+ finally:
+ codex_client.forget_subscription_models(created.id)
+
+
+def test_codex_save_refuses_a_seed_the_plan_catalog_omits(monkeypatch):
+ """Save and chat must judge on the same evidence.
+
+ The inference route treats a known plan catalog as authoritative, so accepting a
+ seed it omits here would persist a model that every send then refuses.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+
+ async def _no_refresh(_provider_id):
+ return set()
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_client, "ensure_subscription_models", _no_refresh
+ )
+ codex_client.forget_subscription_models(created.id)
+ codex_client._offered_models[created.id] = {"gpt-5.5": {"id": "gpt-5.5", "listed": True}}
+ try:
+ with pytest.raises(HTTPException) as refused:
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = ["gpt-5.4"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert refused.value.status_code == 400
+
+ kept = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = ["gpt-5.5"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert kept.models == ["gpt-5.5"]
+ finally:
+ codex_client.forget_subscription_models(created.id)
+
+
+def test_codex_save_refuses_a_row_the_account_cannot_vouch_for(monkeypatch):
+ """A cold worker must not save account A's slugs under account B.
+
+ The form submits the whole selection with any edit, so an ordinary rename carries the
+ saved slugs with it. The inference route already refuses them, so accepting here
+ would persist exactly what every send then rejects.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ listed = "gpt-5.7-nova"
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+
+ async def _refresh(provider_id):
+ codex_client._offered_models[provider_id] = {listed: {"id": listed, "listed": True}}
+ return {listed}
+
+ monkeypatch.setattr(providers_route.openai_codex_client, "ensure_subscription_models", _refresh)
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ codex_client.forget_subscription_models(created.id)
+
+ async def _no_refresh(_provider_id):
+ return set()
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_client, "ensure_subscription_models", _no_refresh
+ )
+ # Cold worker, and the credentials carry no proof for this account.
+ monkeypatch.setattr(
+ providers_route.openai_codex_auth,
+ "load_oauth_bundle",
+ lambda _pid: {"account_id": "acct-b"},
+ )
+ try:
+ with pytest.raises(HTTPException) as refused:
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(display_name = "Renamed", models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert refused.value.status_code == 400
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_auth,
+ "load_oauth_bundle",
+ lambda _pid: {"account_id": "acct-b", "catalog_account_id": "acct-b"},
+ )
+ renamed = asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(display_name = "Renamed", models = [listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert renamed.display_name == "Renamed"
+ assert renamed.models == [listed]
+ finally:
+ codex_client.forget_subscription_models(created.id)
+
+
+def test_codex_save_records_the_account_it_validated_against(monkeypatch):
+ """Saving the row is what proves it, so that is where the proof is written."""
+ from core.inference import openai_codex_client as codex_client
+
+ recorded = []
+
+ async def _remember(provider_id, account_id):
+ recorded.append((provider_id, account_id))
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_auth,
+ "load_oauth_bundle",
+ lambda _pid: {"account_id": "acct-1", "catalog_account_id": "acct-1"},
+ )
+ monkeypatch.setattr(providers_route.openai_codex_auth, "remember_catalog_account", _remember)
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ # Creating does not record: there is no connection behind it yet.
+ assert recorded == []
+
+ codex_client.forget_subscription_models(created.id)
+ try:
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = ["gpt-5.4", "gpt-5.5"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert recorded == [(created.id, "acct-1")]
+
+ # A metadata-only edit carries no selection, so it proves nothing new.
+ recorded.clear()
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(display_name = "Renamed"),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert recorded == []
+ finally:
+ codex_client.forget_subscription_models(created.id)
+
+
+def test_codex_save_that_cannot_record_its_proof_keeps_nothing(monkeypatch):
+ """A save is the row and the proof together, so half of it must not survive.
+
+ provider_oauth_write_guard is a 30s flock and _token_request's httpx timeout is
+ per-phase, not a total budget, so a refresh holding the guard across a stalled token
+ request makes remember_catalog_account raise after update_provider has already
+ committed. Without a rollback the row keeps models nothing on disk says were ever
+ validated, and that outlives the process: with the plan catalog gone after a restart
+ and upstream unreachable, saved_models_proven_for answers False, so chat falls back to
+ the seed and even an ordinary rename is refused.
+ """
+ import json
+
+ from core.inference import openai_codex_auth as codex_auth
+ from core.inference import openai_codex_client as codex_client
+
+ listed = "gpt-5-codex-max" # dynamic: carried by the plan, absent from the seed
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ provider_id = created.id
+
+ credential_secrets.get_or_create_credential_encryption_key()
+ credential_secrets.upsert_secret(
+ credential_secrets.OPENAI_CODEX_OAUTH_KIND,
+ provider_id,
+ json.dumps(
+ {
+ "access_token": "at",
+ "refresh_token": "rt",
+ "expires_at": int(time.time()) + 3600,
+ "account_id": "acct-1",
+ }
+ ),
+ )
+ codex_client._offered_models[provider_id] = {
+ "gpt-5.4": {"id": "gpt-5.4", "listed": True},
+ listed: {"id": listed, "listed": True},
+ }
+ codex_client._catalog_accounts[provider_id] = "acct-1"
+
+ async def _guard_busy(_provider_id, _account_id):
+ raise codex_auth.CodexAuthError("ChatGPT credential update is busy. Please retry.")
+
+ monkeypatch.setattr(providers_route.openai_codex_auth, "remember_catalog_account", _guard_busy)
+
+ try:
+ with pytest.raises(codex_auth.CodexAuthError):
+ asyncio.run(
+ providers_route.update_provider_config(
+ provider_id,
+ ProviderUpdate(models = ["gpt-5.4", listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+
+ # The reported failure and the stored row agree: neither half landed.
+ row = providers_db.get_provider(provider_id)
+ assert row["models"] == ["gpt-5.4"]
+ bundle = codex_auth.load_oauth_bundle(provider_id)
+ assert bundle is not None and bundle.get("catalog_account_id") is None
+
+ # Restart: the catalog is per process, the row and the bundle are not.
+ codex_client.forget_subscription_models(provider_id)
+ assert not codex_client.subscription_catalog_known(provider_id)
+
+ # The row carries no slug the seed cannot vouch for, so an unrelated edit still
+ # saves with upstream unreachable. Left torn, this is a 400.
+ async def _unreachable(_provider_id):
+ return set()
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_client, "ensure_subscription_models", _unreachable
+ )
+ recorded = []
+
+ async def _remember(pid, account_id):
+ recorded.append((pid, account_id))
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_auth, "remember_catalog_account", _remember
+ )
+ renamed = asyncio.run(
+ providers_route.update_provider_config(
+ provider_id,
+ ProviderUpdate(display_name = "Renamed", models = ["gpt-5.4"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert renamed.display_name == "Renamed"
+ assert renamed.models == ["gpt-5.4"]
+ assert recorded == [(provider_id, "acct-1")]
+ finally:
+ codex_client.forget_subscription_models(provider_id)
+
+
+def test_codex_save_records_only_the_account_it_actually_validated(monkeypatch):
+ """A rebind between validating and recording must not stamp the new account.
+
+ remember_catalog_account writes only when the bundle still names the account handed
+ to it, so passing the one validation used is what makes the record honest.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ recorded = []
+
+ async def _remember(provider_id, account_id):
+ recorded.append((provider_id, account_id))
+
+ lookups = []
+
+ def _bundle(_pid):
+ lookups.append(1)
+ # The first read is the one this request judges by; a rebind lands after it, so
+ # every later read of the connection names the new account.
+ return {"account_id": "acct-a" if len(lookups) == 1 else "acct-b"}
+
+ monkeypatch.setattr(providers_route.openai_codex_auth, "load_oauth_bundle", _bundle)
+ monkeypatch.setattr(providers_route.openai_codex_auth, "remember_catalog_account", _remember)
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ codex_client.forget_subscription_models(created.id)
+ lookups.clear()
+ try:
+ asyncio.run(
+ providers_route.update_provider_config(
+ created.id,
+ ProviderUpdate(models = ["gpt-5.4"]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ assert recorded == [(created.id, "acct-a")]
+ finally:
+ codex_client.forget_subscription_models(created.id)
+
+
+def test_deleting_a_codex_connection_releases_its_plan_catalog():
+ """The catalog is per connection and per process, so the delete has to release it.
+
+ Disconnecting the OAuth bundle goes through forget_subscription_models; deleting the
+ whole connection took a different path and left the catalog, the account marker and
+ the request ticket behind for the life of the process. Provider ids come from uuid4,
+ so nothing stale was ever consulted again, but nothing reclaimed it either and a user
+ who adds and removes connections grew the maps without bound.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "ChatGPT subscription",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ provider_id = created.id
+ models = [{"id": "gpt-5.4", "display_name": "GPT-5.4", "listed": True}]
+ codex_client._models_cache[provider_id] = (time.time() + 600, models)
+ codex_client._offered_models[provider_id] = {model["id"]: model for model in models}
+ codex_client._catalog_accounts[provider_id] = "acct-1"
+ codex_client.mark_subscription_catalog_stale(provider_id)
+ codex_client._begin_catalog_request(provider_id)
+ assert codex_client.subscription_catalog_known(provider_id) is True
+
+ try:
+ asyncio.run(
+ providers_route.delete_provider_config(
+ provider_id, credential = ("alice", None), via_api_key = False
+ )
+ )
+ assert providers_db.get_provider(provider_id) is None
+ assert provider_id not in codex_client._models_cache
+ assert provider_id not in codex_client._offered_models
+ assert provider_id not in codex_client._catalog_accounts
+ assert provider_id not in codex_client._stale_catalogs
+ assert provider_id not in codex_client._catalog_requests
+ assert codex_client.subscription_catalog_known(provider_id) is False
+ assert codex_client.offered_subscription_model_ids(provider_id) == set()
+ finally:
+ codex_client.forget_subscription_models(provider_id)
+
+
+def test_a_released_connection_leaves_no_ticket_but_still_retires_its_read():
+ """forget_subscription_models drops the ticket rather than bumping it.
+
+ The counter is shared by every connection, so a number is never reissued and an
+ outstanding read cannot be matched by whatever starts next. Keeping a per-connection
+ entry alive purely to hold the high-water mark was the last thing the release path
+ could not reclaim.
+ """
+ from core.inference import openai_codex_client as codex_client
+
+ ticket = codex_client._begin_catalog_request("released-connection")
+ codex_client.forget_subscription_models("released-connection")
+ assert "released-connection" not in codex_client._catalog_requests
+ # The read that was in flight when the connection went away must still decline.
+ assert codex_client._catalog_requests.get("released-connection") != ticket
+ # A later read anywhere draws a number the retired one cannot be holding.
+ assert codex_client._begin_catalog_request("another-connection") > ticket
+ assert codex_client._begin_catalog_request("released-connection") != ticket
+ codex_client.forget_subscription_models("released-connection")
+ codex_client.forget_subscription_models("another-connection")
+
+
+def test_codex_proof_rollback_leaves_a_concurrent_save_alone(monkeypatch):
+ """The undo takes back this request's write, not whatever the row says by then.
+
+ update_provider_config suspends between committing the row and recording the proof:
+ remember_catalog_account awaits a 30s file lock, and the failure the rollback exists
+ for is exactly the one where that lock was contended. A save the user makes during
+ those seconds commits in between. Restoring the whole pre-request snapshot would put
+ the row back to before *both* requests and erase the second one's successful edit.
+ """
+ import json
+
+ from core.inference import openai_codex_auth as codex_auth
+ from core.inference import openai_codex_client as codex_client
+
+ listed = "gpt-5-codex-max" # dynamic: carried by the plan, absent from the seed
+ created = asyncio.run(
+ providers_route.create_provider_config(
+ ProviderCreate(
+ provider_type = "openai_codex",
+ display_name = "Original name",
+ models = ["gpt-5.4"],
+ ),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ provider_id = created.id
+
+ credential_secrets.get_or_create_credential_encryption_key()
+ credential_secrets.upsert_secret(
+ credential_secrets.OPENAI_CODEX_OAUTH_KIND,
+ provider_id,
+ json.dumps(
+ {
+ "access_token": "at",
+ "refresh_token": "rt",
+ "expires_at": int(time.time()) + 3600,
+ "account_id": "acct-1",
+ }
+ ),
+ )
+ codex_client._offered_models[provider_id] = {
+ "gpt-5.4": {"id": "gpt-5.4", "listed": True},
+ listed: {"id": listed, "listed": True},
+ }
+ codex_client._catalog_accounts[provider_id] = "acct-1"
+
+ gate = asyncio.Event()
+
+ async def _blocked_then_busy(_provider_id, _account_id):
+ # Stands in for provider_oauth_write_guard's flock acquire: a real suspension
+ # point, then the timeout it raises.
+ await gate.wait()
+ raise codex_auth.CodexAuthError("ChatGPT credential update is busy. Please retry.")
+
+ monkeypatch.setattr(
+ providers_route.openai_codex_auth, "remember_catalog_account", _blocked_then_busy
+ )
+
+ async def _overlapping_saves():
+ adds_a_model = asyncio.ensure_future(
+ providers_route.update_provider_config(
+ provider_id,
+ ProviderUpdate(models = ["gpt-5.4", listed]),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+ )
+ for _ in range(100):
+ await asyncio.sleep(0)
+ if gate._waiters:
+ break
+ # Its row is committed and it is now parked in remember_catalog_account.
+ assert providers_db.get_provider(provider_id)["models"] == ["gpt-5.4", listed]
+
+ # The user saves again while that one hangs. This one has no selection of its
+ # own, so it records no proof and completes.
+ await providers_route.update_provider_config(
+ provider_id,
+ ProviderUpdate(display_name = "Renamed while the first save hung"),
+ credential = ("alice", None),
+ via_api_key = False,
+ )
+
+ gate.set()
+ with pytest.raises(codex_auth.CodexAuthError):
+ await adds_a_model
+
+ try:
+ asyncio.run(_overlapping_saves())
+
+ row = providers_db.get_provider(provider_id)
+ # The rename was never in doubt, and nothing it did needs undoing.
+ assert row["display_name"] == "Renamed while the first save hung"
+ # The unproven model still goes back: that half of the failed save is this
+ # request's own, and no one else claimed the column.
+ assert row["models"] == ["gpt-5.4"]
+ bundle = codex_auth.load_oauth_bundle(provider_id)
+ assert bundle is not None and bundle.get("catalog_account_id") is None
+ finally:
+ codex_client.forget_subscription_models(provider_id)
diff --git a/studio/backend/tests/test_openai_codex_subscription.py b/studio/backend/tests/test_openai_codex_subscription.py
index 6ee08f8abd2..6ae69a9332f 100644
--- a/studio/backend/tests/test_openai_codex_subscription.py
+++ b/studio/backend/tests/test_openai_codex_subscription.py
@@ -12,7 +12,7 @@ from pathlib import Path
import sys
import threading
-from types import ModuleType
+from types import ModuleType, SimpleNamespace
import asyncio
import hashlib
import json
@@ -38,7 +38,12 @@ from core.inference.openai_codex_client import (
CodexTransportError,
OpenAICodexClient,
_responses_input,
+ cached_subscription_models,
+ forget_subscription_models,
+ list_subscription_models,
+ offered_subscription_model_ids,
)
+from core.inference import openai_codex_client as codex_client
from core.inference.openai_responses_shared import normalize_function_schema
from core.inference.providers import get_provider_info, list_available_providers
@@ -58,7 +63,6 @@ def test_protocol_constants_and_curated_provider_contract():
assert info["base_url_editable"] is False
assert info["model_ids_editable"] is False
assert info["default_models"] == [
- "gpt-5.3-codex-spark",
"gpt-5.4",
"gpt-5.4-mini",
"gpt-5.5",
@@ -728,6 +732,298 @@ def test_structured_upstream_error_is_actionable_and_bounded():
assert "secret-token" not in str(error.value)
+def test_bare_detail_upstream_error_reaches_the_user():
+ """The subscription endpoint reports a rejected model as a bare "detail"."""
+
+ class FakeStream:
+ async def __aenter__(self):
+ return __import__("httpx").Response(
+ 400,
+ json = {
+ "detail": (
+ "The 'gpt-5.3-codex-spark' model is not supported when using "
+ "Codex with a ChatGPT account."
+ )
+ },
+ )
+
+ async def __aexit__(self, *_args):
+ return False
+
+ class FakeClient:
+ def stream(self, *_args, **_kwargs):
+ return FakeStream()
+
+ async def aclose(self):
+ return None
+
+ async def run():
+ client = OpenAICodexClient("secret-token", "acct-1")
+ await client._client.aclose()
+ client._client = FakeClient()
+ try:
+ return [
+ line
+ async for line in client.stream(
+ provider_id = "provider",
+ thread_id = "thread",
+ messages = [{"role": "user", "content": "hello"}],
+ model = "gpt-5.3-codex-spark",
+ max_tokens = None,
+ reasoning_effort = None,
+ tools = None,
+ tool_choice = None,
+ )
+ ]
+ finally:
+ await client.close()
+
+ with pytest.raises(CodexTransportError) as error:
+ asyncio.run(run())
+ assert error.value.status == 400
+ assert "is not supported" in str(error.value)
+ assert "secret-token" not in str(error.value)
+
+
+def _models_response(payload, status = 200):
+ import httpx
+ class FakeClient:
+ def __init__(self):
+ self.calls = []
+
+ async def get(
+ self,
+ url,
+ headers = None,
+ params = None,
+ ):
+ self.calls.append((url, params))
+ return httpx.Response(status, json = payload)
+
+ async def aclose(self):
+ return None
+
+ return FakeClient()
+
+
+def test_subscription_model_list_keeps_only_listable_slugs(monkeypatch):
+ fake = _models_response(
+ {
+ "models": [
+ {
+ "slug": "gpt-5.4",
+ "visibility": "list",
+ "display_name": "GPT-5.4",
+ "context_window": 272000,
+ "input_modalities": ["text", "image"],
+ "supported_reasoning_levels": [
+ {"effort": "low"},
+ {"effort": "high"},
+ ],
+ },
+ # Internal review slug the picker must never offer.
+ {"slug": "codex-auto-review", "visibility": "hide"},
+ {"slug": "", "visibility": "list"},
+ "not-a-model",
+ ]
+ }
+ )
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("provider-1")
+
+ models = asyncio.run(list_subscription_models("provider-1", "secret-token", "acct-1"))
+
+ assert models == [
+ {
+ "id": "gpt-5.4",
+ "display_name": "GPT-5.4",
+ "context_length": 272000,
+ "vision": True,
+ "reasoning_efforts": ["low", "high"],
+ "listed": True,
+ },
+ # Kept and marked, not dropped: an account can still call a slug it saved while
+ # the slug was listed, and only the picker needs to stop offering it.
+ {
+ "id": "codex-auto-review",
+ "display_name": "codex-auto-review",
+ "context_length": None,
+ "vision": None,
+ "reasoning_efforts": [],
+ "listed": False,
+ },
+ ]
+ assert fake.calls[0][0] == f"{OPENAI_CODEX_API_BASE}/codex/models"
+ assert fake.calls[0][1] == {"client_version": codex_auth.OPENAI_CODEX_CLIENT_VERSION}
+ # A second call is served from cache rather than re-hitting upstream.
+ assert asyncio.run(list_subscription_models("provider-1", "secret-token", "acct-1")) == models
+ assert len(fake.calls) == 1
+ # Outlives the cache so a slow save is still accepted by the provider routes.
+ # Cached for its metadata, but a hidden slug is not authorized by the fetch alone.
+ assert offered_subscription_model_ids("provider-1") == {"gpt-5.4"}
+ assert codex_client.offered_subscription_model("provider-1", "codex-auto-review") is not None
+ forget_subscription_models("provider-1")
+ assert cached_subscription_models("provider-1") is None
+ assert offered_subscription_model_ids("provider-1") == set()
+
+
+def test_subscription_catalog_is_dropped_when_the_account_changes(monkeypatch):
+ """A reconnect can bind the same provider row to a different ChatGPT account.
+
+ Nothing on the reauthorization path clears the catalog, so a lookup keyed only by
+ provider would keep serving the previous plan's slugs for the whole TTL.
+ """
+ first = _models_response({"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: first)
+ forget_subscription_models("provider-4")
+ asyncio.run(list_subscription_models("provider-4", "token-a", "acct-a"))
+ assert offered_subscription_model_ids("provider-4") == {"gpt-5.4"}
+
+ second = _models_response({"models": [{"slug": "gpt-5.5", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: second)
+ # Same provider, new account: the stale catalog must not be served from cache.
+ models = asyncio.run(list_subscription_models("provider-4", "token-b", "acct-b"))
+ assert [model["id"] for model in models] == ["gpt-5.5"]
+ assert offered_subscription_model_ids("provider-4") == {"gpt-5.5"}
+ assert len(second.calls) == 1
+ forget_subscription_models("provider-4")
+
+
+def test_persisting_a_new_account_drops_the_plan_catalog(monkeypatch):
+ """Rebinding a connection to another ChatGPT account retires its catalog at once.
+
+ The user can leave the form before the browser callback lands, so the post-connect
+ picker refresh never runs, and the chat gate only refetches a catalog it does not
+ already have. Nothing else would notice the account changed.
+ """
+ stored = {}
+
+ monkeypatch.setattr(
+ codex_auth.credential_secrets,
+ "upsert_secret",
+ lambda _kind, provider_id, raw: stored.__setitem__(provider_id, raw),
+ )
+ monkeypatch.setattr(
+ codex_auth.credential_secrets,
+ "get_secret",
+ lambda _kind, provider_id: stored.get(provider_id),
+ )
+
+ def _bundle(account_id):
+ return {
+ "access_token": "token",
+ "refresh_token": "refresh",
+ "expires_at": 1,
+ "account_id": account_id,
+ }
+
+ codex_auth.save_oauth_bundle("provider-5", _bundle("acct-a"))
+ codex_client._offered_models["provider-5"] = {
+ "gpt-5.7-nova": {"id": "gpt-5.7-nova", "listed": True}
+ }
+ try:
+ # A refresh for the same account keeps it: only the account identity matters.
+ codex_auth.save_oauth_bundle("provider-5", _bundle("acct-a"))
+ assert offered_subscription_model_ids("provider-5") == {"gpt-5.7-nova"}
+
+ codex_auth.save_oauth_bundle("provider-5", _bundle("acct-b"))
+ assert offered_subscription_model_ids("provider-5") == set()
+ finally:
+ forget_subscription_models("provider-5")
+
+
+def test_a_forced_reload_skips_the_cached_catalog(monkeypatch):
+ """An explicit reload asks about plan changes, so the 600s cache must not answer it."""
+ first = _models_response({"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: first)
+ forget_subscription_models("provider-6")
+ asyncio.run(list_subscription_models("provider-6", "token", "acct-1"))
+ assert len(first.calls) == 1
+
+ second = _models_response({"models": [{"slug": "gpt-5.8-new", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: second)
+ try:
+ # Unforced, the fresh slug stays invisible for the rest of the TTL.
+ cached = asyncio.run(list_subscription_models("provider-6", "token", "acct-1"))
+ assert [model["id"] for model in cached] == ["gpt-5.4"]
+ assert len(second.calls) == 0
+
+ reloaded = asyncio.run(
+ list_subscription_models("provider-6", "token", "acct-1", force = True)
+ )
+ assert [model["id"] for model in reloaded] == ["gpt-5.8-new"]
+ assert len(second.calls) == 1
+ # The refreshed catalog replaces what the picker and the chat gate read.
+ assert offered_subscription_model_ids("provider-6") == {"gpt-5.8-new"}
+ finally:
+ forget_subscription_models("provider-6")
+
+
+def test_subscription_model_list_rejects_non_200(monkeypatch):
+ monkeypatch.setattr(
+ codex_client,
+ "_create_http_client",
+ lambda: _models_response({"detail": "Not Found"}, status = 404),
+ )
+ forget_subscription_models("provider-2")
+
+ with pytest.raises(CodexTransportError) as error:
+ asyncio.run(list_subscription_models("provider-2", "secret-token", "acct-1"))
+ assert error.value.status == 404
+ assert "secret-token" not in str(error.value)
+ assert cached_subscription_models("provider-2") is None
+
+
+def test_model_route_falls_back_to_curated_when_upstream_is_unusable(monkeypatch):
+ from routes import openai_codex_auth as codex_routes
+
+ curated = get_provider_info("openai_codex")["default_models"]
+ monkeypatch.setattr(codex_routes, "_provider", lambda provider_id: {"id": provider_id})
+
+ def call():
+ return asyncio.run(
+ codex_routes.list_subscription_models(
+ "provider-3", _credential = ("user", "session"), via_api_key = False
+ )
+ )
+
+ monkeypatch.setattr(codex_routes.codex_auth, "auth_status", lambda _id: "disconnected")
+ disconnected = call()
+ assert disconnected["source"] == "curated"
+ assert [model["id"] for model in disconnected["models"]] == curated
+
+ async def _resolve(_provider_id):
+ return "secret-token", "acct-1"
+
+ async def _boom(*_args, **_kwargs):
+ raise CodexTransportError("upstream is down")
+
+ monkeypatch.setattr(codex_routes.codex_auth, "auth_status", lambda _id: "connected")
+ monkeypatch.setattr(codex_routes.codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(codex_routes.codex_client, "list_subscription_models", _boom)
+ assert call()["source"] == "curated"
+
+ async def _models(*_args, **_kwargs):
+ return [
+ {
+ "id": "gpt-5.6-terra",
+ "display_name": "GPT-5.6-Terra",
+ "context_length": 272000,
+ "listed": True,
+ },
+ # Present on the plan but not offered: reported as known, never in the picker.
+ {"id": "codex-auto-review", "display_name": "codex-auto-review", "listed": False},
+ ]
+
+ monkeypatch.setattr(codex_routes.codex_client, "list_subscription_models", _models)
+ live = call()
+ assert live["source"] == "subscription"
+ assert [model["id"] for model in live["models"]] == ["gpt-5.6-terra"]
+ assert [model["id"] for model in live["known"]] == ["gpt-5.6-terra", "codex-auto-review"]
+ # The hidden entry keeps its metadata so the picker can still describe it.
+ assert live["known"][1]["display_name"] == "codex-auto-review"
+
+
def test_client_never_emits_done_marker_itself():
# The route owns the one Chat-Completions [DONE] marker.
assert not any("[DONE]" in line for line in asyncio.run(_successful_stream_lines()))
@@ -1186,3 +1482,1369 @@ def test_codex_tool_budget_resolves_parallel_overflow_without_executing_it(monke
# are no longer the tail of the conversation.
assert replayed[-1]["role"] == "user"
assert "provide your final answer now" in replayed[-1]["content"]
+
+
+def _codex_chat_gate(
+ monkeypatch,
+ model: str,
+ resolve = None,
+ saved_models = None,
+):
+ """Drive the chat route far enough to answer "may this model be used?".
+
+ The gate is one line inside ``_proxy_to_external_provider`` and is only
+ reachable through the route, so the access resolver is stubbed to raise: a
+ 401 means the model was accepted and the request moved on, a 400 means it
+ was refused.
+ """
+ from fastapi import HTTPException
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inf
+
+ monkeypatch.setattr(
+ inf.providers_db,
+ "get_provider",
+ lambda _pid: {
+ "id": _pid,
+ "provider_type": "openai_codex",
+ "base_url": OPENAI_CODEX_API_BASE,
+ "display_name": "ChatGPT subscription",
+ "is_enabled": True,
+ "models": list(saved_models or []),
+ },
+ )
+
+ async def _refuse(*_args, **_kwargs):
+ raise codex_auth.CodexAuthError("stub: past the model gate")
+
+ monkeypatch.setattr(codex_auth, "resolve_access", resolve or _refuse)
+
+ async def _is_disconnected():
+ return False
+
+ request = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ is_disconnected = _is_disconnected,
+ )
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "hello"}],
+ provider_id = "codex-1",
+ external_model = model,
+ stream = True,
+ )
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inf._proxy_to_external_provider(payload, request, current_subject = "t"))
+ return excinfo.value
+
+
+def test_chat_accepts_a_plan_listed_slug_the_seed_does_not_carry(monkeypatch):
+ """A slug the picker offered and the provider routes saved must be chattable.
+
+ ``/codex/models`` is the truth once connected, so a plan can list a model
+ newer than the curated seed. The provider routes accept saving it; gating
+ the chat route on the seed alone would reject the very model the user just
+ picked, on every message.
+ """
+ listed = "gpt-5.7-nova"
+ assert listed not in get_provider_info("openai_codex")["default_models"]
+
+ # A catalog that simply does not list it: the refusal is about the model, not the
+ # connection, so the gate never reaches for a refresh.
+ forget_subscription_models("codex-1")
+ codex_client._offered_models["codex-1"] = {"gpt-5.4": {"id": "gpt-5.4", "listed": True}}
+ refused = _codex_chat_gate(monkeypatch, listed)
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+
+ # Exactly what a picker fetch records for this connection.
+ codex_client._offered_models["codex-1"] = {
+ listed: {"id": listed, "display_name": listed, "vision": True, "listed": True}
+ }
+ try:
+ accepted = _codex_chat_gate(monkeypatch, listed)
+ assert accepted.status_code == 401, accepted.detail
+ assert "Choose a curated Codex model." not in str(accepted.detail)
+ # A slug no plan ever listed is still refused.
+ never_listed = _codex_chat_gate(monkeypatch, "gpt-5.3-codex-spark")
+ assert never_listed.status_code == 400
+ assert "Choose a curated Codex model." in str(never_listed.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_refetches_the_plan_catalog_after_a_restart(monkeypatch):
+ """A restart empties the in-memory catalog; the saved slug must still work.
+
+ Nothing refetches /codex/models on startup, so gating on the seed alone would
+ reject a model the user legitimately saved until they reopened the connection
+ editor.
+ """
+ listed = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+
+ calls = []
+
+ async def _resolve(_provider_id):
+ calls.append(_provider_id)
+ # The gate's refresh resolves first; the chat path's own call then stops
+ # the request before it can reach upstream.
+ if len(calls) > 1:
+ raise codex_auth.CodexAuthError("stub: past the model gate")
+ return "secret-token", "acct-1"
+
+ fake = _models_response(
+ {"models": [{"slug": listed, "visibility": "list", "input_modalities": ["text"]}]}
+ )
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ try:
+ # Cold cache, exactly as after a restart: the gate fetches rather than refusing.
+ accepted = _codex_chat_gate(monkeypatch, listed, resolve = _resolve)
+ assert accepted.status_code == 401, accepted.detail
+ assert offered_subscription_model_ids("codex-1") == {listed}
+ assert len(calls) == 2
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_refuses_when_the_catalog_cannot_be_refreshed(monkeypatch):
+ """An unreachable catalog refuses the model; it does not declare the connection bad."""
+ import httpx
+
+ forget_subscription_models("codex-1")
+
+ async def _resolve(_provider_id):
+ return "secret-token", "acct-1"
+
+ class Unreachable:
+ async def get(self, *_args, **_kwargs):
+ raise httpx.ConnectError("upstream down")
+
+ async def aclose(self):
+ return None
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Unreachable())
+ try:
+ refused = _codex_chat_gate(monkeypatch, "gpt-5.7-nova", resolve = _resolve)
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_asks_for_reconnection_rather_than_another_model(monkeypatch):
+ """A dead connection is not a bad model choice, and the message has to say so.
+
+ The catalog is unreadable because the credentials are, so refusing with "choose a
+ curated model" would send the user to fix a selection that may be perfectly valid.
+ """
+ forget_subscription_models("codex-1")
+
+ async def _needs_reauth(_provider_id):
+ raise codex_auth.CodexAuthError("ChatGPT authorization expired. Reconnect.")
+
+ try:
+ refused = _codex_chat_gate(monkeypatch, "gpt-5.7-nova", resolve = _needs_reauth)
+ assert refused.status_code == 401
+ assert "Reconnect" in str(refused.detail)
+ assert "Choose a curated Codex model." not in str(refused.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_reads_vision_support_from_the_plan_catalog(monkeypatch):
+ """A dynamic slug's image support comes from /codex/models, not the static registry."""
+ from fastapi import HTTPException
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inf
+
+ listed = "gpt-5.7-nova"
+ assert listed not in get_provider_info("openai_codex")["model_capabilities"]
+
+ monkeypatch.setattr(
+ inf.providers_db,
+ "get_provider",
+ lambda _pid: {
+ "id": _pid,
+ "provider_type": "openai_codex",
+ "base_url": OPENAI_CODEX_API_BASE,
+ "display_name": "ChatGPT subscription",
+ "is_enabled": True,
+ },
+ )
+
+ async def _refuse(*_args, **_kwargs):
+ raise codex_auth.CodexAuthError("stub: past the image gate")
+
+ monkeypatch.setattr(codex_auth, "resolve_access", _refuse)
+
+ async def _is_disconnected():
+ return False
+
+ def call():
+ request = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ is_disconnected = _is_disconnected,
+ )
+ payload = ChatCompletionRequest(
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="},
+ },
+ ],
+ }
+ ],
+ provider_id = "codex-1",
+ external_model = listed,
+ stream = True,
+ )
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inf._proxy_to_external_provider(payload, request, current_subject = "t"))
+ return excinfo.value
+
+ codex_client._offered_models["codex-1"] = {
+ listed: {"id": listed, "display_name": listed, "vision": False, "listed": True}
+ }
+ try:
+ refused = call()
+ assert refused.status_code == 400
+ assert "does not accept image input" in str(refused.detail)
+ # The same slug listed as image-capable is carried through to the provider.
+ codex_client._offered_models["codex-1"] = {
+ listed: {"id": listed, "display_name": listed, "vision": True, "listed": True}
+ }
+ accepted = call()
+ assert accepted.status_code == 401, accepted.detail
+ assert "does not accept image input" not in str(accepted.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_keeps_a_saved_slug_the_plan_stopped_listing(monkeypatch):
+ """visibility is how a slug is presented, not whether the account may call it.
+
+ An aged slug flips to "hide" and drops out of the normalized catalog. Rebuilding the
+ allowlist from that catalog alone would refuse a model the user saved while it was
+ listed and may still be using.
+ """
+ hidden = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+ # The plan still returns it, marked hidden: that is what ageing out of the picker
+ # looks like, as opposed to a slug the account cannot reach at all.
+ codex_client._offered_models["codex-1"] = {
+ "gpt-5.4": {"id": "gpt-5.4", "listed": True},
+ hidden: {"id": hidden, "listed": False},
+ }
+ try:
+ refused = _codex_chat_gate(monkeypatch, hidden)
+ assert refused.status_code == 400
+
+ accepted = _codex_chat_gate(monkeypatch, hidden, saved_models = [hidden])
+ assert accepted.status_code == 401, accepted.detail
+ assert "Choose a curated Codex model." not in str(accepted.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_retires_a_saved_slug_the_new_account_does_not_carry(monkeypatch):
+ """Reauthorizing to another account is a real revocation, unlike ageing out.
+
+ The saved row still names the previous account's slugs, so trusting it forever would
+ keep sending them upstream on an account that never had them.
+ """
+ stale = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+ try:
+ # No catalog read yet: the row is the only evidence, so it is still trusted.
+ cold = _codex_chat_gate(monkeypatch, stale, saved_models = [stale])
+ assert cold.status_code == 401, cold.detail
+
+ # The new account's catalog does not carry it at all, hidden or otherwise.
+ codex_client._offered_models["codex-1"] = {"gpt-5.5": {"id": "gpt-5.5", "listed": True}}
+ refused = _codex_chat_gate(monkeypatch, stale, saved_models = [stale])
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_reports_reconnection_when_an_image_needs_the_catalog(monkeypatch):
+ """The image gate must not report a text-only model when the connection is dead."""
+ from fastapi import HTTPException
+ from models.inference import ChatCompletionRequest
+ from routes import inference as inf
+
+ saved = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+ monkeypatch.setattr(
+ inf.providers_db,
+ "get_provider",
+ lambda _pid: {
+ "id": _pid,
+ "provider_type": "openai_codex",
+ "base_url": OPENAI_CODEX_API_BASE,
+ "display_name": "ChatGPT subscription",
+ "is_enabled": True,
+ "models": [saved],
+ },
+ )
+
+ async def _needs_reauth(*_args, **_kwargs):
+ raise codex_auth.CodexAuthError("ChatGPT authorization expired. Reconnect.")
+
+ monkeypatch.setattr(codex_auth, "resolve_access", _needs_reauth)
+
+ async def _is_disconnected():
+ return False
+
+ payload = ChatCompletionRequest(
+ messages = [
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="},
+ },
+ ],
+ }
+ ],
+ provider_id = "codex-1",
+ external_model = saved,
+ stream = True,
+ )
+ request = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ is_disconnected = _is_disconnected,
+ )
+ try:
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inf._proxy_to_external_provider(payload, request, current_subject = "t"))
+ assert excinfo.value.status_code == 401
+ assert "does not accept image input" not in str(excinfo.value.detail)
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_a_hidden_slug_is_not_invocable_just_because_the_catalog_was_fetched(monkeypatch):
+ """codex-auto-review and its kin are withheld from the picker on purpose.
+
+ They are cached for their metadata and stay usable on a connection that already
+ carries one, but a catalog fetch alone must not make an internal slug invocable.
+ """
+ hidden = "codex-auto-review"
+ fake = _models_response(
+ {
+ "models": [
+ {"slug": "gpt-5.4", "visibility": "list"},
+ {"slug": hidden, "visibility": "hide"},
+ ]
+ }
+ )
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("codex-1")
+ asyncio.run(list_subscription_models("codex-1", "token", "acct-1"))
+ try:
+ assert offered_subscription_model_ids("codex-1") == {"gpt-5.4"}
+ refused = _codex_chat_gate(monkeypatch, hidden)
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+
+ # Still reachable when the connection already carries it.
+ accepted = _codex_chat_gate(monkeypatch, hidden, saved_models = [hidden])
+ assert accepted.status_code == 401, accepted.detail
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_stops_trusting_the_seed_once_the_plan_catalog_is_known(monkeypatch):
+ """The registry seed bootstraps a connection; it says nothing about this account.
+
+ gpt-5.6-sol is seeded but a Go plan does not carry it, and sending it upstream only
+ to be refused is the failure this PR exists to remove.
+ """
+ seeded = get_provider_info("openai_codex")["default_models"][0]
+ forget_subscription_models("codex-1")
+ try:
+ # Nothing read yet: the seed is all there is, so it is still accepted.
+ cold = _codex_chat_gate(monkeypatch, seeded)
+ assert cold.status_code == 401, cold.detail
+
+ codex_client._offered_models["codex-1"] = {"gpt-5.5": {"id": "gpt-5.5", "listed": True}}
+ refused = _codex_chat_gate(monkeypatch, seeded)
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+
+ accepted = _codex_chat_gate(monkeypatch, "gpt-5.5")
+ assert accepted.status_code == 401, accepted.detail
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_chat_does_not_trust_the_saved_row_after_a_rebind(monkeypatch):
+ """Rebinding empties the catalog on purpose, so absence is not a cold start here."""
+ stale_slug = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+ try:
+ # A plain cold start still trusts the row.
+ cold = _codex_chat_gate(monkeypatch, stale_slug, saved_models = [stale_slug])
+ assert cold.status_code == 401, cold.detail
+
+ # Rebound: the row is not evidence, so the gate reads the new account's catalog
+ # rather than trusting it, and that catalog does not carry the slug.
+ codex_client.mark_subscription_catalog_stale("codex-1")
+
+ async def _resolve(_provider_id):
+ return "secret-token", "acct-b"
+
+ fake = _models_response({"models": [{"slug": "gpt-5.5", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ refused = _codex_chat_gate(
+ monkeypatch, stale_slug, resolve = _resolve, saved_models = [stale_slug]
+ )
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+ assert len(fake.calls) == 1
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_disconnecting_leaves_the_saved_models_unproven(monkeypatch):
+ """A disconnect erases the identity a later save would be compared against.
+
+ The provider row keeps its models, so without a mark here the next account inherits
+ them as cold-start evidence and sends them under its own credentials.
+ """
+ stored = {}
+ monkeypatch.setattr(
+ codex_auth.credential_secrets,
+ "delete_secret",
+ lambda _kind, provider_id: stored.pop(provider_id, None),
+ )
+ forget_subscription_models("provider-7")
+ assert codex_client.subscription_catalog_stale("provider-7") is False
+
+ codex_auth.delete_oauth_bundle("provider-7")
+ assert codex_client.subscription_catalog_stale("provider-7") is True
+ forget_subscription_models("provider-7")
+
+
+def test_evicting_the_response_cache_keeps_authorization_evidence(monkeypatch):
+ """The TTL cache is bounded; what a plan proved about a connection is not.
+
+ Clearing both together made every other connection look cold, which is exactly the
+ state that licenses a saved slug the account no longer carries.
+ """
+ codex_client._models_cache.clear()
+ codex_client._offered_models.clear()
+ codex_client._catalog_accounts.clear()
+ codex_client._offered_models["other"] = {"gpt-5.4": {"id": "gpt-5.4", "listed": True}}
+ codex_client._catalog_accounts["other"] = "acct-other"
+ for filler in range(codex_client._MODELS_CACHE_MAX_ENTRIES):
+ codex_client._models_cache[f"filler-{filler}"] = (time.time() + 600, [])
+
+ fake = _models_response({"models": [{"slug": "gpt-5.5", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ try:
+ asyncio.run(list_subscription_models("provider-8", "token", "acct-8"))
+ assert codex_client.cached_subscription_models("filler-0") is None
+ # The other connection's proof survives the eviction.
+ assert offered_subscription_model_ids("other") == {"gpt-5.4"}
+ assert codex_client._catalog_accounts["other"] == "acct-other"
+ finally:
+ forget_subscription_models("provider-8")
+ forget_subscription_models("other")
+ codex_client._models_cache.clear()
+
+
+def test_a_superseded_catalog_read_does_not_commit(monkeypatch):
+ """A read overtaken by a rebind must not reinstate the account it was reading for.
+
+ Committing late would also clear the mark that says the saved models are unproven,
+ turning a self-correcting state into a sticky one.
+ """
+ import httpx
+
+ forget_subscription_models("provider-9")
+
+ class Rebinding:
+ async def get(self, *_args, **_kwargs):
+ # The rebind lands while this read is out.
+ forget_subscription_models("provider-9")
+ mark = codex_client.mark_subscription_catalog_stale
+ mark("provider-9")
+ return httpx.Response(200, json = {"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+
+ async def aclose(self):
+ return None
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Rebinding())
+ try:
+ models = asyncio.run(list_subscription_models("provider-9", "token-a", "acct-a"))
+ assert [model["id"] for model in models] == ["gpt-5.4"]
+ # Returned to its caller, but never stored over what replaced it.
+ assert codex_client.subscription_catalog_known("provider-9") is False
+ assert codex_client.subscription_catalog_stale("provider-9") is True
+ finally:
+ forget_subscription_models("provider-9")
+
+
+def test_chat_drops_a_catalog_another_worker_rebound(monkeypatch):
+ """The OAuth bundle is shared through the DB; the catalog is per process.
+
+ Studio serializes token refreshes across workers on purpose, so this process can hold
+ a catalog for an account the connection has since moved off.
+ """
+ stale_slug = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+ codex_client._offered_models["codex-1"] = {stale_slug: {"id": stale_slug, "listed": True}}
+ codex_client._catalog_accounts["codex-1"] = "acct-a"
+
+ # What the shared DB now says this connection is bound to.
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-b"})
+ try:
+ refused = _codex_chat_gate(monkeypatch, stale_slug, saved_models = [stale_slug])
+ assert refused.status_code == 401, refused.detail
+ # The catalog for the previous account is gone and the row is unproven again.
+ assert codex_client.subscription_catalog_known("codex-1") is False
+ assert codex_client.subscription_catalog_stale("codex-1") is True
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_the_model_route_reports_a_dead_connection(monkeypatch):
+ """The editor route must say reconnect rather than answer with a healthy seed list."""
+ from routes import openai_codex_auth as codex_routes
+
+ curated = get_provider_info("openai_codex")["default_models"]
+ monkeypatch.setattr(codex_routes, "_provider", lambda provider_id: {"id": provider_id})
+ monkeypatch.setattr(codex_routes.codex_auth, "auth_status", lambda _id: "connected")
+
+ async def _needs_reauth(_provider_id):
+ raise codex_auth.CodexAuthError("ChatGPT authorization is no longer valid.")
+
+ monkeypatch.setattr(codex_routes.codex_auth, "resolve_access", _needs_reauth)
+ answered = asyncio.run(
+ codex_routes.list_subscription_models(
+ "provider-10", _credential = ("user", "session"), via_api_key = False
+ )
+ )
+ # Not a 401: authFetch would read that as an expired Studio session, refresh it and
+ # retry, and the retry would look like a healthy curated list.
+ assert answered["source"] == "reauthorization_required"
+ assert [model["id"] for model in answered["models"]] == curated
+
+
+def test_a_catalog_401_spends_one_forced_refresh(monkeypatch):
+ """Upstream can reject a token before its recorded expiry; the refresh may be fine.
+
+ The responses transport already spends one forced refresh on that, so the editor
+ should not be the only path that gives up and demands a reconnect.
+ """
+ import httpx
+
+ forget_subscription_models("provider-11")
+ calls = []
+
+ class Rejecting:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ calls.append(headers["Authorization"])
+ if len(calls) == 1:
+ return httpx.Response(401, json = {"detail": "expired"})
+ return httpx.Response(200, json = {"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+
+ async def aclose(self):
+ return None
+
+ refreshed = []
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ refreshed.append(force_refresh)
+ return "fresh-token", "acct-1"
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Rejecting())
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ try:
+ models = asyncio.run(list_subscription_models("provider-11", "stale-token", "acct-1"))
+ assert [model["id"] for model in models] == ["gpt-5.4"]
+ assert refreshed == [True]
+ assert calls == ["Bearer stale-token", "Bearer fresh-token"]
+ finally:
+ forget_subscription_models("provider-11")
+
+
+def test_a_second_catalog_401_asks_for_reconnection(monkeypatch):
+ """A refresh that does not help is a real reauthorization, not an endless retry."""
+ import httpx
+
+ forget_subscription_models("provider-12")
+
+ class AlwaysRejecting:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ return httpx.Response(401, json = {"detail": "expired"})
+
+ async def aclose(self):
+ return None
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "fresh-token", "acct-1"
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: AlwaysRejecting())
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ try:
+ with pytest.raises(CodexReauthorizationError):
+ asyncio.run(list_subscription_models("provider-12", "stale-token", "acct-1"))
+ finally:
+ forget_subscription_models("provider-12")
+
+
+def test_a_refresh_that_cannot_be_reached_stays_retryable(monkeypatch):
+ """An unanswered refresh is not a rejected credential.
+
+ resolve_access raises the permanent variant only when the refresh token itself was
+ rejected, so anything else has to stay transient or the user is sent to reconnect a
+ connection whose credentials are fine.
+ """
+ import httpx
+
+ forget_subscription_models("provider-13")
+
+ class Rejecting:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ return httpx.Response(401, json = {"detail": "expired"})
+
+ async def aclose(self):
+ return None
+
+ async def _unreachable(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ raise codex_auth.CodexAuthError("token endpoint unreachable")
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Rejecting())
+ monkeypatch.setattr(codex_auth, "resolve_access", _unreachable)
+ try:
+ with pytest.raises(CodexTransportError) as excinfo:
+ asyncio.run(list_subscription_models("provider-13", "stale", "acct-1"))
+ assert not isinstance(excinfo.value, CodexReauthorizationError)
+ finally:
+ forget_subscription_models("provider-13")
+
+
+def test_a_rejected_refresh_credential_is_a_reauthorization(monkeypatch):
+ """The permanent variant still means reconnect."""
+ import httpx
+
+ forget_subscription_models("provider-14")
+
+ class Rejecting:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ return httpx.Response(401, json = {"detail": "expired"})
+
+ async def aclose(self):
+ return None
+
+ async def _rejected(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ raise codex_auth.CodexReauthorizationRequired("refresh token rejected")
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Rejecting())
+ monkeypatch.setattr(codex_auth, "resolve_access", _rejected)
+ try:
+ with pytest.raises(CodexReauthorizationError):
+ asyncio.run(list_subscription_models("provider-14", "stale", "acct-1"))
+ finally:
+ forget_subscription_models("provider-14")
+
+
+def test_a_catalog_is_not_committed_for_an_account_another_worker_replaced(monkeypatch):
+ """The request counter is process-local; rebinding travels through the shared DB.
+
+ A read this worker started is not retired by another worker's rebind, so the stored
+ bundle is the only thing that can say the answer is for the wrong account.
+ """
+ import httpx
+
+ forget_subscription_models("provider-15")
+
+ class Slow:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ return httpx.Response(200, json = {"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+
+ async def aclose(self):
+ return None
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Slow())
+ # While the read was out, another worker rebound the connection to acct-b.
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-b"})
+ try:
+ models = asyncio.run(list_subscription_models("provider-15", "token-a", "acct-a"))
+ assert [model["id"] for model in models] == ["gpt-5.4"]
+ assert codex_client.subscription_catalog_known("provider-15") is False
+
+ # The same read for the account the DB actually names does commit.
+ forget_subscription_models("provider-15")
+ asyncio.run(list_subscription_models("provider-15", "token-b", "acct-b"))
+ assert offered_subscription_model_ids("provider-15") == {"gpt-5.4"}
+ finally:
+ forget_subscription_models("provider-15")
+
+
+def test_the_model_route_reports_an_already_marked_connection(monkeypatch):
+ """A bundle marked by someone else still has to reach the editor as reconnect."""
+ from routes import openai_codex_auth as codex_routes
+
+ curated = get_provider_info("openai_codex")["default_models"]
+ monkeypatch.setattr(codex_routes, "_provider", lambda provider_id: {"id": provider_id})
+ monkeypatch.setattr(
+ codex_routes.codex_auth, "auth_status", lambda _id: "reauthorization_required"
+ )
+ answered = asyncio.run(
+ codex_routes.list_subscription_models(
+ "provider-16", _credential = ("user", "session"), via_api_key = False
+ )
+ )
+ assert answered["source"] == "reauthorization_required"
+ assert [model["id"] for model in answered["models"]] == curated
+
+ monkeypatch.setattr(codex_routes.codex_auth, "auth_status", lambda _id: "disconnected")
+ plain = asyncio.run(
+ codex_routes.list_subscription_models(
+ "provider-16", _credential = ("user", "session"), via_api_key = False
+ )
+ )
+ assert plain["source"] == "curated"
+
+
+def test_an_overtaken_read_still_answers_its_own_caller(monkeypatch):
+ """Its models came from upstream for this account even though a newer read owns the cache.
+
+ Reporting nothing listed would let a manual reload overlapping a chat refuse a model
+ the chat's own lookup had just seen.
+ """
+ import httpx
+
+ forget_subscription_models("provider-17")
+
+ class Overtaken:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ # A newer read for the same connection starts while this one is out.
+ codex_client._begin_catalog_request("provider-17")
+ return httpx.Response(200, json = {"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+
+ async def aclose(self):
+ return None
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "token", "acct-1"
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Overtaken())
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-1"})
+ try:
+ listed = asyncio.run(codex_client.ensure_subscription_models("provider-17"))
+ assert listed == {"gpt-5.4"}
+ # Still not stored: the newer read owns the cache.
+ assert codex_client.subscription_catalog_known("provider-17") is False
+ finally:
+ forget_subscription_models("provider-17")
+
+
+def test_an_overtaken_read_is_dropped_when_the_account_moved(monkeypatch):
+ """If a rebind is what overtook it, its models belong to the previous account."""
+ import httpx
+
+ forget_subscription_models("provider-18")
+
+ class Overtaken:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ codex_client._begin_catalog_request("provider-18")
+ return httpx.Response(200, json = {"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+
+ async def aclose(self):
+ return None
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "token", "acct-a"
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Overtaken())
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-b"})
+ try:
+ assert asyncio.run(codex_client.ensure_subscription_models("provider-18")) == set()
+ finally:
+ forget_subscription_models("provider-18")
+
+
+def test_a_cold_worker_does_not_trust_a_row_it_cannot_vouch_for(monkeypatch):
+ """The stale mark dies with the process; the record next to the credentials does not."""
+ saved = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+
+ import httpx
+
+ calls = []
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ calls.append(_provider_id)
+ # The gate's own refresh resolves; the chat path's later call stops the request.
+ if len(calls) > 1:
+ raise codex_auth.CodexAuthError("stub: past the model gate")
+ return "token", "acct-b"
+
+ class Unreachable:
+ async def get(self, *_args, **_kwargs):
+ raise httpx.ConnectError("upstream down")
+
+ async def aclose(self):
+ return None
+
+ # Cold: the refresh cannot reach upstream, so the catalog stays unknown and the
+ # decision is the cold branch alone.
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: Unreachable())
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-b"})
+ try:
+ refused = _codex_chat_gate(monkeypatch, saved, resolve = _resolve, saved_models = [saved])
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+
+ # The same cold process, with the row on record as proven for this account.
+ monkeypatch.setattr(
+ codex_auth,
+ "load_oauth_bundle",
+ lambda _pid: {"account_id": "acct-b", "catalog_account_id": "acct-b"},
+ )
+ proven_calls = []
+
+ async def _always_refuse(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ proven_calls.append(_provider_id)
+ raise codex_auth.CodexAuthError("stub: past the model gate")
+
+ accepted = _codex_chat_gate(
+ monkeypatch, saved, resolve = _always_refuse, saved_models = [saved]
+ )
+ assert accepted.status_code == 401, accepted.detail
+ # Allowed straight off the row, so the gate never reached for a catalog: the one
+ # call is the chat path's own.
+ assert len(proven_calls) == 1
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_reading_a_catalog_does_not_by_itself_prove_the_saved_row(monkeypatch):
+ """Reading a catalog says which account answered, not that the row was judged by it.
+
+ After a rebind the user can open the editor, which fetches, and then cancel without
+ saving, leaving the previous account's slugs in the row. Recording proof on the read
+ would authorize exactly those on the next cold start.
+ """
+ stored = {"provider-19": None}
+ bundle = {
+ "access_token": "token",
+ "refresh_token": "refresh",
+ "expires_at": 1,
+ "account_id": "acct-1",
+ }
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: dict(bundle))
+ monkeypatch.setattr(
+ codex_auth,
+ "save_oauth_bundle",
+ lambda provider_id, value: stored.__setitem__(provider_id, value),
+ )
+ fake = _models_response({"models": [{"slug": "gpt-5.4", "visibility": "list"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("provider-19")
+ try:
+ asyncio.run(list_subscription_models("provider-19", "token", "acct-1"))
+ assert stored["provider-19"] is None
+ finally:
+ forget_subscription_models("provider-19")
+
+
+def test_a_token_refresh_keeps_the_catalog_proof(monkeypatch):
+ """Rotating credentials is not rebinding, so the proof has to survive it.
+
+ _validate_token_payload rebuilds the bundle from the token response alone, which
+ knows nothing about which account the saved models were proven for.
+ """
+ stored = {}
+
+ bundle = {
+ "access_token": "old",
+ "refresh_token": "refresh-1",
+ "expires_at": 1,
+ "account_id": "acct-1",
+ "catalog_account_id": "acct-1",
+ }
+
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: dict(bundle))
+ monkeypatch.setattr(
+ codex_auth,
+ "save_oauth_bundle",
+ lambda provider_id, value: stored.__setitem__(provider_id, value),
+ )
+ monkeypatch.setattr(
+ codex_auth,
+ "_validate_token_payload",
+ lambda _body, _previous: {
+ "access_token": "new",
+ "refresh_token": "refresh-1",
+ "expires_at": 2,
+ "account_id": "acct-1",
+ },
+ )
+
+ async def _token_request(_data):
+ return {}
+
+ monkeypatch.setattr(codex_auth, "_token_request", _token_request)
+
+ @asynccontextmanager
+ async def _guard(_provider_id):
+ yield
+
+ monkeypatch.setattr(codex_auth, "provider_oauth_write_guard", _guard)
+
+ token, account = asyncio.run(codex_auth.resolve_access("provider-20", force_refresh = True))
+ assert (token, account) == ("new", "acct-1")
+ assert stored["provider-20"]["catalog_account_id"] == "acct-1"
+
+
+def test_recording_the_proof_never_overwrites_newer_credentials(monkeypatch):
+ """The write is guarded and re-reads inside it, so a rotation cannot be undone."""
+ stored = {
+ "access_token": "rotated",
+ "refresh_token": "refresh-2",
+ "expires_at": 9,
+ "account_id": "acct-1",
+ }
+ saved = []
+
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: dict(stored))
+ monkeypatch.setattr(codex_auth, "save_oauth_bundle", lambda _pid, value: saved.append(value))
+
+ @asynccontextmanager
+ async def _guard(_provider_id):
+ yield
+
+ monkeypatch.setattr(codex_auth, "provider_oauth_write_guard", _guard)
+
+ asyncio.run(codex_auth.remember_catalog_account("provider-21", "acct-1"))
+ assert len(saved) == 1
+ # The tokens written back are the ones read inside the guard, not any older copy.
+ assert saved[0]["access_token"] == "rotated"
+ assert saved[0]["refresh_token"] == "refresh-2"
+ assert saved[0]["catalog_account_id"] == "acct-1"
+
+
+def test_a_second_catalog_401_is_recorded_on_the_connection(monkeypatch):
+ """Raising alone leaves auth_status saying connected, so nothing offers Reconnect."""
+ import httpx
+
+ forget_subscription_models("provider-22")
+ marked = []
+
+ class AlwaysRejecting:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ return httpx.Response(401, json = {"detail": "expired"})
+
+ async def aclose(self):
+ return None
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "fresh-token", "acct-1"
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: AlwaysRejecting())
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(
+ codex_auth,
+ "mark_reauthorization_required",
+ lambda provider_id, expected_access_token = None: marked.append(
+ (provider_id, expected_access_token)
+ ),
+ )
+ try:
+ with pytest.raises(CodexReauthorizationError):
+ asyncio.run(list_subscription_models("provider-22", "stale", "acct-1"))
+ # Recorded against the refreshed token, not the stale one it started with.
+ assert marked == [("provider-22", "fresh-token")]
+ finally:
+ forget_subscription_models("provider-22")
+
+
+def test_a_catalog_with_nothing_offerable_is_not_committed(monkeypatch):
+ """The route answers such a catalog with the seed, so the two must not disagree.
+
+ Committing it would leave the picker offering seeds while validation and chat read
+ the same empty catalog and refuse them.
+ """
+ fake = _models_response({"models": [{"slug": "codex-auto-review", "visibility": "hide"}]})
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("provider-23")
+ try:
+ models = asyncio.run(list_subscription_models("provider-23", "token", "acct-1"))
+ assert [model["id"] for model in models] == ["codex-auto-review"]
+ assert codex_client.subscription_catalog_known("provider-23") is False
+ finally:
+ forget_subscription_models("provider-23")
+
+
+def test_a_cold_worker_rejects_credentials_for_another_account(monkeypatch):
+ """With no catalog here, the catalog comparison has no opinion to offer.
+
+ The row was authorized from the persisted proof against the account the gate read, so
+ that is what the resolved credentials have to match.
+ """
+ saved = "gpt-5.7-nova"
+ forget_subscription_models("codex-1")
+ reads = []
+
+ def _bundle(_pid):
+ reads.append(1)
+ # The gate reads acct-a and authorizes off the proof; a rebind lands before
+ # resolve_access answers, which then returns acct-b.
+ return {"account_id": "acct-a", "catalog_account_id": "acct-a"}
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "token-b", "acct-b"
+
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", _bundle)
+ try:
+ refused = _codex_chat_gate(monkeypatch, saved, resolve = _resolve, saved_models = [saved])
+ assert refused.status_code == 400
+ assert "Choose a curated Codex model." in str(refused.detail)
+ # The connection is left needing a fresh catalog before anything is trusted again.
+ assert codex_client.subscription_catalog_stale("codex-1") is True
+ finally:
+ forget_subscription_models("codex-1")
+
+
+def test_the_reauthorization_marker_is_written_under_the_guard(monkeypatch):
+ """Read and write have to be one step, or a rotation in between is written back over.
+
+ The streaming error path already takes this guard; the catalog path is the same kind
+ of write and needs the same protection.
+ """
+ import httpx
+
+ forget_subscription_models("provider-24")
+ order = []
+
+ class AlwaysRejecting:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ return httpx.Response(401, json = {"detail": "expired"})
+
+ async def aclose(self):
+ return None
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "fresh-token", "acct-1"
+
+ @asynccontextmanager
+ async def _guard(provider_id):
+ order.append(("enter", provider_id))
+ try:
+ yield
+ finally:
+ order.append(("exit", provider_id))
+
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: AlwaysRejecting())
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(codex_auth, "provider_oauth_write_guard", _guard)
+ monkeypatch.setattr(
+ codex_auth,
+ "mark_reauthorization_required",
+ lambda provider_id, expected_access_token = None: order.append(("mark", provider_id)),
+ )
+ try:
+ with pytest.raises(CodexReauthorizationError):
+ asyncio.run(list_subscription_models("provider-24", "stale", "acct-1"))
+ assert order == [
+ ("enter", "provider-24"),
+ ("mark", "provider-24"),
+ ("exit", "provider-24"),
+ ]
+ finally:
+ forget_subscription_models("provider-24")
+
+
+def test_one_malformed_entry_does_not_cost_the_whole_catalog(monkeypatch):
+ """A scalar where a list belongs must drop that entry, not the account's plan.
+
+ ``supported_reasoning_levels`` was the one field guarded with ``or []``, which only
+ covers a falsy value. A scalar raised TypeError out of list_subscription_models, and
+ every caller turns that into "no catalog": the picker falls back to the curated seed
+ and the chat gate stops recognising slugs it had just been offering.
+ """
+ fake = _models_response(
+ {
+ "models": [
+ {"slug": "gpt-5.4", "visibility": "list", "supported_reasoning_levels": 5},
+ {"slug": "gpt-5.5", "visibility": "list", "supported_reasoning_levels": "low"},
+ {
+ "slug": "gpt-5.6-sol",
+ "visibility": "list",
+ "supported_reasoning_levels": [{"effort": "high"}],
+ },
+ ]
+ }
+ )
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("provider-malformed")
+ try:
+ models = asyncio.run(list_subscription_models("provider-malformed", "token", "acct-1"))
+ assert [model["id"] for model in models] == ["gpt-5.4", "gpt-5.5", "gpt-5.6-sol"]
+ assert [model["reasoning_efforts"] for model in models] == [[], [], ["high"]]
+ assert offered_subscription_model_ids("provider-malformed") == {
+ "gpt-5.4",
+ "gpt-5.5",
+ "gpt-5.6-sol",
+ }
+ finally:
+ forget_subscription_models("provider-malformed")
+
+
+def test_a_repeated_slug_cannot_be_offered_and_refused_at_once(monkeypatch):
+ """The offered list and the by-id map must describe a duplicate the same way.
+
+ The list keeps every entry while the map keeps the last, so a slug listed once and
+ hidden once was reported to the picker as offered and recorded for the chat gate as
+ hidden. The picker offered it and every send refused it.
+ """
+ fake = _models_response(
+ {
+ "models": [
+ {"slug": "gpt-5.4", "visibility": "list", "display_name": "First"},
+ {"slug": "gpt-5.4", "visibility": "hide", "display_name": "Second"},
+ ]
+ }
+ )
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("provider-duplicate")
+ try:
+ models = asyncio.run(list_subscription_models("provider-duplicate", "token", "acct-1"))
+ assert [model["id"] for model in models] == ["gpt-5.4"]
+ assert models[0]["display_name"] == "First"
+ assert models[0]["listed"] is True
+ offered = [model["id"] for model in models if model["listed"]]
+ assert set(offered) == offered_subscription_model_ids("provider-duplicate")
+ finally:
+ forget_subscription_models("provider-duplicate")
+
+
+def test_a_boolean_context_window_is_not_reported_as_a_length(monkeypatch):
+ """bool is a subclass of int, so `true` would reach the picker as a context length."""
+ fake = _models_response(
+ {"models": [{"slug": "gpt-5.4", "visibility": "list", "context_window": True}]}
+ )
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: fake)
+ forget_subscription_models("provider-boolctx")
+ try:
+ models = asyncio.run(list_subscription_models("provider-boolctx", "token", "acct-1"))
+ assert models[0]["context_length"] is None
+ finally:
+ forget_subscription_models("provider-boolctx")
+
+
+def _gated_models_client(gate, slug):
+ """A models endpoint whose response the test releases, not the network."""
+ import httpx
+
+ class Gated:
+ async def get(
+ self,
+ _url,
+ headers = None,
+ params = None,
+ ):
+ await gate.wait()
+ return httpx.Response(200, json = {"models": [{"slug": slug, "visibility": "list"}]})
+
+ async def aclose(self):
+ return None
+
+ return Gated()
+
+
+def test_a_disconnect_mid_read_retires_that_read_and_releases_its_ticket(monkeypatch):
+ """Dropping the ticket must still retire the read that was holding it.
+
+ forget_subscription_models releases the entry rather than writing a larger number
+ over it, so an outstanding read finds nothing there instead of finding a mismatch.
+ Either way it must answer its own caller without reinstating the catalog that was
+ just dropped.
+ """
+ gate = asyncio.Event()
+ monkeypatch.setattr(
+ codex_client, "_create_http_client", lambda: _gated_models_client(gate, "gpt-5.4")
+ )
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "token", "acct-1"
+
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-1"})
+ forget_subscription_models("provider-disconnect-race")
+
+ async def run():
+ task = asyncio.create_task(
+ list_subscription_models("provider-disconnect-race", "token", "acct-1")
+ )
+ await asyncio.sleep(0)
+ forget_subscription_models("provider-disconnect-race")
+ assert "provider-disconnect-race" not in codex_client._catalog_requests
+ gate.set()
+ return await task
+
+ try:
+ models = asyncio.run(run())
+ assert [model["id"] for model in models] == ["gpt-5.4"]
+ assert codex_client.subscription_catalog_known("provider-disconnect-race") is False
+ assert offered_subscription_model_ids("provider-disconnect-race") == set()
+ finally:
+ forget_subscription_models("provider-disconnect-race")
+
+
+def test_a_read_started_after_a_release_cannot_be_matched_by_the_older_one(monkeypatch):
+ """Why the ticket counter is shared by every connection rather than per connection.
+
+ Releasing the entry and then counting up from it again would hand the next read the
+ same number the outstanding one is holding, and that stale read would then commit
+ its catalog over the newer one. Drawing from a counter that never reissues a value
+ is what makes releasing the entry safe.
+ """
+ first_gate = asyncio.Event()
+ second_gate = asyncio.Event()
+ clients = [
+ _gated_models_client(first_gate, "old-slug"),
+ _gated_models_client(second_gate, "new-slug"),
+ ]
+ monkeypatch.setattr(codex_client, "_create_http_client", lambda: clients.pop(0))
+
+ async def _resolve(
+ _provider_id,
+ force_refresh = False,
+ expected_access_token = None,
+ ):
+ return "token", "acct-1"
+
+ monkeypatch.setattr(codex_auth, "resolve_access", _resolve)
+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _pid: {"account_id": "acct-1"})
+ forget_subscription_models("provider-release-race")
+
+ async def run():
+ first = asyncio.create_task(
+ list_subscription_models("provider-release-race", "token", "acct-1")
+ )
+ await asyncio.sleep(0)
+ forget_subscription_models("provider-release-race")
+ second = asyncio.create_task(
+ list_subscription_models("provider-release-race", "token", "acct-1")
+ )
+ await asyncio.sleep(0)
+ second_gate.set()
+ await second
+ first_gate.set()
+ await first
+
+ try:
+ asyncio.run(run())
+ assert offered_subscription_model_ids("provider-release-race") == {"new-slug"}
+ finally:
+ forget_subscription_models("provider-release-race")
diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.ts
index b7c61555819..57ecc03946e 100644
--- a/studio/frontend/src/features/chat/api/providers-api.ts
+++ b/studio/frontend/src/features/chat/api/providers-api.ts
@@ -57,6 +57,8 @@ export interface ProviderModelInfo {
display_name: string;
context_length?: number | null;
owned_by?: string | null;
+ /** Only the ChatGPT plan catalog reports this; the registry describes the rest. */
+ vision?: boolean | null;
}
export interface ProviderTestResult {
@@ -314,6 +316,27 @@ export async function listProviderModels(payload: {
}
+export interface CodexSubscriptionModels {
+ models: ProviderModelInfo[];
+ /** Every model the plan returned, offered or not: absent from this means the account
+ * cannot reach it, while present-but-unoffered only means it is no longer shown. */
+ known?: ProviderModelInfo[];
+ /** "reauthorization_required" is a curated answer that also says the connection has
+ * to be reconnected: the picker must not treat it as the plan's catalog. */
+ source: "subscription" | "curated" | "reauthorization_required";
+}
+
+export async function fetchCodexSubscriptionModels(
+ providerId: string,
+ options?: { refresh?: boolean },
+): Promise<CodexSubscriptionModels> {
+ // An explicit reload asks about plan changes, so it must not be served from cache.
+ const query = options?.refresh ? "?refresh=true" : "";
+ const response = await authFetch(`/api/providers/${providerId}/codex/models${query}`);
+ return parseJsonOrThrow<CodexSubscriptionModels>(response);
+}
+
+
export interface CodexOAuthFlow {
flow_id: string;
method: "browser" | "device";
diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
index a27efde0754..53d784533ee 100644
--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx
@@ -40,9 +40,12 @@ import { ApiProviderLogo } from "./api-provider-logo";
import { OpenAICodexConnect } from "./openai-codex-connect";
import {
+ type CodexSubscriptionModels,
+ type ProviderAuthStatus,
type ProviderRegistryEntry,
createProviderConfig,
deleteProviderConfig,
+ fetchCodexSubscriptionModels,
listProviderModels,
listProviderRegistry,
testProviderConnection,
@@ -64,7 +67,9 @@ import {
isCustomProviderType,
LEGACY_CUSTOM_PROVIDER_TYPE,
CUSTOM_PROVIDER_DISPLAY_NAME,
+ getProviderModelCapabilities,
providerModelSupportsStudioTools,
+ setProviderModelCapabilities,
removeExternalProviderApiKey,
supportsProviderMaxOutputTokens,
supportsProviderReasoningToggle,
@@ -73,6 +78,7 @@ import {
} from "./external-providers";
import { useExternalProvidersStore } from "./stores/external-providers-store";
import {
+ mergeLearnedModelCapabilities,
pruneProviderModelIds,
syncExternalProvidersFromBackend,
} from "./sync-external-providers";
@@ -153,6 +159,74 @@ interface ChatProvidersSettingsProps {
onProvidersChange: (providers: ExternalProviderConfig[]) => void;
}
+export function codexCapabilitiesWithPlanModels(
+ entry: ProviderRegistryEntry | undefined,
+ listed: CodexSubscriptionModels | null,
+ stored: Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined,
+): Record<string, { vision?: boolean; studio_tools?: boolean }> | null {
+ if (!listed || listed.source !== "subscription") return null;
+ // The registry row is what says which slugs the plan is allowed to describe and what
+ // the provider-wide studio_tools answer is. Without it every seed model reads as one
+ // the registry never listed, so the plan's modalities are written over the registry's
+ // for slugs the registry does describe, and the wildcard entry that carries
+ // studio_tools for the whole provider type is dropped rather than rewritten. Both are
+ // persisted, so an editor opened before the registry finished loading, or after that
+ // fetch failed, leaves the composer wrong until the next successful sync. Learning
+ // nothing here is the honest answer; the next fetch with a registry in hand records it.
+ if (!entry) return null;
+ const registryCapabilities = entry.model_capabilities ?? {};
+ // The map is keyed by provider type, not by connection, so it must start from what
+ // is already learned: a second ChatGPT connection lists its own slugs, and rebuilding
+ // from the registry alone would drop the first one's.
+ const capabilities = mergeLearnedModelCapabilities(
+ stored,
+ registryCapabilities,
+ entry?.supports_studio_tools,
+ );
+ // Hidden entries are described too: they stay selectable, so the composer needs their
+ // modalities as much as the offered ones.
+ for (const model of listed.known ?? listed.models) {
+ // Only the plan describes a slug the registry never listed. Without it the
+ // composer reads "unknown" as "allowed" and offers image attachments that the
+ // backend then refuses on every send. A catalog entry carrying no modality list
+ // normalizes to null upstream and the backend gate is bool(vision), so the honest
+ // mirror here is false rather than recording nothing at all.
+ if (!(model.id in registryCapabilities)) {
+ capabilities[model.id] = {
+ ...capabilities[model.id],
+ vision: model.vision === true,
+ };
+ }
+ }
+ return capabilities;
+}
+
+
+export function resolveCodexPickerModels(
+ curated: string[],
+ savedModels: string[],
+ listed: CodexSubscriptionModels | null,
+): { catalog: string[]; selected: string[] } {
+ // Only the plan's own catalog can retire a saved slug. The backend answers with the
+ // curated seed when it could not reach upstream, so treating that as the catalog
+ // would drop a saved model and the next unrelated save would make the loss stick.
+ const planListed = listed?.source === "subscription" && listed.models.length > 0;
+ if (!planListed) {
+ const catalog = [...new Set([...curated, ...savedModels])];
+ const offered = new Set(catalog);
+ return { catalog, selected: savedModels.filter((model) => offered.has(model)) };
+ }
+ const offeredIds = listed.models.map((model) => model.id);
+ // A saved slug the plan still returns is kept even when it is no longer offered:
+ // "hide" retires a model from the picker, it does not revoke one already in use.
+ // Only a slug the plan does not return at all is retired from the selection.
+ const known = new Set((listed.known ?? listed.models).map((model) => model.id));
+ const selected = savedModels.filter((model) => known.has(model));
+ const catalog = [...new Set([...offeredIds, ...selected])];
+ return { catalog, selected };
+}
+
+
export function ChatProvidersSettings({
providers,
onProvidersChange,
@@ -182,6 +256,8 @@ export function ChatProvidersSettings({
const [syncingProviders, setSyncingProviders] = useState(false);
const [registryLoading, setRegistryLoading] = useState(false);
const [modelsLoading, setModelsLoading] = useState(false);
+ // Only the newest Codex catalog request may write to the form.
+ const codexCatalogRequestRef = useRef(0);
const [mutatingProvider, setMutatingProvider] = useState(false);
const [manualModelIds, setManualModelIds] = useState("");
const [modelSearchQuery, setModelSearchQuery] = useState("");
@@ -277,8 +353,10 @@ export function ChatProvidersSettings({
const loadModelsTitle =
isManualModelList && isCustomProvider
? "This connection uses manual model IDs"
- : isCuratedModelList
- ? "Full catalog is not fetched for this connection"
+ : providerType === "openai_codex"
+ ? "Load the models this ChatGPT plan can reach"
+ : isCuratedModelList
+ ? "Full catalog is not fetched for this connection"
: missingModelCatalogBaseUrl
? "Enter a Base URL before loading models"
: missingModelCatalogApiKey
@@ -417,6 +495,11 @@ export function ChatProvidersSettings({
}, [onProvidersChange]);
function resetForm() {
+ // Any form transition retires an in-flight Codex catalog request. Its spinner goes
+ // with it: the state is shared across forms, so leaving it set would hold the next
+ // form's Load and Save controls disabled until the abandoned request times out.
+ codexCatalogRequestRef.current += 1;
+ setModelsLoading(false);
setEditingProviderId(null);
setApiKey("");
@@ -538,6 +621,32 @@ export function ChatProvidersSettings({
toast.info("This connection uses manual model IDs.");
return;
}
+ if (providerType === "openai_codex") {
+ // Registry-curated, but the real catalog comes from the plan, so this control has
+ // to refetch it. Falling into the branch below would leave the only way to retry a
+ // failed catalog fetch closing and reopening the form.
+ if (!editingProviderId) {
+ toast.info("Connect this ChatGPT subscription to load the models it can reach.");
+ return;
+ }
+ const provider = providersRef.current.find(
+ (candidate) => candidate.id === editingProviderId,
+ );
+ setModelsLoading(true);
+ // The live checkboxes, not the persisted list: a manual reload re-reads the
+ // catalog, it does not revert edits the user has not saved yet.
+ const applied = await applyCodexSubscriptionModels(
+ editingProviderId,
+ selectedModelIds,
+ provider?.authStatus,
+ true,
+ ).catch(() => true);
+ // Only the request that still owns the form clears the shared flag. An abandoned
+ // one would re-enable Save while the newer request is out, letting the form be
+ // saved and then mutated when that request lands.
+ if (applied) setModelsLoading(false);
+ return;
+ }
if (isCuratedModelList) {
toast.info(
"This connection has a very large model catalog. Use the suggestions and add model IDs manually — full list is not fetched.",
@@ -942,7 +1051,70 @@ export function ChatProvidersSettings({
}
}
+ async function applyCodexSubscriptionModels(
+ providerId: string,
+ savedModels: string[],
+ authStatus: ProviderAuthStatus | undefined,
+ refresh = false,
+ ): Promise<boolean> {
+ const request = ++codexCatalogRequestRef.current;
+ const curated = registryByType.get("openai_codex")?.default_models ?? [];
+ let listed: CodexSubscriptionModels | null = null;
+ if (authStatus === "connected") {
+ try {
+ listed = await fetchCodexSubscriptionModels(providerId, { refresh });
+ } catch {
+ // Keep the curated seed: the form must still open when upstream is unreachable.
+ }
+ }
+ if (request !== codexCatalogRequestRef.current) {
+ // The form moved to another connection while this catalog was in flight, and
+ // applying it here would save the first connection's models onto the second.
+ return false;
+ }
+ const capabilities = codexCapabilitiesWithPlanModels(
+ registryByType.get("openai_codex"),
+ listed,
+ getProviderModelCapabilities("openai_codex"),
+ );
+ if (capabilities) setProviderModelCapabilities("openai_codex", capabilities);
+ if (listed?.source === "reauthorization_required") {
+ // The backend already marked the bundle; resync so the connect panel offers
+ // Reconnect instead of leaving the connection looking healthy.
+ void syncExternalProvidersFromBackend(providersRef.current)
+ .then((synced) => {
+ providersRef.current = synced;
+ onProvidersChange(synced);
+ })
+ .catch(() => undefined);
+ }
+ const picker = resolveCodexPickerModels(curated, savedModels, listed);
+ if (refresh && listed?.source !== "subscription") {
+ // A curated fallback is not the account's catalog, so it retires nothing: keep
+ // whatever is on screen, including a model checked while the request was out.
+ setAvailableModels((previous) => [...new Set([...picker.catalog, ...previous])]);
+ setManualModelIds("");
+ return true;
+ }
+ setAvailableModels(picker.catalog);
+ if (refresh) {
+ // The checkboxes stay live while the request is out, so reconcile against the
+ // latest selection rather than the snapshot taken when the reload began. This is
+ // what the remote-catalog path above already does.
+ const offered = new Set(picker.catalog);
+ setSelectedModelIds((previous) => previous.filter((id) => offered.has(id)));
+ } else {
+ setSelectedModelIds(picker.selected);
+ }
+ setManualModelIds("");
+ return true;
+ }
+
async function editProvider(provider: ExternalProviderConfig) {
+ // Switching connections retires an in-flight catalog request, including on the
+ // branches below that never reach applyCodexSubscriptionModels.
+ codexCatalogRequestRef.current += 1;
+ setModelsLoading(false);
setEditingProviderId(provider.id);
autoOpenedAddFormRef.current = true;
setPage("form");
@@ -1002,6 +1174,19 @@ export function ChatProvidersSettings({
);
return;
}
+ if (provider.authKind === "chatgpt_oauth") {
+ // The form is already on screen and the reset emptied the catalog, so this fetch
+ // needs the same spinner the manual reload has. Without it the editor looks like a
+ // connection with no models, and Save answers "load available models first".
+ setModelsLoading(true);
+ const applied = await applyCodexSubscriptionModels(
+ provider.id,
+ provider.models,
+ provider.authStatus,
+ ).catch(() => true);
+ if (applied) setModelsLoading(false);
+ return;
+ }
const entry = registryByType.get(provider.providerType);
if (entry?.model_list_mode === "curated") {
const defaults = new Set(entry.default_models);
@@ -1443,9 +1628,51 @@ export function ChatProvidersSettings({
authStatus={providers.find((provider) => provider.id === editingProviderId)?.authStatus}
ensureProvider={ensureCodexProvider}
onChanged={async () => {
- const synced = await syncExternalProvidersFromBackend(providersRef.current);
- providersRef.current = synced;
- onProvidersChange(synced);
+ // The form can move while this sync is out, and the id below is the one
+ // captured when the flow started. Every transition retires the catalog
+ // generation, so a change here means this continuation is for a form the
+ // user has already left.
+ // Taking a generation rather than reading one, the way every other
+ // transition does. Reading it shares a ticket with a catalog request that
+ // is already out, and an authorization change retires that request
+ // anyway: leaving it owning the form let it land, clear the shared
+ // loading flag and re-enable Save while this continuation was still
+ // syncing, which is the state the flag exists to prevent.
+ const request = ++codexCatalogRequestRef.current;
+ const changedProviderId = editingProviderId;
+ // Save is gated on this flag. Leaving it clear here lets the connection
+ // be saved with the pre-authorization seed selection before the plan's
+ // own catalog arrives, and those slugs then fail on every send.
+ setModelsLoading(true);
+ let owned = true;
+ try {
+ const synced = await syncExternalProvidersFromBackend(providersRef.current);
+ providersRef.current = synced;
+ onProvidersChange(synced);
+ if (request !== codexCatalogRequestRef.current) {
+ owned = false;
+ return;
+ }
+ const connected = synced.find(
+ (provider) => provider.id === changedProviderId,
+ );
+ if (connected) {
+ owned = await applyCodexSubscriptionModels(
+ connected.id,
+ connected.models,
+ connected.authStatus,
+ );
+ }
+ } catch (error) {
+ // A failed sync still has to answer the ownership question: the user
+ // can cancel this form while it is out and start another request, and
+ // clearing the flag then would re-enable Save during that one.
+ owned = request === codexCatalogRequestRef.current;
+ throw error;
+ } finally {
+ // Only the request that still owns the form clears the shared flag.
+ if (owned) setModelsLoading(false);
+ }
}}
/>
) : null}
diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.ts
index 68eccaf0702..33456148b78 100644
--- a/studio/frontend/src/features/chat/external-providers.ts
+++ b/studio/frontend/src/features/chat/external-providers.ts
@@ -167,6 +167,13 @@ function persistProviderModelCapabilities(): void {
}
}
+export function getProviderModelCapabilities(
+ providerType: string,
+): Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined {
+ hydrateProviderModelCapabilities();
+ return REGISTRY_MODEL_CAPABILITIES.get(providerType);
+}
+
export function setProviderModelCapabilities(
providerType: string,
capabilities: Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined,
diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.ts
index c3b82d69cf8..d14e22e3246 100644
--- a/studio/frontend/src/features/chat/sync-external-providers.ts
+++ b/studio/frontend/src/features/chat/sync-external-providers.ts
@@ -26,6 +26,7 @@ import {
PROVIDER_CAPABILITY_WILDCARD,
pruneProviderModelCapabilities,
+ getProviderModelCapabilities,
setProviderModelCapabilities,
supportsProviderPromptCaching,
supportsProviderPromptCacheTtl,
@@ -34,6 +35,8 @@ import {
const ANTHROPIC_DATED_SNAPSHOT_SUFFIX = /-\d{8}$/;
const OPENAI_DEPRECATED_MODELS = new Set(["gpt-5.3"]);
+// Rejected for every ChatGPT account, so drop it from selections saved earlier.
+const OPENAI_CODEX_UNSUPPORTED_MODELS = new Set(["gpt-5.3-codex-spark"]);
const OPENROUTER_EXCLUDED_MODELS = new Set([
"google/chirp-3",
"kwaivgi/kling-v3.0-pro",
@@ -84,6 +87,32 @@ export function resolveUiProviderTypeFromConfig(
return configProviderType;
}
+export function mergeLearnedModelCapabilities(
+ stored: Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined,
+ registryCapabilities: Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined,
+ supportsStudioTools: boolean | undefined,
+): Record<string, { vision?: boolean; studio_tools?: boolean }> {
+ const fromRegistry = registryCapabilities ?? {};
+ // A plan-listed slug is learned at runtime and the registry cannot describe it, so
+ // rewriting this map from the registry alone would drop it and leave the composer
+ // reading "unknown" as allowed again on the next start.
+ const capabilities: Record<string, { vision?: boolean; studio_tools?: boolean }> = {};
+ for (const [modelId, capability] of Object.entries(stored ?? {})) {
+ if (modelId !== PROVIDER_CAPABILITY_WILDCARD && !(modelId in fromRegistry)) {
+ capabilities[modelId] = capability;
+ }
+ }
+ Object.assign(capabilities, fromRegistry);
+ if (typeof supportsStudioTools === "boolean") {
+ capabilities[PROVIDER_CAPABILITY_WILDCARD] = {
+ ...capabilities[PROVIDER_CAPABILITY_WILDCARD],
+ studio_tools: supportsStudioTools,
+ };
+ }
+ return capabilities;
+}
+
+
export function pruneProviderModelIds(
providerType: string,
modelIds: string[],
@@ -97,9 +126,30 @@ export function pruneProviderModelIds(
if (providerType === "openrouter") {
return modelIds.filter((id) => !OPENROUTER_EXCLUDED_MODELS.has(id));
}
+ if (providerType === "openai_codex") {
+ return modelIds.filter((id) => !OPENAI_CODEX_UNSUPPORTED_MODELS.has(id));
+ }
return modelIds;
}
+/** Which model ids a synced connection ends up with: server, else browser-saved, else seed.
+ *
+ * The saved list is pruned BEFORE the emptiness test, not after it. A browser selection
+ * made up entirely of retired slugs is no selection at all: resolving to it empties the
+ * picker, and the caller's backfill would send that empty list to a backend that rejects
+ * it. `serverModels` and `defaultModels` arrive pruned already. */
+export function resolveSyncedModelIds(
+ providerType: string,
+ serverModels: string[],
+ savedModels: string[],
+ defaultModels: string[],
+): string[] {
+ if (serverModels.length > 0) return serverModels;
+ const prunedSaved = pruneProviderModelIds(providerType, savedModels);
+ return prunedSaved.length > 0 ? prunedSaved : defaultModels;
+}
+
+
/** Carry browser-local provider knobs through a backend sync rebuild. */
export function mergeLocalProviderOptions(
existing: ExternalProviderConfig | undefined,
@@ -147,13 +197,11 @@ export async function syncExternalProvidersFromBackend(
// Self-hosted model ids are user-supplied, so there is no per-model entry to
// key off. The registry declares studio_tools once per provider type; park
// it under the wildcard so the per-model lookup can fall back to it.
- const capabilities = { ...(entry.model_capabilities ?? {}) };
- if (typeof entry.supports_studio_tools === "boolean") {
- capabilities[PROVIDER_CAPABILITY_WILDCARD] = {
- ...capabilities[PROVIDER_CAPABILITY_WILDCARD],
- studio_tools: entry.supports_studio_tools,
- };
- }
+ const capabilities = mergeLearnedModelCapabilities(
+ getProviderModelCapabilities(entry.provider_type),
+ entry.model_capabilities,
+ entry.supports_studio_tools,
+ );
setProviderModelCapabilities(entry.provider_type, capabilities);
}
// Writing per returned entry can only correct what came back. Capabilities are
@@ -212,21 +260,17 @@ export async function syncExternalProvidersFromBackend(
);
const savedModels = existing?.models ?? [];
const savedAvailableModels = existing?.availableModels ?? [];
- const resolvedModels = pruneProviderModelIds(
+ const resolvedModels = resolveSyncedModelIds(
uiProviderType,
- serverModels.length > 0
- ? serverModels
- : savedModels.length > 0
- ? savedModels
- : defaultModels,
+ serverModels,
+ savedModels,
+ defaultModels,
);
- const resolvedAvailableModels = pruneProviderModelIds(
+ const resolvedAvailableModels = resolveSyncedModelIds(
uiProviderType,
- serverAvailableModels.length > 0
- ? serverAvailableModels
- : savedAvailableModels.length > 0
- ? savedAvailableModels
- : defaultModels,
+ serverAvailableModels,
+ savedAvailableModels,
+ defaultModels,
);
const needsModelBackfill =
serverModels.length === 0 && savedModels.length > 0;
diff --git a/studio/frontend/tests/codex-learned-capabilities-survive-sync.test.ts b/studio/frontend/tests/codex-learned-capabilities-survive-sync.test.ts
new file mode 100644
index 00000000000..d2fb7485524
--- /dev/null
+++ b/studio/frontend/tests/codex-learned-capabilities-survive-sync.test.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+import { createServer, type ViteDevServer } from "vite";
+
+type Capability = { vision?: boolean; studio_tools?: boolean };
+type Merge = (
+ stored: Record<string, Capability> | undefined,
+ registryCapabilities: Record<string, Capability> | undefined,
+ supportsStudioTools: boolean | undefined,
+) => Record<string, Capability>;
+
+let vite: ViteDevServer;
+let mergeLearnedModelCapabilities: Merge;
+
+const REGISTRY: Record<string, Capability> = {
+ "gpt-5.4": { vision: true, studio_tools: true },
+};
+
+before(async () => {
+ vite = await createServer({ appType: "custom", server: { middlewareMode: true } });
+ const loaded = await vite.ssrLoadModule("/src/features/chat/sync-external-providers.ts");
+ mergeLearnedModelCapabilities = loaded.mergeLearnedModelCapabilities as Merge;
+});
+
+after(async () => {
+ await vite.close();
+});
+
+test("a plan-listed slug's capability survives a registry rewrite", () => {
+ // The startup credential bootstrap syncs before anything fetches /codex/models, so
+ // dropping the learned entry here lets the composer offer attachments again.
+ const merged = mergeLearnedModelCapabilities(
+ { "gpt-5.7-nova": { vision: false }, "gpt-5.4": { vision: true, studio_tools: true } },
+ REGISTRY,
+ true,
+ );
+ assert.deepEqual(merged["gpt-5.7-nova"], { vision: false });
+});
+
+test("the registry wins for models it describes", () => {
+ const merged = mergeLearnedModelCapabilities(
+ { "gpt-5.4": { vision: false } },
+ REGISTRY,
+ true,
+ );
+ assert.deepEqual(merged["gpt-5.4"], { vision: true, studio_tools: true });
+});
+
+test("the studio-tools wildcard is re-established, never inherited stale", () => {
+ const merged = mergeLearnedModelCapabilities({ "*": { studio_tools: true } }, REGISTRY, false);
+ assert.deepEqual(merged["*"], { studio_tools: false });
+});
+
+test("no stored capabilities is the plain registry map", () => {
+ assert.deepEqual(mergeLearnedModelCapabilities(undefined, REGISTRY, undefined), REGISTRY);
+});
diff --git a/studio/frontend/tests/codex-models-endpoint-skew.test.ts b/studio/frontend/tests/codex-models-endpoint-skew.test.ts
new file mode 100644
index 00000000000..73ccff69eb5
--- /dev/null
+++ b/studio/frontend/tests/codex-models-endpoint-skew.test.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// New frontend against an OLD backend that has no /api/providers/{id}/codex/models.
+// Three shapes that skew actually produces -- 404 JSON, a 200 SPA index.html, and a
+// 401 from an auth gateway -- must all land on the curated seed with the saved
+// selection intact. A wipe here is not cosmetic: the next unrelated Save persists the
+// emptied picker and the connection loses models the account can still reach.
+
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+import { createServer, type ViteDevServer } from "vite";
+
+interface SubscriptionModels {
+ models: { id: string; vision?: boolean | null }[];
+ known?: { id: string; vision?: boolean | null }[];
+ source: "subscription" | "curated" | "reauthorization_required";
+}
+
+type Fetch = (
+ providerId: string,
+ options?: { refresh?: boolean },
+) => Promise<SubscriptionModels>;
+type Resolve = (
+ curated: string[],
+ savedModels: string[],
+ listed: SubscriptionModels | null,
+) => { catalog: string[]; selected: string[] };
+
+let vite: ViteDevServer;
+let fetchCodexSubscriptionModels: Fetch;
+let resolveCodexPickerModels: Resolve;
+
+const CURATED = ["gpt-5.4", "gpt-5.5"];
+const SAVED = ["gpt-5.4", "gpt-5.7-nova"];
+
+before(async () => {
+ vite = await createServer({ appType: "custom", server: { middlewareMode: true } });
+ const api = await vite.ssrLoadModule("/src/features/chat/api/providers-api.ts");
+ fetchCodexSubscriptionModels = api.fetchCodexSubscriptionModels as Fetch;
+ const dialog = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ resolveCodexPickerModels = dialog.resolveCodexPickerModels as Resolve;
+});
+
+after(async () => {
+ await vite.close();
+});
+
+function stubFetch(response: Response): () => void {
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => response.clone()) as typeof globalThis.fetch;
+ return () => {
+ globalThis.fetch = original;
+ };
+}
+
+/** What applyCodexSubscriptionModels does with the call: any throw degrades to null. */
+async function listedOrNull(providerId: string): Promise<SubscriptionModels | null> {
+ try {
+ return await fetchCodexSubscriptionModels(providerId);
+ } catch {
+ return null;
+ }
+}
+
+test("an old backend's 404 degrades to the curated seed and keeps the selection", async () => {
+ const restore = stubFetch(
+ new Response(JSON.stringify({ detail: "Not Found" }), {
+ status: 404,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ try {
+ const listed = await listedOrNull("provider-1");
+ assert.equal(listed, null);
+ const { catalog, selected } = resolveCodexPickerModels(CURATED, SAVED, listed);
+ assert.deepEqual(selected, SAVED);
+ for (const model of CURATED) assert.ok(catalog.includes(model));
+ } finally {
+ restore();
+ }
+});
+
+test("an old backend's SPA index.html degrades to the curated seed", async () => {
+ // A dev proxy or a single-page fallback answers an unknown /api path with 200 and
+ // the app shell. response.json() rejects and parseJsonOrThrow hands back null on an
+ // ok response, so the picker must read that the same way it reads a throw.
+ const restore = stubFetch(
+ new Response("<!doctype html><html><body></body></html>", {
+ status: 200,
+ headers: { "content-type": "text/html" },
+ }),
+ );
+ try {
+ const listed = await listedOrNull("provider-1");
+ assert.equal(listed, null);
+ const { selected } = resolveCodexPickerModels(CURATED, SAVED, listed);
+ assert.deepEqual(selected, SAVED);
+ } finally {
+ restore();
+ }
+});
+
+test("a body without a source field is not mistaken for a plan catalog", async () => {
+ // An intermediate backend that grew the route before the source discriminator would
+ // otherwise be read as authoritative and retire every saved slug it omits.
+ const restore = stubFetch(
+ new Response(JSON.stringify({ models: [{ id: "gpt-5.4" }] }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ try {
+ const listed = await fetchCodexSubscriptionModels("provider-1");
+ assert.notEqual(listed?.source, "subscription");
+ const { selected } = resolveCodexPickerModels(CURATED, SAVED, listed);
+ assert.deepEqual(selected, SAVED);
+ } finally {
+ restore();
+ }
+});
+
+test("a gateway 401 on the unknown path still keeps the selection", async () => {
+ // Kept last: authFetch reads every 401 as an expired Studio session and runs the
+ // refresh-and-retry path, which is why the backend answers a dead ChatGPT connection
+ // with 200 + source:"reauthorization_required" instead of a 401. Whatever that path
+ // decides, the picker must still land on the seed with the selection intact.
+ const location = { pathname: "/chat", href: "/chat" };
+ const globals = globalThis as { window?: unknown; localStorage?: unknown };
+ const originalWindow = globals.window;
+ const originalStorage = globals.localStorage;
+ const store = new Map<string, string>();
+ globals.localStorage = {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, String(value)),
+ removeItem: (key: string) => void store.delete(key),
+ clear: () => store.clear(),
+ key: () => null,
+ length: 0,
+ };
+ globals.window = { location, localStorage: globals.localStorage };
+ const restore = stubFetch(
+ new Response(JSON.stringify({ detail: "Unauthorized" }), {
+ status: 401,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ try {
+ const listed = await listedOrNull("provider-1");
+ assert.equal(listed, null);
+ const { selected } = resolveCodexPickerModels(CURATED, SAVED, listed);
+ assert.deepEqual(selected, SAVED);
+ // The session-expiry path may also navigate; either way it must not have
+ // rewritten the picker.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ } finally {
+ restore();
+ globals.window = originalWindow;
+ globals.localStorage = originalStorage;
+ }
+});
diff --git a/studio/frontend/tests/codex-picker-catalog-fallback.test.ts b/studio/frontend/tests/codex-picker-catalog-fallback.test.ts
new file mode 100644
index 00000000000..9f37e327f81
--- /dev/null
+++ b/studio/frontend/tests/codex-picker-catalog-fallback.test.ts
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+import { createServer, type ViteDevServer } from "vite";
+
+interface SubscriptionModels {
+ models: { id: string; vision?: boolean | null }[];
+ known?: { id: string; vision?: boolean | null }[];
+ source: "subscription" | "curated" | "reauthorization_required";
+}
+
+type Resolve = (
+ curated: string[],
+ savedModels: string[],
+ listed: SubscriptionModels | null,
+) => { catalog: string[]; selected: string[] };
+
+let vite: ViteDevServer;
+let resolveCodexPickerModels: Resolve;
+
+const CURATED = ["gpt-5.4", "gpt-5.5"];
+
+before(async () => {
+ vite = await createServer({ appType: "custom", server: { middlewareMode: true } });
+ const loaded = await vite.ssrLoadModule(
+ "/src/features/chat/chat-providers-dialog.tsx",
+ );
+ resolveCodexPickerModels = loaded.resolveCodexPickerModels as Resolve;
+});
+
+after(async () => {
+ await vite.close();
+});
+
+test("a plan catalog drives the picker and retires slugs it no longer lists", () => {
+ const { catalog, selected } = resolveCodexPickerModels(
+ CURATED,
+ ["gpt-5.4", "gpt-5.7-nova"],
+ { models: [{ id: "gpt-5.7-nova" }], source: "subscription" },
+ );
+ assert.deepEqual(catalog, ["gpt-5.7-nova"]);
+ assert.deepEqual(selected, ["gpt-5.7-nova"]);
+});
+
+test("a curated fallback keeps every saved model selected", () => {
+ // The backend answers with the seed when it cannot reach upstream. Dropping the
+ // saved dynamic slug here would lose it on the next unrelated save.
+ const { catalog, selected } = resolveCodexPickerModels(
+ CURATED,
+ ["gpt-5.4", "gpt-5.7-nova"],
+ { models: CURATED.map((id) => ({ id })), source: "curated" },
+ );
+ assert.ok(catalog.includes("gpt-5.7-nova"));
+ assert.deepEqual(selected, ["gpt-5.4", "gpt-5.7-nova"]);
+});
+
+test("an unreachable backend keeps every saved model selected", () => {
+ const { selected } = resolveCodexPickerModels(
+ CURATED,
+ ["gpt-5.4", "gpt-5.7-nova"],
+ null,
+ );
+ assert.deepEqual(selected, ["gpt-5.4", "gpt-5.7-nova"]);
+});
+
+test("an empty plan catalog is not treated as an empty account", () => {
+ const { selected } = resolveCodexPickerModels(
+ CURATED,
+ ["gpt-5.4"],
+ { models: [], source: "subscription" },
+ );
+ assert.deepEqual(selected, ["gpt-5.4"]);
+});
+
+interface RegistryEntry {
+ model_capabilities?: Record<string, { vision?: boolean; studio_tools?: boolean }>;
+ supports_studio_tools?: boolean;
+}
+
+type Capabilities = (
+ entry: RegistryEntry | undefined,
+ listed: (SubscriptionModels & { models: { id: string; vision?: boolean | null }[] }) | null,
+ stored: Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined,
+) => Record<string, { vision?: boolean; studio_tools?: boolean }> | null;
+
+const ENTRY: RegistryEntry = {
+ model_capabilities: { "gpt-5.4": { vision: true, studio_tools: true } },
+ supports_studio_tools: true,
+};
+
+test("a plan-listed slug carries its own vision flag into the capability map", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const codexCapabilitiesWithPlanModels = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ const capabilities = codexCapabilitiesWithPlanModels(
+ ENTRY,
+ {
+ source: "subscription",
+ models: [{ id: "gpt-5.7-nova", vision: false }, { id: "gpt-5.7-eos", vision: true }],
+ },
+ undefined,
+ );
+ // Without this the composer reads "unknown" as allowed and offers attachments the
+ // backend refuses on every send.
+ assert.equal(capabilities?.["gpt-5.7-nova"].vision, false);
+ assert.equal(capabilities?.["gpt-5.7-eos"].vision, true);
+ // The registry's own entries survive untouched.
+ assert.deepEqual(capabilities?.["gpt-5.4"], { vision: true, studio_tools: true });
+});
+
+test("a curated fallback never rewrites the capability map", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const codexCapabilitiesWithPlanModels = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ assert.equal(
+ codexCapabilitiesWithPlanModels(
+ ENTRY,
+ { source: "curated", models: [{ id: "gpt-5.7-nova", vision: true }] },
+ undefined,
+ ),
+ null,
+ );
+ assert.equal(codexCapabilitiesWithPlanModels(ENTRY, null, undefined), null);
+});
+
+test("a plan that describes nothing new never overrides the registry", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const codexCapabilitiesWithPlanModels = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ const capabilities = codexCapabilitiesWithPlanModels(
+ ENTRY,
+ { source: "subscription", models: [{ id: "gpt-5.4", vision: false }, { id: "gpt-5.7-nova" }] },
+ undefined,
+ );
+ assert.deepEqual(capabilities?.["gpt-5.4"], { vision: true, studio_tools: true });
+ // No modality list normalizes to null upstream and the backend gate is bool(vision),
+ // so the UI has to say false too or it offers attachments that every send refuses.
+ assert.deepEqual(capabilities?.["gpt-5.7-nova"], { vision: false });
+});
+
+
+test("another connection's learned slug survives this one's catalog", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const codexCapabilitiesWithPlanModels = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ // The map is keyed by provider type, so a second ChatGPT connection's catalog must
+ // not erase what the first one taught it.
+ const capabilities = codexCapabilitiesWithPlanModels(
+ ENTRY,
+ { source: "subscription", models: [{ id: "gpt-5.7-eos", vision: true }] },
+ { "gpt-5.7-nova": { vision: false } },
+ );
+ assert.deepEqual(capabilities?.["gpt-5.7-nova"], { vision: false });
+ assert.deepEqual(capabilities?.["gpt-5.7-eos"], { vision: true });
+});
+
+
+test("a saved slug the plan still returns survives losing its picker slot", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const resolve = loaded.resolveCodexPickerModels as Resolve;
+ // "hide" retires a model from the picker; it does not revoke one already in use, and
+ // dropping it here would make the next save delete it from the connection.
+ const { catalog, selected } = resolve(
+ CURATED,
+ ["gpt-5.7-nova"],
+ {
+ models: [{ id: "gpt-5.4" }],
+ known: [{ id: "gpt-5.4" }, { id: "gpt-5.7-nova" }],
+ source: "subscription",
+ },
+ );
+ assert.deepEqual(selected, ["gpt-5.7-nova"]);
+ assert.ok(catalog.includes("gpt-5.7-nova"));
+});
+
+test("a slug the plan no longer returns at all is retired", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const resolve = loaded.resolveCodexPickerModels as Resolve;
+ const { selected } = resolve(
+ CURATED,
+ ["gpt-5.6-sol"],
+ { models: [{ id: "gpt-5.4" }], known: [{ id: "gpt-5.4" }], source: "subscription" },
+ );
+ assert.deepEqual(selected, []);
+});
+
+
+test("a hidden saved slug still contributes its capability", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const capabilities = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ // Hidden slugs stay selectable, so a fresh browser has to learn their modalities from
+ // here or the composer guesses and offers what the chat route refuses.
+ const resolved = capabilities(
+ ENTRY,
+ {
+ source: "subscription",
+ models: [{ id: "gpt-5.4", vision: true }],
+ known: [{ id: "gpt-5.4", vision: true }, { id: "gpt-5.7-nova", vision: false }],
+ },
+ undefined,
+ );
+ assert.deepEqual(resolved?.["gpt-5.7-nova"], { vision: false });
+});
+
+
+test("a reauthorization answer retires nothing and describes nothing", async () => {
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const resolve = loaded.resolveCodexPickerModels as Resolve;
+ const capabilities = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ // It carries the seed, but the connection is dead: nothing about it is authoritative.
+ const { selected } = resolve(
+ CURATED,
+ ["gpt-5.4", "gpt-5.7-nova"],
+ { models: CURATED.map((id) => ({ id })), source: "reauthorization_required" },
+ );
+ assert.deepEqual(selected, ["gpt-5.4", "gpt-5.7-nova"]);
+ assert.equal(
+ capabilities(ENTRY, {
+ source: "reauthorization_required",
+ models: [{ id: "gpt-5.7-nova", vision: true }],
+ }, undefined),
+ null,
+ );
+});
+
+test("a catalog that arrives before the registry does not rewrite what is learned", async () => {
+ // registryByType is empty until the mount fetch resolves, and stays empty when it
+ // fails, while the Edit button is gated only on a pending mutation. The plan catalog
+ // can therefore land with no registry row behind it. Writing then would drop the
+ // wildcard that carries studio_tools for the whole provider type and overwrite the
+ // registry's own vision flags with the plan's, and both are persisted.
+ const loaded = await vite.ssrLoadModule("/src/features/chat/chat-providers-dialog.tsx");
+ const codexCapabilitiesWithPlanModels = loaded.codexCapabilitiesWithPlanModels as Capabilities;
+ const stored = {
+ "gpt-5.4": { vision: true, studio_tools: true },
+ "*": { studio_tools: true },
+ };
+ const capabilities = codexCapabilitiesWithPlanModels(
+ undefined,
+ {
+ source: "subscription",
+ models: [{ id: "gpt-5.4", vision: false }],
+ },
+ stored,
+ );
+ assert.equal(capabilities, null);
+});
diff --git a/studio/frontend/tests/codex-retired-model-sync-fallback.test.ts b/studio/frontend/tests/codex-retired-model-sync-fallback.test.ts
new file mode 100644
index 00000000000..6e98d24ce5d
--- /dev/null
+++ b/studio/frontend/tests/codex-retired-model-sync-fallback.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { after, before, test } from "node:test";
+import { createServer, type ViteDevServer } from "vite";
+
+type Resolve = (
+ providerType: string,
+ serverModels: string[],
+ savedModels: string[],
+ defaultModels: string[],
+) => string[];
+
+let vite: ViteDevServer;
+let resolveSyncedModelIds: Resolve;
+
+const RETIRED = "gpt-5.3-codex-spark";
+const SEED = ["gpt-5.4", "gpt-5.5"];
+
+before(async () => {
+ vite = await createServer({ appType: "custom", server: { middlewareMode: true } });
+ const loaded = await vite.ssrLoadModule("/src/features/chat/sync-external-providers.ts");
+ resolveSyncedModelIds = loaded.resolveSyncedModelIds as Resolve;
+});
+
+after(async () => {
+ await vite.close();
+});
+
+test("a saved selection of only the retired slug falls back to the seed", () => {
+ // This is the upgrade path the PR exists for: the connection would otherwise sync to
+ // an empty model list, vanish from the picker, and backfill [] that the backend 400s.
+ const resolved = resolveSyncedModelIds("openai_codex", [], [RETIRED], SEED);
+ assert.deepEqual(resolved, SEED);
+});
+
+test("a saved selection that survives pruning is kept", () => {
+ const resolved = resolveSyncedModelIds("openai_codex", [], [RETIRED, "gpt-5.5"], SEED);
+ assert.deepEqual(resolved, ["gpt-5.5"]);
+});
+
+test("the server list wins whenever it has anything", () => {
+ const resolved = resolveSyncedModelIds("openai_codex", ["gpt-5.4"], [RETIRED], SEED);
+ assert.deepEqual(resolved, ["gpt-5.4"]);
+});
+
+test("an unrelated provider type is untouched by codex pruning", () => {
+ const resolved = resolveSyncedModelIds("openai", [], [RETIRED], SEED);
+ assert.deepEqual(resolved, [RETIRED]);
+});
+
+test("nothing anywhere still yields the seed", () => {
+ assert.deepEqual(resolveSyncedModelIds("openai_codex", [], [], SEED), SEED);
+});