DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(codex): persist managed reasoning effort overrides (#789)
NoxsMedia104e844b5594
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 9826140ce..827139cdf 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -21,7 +21,11 @@ logger = logging.getLogger(__name__)from deeptutor.multi_user.context import get_current_userfrom deeptutor.multi_user.model_access import allowed_llm_options-from deeptutor.services.codex_auth import CodexAuthError, get_codex_oauth_service+from deeptutor.services.codex_auth import (+ CodexAuthError,+ get_codex_oauth_service,+ reconcile_codex_catalog_update,+)from deeptutor.services.config import (get_config_test_runner,get_model_catalog_service,@@ -171,6 +175,11 @@ class CatalogPayload(BaseModel):catalog: dict[str, Any]+class CodexReasoningEffortUpdate(BaseModel):+ model: str = Field(min_length=1)+ reasoning_effort: str | None = None++class FetchModelsPayload(BaseModel):binding: str = ""base_url: str@@ -605,6 +614,20 @@ async def refresh_openai_codex_models() -> dict[str, Any]:raise _codex_http_exception(exc) from None[email protected]("/providers/openai-codex/models/reasoning-effort")+async def update_openai_codex_reasoning_effort(+ payload: CodexReasoningEffortUpdate,+) -> dict[str, Any]:+ _require_codex_oauth_actor()+ try:+ return await get_codex_oauth_service().set_reasoning_effort(+ payload.model,+ payload.reasoning_effort,+ )+ except CodexAuthError as exc:+ raise _codex_http_exception(exc) from None++@router.get("/catalog")async def get_catalog():_require_settings_admin()@@ -1052,7 +1075,9 @@ async def get_llm_options():@router.put("/catalog")async def update_catalog(payload: CatalogPayload):_require_settings_admin()- catalog = get_model_catalog_service().save(payload.catalog)+ service = get_model_catalog_service()+ proposed = reconcile_codex_catalog_update(service.load(), payload.catalog)+ catalog = service.save(proposed)_invalidate_runtime_caches()return {"catalog": catalog}@@ -1060,12 +1085,16 @@ async def update_catalog(payload: CatalogPayload):@router.post("/apply")async def apply_catalog(payload: CatalogPayload | None = None):_require_settings_admin()- catalog = payload.catalog if payload is not None else get_model_catalog_service().load()- applied = get_model_catalog_service().apply(catalog)+ service = get_model_catalog_service()+ current = service.load()+ catalog = (+ reconcile_codex_catalog_update(current, payload.catalog) if payload is not None else current+ )+ applied = service.apply(catalog)_invalidate_runtime_caches()return {"message": "Catalog applied to runtime settings.",- "catalog": get_model_catalog_service().load(),+ "catalog": service.load(),"runtime": applied,}diff --git a/deeptutor/multi_user/personal_models.py b/deeptutor/multi_user/personal_models.pyindex 1b215fceb..117166495 100644--- a/deeptutor/multi_user/personal_models.py+++ b/deeptutor/multi_user/personal_models.py@@ -34,6 +34,17 @@ from deeptutor.services.config.model_catalog import ModelCatalogServicefrom .paths import get_owner_path_service+_CODEX_MANAGED_BY = "openai_codex_oauth"+++def _codex_profile_is_current(profile: dict[str, Any]) -> bool:+ try:+ from deeptutor.services.codex_auth import get_codex_oauth_service++ return get_codex_oauth_service().profile_matches_current_account(profile)+ except Exception:+ return False+def owner_catalog_service() -> ModelCatalogService:"""Model catalog of the account that owns the current scope.@@ -69,7 +80,11 @@ def _personal_catalog_profiles() -> list[dict[str, Any]]:return []profiles = service.load().get("services", {}).get("llm", {}).get("profiles", []) or []return [- profile for profile in profiles if isinstance(profile, dict) and is_owner_bound(profile)+ profile+ for profile in profiles+ if isinstance(profile, dict)+ and is_owner_bound(profile)+ and (profile.get("managed_by") != _CODEX_MANAGED_BY or _codex_profile_is_current(profile))]diff --git a/deeptutor/services/codex_auth/__init__.py b/deeptutor/services/codex_auth/__init__.pyindex b88672c9e..622148d31 100644--- a/deeptutor/services/codex_auth/__init__.py+++ b/deeptutor/services/codex_auth/__init__.py@@ -9,7 +9,11 @@ from .contracts import (TokenClaims,decode_codex_jwt,)-from .service import CodexOAuthService, get_codex_oauth_service+from .service import (+ CodexOAuthService,+ get_codex_oauth_service,+ reconcile_codex_catalog_update,+)__all__ = ["CatalogSnapshot",@@ -21,4 +25,5 @@ __all__ = ["TokenClaims","decode_codex_jwt","get_codex_oauth_service",+ "reconcile_codex_catalog_update",]diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.pyindex 271e80a77..bfab3aff9 100644--- a/deeptutor/services/codex_auth/service.py+++ b/deeptutor/services/codex_auth/service.py@@ -3,8 +3,9 @@from __future__ import annotationsimport asyncio-from collections.abc import AsyncIterator, Awaitable, Callable+from collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom contextlib import asynccontextmanager+from copy import deepcopyfrom dataclasses import dataclassimport hashlibimport logging@@ -81,7 +82,14 @@ def codex_model_id(slug: str) -> str:return f"llm-model-openai-codex-{digest}"-def _managed_model(model: CodexModel) -> dict[str, Any]:+def _codex_account_binding(account_id: str) -> str:+ return hashlib.sha256(account_id.encode("utf-8")).hexdigest()+++def _managed_model(+ model: CodexModel,+ reasoning_effort: str | None = None,+) -> dict[str, Any]:managed = {"id": codex_model_id(model.slug),"name": model.display_name,@@ -98,11 +106,19 @@ def _managed_model(model: CodexModel) -> dict[str, Any]:if context_window is not None:managed["context_window"] = str(context_window)managed["context_window_source"] = "metadata"+ if reasoning_effort in model.supported_reasoning_levels:+ managed["reasoning_effort"] = reasoning_effortreturn managed-def _managed_profile(snapshot: CatalogSnapshot) -> dict[str, Any]:- return {+def _managed_profile(+ snapshot: CatalogSnapshot,+ reasoning_efforts: Mapping[str, str] | None = None,+ *,+ account_binding: str | None = None,+) -> dict[str, Any]:+ overrides = reasoning_efforts or {}+ profile = {"id": CODEX_PROFILE_ID,"name": "OpenAI Codex","binding": "openai_codex",@@ -116,13 +132,113 @@ def _managed_profile(snapshot: CatalogSnapshot) -> dict[str, Any]:# profile stays with the operator who signed in and is never shared with# other users through grants (see deeptutor/multi_user/model_access.py)."owner_bound": True,- "models": [_managed_model(model) for model in snapshot.models],+ "models": [_managed_model(model, overrides.get(model.slug)) for model in snapshot.models],}+ if account_binding is not None:+ profile["codex_account_binding"] = account_binding+ return profile+++def _managed_profile_indexes(profiles: list[Any]) -> list[int]:+ return [+ index+ for index, profile in enumerate(profiles)+ if isinstance(profile, Mapping) and profile.get("managed_by") == MANAGED_BY+ ]+++def _reasoning_efforts(profile: Mapping[str, Any]) -> dict[str, str]:+ models = profile.get("models")+ if not isinstance(models, list):+ return {}+ overrides: dict[str, str] = {}+ for model in models:+ if not isinstance(model, Mapping):+ continue+ slug = model.get("model")+ effort = model.get("reasoning_effort")+ if isinstance(slug, str) and slug and isinstance(effort, str) and effort:+ overrides.setdefault(slug, effort)+ return overrides+++def reconcile_codex_catalog_update(+ current_catalog: Mapping[str, Any],+ proposed_catalog: Mapping[str, Any],+) -> dict[str, Any]:+ """Keep provider-owned Codex metadata authoritative on catalog writes."""+ reconciled = deepcopy(dict(proposed_catalog))+ current_profiles = current_catalog.get("services", {}).get("llm", {}).get("profiles", [])+ proposed_services_raw = reconciled.get("services")+ proposed_services = (+ dict(proposed_services_raw) if isinstance(proposed_services_raw, Mapping) else {}+ )+ reconciled["services"] = proposed_services+ proposed_llm_raw = proposed_services.get("llm")+ proposed_llm = dict(proposed_llm_raw) if isinstance(proposed_llm_raw, Mapping) else {}+ proposed_services["llm"] = proposed_llm+ proposed_profiles = proposed_llm.get("profiles")+ if not isinstance(proposed_profiles, list):+ proposed_profiles = []+ proposed_llm["profiles"] = proposed_profiles+ if not isinstance(current_profiles, list):+ return reconciled++ current_indexes = _managed_profile_indexes(current_profiles)+ proposed_indexes = _managed_profile_indexes(proposed_profiles)+ proposed_index_set = set(proposed_indexes)+ if not current_indexes:+ proposed_llm["profiles"] = [+ profile+ for index, profile in enumerate(proposed_profiles)+ if index not in proposed_index_set+ ]+ return reconciled++ current_profile = deepcopy(dict(current_profiles[current_indexes[0]]))+ proposed_profile = proposed_profiles[proposed_indexes[0]] if proposed_indexes else None+ current_binding = current_profile.get("codex_account_binding")+ proposed_binding = (+ proposed_profile.get("codex_account_binding")+ if isinstance(proposed_profile, Mapping)+ else None+ )+ same_bound_account = (+ isinstance(current_binding, str)+ and bool(current_binding)+ and proposed_binding == current_binding+ )+ requested = (+ _reasoning_efforts(proposed_profile)+ if isinstance(proposed_profile, Mapping) and same_bound_account+ else _reasoning_efforts(current_profile)+ )+ for model in current_profile.get("models", []):+ if not isinstance(model, dict):+ continue+ model.pop("reasoning_effort", None)+ slug = model.get("model")+ supported = model.get("codex_supported_reasoning_levels")+ effort = requested.get(slug) if isinstance(slug, str) else None+ if isinstance(supported, list) and effort in supported:+ model["reasoning_effort"] = effort++ insert_at = proposed_indexes[0] if proposed_indexes else current_indexes[0]+ unmanaged = [+ profile+ for index, profile in enumerate(proposed_profiles)+ if index not in proposed_index_set+ ]+ unmanaged.insert(min(insert_at, len(unmanaged)), current_profile)+ proposed_llm["profiles"] = unmanaged+ return reconcileddef sync_codex_catalog(catalog_service: ModelCatalogService,snapshot: CatalogSnapshot,+ *,+ account_id: str | None = None,) -> CatalogSyncResult:"""Publish the managed Codex profile into the shared model catalog.@@ -131,22 +247,38 @@ def sync_codex_catalog(install is usable right after sign-in without ever silently replacing amodel somebody already picked."""- profile = _managed_profile(snapshot)activated = Falsedef mutate(catalog: dict[str, Any]) -> None:nonlocal activatedllm = catalog["services"]["llm"]profiles = llm.setdefault("profiles", [])- managed_indexes = [- index- for index, existing in enumerate(profiles)- if existing.get("managed_by") == MANAGED_BY- ]+ # OAuth refreshes rebuild managed profiles, so preserve only the user-selected+ # reasoning override by the provider's stable model slug.+ managed_indexes = _managed_profile_indexes(profiles)+ account_binding = _codex_account_binding(account_id) if account_id is not None else None+ existing_profile = profiles[managed_indexes[0]] if managed_indexes else None+ preserve_overrides = account_binding is None or (+ isinstance(existing_profile, Mapping)+ and existing_profile.get("codex_account_binding") == account_binding+ )+ reasoning_efforts = (+ _reasoning_efforts(existing_profile)+ if isinstance(existing_profile, Mapping) and preserve_overrides+ else {}+ )+ profile = _managed_profile(+ snapshot,+ reasoning_efforts,+ account_binding=account_binding,+ )if managed_indexes:first_index = managed_indexes[0]+ managed_index_set = set(managed_indexes)profiles[:] = [- existing for existing in profiles if existing.get("managed_by") != MANAGED_BY+ existing+ for index, existing in enumerate(profiles)+ if index not in managed_index_set]profiles.insert(min(first_index, len(profiles)), profile)else:@@ -343,15 +475,32 @@ class CodexOAuthService:payload,expected_generation=operation.expected_generation,)- committed = self._store.commit_credentials(- credentials,- expected_generation=operation.expected_generation,- )+ async with self._catalog_sync_lock:+ catalog = self._model_catalog.load()+ profiles = catalog.get("services", {}).get("llm", {}).get("profiles", [])+ managed_indexes = (+ _managed_profile_indexes(profiles) if isinstance(profiles, list) else []+ )+ committed = self._store.commit_credentials(+ credentials,+ expected_generation=operation.expected_generation,+ )+ account_binding = _codex_account_binding(committed.account_id)+ if any(+ not isinstance(profiles[index], Mapping)+ or profiles[index].get("codex_account_binding") != account_binding+ for index in managed_indexes+ ):+ remove_codex_catalog(self._model_catalog)operation.operation_state = "fetching_models"await self._catalog.invalidate()snapshot = await self._catalog.get(committed, force=True)async with self._catalog_sync_lock:- sync_result = sync_codex_catalog(self._model_catalog, snapshot)+ sync_result = sync_codex_catalog(+ self._model_catalog,+ snapshot,+ account_id=committed.account_id,+ )self._last_snapshot = snapshotoperation.activated = sync_result.activatedoperation.operation_state = "completed"@@ -420,7 +569,11 @@ class CodexOAuthService:409,)snapshot = await self._catalog.get(credentials, force=True)- sync_codex_catalog(self._model_catalog, snapshot)+ sync_codex_catalog(+ self._model_catalog,+ snapshot,+ account_id=credentials.account_id,+ )self._last_snapshot = snapshotreturn self.public_status()@@ -438,6 +591,54 @@ class CodexOAuthService:refreshed = await self._refresh_credentials(credentials)return refreshed.public_token()+ def profile_matches_current_account(self, profile: Mapping[str, Any]) -> bool:+ credentials = self._store.load_credentials()+ return bool(+ credentials is not None+ and profile.get("managed_by") == MANAGED_BY+ and profile.get("codex_account_binding")+ == _codex_account_binding(credentials.account_id)+ )++ def validate_runtime_profile(+ self,+ token: CodexToken,+ model_slug: str,+ reasoning_effort: str | None,+ ) -> None:+ """Reject a model config that no longer belongs to the loaded token."""+ credentials = self._store.load_credentials()+ catalog = self._model_catalog.load()+ profiles = catalog.get("services", {}).get("llm", {}).get("profiles", [])+ managed_indexes = _managed_profile_indexes(profiles) if isinstance(profiles, list) else []+ profile = profiles[managed_indexes[0]] if managed_indexes else None+ if (+ credentials is None+ or credentials.generation != token.generation+ or credentials.account_id != token.account_id+ or not isinstance(profile, Mapping)+ or profile.get("codex_account_binding") != _codex_account_binding(token.account_id)+ ):+ raise CodexAuthError(+ "codex_catalog_unavailable",+ "Refresh Codex models before using this configuration.",+ 409,+ )++ for model in profile.get("models", []):+ if not isinstance(model, Mapping) or model.get("model") != model_slug:+ continue+ stored_effort = model.get("reasoning_effort")+ effective_effort = stored_effort if isinstance(stored_effort, str) else None+ if effective_effort == reasoning_effort:+ return+ break+ raise CodexAuthError(+ "codex_catalog_unavailable",+ "Refresh Codex models before using this configuration.",+ 409,+ )+async def _refresh_credentials(self,credentials: CodexCredentials,@@ -525,6 +726,61 @@ class CodexOAuthService:async with self._inference_lock:self._logging_out = False+ async def set_reasoning_effort(+ self,+ model_slug: str,+ reasoning_effort: str | None,+ ) -> dict[str, Any]:+ async with self._catalog_sync_lock:++ def mutate(catalog: dict[str, Any]) -> None:+ profiles = catalog["services"]["llm"].get("profiles", [])+ managed_indexes = _managed_profile_indexes(profiles)+ if not managed_indexes:+ raise CodexAuthError(+ "codex_catalog_unavailable",+ "Sign in to Codex before changing reasoning effort.",+ 409,+ )+ profile = profiles[managed_indexes[0]]+ account_binding = profile.get("codex_account_binding")+ credentials = self._store.load_credentials()+ if (+ not isinstance(account_binding, str)+ or credentials is None+ or account_binding != _codex_account_binding(credentials.account_id)+ ):+ raise CodexAuthError(+ "codex_catalog_unavailable",+ "Refresh Codex models before changing reasoning effort.",+ 409,+ )+ for model in profile.get("models", []):+ if not isinstance(model, dict) or model.get("model") != model_slug:+ continue+ supported = model.get("codex_supported_reasoning_levels")+ if reasoning_effort is not None and (+ not isinstance(supported, list) or reasoning_effort not in supported+ ):+ raise CodexAuthError(+ "reasoning_effort_unsupported",+ "The selected Codex model does not support that reasoning effort.",+ 422,+ )+ if reasoning_effort is None:+ model.pop("reasoning_effort", None)+ else:+ model["reasoning_effort"] = reasoning_effort+ return+ raise CodexAuthError(+ "codex_model_not_found",+ "The selected model is not part of this Codex account.",+ 404,+ )++ self._model_catalog.update(mutate)+ return self.public_status()+def public_status(self) -> dict[str, Any]:operation = self._operationcredentials: CodexCredentials | None = None@@ -566,6 +822,7 @@ class CodexOAuthService:"catalog_source": snapshot.source if snapshot is not None else None,"catalog_fetched_at": (snapshot.fetched_at if snapshot is not None else None),"active_model": self._active_codex_model(),+ "models": self._reasoning_effort_models(credentials),"activated": (operation.activated if operation is not None else False),"error_code": (storage_error or (operation.error_code if operation is not None else None)@@ -608,6 +865,54 @@ class CodexOAuthService:value = model.get("model")return value if isinstance(value, str) and value else None+ def _reasoning_effort_models(+ self,+ credentials: CodexCredentials | None,+ ) -> list[dict[str, Any]]:+ catalog = self._model_catalog.load()+ profiles = catalog.get("services", {}).get("llm", {}).get("profiles", [])+ if not isinstance(profiles, list):+ return []+ managed_indexes = _managed_profile_indexes(profiles)+ if not managed_indexes:+ return []+ profile = profiles[managed_indexes[0]]+ account_binding = profile.get("codex_account_binding")+ if (+ not isinstance(account_binding, str)+ or credentials is None+ or account_binding != _codex_account_binding(credentials.account_id)+ ):+ return []+ models = profile.get("models", [])+ if not isinstance(models, list):+ return []++ result: list[dict[str, Any]] = []+ for model in models:+ if not isinstance(model, Mapping):+ continue+ slug = model.get("model")+ if not isinstance(slug, str) or not slug:+ continue+ name = model.get("name")+ supported = model.get("codex_supported_reasoning_levels")+ levels = (+ [level for level in supported if isinstance(level, str)]+ if isinstance(supported, list)+ else []+ )+ effort = model.get("reasoning_effort")+ result.append(+ {+ "model": slug,+ "name": name if isinstance(name, str) and name else slug,+ "supported_reasoning_levels": levels,+ "reasoning_effort": effort if isinstance(effort, str) else None,+ }+ )+ return result+def _credentials_from_payload(self,payload: dict[str, Any],@@ -870,6 +1175,7 @@ __all__ = ["codex_model_id","deliver_codex_oauth_callback","get_codex_oauth_service",+ "reconcile_codex_catalog_update","remove_codex_catalog","ssh_forward_command","sync_codex_catalog",diff --git a/deeptutor/services/llm/provider_core/openai_codex_provider.py b/deeptutor/services/llm/provider_core/openai_codex_provider.pyindex 95a15d68d..d4bdd17c6 100644--- a/deeptutor/services/llm/provider_core/openai_codex_provider.py+++ b/deeptutor/services/llm/provider_core/openai_codex_provider.py@@ -50,10 +50,11 @@ class OpenAICodexProvider(LLMProvider):on_content_delta: Callable[[str], Awaitable[None]] | None = None,) -> LLMResponse:model_name = model or self.default_model+ model_slug = _strip_model_prefix(model_name)system_prompt, input_items = convert_messages(messages)body: dict[str, Any] = {- "model": _strip_model_prefix(model_name),+ "model": model_slug,"store": False,"stream": True,"instructions": system_prompt,@@ -73,6 +74,7 @@ class OpenAICodexProvider(LLMProvider):async with service.inference_guard():try:token = await self._load_token()+ service.validate_runtime_profile(token, model_slug, reasoning_effort)headers = _build_headers(token.account_id, token.access_token)try:content, tool_calls, finish_reason = await _request_codex(diff --git a/tests/api/test_codex_oauth_scope.py b/tests/api/test_codex_oauth_scope.pyindex 0a682451f..597cbb869 100644--- a/tests/api/test_codex_oauth_scope.py+++ b/tests/api/test_codex_oauth_scope.py@@ -58,6 +58,14 @@ class _Service:self.calls.append("refresh")return {"connection": "connected"}+ async def set_reasoning_effort(+ self,+ model: str,+ reasoning_effort: str | None,+ ) -> dict[str, Any]:+ self.calls.append(f"reasoning:{model}:{reasoning_effort}")+ return {"connection": "connected"}+def _user(uid: str, *, role: str, root) -> CurrentUser:return CurrentUser(@@ -92,6 +100,18 @@ def test_an_ordinary_user_drives_their_own_codex_lifecycle(client, method, path)assert service.calls, "the request must reach the owner-scoped service"+def test_an_ordinary_user_sets_their_own_codex_reasoning_effort(client) -> None:+ test_client, service, _current = client++ response = test_client.post(+ "/api/v1/settings/providers/openai-codex/models/reasoning-effort",+ json={"model": "gpt-5.6-sol", "reasoning_effort": "high"},+ )++ assert response.status_code == 200+ assert service.calls == ["reasoning:gpt-5.6-sol:high"]++@pytest.mark.parametrize(("method", "path"), CODEX_ROUTES)def test_a_partner_is_refused(client, tmp_path, method, path) -> None:"""A partner inherits its owner's login at call time; letting it in here@@ -103,3 +123,16 @@ def test_a_partner_is_refused(client, tmp_path, method, path) -> None:assert response.status_code == 403assert service.calls == []+++def test_a_partner_cannot_change_their_owners_reasoning_effort(client, tmp_path) -> None:+ test_client, service, current = client+ current["user"] = _user(f"{PARTNER_USER_PREFIX}ada", role="user", root=tmp_path / "partner-ada")++ response = test_client.post(+ "/api/v1/settings/providers/openai-codex/models/reasoning-effort",+ json={"model": "gpt-5.6-sol", "reasoning_effort": "high"},+ )++ assert response.status_code == 403+ assert service.calls == []diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex c8551bb75..dde4aa324 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -204,6 +204,37 @@ def _build_catalog(}+def _managed_codex_profile(+ supported: list[str],+ reasoning_effort: str | None = None,+ *,+ account_binding: str | None = "account-binding",+) -> dict[str, Any]:+ model = {+ "id": "llm-model-openai-codex-sol",+ "name": "GPT 5.6 Sol",+ "model": "gpt-5.6-sol",+ "context_window": "128000",+ "context_window_source": "metadata",+ "codex_supported_reasoning_levels": supported,+ }+ if reasoning_effort is not None:+ model["reasoning_effort"] = reasoning_effort+ profile = {+ "id": "llm-profile-openai-codex-managed",+ "name": "OpenAI Codex",+ "binding": "openai_codex",+ "base_url": "https://chatgpt.com/backend-api",+ "api_key": "",+ "managed_by": "openai_codex_oauth",+ "read_only": True,+ "models": [model],+ }+ if account_binding is not None:+ profile["codex_account_binding"] = account_binding+ return profile++def _patch_runtime(monkeypatch: pytest.MonkeyPatch,service: _FakeCatalogService,@@ -671,6 +702,188 @@ async def test_apply_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monkassert new_embedding_client.config.model == "text-embedding-after-apply"[email protected]("operation", ["save", "apply"])+ ("supported", "requested", "expected"),+ [+ (["medium"], "high", None),+ (["medium", "high"], "high", "high"),+ (["medium", "high"], None, None),+ ],+)+async def test_catalog_writes_preserve_current_managed_codex_metadata(+ monkeypatch: pytest.MonkeyPatch,+ operation: str,+ supported: list[str],+ requested: str | None,+ expected: str | None,+) -> None:+ current = _build_catalog(+ llm_model="gpt-standard",+ llm_base_url="https://llm.example/v1",+ llm_api_key="llm-key",+ embedding_model="text-embedding-current",+ embedding_base_url="https://embedding.example/v1/embeddings",+ embedding_api_key="",+ )+ managed_profile = _managed_codex_profile(+ supported,+ reasoning_effort="medium" if requested is None else None,+ )+ managed_model = managed_profile["models"][0]+ current["services"]["llm"]["profiles"].append(managed_profile)+ current["services"]["llm"]["active_profile_id"] = managed_profile["id"]+ current["services"]["llm"]["active_model_id"] = managed_model["id"]+ service = _FakeCatalogService(current)+ monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)++ stale_draft = deepcopy(current)+ stale_draft["services"]["embedding"]["profiles"][0]["name"] = "Unsaved edit"+ stale_model = stale_draft["services"]["llm"]["profiles"][1]["models"][0]+ stale_model["context_window"] = "272000"+ stale_model["codex_supported_reasoning_levels"] = ["medium", "high", "xhigh"]+ if requested is not None:+ stale_model["reasoning_effort"] = requested+ else:+ stale_model.pop("reasoning_effort", None)+ payload = settings_router.CatalogPayload(catalog=stale_draft)++ if operation == "save":+ await settings_router.update_catalog(payload)+ else:+ await settings_router.apply_catalog(payload)++ stored = service.load()+ stored_model = stored["services"]["llm"]["profiles"][1]["models"][0]+ assert stored_model["context_window"] == "128000"+ assert stored_model["codex_supported_reasoning_levels"] == supported+ assert stored_model.get("reasoning_effort") == expected+ assert stored["services"]["embedding"]["profiles"][0]["name"] == "Unsaved edit"++[email protected]("operation", ["save", "apply"])+ ("current_binding", "proposed_binding"),+ [+ ("account-b-binding", "account-a-binding"),+ (None, None),+ ],+)+async def test_catalog_write_rejects_unbound_or_cross_account_codex_reasoning_changes(+ monkeypatch: pytest.MonkeyPatch,+ operation: str,+ current_binding: str | None,+ proposed_binding: str | None,+) -> None:+ current = _build_catalog(+ llm_model="gpt-standard",+ llm_base_url="https://llm.example/v1",+ llm_api_key="llm-key",+ embedding_model="text-embedding-current",+ embedding_base_url="https://embedding.example/v1/embeddings",+ embedding_api_key="",+ )+ current_profile = _managed_codex_profile(+ ["medium", "high"],+ reasoning_effort="medium",+ account_binding=current_binding,+ )+ current["services"]["llm"]["profiles"].append(current_profile)+ service = _FakeCatalogService(current)+ monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)++ stale_draft = deepcopy(current)+ stale_profile = stale_draft["services"]["llm"]["profiles"][1]+ if proposed_binding is None:+ stale_profile.pop("codex_account_binding", None)+ else:+ stale_profile["codex_account_binding"] = proposed_binding+ stale_profile["models"][0]["reasoning_effort"] = "high"+ payload = settings_router.CatalogPayload(catalog=stale_draft)++ if operation == "save":+ await settings_router.update_catalog(payload)+ else:+ await settings_router.apply_catalog(payload)++ stored_profile = service.load()["services"]["llm"]["profiles"][1]+ assert stored_profile.get("codex_account_binding") == current_binding+ assert stored_profile["models"][0]["reasoning_effort"] == "medium"++[email protected]("current_has_managed", [True, False])+async def test_catalog_write_uses_current_managed_codex_profile_presence(+ monkeypatch: pytest.MonkeyPatch,+ current_has_managed: bool,+) -> None:+ base = _build_catalog(+ llm_model="gpt-standard",+ llm_base_url="https://llm.example/v1",+ llm_api_key="llm-key",+ embedding_model="text-embedding-current",+ embedding_base_url="https://embedding.example/v1/embeddings",+ embedding_api_key="",+ )+ current = deepcopy(base)+ stale_draft = deepcopy(base)+ managed_profile = _managed_codex_profile(["medium", "high"])+ if current_has_managed:+ current["services"]["llm"]["profiles"].append(managed_profile)+ else:+ stale_draft["services"]["llm"]["profiles"].append(managed_profile)+ service = _FakeCatalogService(current)+ monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)++ await settings_router.update_catalog(settings_router.CatalogPayload(catalog=stale_draft))++ managed = [+ profile+ for profile in service.load()["services"]["llm"]["profiles"]+ if profile.get("managed_by") == "openai_codex_oauth"+ ]+ assert bool(managed) is current_has_managed++[email protected]("operation", ["save", "apply"])+async def test_incomplete_catalog_write_preserves_the_current_managed_codex_profile(+ monkeypatch: pytest.MonkeyPatch,+ operation: str,+) -> None:+ current = _build_catalog(+ llm_model="gpt-standard",+ llm_base_url="https://llm.example/v1",+ llm_api_key="llm-key",+ embedding_model="text-embedding-current",+ embedding_base_url="https://embedding.example/v1/embeddings",+ embedding_api_key="",+ )+ managed_profile = _managed_codex_profile(+ ["medium", "high"],+ reasoning_effort="medium",+ account_binding="current-account-binding",+ )+ current["services"]["llm"]["profiles"].append(managed_profile)+ service = _FakeCatalogService(current)+ monkeypatch.setattr(settings_router, "get_model_catalog_service", lambda: service)+ monkeypatch.setattr(settings_router, "_invalidate_runtime_caches", lambda: None)+ payload = settings_router.CatalogPayload(catalog={"version": 1})++ if operation == "save":+ await settings_router.update_catalog(payload)+ else:+ await settings_router.apply_catalog(payload)++ stored_profiles = service.load()["services"]["llm"]["profiles"]+ assert stored_profiles == [managed_profile]++@pytest.mark.asyncioasync def test_enabled_tools_roundtrip(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:settings_file = tmp_path / "interface.json"diff --git a/tests/multi_user/test_personal_codex_models.py b/tests/multi_user/test_personal_codex_models.pyindex 8ffd7796f..599ed9a70 100644--- a/tests/multi_user/test_personal_codex_models.py+++ b/tests/multi_user/test_personal_codex_models.py@@ -67,6 +67,16 @@ def no_grants(monkeypatch):monkeypatch.setattr(model_access, "load_grant", lambda _uid=None: {"models": {"llm": []}})[email protected](autouse=True)+def current_codex_profile(monkeypatch):+ monkeypatch.setattr(+ personal_models,+ "_codex_profile_is_current",+ lambda _profile: True,+ raising=False,+ )++def test_personal_catalog_is_the_users_own_file_not_the_shared_one(as_user, mu_isolated_root):"""The whole isolation argument rests on this: nothing a user does canreach the catalog the administrator manages."""@@ -99,6 +109,28 @@ def test_signed_in_user_sees_their_own_codex_models(as_user, monkeypatch, no_gra) == {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}+def test_mismatched_codex_profile_is_not_exposed_as_a_personal_model(+ as_user,+ monkeypatch,+ no_grants,+):+ monkeypatch.setattr(model_access, "admin_catalog", lambda: _admin_catalog([]))+ _sign_in_codex(as_user, "u_alice", "m-sol", "gpt-5.6-sol")+ monkeypatch.setattr(+ personal_models,+ "_codex_profile_is_current",+ lambda _profile: False,+ )++ with as_user("u_alice"):+ assert model_access.redacted_model_access()["llm"] == []+ assert model_access.has_capability_access("llm") is False+ with pytest.raises(PermissionError):+ model_access.apply_allowed_llm_selection(+ {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}+ )++def test_one_users_codex_is_invisible_to_another(as_user, monkeypatch, no_grants):monkeypatch.setattr(model_access, "admin_catalog", lambda: _admin_catalog([]))_sign_in_codex(as_user, "u_alice", "m-sol", "gpt-5.6-sol")diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.pyindex def6aa93d..688cf739d 100644--- a/tests/services/codex_auth/test_service.py+++ b/tests/services/codex_auth/test_service.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asynciofrom copy import deepcopy+import hashlibimport jsonfrom pathlib import Pathfrom typing import Any@@ -28,6 +29,7 @@ from deeptutor.services.codex_auth.service import ()from deeptutor.services.codex_auth.storage import CodexCredentialStorefrom deeptutor.services.config.model_catalog import ModelCatalogService+from deeptutor.services.config.provider_runtime import resolve_llm_runtime_configdef test_each_user_gets_their_own_codex_credential_root(@@ -166,6 +168,7 @@ def _model(*,display_name: str | None = None,priority: int = 1,+ supported_reasoning_levels: tuple[str, ...] = ("medium", "high"),context_window: int | None = None,max_context_window: int | None = None,) -> CodexModel:@@ -175,7 +178,7 @@ def _model(priority=priority,visibility="list",default_reasoning_level="medium",- supported_reasoning_levels=("medium", "high"),+ supported_reasoning_levels=supported_reasoning_levels,supports_reasoning_summary=True,supports_parallel_tool_calls=True,use_responses_lite=False,@@ -276,6 +279,22 @@ def test_sync_publishes_a_read_only_owner_bound_codex_profile(tmp_path: Path) ->assert profile["models"][0]["context_window_source"] == "metadata"+def test_sync_binds_the_managed_profile_without_storing_the_raw_account_id(+ tmp_path: Path,+) -> None:+ service, _original = _seeded_service(tmp_path)++ result = sync_codex_catalog(+ service,+ _snapshot("live", _model("gpt-5.6-sol")),+ account_id="account-123",+ )++ profile = _managed_profile(result.catalog)+ assert profile["codex_account_binding"] == hashlib.sha256(b"account-123").hexdigest()+ assert "account-123" not in json.dumps(profile)++def test_sync_uses_max_context_window_when_current_window_is_missing(tmp_path: Path) -> None:service = ModelCatalogService(tmp_path / "model_catalog.json")@@ -347,6 +366,118 @@ def test_refresh_replaces_only_managed_models(tmp_path: Path) -> None:)+def test_refresh_preserves_a_supported_reasoning_override_for_the_same_model(+ tmp_path: Path,+) -> None:+ service = ModelCatalogService(tmp_path / "model_catalog.json")+ initial = sync_codex_catalog(+ service,+ _snapshot("live", _model("gpt-5.6-sol"), _model("gpt-5.6-terra")),+ account_id="account-a",+ )+ profile = _managed_profile(initial.catalog)+ profile["models"][0]["reasoning_effort"] = "high"+ service.save(initial.catalog)++ refreshed = sync_codex_catalog(+ service,+ _snapshot("live", _model("gpt-5.6-terra"), _model("gpt-5.6-sol")),+ account_id="account-a",+ )++ efforts = {+ model["model"]: model.get("reasoning_effort")+ for model in _managed_profile(refreshed.catalog)["models"]+ }+ assert efforts == {"gpt-5.6-terra": None, "gpt-5.6-sol": "high"}+ assert resolve_llm_runtime_config(catalog=refreshed.catalog).reasoning_effort == "high"+++def test_account_switch_does_not_carry_a_reasoning_override(+ tmp_path: Path,+) -> None:+ service = ModelCatalogService(tmp_path / "model_catalog.json")+ initial = sync_codex_catalog(+ service,+ _snapshot("live", _model("gpt-5.6-sol")),+ account_id="account-a",+ )+ _managed_profile(initial.catalog)["models"][0]["reasoning_effort"] = "high"+ service.save(initial.catalog)++ switched = sync_codex_catalog(+ service,+ _snapshot("live", _model("gpt-5.6-sol")),+ account_id="account-b",+ )++ profile = _managed_profile(switched.catalog)+ assert "reasoning_effort" not in profile["models"][0]+ assert profile["codex_account_binding"] == hashlib.sha256(b"account-b").hexdigest()+++def test_refresh_drops_a_reasoning_override_the_model_no_longer_supports(+ tmp_path: Path,+) -> None:+ service = ModelCatalogService(tmp_path / "model_catalog.json")+ initial = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))+ profile = _managed_profile(initial.catalog)+ profile["models"][0]["reasoning_effort"] = "high"+ service.save(initial.catalog)++ refreshed = sync_codex_catalog(+ service,+ _snapshot(+ "live",+ _model("gpt-5.6-sol", supported_reasoning_levels=("medium",)),+ ),+ )++ model = _managed_profile(refreshed.catalog)["models"][0]+ assert "reasoning_effort" not in model+++def test_refresh_keeps_the_canonical_profile_override_when_removing_duplicates(+ tmp_path: Path,+) -> None:+ service = ModelCatalogService(tmp_path / "model_catalog.json")+ initial = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))+ canonical = _managed_profile(initial.catalog)+ canonical["models"][0]["reasoning_effort"] = "medium"+ duplicate = deepcopy(canonical)+ duplicate["id"] = f"{CODEX_PROFILE_ID}-duplicate"+ duplicate["models"][0]["reasoning_effort"] = "high"+ initial.catalog["services"]["llm"]["profiles"].append(duplicate)+ service.save(initial.catalog)++ refreshed = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))++ managed = [+ profile+ for profile in refreshed.catalog["services"]["llm"]["profiles"]+ if profile.get("managed_by") == MANAGED_BY+ ]+ assert len(managed) == 1+ assert managed[0]["models"][0]["reasoning_effort"] == "medium"+++def test_refresh_ignores_an_override_with_a_non_string_model_identity(+ tmp_path: Path,+) -> None:+ service = ModelCatalogService(tmp_path / "model_catalog.json")+ initial = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))+ stale = _managed_profile(initial.catalog)["models"][0]+ stale["model"] = []+ stale["reasoning_effort"] = "high"+ service.save(initial.catalog)++ refreshed = sync_codex_catalog(service, _snapshot("live", _model("gpt-5.6-sol")))++ model = _managed_profile(refreshed.catalog)["models"][0]+ assert model["model"] == "gpt-5.6-sol"+ assert "reasoning_effort" not in model++def test_refresh_repoints_a_selection_whose_model_left_the_account(tmp_path: Path) -> None:service = ModelCatalogService(tmp_path / "model_catalog.json")sync_codex_catalog(service, _snapshot("live", _model("retired-model")))@@ -515,13 +646,14 @@ def _stored_credentials(token: str = "old",*,expires_at: int = 10_000,+ account_id: str = "account-123",) -> CodexCredentials:return CodexCredentials(schema_version=1,access_token=f"{token}-access",refresh_token=f"{token}-refresh",id_token=f"{token}-id",- account_id="account-123",+ account_id=account_id,expires_at=expires_at,generation=0,)@@ -579,6 +711,155 @@ async def _wait_until_terminal(service: CodexOAuthService) -> dict[str, Any]:raise AssertionError("Codex login operation did not finish")+def _bound_reasoning_service(+ tmp_path: Path,+ snapshot: CatalogSnapshot,+) -> tuple[CodexOAuthService, ModelCatalogService]:+ model_catalog, _original = _seeded_service(tmp_path)+ store = CodexCredentialStore(tmp_path / "secrets")+ credentials = _stored_credentials()+ store.commit_credentials(credentials, expected_generation=0)+ sync_codex_catalog(+ model_catalog,+ snapshot,+ account_id=credentials.account_id,+ )+ return (+ CodexOAuthService(+ store,+ FakeCatalog(snapshot),+ model_catalog,+ oauth_client=FakeOAuthClient(),+ ),+ model_catalog,+ )+++async def test_owner_sets_supported_reasoning_effort_on_their_managed_model(+ tmp_path: Path,+) -> None:+ snapshot = _snapshot("live", _model("gpt-5.6-sol"), _model("gpt-5.6-terra"))+ service, model_catalog = _bound_reasoning_service(tmp_path, snapshot)+ synced = model_catalog.load()+ llm = synced["services"]["llm"]+ llm["active_profile_id"] = CODEX_PROFILE_ID+ llm["active_model_id"] = codex_model_id("gpt-5.6-sol")+ model_catalog.save(synced)++ status = await service.set_reasoning_effort("gpt-5.6-sol", "high")++ catalog = model_catalog.load()+ models = _managed_profile(catalog)["models"]+ assert models[0]["reasoning_effort"] == "high"+ assert "reasoning_effort" not in models[1]+ assert status["models"] == [+ {+ "model": "gpt-5.6-sol",+ "name": "gpt-5.6-sol",+ "supported_reasoning_levels": ["medium", "high"],+ "reasoning_effort": "high",+ },+ {+ "model": "gpt-5.6-terra",+ "name": "gpt-5.6-terra",+ "supported_reasoning_levels": ["medium", "high"],+ "reasoning_effort": None,+ },+ ]+ assert resolve_llm_runtime_config(catalog=catalog).reasoning_effort == "high"+++async def test_runtime_validation_rejects_a_stale_reasoning_effort(tmp_path: Path) -> None:+ snapshot = _snapshot("live", _model("gpt-5.6-sol"))+ service, _model_catalog = _bound_reasoning_service(tmp_path, snapshot)+ token = await service.get_token()+ validator = getattr(service, "validate_runtime_profile", None)++ assert callable(validator)+ with pytest.raises(CodexAuthError) as exc_info:+ validator(token, "gpt-5.6-sol", "high")++ assert exc_info.value.code == "codex_catalog_unavailable"+ assert exc_info.value.http_status == 409+++def test_profile_binding_matches_only_current_credentials(tmp_path: Path) -> None:+ snapshot = _snapshot("live", _model("gpt-5.6-sol"))+ service, model_catalog = _bound_reasoning_service(tmp_path, snapshot)+ profile = _managed_profile(model_catalog.load())+ matcher = getattr(service, "profile_matches_current_account", None)++ assert callable(matcher)+ assert matcher(profile) is True+ profile["codex_account_binding"] = "stale-account-binding"+ assert matcher(profile) is False+++async def test_owner_cannot_set_an_unsupported_reasoning_effort(tmp_path: Path) -> None:+ snapshot = _snapshot("live", _model("gpt-5.6-sol", supported_reasoning_levels=("medium",)))+ service, model_catalog = _bound_reasoning_service(tmp_path, snapshot)+ before = model_catalog.load()++ with pytest.raises(CodexAuthError) as exc_info:+ await service.set_reasoning_effort("gpt-5.6-sol", "high")++ assert exc_info.value.code == "reasoning_effort_unsupported"+ assert exc_info.value.http_status == 422+ assert model_catalog.load() == before+++async def test_owner_can_restore_provider_default_reasoning_effort(tmp_path: Path) -> None:+ snapshot = _snapshot("live", _model("gpt-5.6-sol"))+ service, model_catalog = _bound_reasoning_service(tmp_path, snapshot)+ synced = model_catalog.load()+ _managed_profile(synced)["models"][0]["reasoning_effort"] = "high"+ model_catalog.save(synced)++ status = await service.set_reasoning_effort("gpt-5.6-sol", None)++ model = _managed_profile(model_catalog.load())["models"][0]+ assert "reasoning_effort" not in model+ assert status["models"][0]["reasoning_effort"] is None+++async def test_owner_cannot_update_a_model_outside_their_managed_profile(tmp_path: Path) -> None:+ snapshot = _snapshot("live", _model("gpt-5.6-sol"))+ service, model_catalog = _bound_reasoning_service(tmp_path, snapshot)+ before = model_catalog.load()++ with pytest.raises(CodexAuthError) as exc_info:+ await service.set_reasoning_effort("deepseek-ai/DeepSeek-V3", "high")++ assert exc_info.value.code == "codex_model_not_found"+ assert exc_info.value.http_status == 404+ assert model_catalog.load() == before+++async def test_reasoning_effort_requires_a_managed_codex_profile(tmp_path: Path) -> None:+ model_catalog, _original = _seeded_service(tmp_path)+ snapshot = _snapshot("live", _model("gpt-5.6-sol"))+ service = CodexOAuthService(+ CodexCredentialStore(tmp_path / "secrets"),+ FakeCatalog(snapshot),+ model_catalog,+ oauth_client=FakeOAuthClient(),+ )+ before = model_catalog.load()++ with pytest.raises(CodexAuthError) as exc_info:+ await service.set_reasoning_effort("gpt-5.6-sol", "high")++ assert exc_info.value.code == "codex_catalog_unavailable"+ assert exc_info.value.http_status == 409+ assert model_catalog.load() == before++@pytest.mark.asyncioasync def test_successful_live_login_keeps_the_existing_model_selection(tmp_path: Path,@@ -857,6 +1138,121 @@ async def test_catalog_failure_keeps_auth_but_not_selection(tmp_path: Path) -> Nassert store.load_credentials() is not None[email protected]("has_previous_credentials", [True, False])+async def test_account_switch_retires_old_catalog_before_fetching_new_models(+ tmp_path: Path,+ has_previous_credentials: bool,+) -> None:+ service, callback, oauth, catalog, store, model_catalog = await _oauth_service(tmp_path)+ if has_previous_credentials:+ store.commit_credentials(+ _stored_credentials(account_id="account-a"),+ expected_generation=0,+ )+ fallback_selection = _selection(model_catalog.load())+ account_a = sync_codex_catalog(+ model_catalog,+ _snapshot("account-a", _model("gpt-5.6-sol")),+ account_id="account-a",+ ).catalog+ profile = _managed_profile(account_a)+ profile["models"][0]["reasoning_effort"] = "high"+ llm = account_a["services"]["llm"]+ llm["active_profile_id"] = profile["id"]+ llm["active_model_id"] = profile["models"][0]["id"]+ model_catalog.save(account_a)++ oauth.exchange_payload["account_id"] = "account-b"+ catalog.snapshot = _snapshot("account-b", _model("gpt-5.6-sol"))+ catalog.get_started = asyncio.Event()+ catalog.get_release = asyncio.Event()++ started = await service.start_login()+ callback.complete(started["authorize_url"])+ await asyncio.wait_for(catalog.get_started.wait(), timeout=1)++ current = store.load_credentials()+ assert current is not None+ assert current.account_id == "account-b"+ during_fetch = model_catalog.load()+ assert not any(+ profile.get("managed_by") == MANAGED_BY+ for profile in during_fetch["services"]["llm"]["profiles"]+ )+ assert _selection(during_fetch) == fallback_selection++ catalog.get_release.set()+ status = await _wait_until_terminal(service)+ assert status["operation_state"] == "completed"+++async def test_failed_account_switch_rejects_a_stale_reasoning_write(+ tmp_path: Path,+) -> None:+ service, callback, oauth, catalog, store, model_catalog = await _oauth_service(tmp_path)+ store.commit_credentials(+ _stored_credentials(account_id="account-a"),+ expected_generation=0,+ )+ account_a = _snapshot("account-a", _model("account-a-only"))+ sync_codex_catalog(+ model_catalog,+ account_a,+ account_id="account-a",+ )+ oauth.exchange_payload["account_id"] = "account-b"+ catalog.error = CodexAuthError(+ "catalog_unavailable",+ "The Codex model catalog is unavailable.",+ 503,+ )++ started = await service.start_login()+ callback.complete(started["authorize_url"])+ status = await _wait_until_terminal(service)+ before = model_catalog.load()++ current = store.load_credentials()+ assert current is not None+ assert current.account_id == "account-b"+ assert status["operation_state"] == "failed"+ assert status["models"] == []+ assert not any(+ profile.get("managed_by") == MANAGED_BY for profile in before["services"]["llm"]["profiles"]+ )+ with pytest.raises(CodexAuthError) as exc_info:+ await service.set_reasoning_effort("account-a-only", "high")+ assert exc_info.value.code == "codex_catalog_unavailable"+ assert model_catalog.load() == before+++async def test_unbound_managed_profile_is_hidden_and_read_only_until_refresh(+ tmp_path: Path,+) -> None:+ model_catalog, _original = _seeded_service(tmp_path)+ snapshot = _snapshot("legacy", _model("gpt-5.6-sol"))+ sync_codex_catalog(model_catalog, snapshot)+ store = CodexCredentialStore(tmp_path / "credentials")+ store.commit_credentials(_stored_credentials(), expected_generation=0)+ service = CodexOAuthService(+ store,+ FakeCatalog(snapshot),+ model_catalog,+ oauth_client=FakeOAuthClient(),+ )+ before = model_catalog.load()++ with pytest.raises(CodexAuthError) as exc_info:+ await service.set_reasoning_effort("gpt-5.6-sol", "high")++ assert exc_info.value.code == "codex_catalog_unavailable"+ assert service.public_status()["models"] == []+ assert model_catalog.load() == before++@pytest.mark.asyncio@pytest.mark.parametrize("failure", ["state", "timeout", "exchange"])async def test_login_failures_do_not_overwrite_old_credentials(diff --git a/tests/services/llm/test_codex_disable_ssl_verify.py b/tests/services/llm/test_codex_disable_ssl_verify.pyindex 91a062ff1..6f65e94f7 100644--- a/tests/services/llm/test_codex_disable_ssl_verify.py+++ b/tests/services/llm/test_codex_disable_ssl_verify.py@@ -41,6 +41,14 @@ def _stub_token_loader(monkeypatch: pytest.MonkeyPatch) -> None:async def recover_after_unauthorized(self, generation: int) -> None:del generation+ def validate_runtime_profile(+ self,+ token: _Token,+ model_slug: str,+ reasoning_effort: str | None,+ ) -> None:+ del token, model_slug, reasoning_effort+monkeypatch.setattr(openai_codex_provider,"get_codex_oauth_service",diff --git a/tests/services/llm/test_openai_codex_oauth_provider.py b/tests/services/llm/test_openai_codex_oauth_provider.pyindex 5199a0a96..60b658e0c 100644--- a/tests/services/llm/test_openai_codex_oauth_provider.py+++ b/tests/services/llm/test_openai_codex_oauth_provider.py@@ -25,6 +25,7 @@ class FakeCodexService:self.token_calls = 0self.guard_entries = 0self.recovered_generation: int | None = None+ self.runtime_validations: list[tuple[CodexToken, str, str | None]] = []async def get_token(self) -> CodexToken:self.token_calls += 1@@ -33,6 +34,14 @@ class FakeCodexService:async def recover_after_unauthorized(self, generation: int) -> None:self.recovered_generation = generation+ def validate_runtime_profile(+ self,+ token: CodexToken,+ model_slug: str,+ reasoning_effort: str | None,+ ) -> None:+ self.runtime_validations.append((token, model_slug, reasoning_effort))+@asynccontextmanagerasync def inference_guard(self) -> AsyncIterator[None]:self.guard_entries += 1@@ -87,6 +96,7 @@ async def test_provider_uses_deeptutor_token_service_and_raw_sol_id(assert result.finish_reason == "stop"assert service.token_calls == 1assert service.guard_entries == 1+ assert service.runtime_validations == [(service.token, "gpt-5.6-sol", "medium")]assert url == CODEX_RESPONSES_URLassert headers["Authorization"] == "Bearer test-access-token"assert headers["chatgpt-account-id"] == "account-123"diff --git a/web/components/settings/CodexOAuthCard.tsx b/web/components/settings/CodexOAuthCard.tsxindex 52f2092c9..c1a241073 100644--- a/web/components/settings/CodexOAuthCard.tsx+++ b/web/components/settings/CodexOAuthCard.tsx@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next";import Button from "@/components/ui/Button";import { invalidateLLMOptionsCache } from "@/lib/llm-options";+import { reasoningEffortOptionsFromSupportedLevels } from "@/lib/reasoning-effort";import {buildSshForwardCommand,cancelCodexLogin,@@ -19,15 +20,22 @@ import {refreshCodexModels,shouldPollCodexStatus,startCodexLogin,+ setCodexReasoningEffort,type CodexLoginStart,type CodexOAuthStatus,+ type CodexReasoningModel,} from "@/lib/codex-oauth";import { useSettings } from "./SettingsContext";export function CodexOAuthCard() {const { t } = useTranslation();- const { reloadSettings, hasUnsavedChanges, setToast } = useSettings();+ const {+ catalogEditable,+ reloadSettings,+ hasUnsavedChanges,+ setToast,+ } = useSettings();const [status, setStatus] = useState<CodexOAuthStatus | null>(null);const [pending, setPending] = useState(false);const [errorKey, setErrorKey] = useState<string | null>(null);@@ -277,6 +285,29 @@ export function CodexOAuthCard() {}};+ const updateReasoningEffort = async (+ model: CodexReasoningModel,+ value: string,+ ) => {+ invalidateStatusRequests();+ setPending(true);+ try {+ const nextStatus = await setCodexReasoningEffort(model.model, value || null);+ invalidateStatusRequests();+ recordStatus(nextStatus);+ setErrorKey(null);+ setToast(t("codex.oauth.reasoningSaved"));+ } catch (error) {+ setErrorKey(+ codexErrorMessageKey(+ error instanceof CodexOAuthApiError ? error.code : null,+ ),+ );+ } finally {+ setPending(false);+ }+ };+const polling = Boolean(status && shouldPollCodexStatus(status));const connected = status?.connection === "connected";const messageKey =@@ -319,6 +350,47 @@ export function CodexOAuthCard() {{t("codex.oauth.modelCount", { count: status.model_count })}</p>)}+ {connected &&+ catalogEditable === false &&+ status.models.length > 0 && (+ <div className="mt-4 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">+ <p className="text-sm font-medium">+ {t("codex.oauth.reasoningTitle")}+ </p>+ <p className="mt-1 text-xs text-[var(--muted-foreground)]">+ {t("codex.oauth.reasoningDescription")}+ </p>+ <div className="mt-3 space-y-3">+ {status.models.map((model) => {+ const options = reasoningEffortOptionsFromSupportedLevels(+ model.supported_reasoning_levels,+ );+ if (options.length === 0) return null;+ return (+ <label key={model.model} className="block">+ <span className="mb-1 block truncate text-xs font-medium">+ {model.name}+ </span>+ <select+ className="h-9 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 text-sm text-[var(--foreground)] outline-none focus:border-[var(--ring)] disabled:cursor-not-allowed disabled:opacity-60"+ value={model.reasoning_effort || ""}+ disabled={pending}+ onChange={(event) =>+ void updateReasoningEffort(model, event.target.value)+ }+ >+ {options.map((option) => (+ <option key={option.value || "auto"} value={option.value}>+ {t(option.label)}+ </option>+ ))}+ </select>+ </label>+ );+ })}+ </div>+ </div>+ )}{remoteAccess && remoteGuidance && (<div className="mt-4 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3"><p className="text-sm font-medium">diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsxindex 9dde6b2f1..2e0f9840b 100644--- a/web/components/settings/ServiceConfigEditor.tsx+++ b/web/components/settings/ServiceConfigEditor.tsx@@ -16,9 +16,16 @@ import {import { useTranslation } from "react-i18next";import ProviderIcon from "@/components/common/ProviderIcon";-import { reasoningEffortOptions } from "@/lib/reasoning-effort";+import {+ reasoningEffortOptions,+ reasoningEffortOptionsFromSupportedLevels,+} from "@/lib/reasoning-effort";import { CodexOAuthCard } from "./CodexOAuthCard";-import { isCodexOAuthProfile, isManagedCodexProfile } from "./codex-profile";+import {+ isBoundManagedCodexProfile,+ isCodexOAuthProfile,+ isManagedCodexProfile,+} from "./codex-profile";import {type CatalogModel,type CatalogProfile,@@ -89,6 +96,7 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {(option) => option.value === activeProviderValue,);const isManagedCodex = isManagedCodexProfile(activeProfile);+ const isBoundManagedCodex = isBoundManagedCodexProfile(activeProfile);const isCodexOAuth = isCodexOAuthProfile(service,activeProviderValue,@@ -137,11 +145,17 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {: null;const reasoningOptions =service === "llm" && activeModel- ? reasoningEffortOptions(- activeProfile?.binding,- activeModel.model,- activeModel.reasoning_effort,- )+ ? isManagedCodex+ ? isBoundManagedCodex+ ? reasoningEffortOptionsFromSupportedLevels(+ activeModel.codex_supported_reasoning_levels ?? [],+ )+ : []+ : reasoningEffortOptions(+ activeProfile?.binding,+ activeModel.model,+ activeModel.reasoning_effort,+ ): [];const startModelRename = (model: CatalogModel) => {@@ -502,43 +516,49 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {})}</div>)}- {activeModel && !isCodexOAuth && (+ {activeModel && (!isCodexOAuth || isBoundManagedCodex) && (<div className="grid gap-4 sm:grid-cols-2">- <div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">- {t("Model ID")}+ {!isCodexOAuth && (+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("Model ID")}+ </div>+ <input+ className={inputClass}+ value={activeModel.model}+ onChange={(e) =>+ updateModelField(service, "model", e.target.value)+ }+ placeholder="gpt-4o"+ /></div>- <input- className={inputClass}- value={activeModel.model}- onChange={(e) =>- updateModelField(service, "model", e.target.value)- }- placeholder="gpt-4o"- />- </div>+ )}{service === "llm" && (<>- <div>- <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">- {t("Context Window")}- </div>- <input- className={inputClass}- inputMode="numeric"- value={activeModel.context_window || ""}- onChange={(e) =>- updateContextWindowField(e.target.value)- }- placeholder="65536"- />- <ContextWindowMeta model={activeModel} />- </div>- <ContextWindowDetectionBanner- model={activeModel}- detection={activeLlmDetection}- onApply={applyDetectedContextWindow}- />+ {!isCodexOAuth && (+ <>+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {t("Context Window")}+ </div>+ <input+ className={inputClass}+ inputMode="numeric"+ value={activeModel.context_window || ""}+ onChange={(e) =>+ updateContextWindowField(e.target.value)+ }+ placeholder="65536"+ />+ <ContextWindowMeta model={activeModel} />+ </div>+ <ContextWindowDetectionBanner+ model={activeModel}+ detection={activeLlmDetection}+ onApply={applyDetectedContextWindow}+ />+ </>+ )}{reasoningOptions.length > 0 && (<div><div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">diff --git a/web/components/settings/SettingsContext.tsx b/web/components/settings/SettingsContext.tsxindex 729c25d37..acbd146f0 100644--- a/web/components/settings/SettingsContext.tsx+++ b/web/components/settings/SettingsContext.tsx@@ -51,6 +51,7 @@ export type CatalogModel = {context_window_source?: string;context_window_detected_at?: string;reasoning_effort?: string;+ codex_supported_reasoning_levels?: string[];// Voice (TTS): free-form provider/model-specific voice string, e.g.// "alloy", "autumn", "model:voice". `response_format` is the TTS output// codec (mp3/wav/...) and is reused by imagegen ("url"/"b64_json").@@ -81,6 +82,7 @@ export type CatalogProfile = {id: string;name: string;managed_by?: string;+ codex_account_binding?: string;read_only?: boolean;binding?: string;provider?: string;diff --git a/web/components/settings/codex-profile.ts b/web/components/settings/codex-profile.tsindex e9b419f93..5c382004c 100644--- a/web/components/settings/codex-profile.ts+++ b/web/components/settings/codex-profile.ts@@ -14,6 +14,20 @@ export function isManagedCodexProfile(return profile?.managed_by === CODEX_MANAGED_BY;}+/** A managed profile may accept reasoning overrides only after an account-bound refresh. */+export function isBoundManagedCodexProfile(+ profile:+ | Pick<CatalogProfile, "managed_by" | "codex_account_binding">+ | null+ | undefined,+): boolean {+ return (+ isManagedCodexProfile(profile) &&+ typeof profile?.codex_account_binding === "string" &&+ Boolean(profile.codex_account_binding.trim())+ );+}+/*** Whether a profile authenticates through Codex OAuth instead of typed credentials.*diff --git a/web/lib/codex-oauth.ts b/web/lib/codex-oauth.tsindex b2fbaa758..e9bd9e810 100644--- a/web/lib/codex-oauth.ts+++ b/web/lib/codex-oauth.ts@@ -1,5 +1,12 @@import { apiFetch, apiUrl } from "@/lib/api";+export type CodexReasoningModel = {+ model: string;+ name: string;+ supported_reasoning_levels: string[];+ reasoning_effort: string | null;+};+export type CodexOAuthStatus = {connection: "disconnected" | "authorizing" | "connected" | "error";operation_id: string | null;@@ -26,6 +33,7 @@ export type CodexOAuthStatus = {| null;catalog_fetched_at: number | null;active_model: string | null;+ models: CodexReasoningModel[];activated: boolean;error_code: string | null;};@@ -123,9 +131,16 @@ export async function requestCodex<T>(path: string,method: "GET" | "POST",fetchImpl: typeof apiFetch = apiFetch,+ body?: unknown,): Promise<T> {const response = await fetchImpl(apiUrl(`${BASE}${path}`), {method,+ ...(body === undefined+ ? {}+ : {+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ }),skipAuthRedirect: true,});if (response.ok) {@@ -169,6 +184,19 @@ export function refreshCodexModels(): Promise<CodexOAuthStatus> {return requestCodex<CodexOAuthStatus>("/models/refresh", "POST");}+export function setCodexReasoningEffort(+ model: string,+ reasoningEffort: string | null,+ fetchImpl: typeof apiFetch = apiFetch,+): Promise<CodexOAuthStatus> {+ return requestCodex<CodexOAuthStatus>(+ "/models/reasoning-effort",+ "POST",+ fetchImpl,+ { model, reasoning_effort: reasoningEffort },+ );+}+export function logoutCodex(): Promise<CodexOAuthStatus> {return requestCodex<CodexOAuthStatus>("/oauth/logout", "POST");}@@ -193,6 +221,12 @@ export function codexErrorMessageKey(code: string | null): string {return "codex.oauth.callbackUnavailable";}if (code === "invalid_response") return "codex.oauth.invalidResponse";+ if (code === "reasoning_effort_unsupported") {+ return "codex.oauth.reasoningUnsupported";+ }+ if (code === "codex_model_not_found" || code === "codex_catalog_unavailable") {+ return "codex.oauth.reasoningCatalogChanged";+ }if (code === "login_cancelled") return "codex.oauth.cancelled";if (code === "authorization_denied") return "codex.oauth.denied";return "codex.oauth.requestFailed";diff --git a/web/lib/reasoning-effort.ts b/web/lib/reasoning-effort.tsindex 3f95223d6..5697814fa 100644--- a/web/lib/reasoning-effort.ts+++ b/web/lib/reasoning-effort.ts@@ -166,6 +166,13 @@ export function reasoningEffortOptions(return options([], current);}+export function reasoningEffortOptionsFromSupportedLevels(+ values: readonly string[],+): ReasoningEffortOption[] {+ const supported = [...new Set(values.map((value) => value.trim()).filter(Boolean))];+ return options(supported, "");+}+export function setModelReasoningEffort(model: { reasoning_effort?: string },value: string,diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ff90b5cf9..087c16b2b 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2777,6 +2777,11 @@"codex.oauth.denied": "Codex authorization was denied.","codex.oauth.requestFailed": "The Codex request failed. Try again.","codex.oauth.modelCount": "Models: {{count}}",+ "codex.oauth.reasoningTitle": "Reasoning effort",+ "codex.oauth.reasoningDescription": "Choose a default for each Codex model. Only levels supported by that model are available.",+ "codex.oauth.reasoningSaved": "Codex reasoning effort saved.",+ "codex.oauth.reasoningUnsupported": "That reasoning effort is no longer supported. Refresh models and choose again.",+ "codex.oauth.reasoningCatalogChanged": "The Codex model list changed. Refresh models and try again.","contextBudget.title": "Context window","contextBudget.chipAria": "Context window: {{percent}} used","contextBudget.usage": "{{used}} / {{total}} ({{percent}})",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 5cec632a7..7694f739a 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2777,6 +2777,11 @@"codex.oauth.denied": "Codex 授权被拒绝。","codex.oauth.requestFailed": "Codex 请求失败,请重试。","codex.oauth.modelCount": "模型:{{count}}",+ "codex.oauth.reasoningTitle": "推理强度",+ "codex.oauth.reasoningDescription": "为每个 Codex 模型选择默认推理强度。仅显示该模型实际支持的等级。",+ "codex.oauth.reasoningSaved": "Codex 推理强度已保存。",+ "codex.oauth.reasoningUnsupported": "该推理强度已不受支持,请刷新模型后重新选择。",+ "codex.oauth.reasoningCatalogChanged": "Codex 模型列表已变化,请刷新模型后重试。","contextBudget.title": "上下文窗口","contextBudget.chipAria": "上下文窗口:已用 {{percent}}","contextBudget.usage": "{{used}} / {{total}}({{percent}})",diff --git a/web/tests/codex-oauth-client.test.ts b/web/tests/codex-oauth-client.test.tsindex 3d3d3ae44..1ffdf5308 100644--- a/web/tests/codex-oauth-client.test.ts+++ b/web/tests/codex-oauth-client.test.ts@@ -11,6 +11,7 @@ import {codexStatusMessageKey,isLoopbackHostname,requestCodex,+ setCodexReasoningEffort,shouldPollCodexStatus,type CodexLoginStart,type CodexOAuthStatus,@@ -36,6 +37,7 @@ function status(overrides: Partial<CodexOAuthStatus> = {}): CodexOAuthStatus {catalog_source: null,catalog_fetched_at: null,active_model: null,+ models: [],activated: false,error_code: null,...overrides,@@ -261,6 +263,29 @@ test("Codex OAuth preserves structured errors from non-successful responses", as);});+test("ordinary users send a scoped Codex reasoning effort update", async () => {+ let capturedUrl = "";+ let capturedInit: RequestInit | undefined;+ const fetchImpl = async (+ input: RequestInfo | URL,+ init?: RequestInit,+ ): Promise<Response> => {+ capturedUrl = String(input);+ capturedInit = init;+ return Response.json(status({ connection: "connected" }));+ };++ await setCodexReasoningEffort("gpt-5.6-sol", "high", fetchImpl);++ assert.match(capturedUrl, /\/providers\/openai-codex\/models\/reasoning-effort$/);+ assert.equal(capturedInit?.method, "POST");+ assert.equal(capturedInit?.headers && new Headers(capturedInit.headers).get("content-type"), "application/json");+ assert.equal(+ capturedInit?.body,+ JSON.stringify({ model: "gpt-5.6-sol", reasoning_effort: "high" }),+ );+});+test("Codex terminal operation states stop polling", () => {for (const operation_state of ["completed",@@ -336,6 +361,16 @@ test("Codex error codes map to stable translation keys", () => {codexErrorMessageKey("invalid_response"),"codex.oauth.invalidResponse",);+ assert.equal(+ codexErrorMessageKey("reasoning_effort_unsupported"),+ "codex.oauth.reasoningUnsupported",+ );+ for (const code of ["codex_model_not_found", "codex_catalog_unavailable"]) {+ assert.equal(+ codexErrorMessageKey(code),+ "codex.oauth.reasoningCatalogChanged",+ );+ }});function componentBlock(diff --git a/web/tests/codex-oauth-settings-contract.test.ts b/web/tests/codex-oauth-settings-contract.test.tsindex 49573b84d..05ea09416 100644--- a/web/tests/codex-oauth-settings-contract.test.ts+++ b/web/tests/codex-oauth-settings-contract.test.ts@@ -4,10 +4,20 @@ import path from "node:path";import test from "node:test";import { createInstance } from "i18next";+import {+ CODEX_MANAGED_BY,+ isBoundManagedCodexProfile,+} from "../components/settings/codex-profile";+const EDITOR = path.resolve(process.cwd(),"components/settings/ServiceConfigEditor.tsx",);+const CARD = path.resolve(+ process.cwd(),+ "components/settings/CodexOAuthCard.tsx",+);+const CLIENT = path.resolve(process.cwd(), "lib/codex-oauth.ts");const HELPER = path.resolve(process.cwd(),"components/settings/codex-profile.ts",@@ -35,12 +45,48 @@ test("the Codex profile predicates live in one place", () => {);});-test("managed Codex profiles cannot expose profile or model editing", () => {+test("managed Codex reasoning controls require a current account binding", () => {+ const editor = readFileSync(EDITOR, "utf8");++ assert.equal(+ isBoundManagedCodexProfile({+ managed_by: CODEX_MANAGED_BY,+ codex_account_binding: "account-binding",+ }),+ true,+ );+ assert.equal(+ isBoundManagedCodexProfile({ managed_by: CODEX_MANAGED_BY }),+ false,+ );+ assert.match(editor, /isBoundManagedCodexProfile\(activeProfile\)/);+});++test("managed Codex profiles expose only provider-supported reasoning effort", () => {const source = readFileSync(EDITOR, "utf8");assert.match(source, /isManagedCodexProfile\(/);assert.match(source, /disabled=\{isManagedCodex\}/);assert.match(source, /!isCodexOAuth/);+ assert.match(source, /activeModel\.codex_supported_reasoning_levels/);+ assert.match(source, /!isCodexOAuth \|\| isBoundManagedCodex/);+});++test("ordinary users can edit only their owner-scoped Codex reasoning overrides", () => {+ const card = readFileSync(CARD, "utf8");+ const client = readFileSync(CLIENT, "utf8");++ assert.match(client, /models: CodexReasoningModel\[\]/);+ assert.match(card, /catalogEditable === false/);+ assert.match(card, /status\.models\.map\(\(model\)/);+ assert.match(+ card,+ /reasoningEffortOptionsFromSupportedLevels\(\s*model\.supported_reasoning_levels/,+ );+ assert.match(+ card,+ /setCodexReasoningEffort\(model\.model, value \|\| null\)/,+ );});test("Codex OAuth copy stays in sync across locales", () => {@@ -67,6 +113,11 @@ test("Codex OAuth copy stays in sync across locales", () => {"codex.oauth.callbackMissingUnknown","codex.oauth.callbackUnavailable","codex.oauth.invalidResponse",+ "codex.oauth.reasoningTitle",+ "codex.oauth.reasoningDescription",+ "codex.oauth.reasoningSaved",+ "codex.oauth.reasoningUnsupported",+ "codex.oauth.reasoningCatalogChanged",]) {assert.ok(codexKeys(en).includes(key));assert.equal(typeof en[key], "string");diff --git a/web/tests/reasoning-effort.test.ts b/web/tests/reasoning-effort.test.tsindex 2278de6f9..b6aedfba4 100644--- a/web/tests/reasoning-effort.test.ts+++ b/web/tests/reasoning-effort.test.ts@@ -3,6 +3,7 @@ import test from "node:test";import {reasoningEffortOptions,+ reasoningEffortOptionsFromSupportedLevels,setModelReasoningEffort,} from "../lib/reasoning-effort";@@ -106,6 +107,21 @@ test("unknown models stay hidden unless they already carry an override", () => {]);});+test("managed profiles use only the provider-supported reasoning levels", () => {+ assert.deepEqual(+ reasoningEffortOptionsFromSupportedLevels(["medium", "high"]).map(+ (option) => option.value,+ ),+ ["", "medium", "high"],+ );+ assert.deepEqual(+ reasoningEffortOptionsFromSupportedLevels(["high", "", "high", "medium"]).map(+ (option) => option.value,+ ),+ ["", "high", "medium"],+ );+});+test("Auto removes the catalog field instead of persisting an empty string", () => {const model: { reasoning_effort?: string } = {reasoning_effort: "high",