DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(codex): automatically discover client versions for model catalog refresh
ZJPexcd7c720eb11e
diff --git a/README.md b/README.mdindex 6f5ba78c5..94a228261 100644--- a/README.md+++ b/README.md@@ -803,6 +803,10 @@ Most sections use a draft-and-apply flow, so you can test a provider before comm**OpenAI Codex OAuth (experimental).** Picking **OpenAI Codex** under Models → LLM replaces the API-key fields with a browser sign-in that runs against your own ChatGPT plan, so no `OPENAI_API_KEY` is needed. Tokens live only in `data/system/user-secrets/<owner>/private/openai-codex/` — in the multi-container Compose deployment, outside every tree the exec sandbox can reach — and DeepTutor never reads or modifies your `~/.codex` CLI login. The model list comes from that account's live catalog; signing in publishes the profile but only becomes the active model when no LLM is configured yet. Because a token authorizes one person's plan, the profile is not shareable through user grants — each account signs in for itself, ordinary users included: their card sits under Models → LLM, and the resulting models, catalog, and sign-out stay private to that account.+On sign-in and **Refresh models**, DeepTutor reads the latest stable `@openai/codex` version from the official npm registry and uses it as the catalog request's `client_version`. This is metadata-only: it does not install, download, or upgrade the Codex CLI, and the npm request carries no OAuth credentials. Discovery has a three-second deadline and a 64 KiB response limit. If it fails, DeepTutor uses the last successful version for that account, or its built-in fallback when none is cached. Only a successfully parsed live catalog saves a new version; validators are never reused across versions or credential generations. A version rejection or incompatible catalog structure permits one retry with the previous version; authentication, rate-limit, and TLS failures are not retried as version problems. A failed manual refresh reports an error rather than presenting an old cached catalog as refreshed.++Successful version history survives same-account token renewal and catalog authentication errors, without making invalidated model data or ETags usable again. Signing out clears that account's local cache, including the version history. Ordinary status reads and inference do not query npm. New catalog entries do not replace a model you already selected or restart learning sessions; appearing in the catalog does not establish full inference-protocol compatibility. There is no background version updater or user version setting.+Default local Docker and Podman deployments use separate loopback networks and need a temporary bridge during sign-in. Follow the [temporary local Codex OAuth bridge guide](./CONTAINERIZATION.md#temporary-local-codex-oauth-bridge) for the exact Docker, Compose, Podman, and teardown commands.For a remote deployment, the browser's `localhost` and the server's `localhost` are different machines, so an ordinary reverse proxy alone cannot carry the browser's localhost callback to the server. Use an SSH tunnel as the callback bridge. The tunnel reaches the already-published Web port; Next.js rewrites only the exact callback path to the public callback broker, and the broker validates `state` before routing to the original OAuth operation. The callback listener remains on the backend loopback, ports `1455` and `1457` are not published, and this path supports the default Docker bridge network.diff --git a/deeptutor/services/codex_auth/catalog.py b/deeptutor/services/codex_auth/catalog.pyindex b22f07c3d..a64428eda 100644--- a/deeptutor/services/codex_auth/catalog.py+++ b/deeptutor/services/codex_auth/catalog.py@@ -5,11 +5,13 @@ from __future__ import annotationsfrom collections.abc import Callable, Mappingfrom dataclasses import replaceimport hashlib+import sslimport timefrom typing import Anyimport httpx+from .client_version import latest_client_versionfrom .constants import (CODEX_CLIENT_VERSION,CODEX_FRESH_CACHE_SECONDS,@@ -122,10 +124,12 @@ class CodexModelCatalog:store: CodexCredentialStore,*,http: httpx.AsyncClient,+ version_http: httpx.AsyncClient | None = None,clock: Callable[[], float] = time.time,) -> None:self._store = storeself._http = http+ self._version_http = version_httpself._clock = clockasync def get(@@ -133,58 +137,126 @@ class CodexModelCatalog:credentials: CodexCredentials,force: bool,) -> CatalogSnapshot:+ """Read the account catalog; discover CLI metadata only on explicit refresh."""now = int(self._clock())account_hash = hashlib.sha256(credentials.account_id.encode("utf-8")).hexdigest()- cache = self._matching_cache(credentials, account_hash)+ account_cache = self._matching_cache(account_hash)+ previous_version = (+ account_cache.client_version if account_cache else None+ ) or CODEX_CLIENT_VERSION+ # A credential rotation preserves only the account's successful version,+ # never its previous generation's model data, freshness or validator.+ cache = (+ account_cache+ if account_cache is not None+ and account_cache.models_valid+ and account_cache.generation == credentials.generation+ else None+ )+ client_version = previous_version+ if force:+ client_version = await latest_client_version(self._version_http) or client_versionif cache is not None and not force and self._age(cache, now) <= CODEX_FRESH_CACHE_SECONDS:return replace(cache, source="fresh-cache")+ try:+ return await self._fetch(credentials, cache, now, account_hash, client_version, force)+ except CodexAuthError as exc:+ # Only explicit version rejection or incompatible catalog structure+ # can justify a single retry. Auth, rate limits and transport/security+ # failures must retain their own meaning.+ if client_version == previous_version or exc.code not in {+ "catalog_version_unsupported",+ "catalog_invalid",+ }:+ raise+ return await self._fetch(credentials, cache, now, account_hash, previous_version, force)++ async def _fetch(+ self,+ credentials: CodexCredentials,+ cache: CatalogSnapshot | None,+ now: int,+ account_hash: str,+ client_version: str,+ force: bool,+ ) -> CatalogSnapshot:headers = {"Authorization": f"Bearer {credentials.access_token}","Accept": "application/json","chatgpt-account-id": credentials.account_id,}- if cache is not None and cache.etag:+ if cache is not None and cache.client_version == client_version and cache.etag:headers["If-None-Match"] = cache.etagtry:response = await self._http.get(CODEX_MODELS_URL,- params={"client_version": CODEX_CLIENT_VERSION},+ params={"client_version": client_version},headers=headers,)except httpx.RequestError as exc:- return self._stale_or_raise(cache, now, exc)+ cause: BaseException | None = exc+ while cause is not None:+ if isinstance(cause, ssl.SSLError):+ raise CodexAuthError(+ "catalog_tls_error",+ "The secure connection to the Codex model catalog failed.",+ 502,+ ) from exc+ cause = cause.__cause__ or cause.__context__+ return self._stale_or_raise(None if force else cache, now, exc)if response.status_code == 401:- await self.invalidate()+ self._store.invalidate_catalog_models(account_hash, generation=credentials.generation)raise CodexAuthError("catalog_unauthorized","Codex authentication is no longer authorized.",401,)if response.status_code == 403:- await self.invalidate()+ self._store.invalidate_catalog_models(account_hash, generation=credentials.generation)raise CodexAuthError("catalog_forbidden","This Codex account cannot access the model catalog.",403,)if response.status_code == 304:- if cache is None:+ if cache is None or cache.client_version != client_version:raise CodexAuthError(- "catalog_invalid",+ "catalog_invalid_response","Codex returned an invalid model catalog response.",502,)snapshot = replace(cache, source="revalidated-cache", fetched_at=now)- self._store.save_catalog_cache(snapshot.to_dict())+ self._store.commit_catalog_cache(snapshot)return snapshot+ if response.status_code == 429:+ raise CodexAuthError(+ "catalog_rate_limited",+ "Codex model catalog requests are rate limited. Try again later.",+ 429,+ )+ if response.status_code in {400, 422}:+ try:+ error_payload = response.json()+ except ValueError:+ error_payload = None+ error = error_payload.get("error") if isinstance(error_payload, dict) else None+ if isinstance(error, dict) and error.get("code") in {+ "unsupported_client_version",+ "client_version_unsupported",+ }:+ raise CodexAuthError(+ "catalog_version_unsupported",+ "Codex rejected the model catalog client version.",+ 502,+ )try:response.raise_for_status()except httpx.HTTPStatusError as exc:- return self._stale_or_raise(cache, now, exc)+ return self._stale_or_raise(None if force else cache, now, exc)content_length = response.headers.get("content-length")if (@@ -201,7 +273,7 @@ class CodexModelCatalog:payload = response.json()except ValueError as exc:raise CodexAuthError(- "catalog_invalid",+ "catalog_invalid_response","Codex returned an invalid model catalog.",502,) from exc@@ -219,8 +291,9 @@ class CodexModelCatalog:etag=response.headers.get("etag"),generation=credentials.generation,account_hash=account_hash,+ client_version=client_version,)- self._store.save_catalog_cache(snapshot.to_dict())+ self._store.commit_catalog_cache(snapshot)return snapshotasync def invalidate(self) -> None:@@ -228,7 +301,6 @@ class CodexModelCatalog:def _matching_cache(self,- credentials: CodexCredentials,account_hash: str,) -> CatalogSnapshot | None:try:@@ -241,8 +313,6 @@ class CodexModelCatalog:raiseself._store.clear_catalog_cache()return None- if snapshot.generation != credentials.generation:- return Noneif snapshot.account_hash != account_hash:return Nonereturn snapshotdiff --git a/deeptutor/services/codex_auth/client_version.py b/deeptutor/services/codex_auth/client_version.pynew file mode 100644index 000000000..d1a751069--- /dev/null+++ b/deeptutor/services/codex_auth/client_version.py@@ -0,0 +1,55 @@+"""Read only the official CLI package metadata, never CLI code or OAuth state."""++from __future__ import annotations++import asyncio+import json+import re++import httpx++from .constants import (+ CODEX_MAX_VERSION_BYTES,+ CODEX_NPM_LATEST_URL,+ CODEX_STABLE_VERSION_PATTERN,+ CODEX_VERSION_TIMEOUT_SECONDS,+)+++async def latest_client_version(http: httpx.AsyncClient | None = None) -> str | None:+ """Return a validated stable version, or None when discovery is unavailable.++ A separate default client and a standalone request prevent OAuth headers,+ client auth and cookies from being inherited. Redirects are never followed.+ The deadline bounds the entire exchange, including streamed response bytes.+ """+ if http is None:+ async with httpx.AsyncClient(timeout=CODEX_VERSION_TIMEOUT_SECONDS) as client:+ return await latest_client_version(client)+ try:+ async with asyncio.timeout(CODEX_VERSION_TIMEOUT_SECONDS):+ request = httpx.Request(+ "GET", CODEX_NPM_LATEST_URL, headers={"Accept": "application/json"}+ )+ response = await http.send(request, auth=None, follow_redirects=False, stream=True)+ try:+ response.raise_for_status()+ length = response.headers.get("content-length", "")+ if length.isdigit() and int(length) > CODEX_MAX_VERSION_BYTES:+ return None+ content = bytearray()+ async for chunk in response.aiter_bytes():+ if len(content) + len(chunk) > CODEX_MAX_VERSION_BYTES:+ return None+ content.extend(chunk)+ payload = json.loads(content)+ finally:+ await response.aclose()+ if not isinstance(payload, dict) or payload.get("name") != "@openai/codex":+ return None+ version = payload.get("version")+ if isinstance(version, str) and re.fullmatch(CODEX_STABLE_VERSION_PATTERN, version):+ return version+ except (httpx.HTTPError, TimeoutError, ValueError, RecursionError):+ return None+ return Nonediff --git a/deeptutor/services/codex_auth/constants.py b/deeptutor/services/codex_auth/constants.pyindex a5d13a35a..1e66f1ed1 100644--- a/deeptutor/services/codex_auth/constants.py+++ b/deeptutor/services/codex_auth/constants.py@@ -5,6 +5,10 @@ CODEX_UPSTREAM_COMMIT = "81da9deb065d7adb283816b19b40f89bcc484276"# 3d2ee51ca2d5db578f328aa75e20aa22c0197c9a. Older versions omit eligible models.# This request version is independent of the installed CLI and OAuth audit above.CODEX_CLIENT_VERSION = "0.153.4"+CODEX_STABLE_VERSION_PATTERN = r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"+CODEX_NPM_LATEST_URL = "https://registry.npmjs.org/@openai%2Fcodex/latest"+CODEX_VERSION_TIMEOUT_SECONDS = 3+CODEX_MAX_VERSION_BYTES = 64 * 1024CODEX_OAUTH_ISSUER = "https://auth.openai.com"CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"CODEX_OAUTH_SCOPE = "openid profile email offline_access api.connectors.read api.connectors.invoke"diff --git a/deeptutor/services/codex_auth/contracts.py b/deeptutor/services/codex_auth/contracts.pyindex 754b7180b..d66892736 100644--- a/deeptutor/services/codex_auth/contracts.py+++ b/deeptutor/services/codex_auth/contracts.py@@ -6,8 +6,11 @@ import base64from collections.abc import Mappingfrom dataclasses import dataclass, fieldimport json+import refrom typing import Any, Literal+from .constants import CODEX_STABLE_VERSION_PATTERN+CatalogSource = Literal["live", "fresh-cache", "revalidated-cache", "stale-cache"]@@ -194,12 +197,16 @@ def _require_optional_positive_int(value: object) -> int | None:@dataclass(frozen=True)class CatalogSnapshot:+ """A catalog plus account-bound version history, retained after auth invalidation."""+models: tuple[CodexModel, ...]source: CatalogSourcefetched_at: intetag: str | Nonegeneration: intaccount_hash: str+ client_version: str | None = None+ models_valid: bool = Truedef to_dict(self) -> dict[str, object]:return {@@ -209,6 +216,8 @@ class CatalogSnapshot:"etag": self.etag,"generation": self.generation,"account_hash": self.account_hash,+ "client_version": self.client_version,+ "models_valid": self.models_valid,}@classmethod@@ -216,6 +225,15 @@ class CatalogSnapshot:try:models = payload["models"]source = payload["source"]+ client_version = payload.get("client_version")+ models_valid = payload.get("models_valid", True)+ if not isinstance(models_valid, bool):+ raise ValueError+ if client_version is not None and (+ not isinstance(client_version, str)+ or re.fullmatch(CODEX_STABLE_VERSION_PATTERN, client_version) is None+ ):+ raise ValueErrorif not isinstance(models, list):raise TypeErrorif source not in {"live", "fresh-cache", "revalidated-cache", "stale-cache"}:@@ -227,6 +245,8 @@ class CatalogSnapshot:etag=str(payload["etag"]) if payload.get("etag") is not None else None,generation=int(payload["generation"]),account_hash=str(payload["account_hash"]),+ client_version=client_version,+ models_valid=models_valid,)except (KeyError, TypeError, ValueError) as exc:raise CodexAuthError(diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.pyindex ac6ae51a6..ab84d13e6 100644--- a/deeptutor/services/codex_auth/service.py+++ b/deeptutor/services/codex_auth/service.py@@ -576,7 +576,8 @@ class CodexOAuthService:):remove_codex_catalog(self._model_catalog)operation.operation_state = "fetching_models"- await self._catalog.invalidate()+ # Catalog reads reject another account or credential generation,+ # while retaining this account's last successful client version.snapshot = await self._catalog.get(committed, force=True)async with self._catalog_sync_lock:sync_result = sync_codex_catalog(@@ -651,7 +652,12 @@ class CodexOAuthService:"Codex authentication changed before models could be refreshed.",409,)- snapshot = await self._catalog.get(credentials, force=True)+ try:+ snapshot = await self._catalog.get(credentials, force=True)+ except CodexAuthError as exc:+ if exc.code in {"catalog_unauthorized", "catalog_forbidden"}:+ self._last_snapshot = None+ raisesync_codex_catalog(self._model_catalog,snapshot,@@ -744,7 +750,8 @@ class CodexOAuthService:refreshed,expected_generation=credentials.generation,)- await self._catalog.invalidate()+ # Generation matching invalidates model data without discarding the+ # same account's successful catalog client version.return committedasync def recover_after_unauthorized(self, generation: int) -> None:@@ -930,7 +937,7 @@ class CodexOAuthService:cached = CatalogSnapshot.from_dict(payload)except CodexAuthError:return None- if cached.generation != credentials.generation:+ if not cached.models_valid or cached.generation != credentials.generation:return Nonereturn cacheddiff --git a/deeptutor/services/codex_auth/storage.py b/deeptutor/services/codex_auth/storage.pyindex 17d46d9e3..ffbcb9085 100644--- a/deeptutor/services/codex_auth/storage.py+++ b/deeptutor/services/codex_auth/storage.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom collections.abc import Iterator, Mappingfrom contextlib import contextmanagerfrom dataclasses import replace+import hashlibimport jsonimport osfrom pathlib import Path@@ -14,7 +15,7 @@ import tempfileimport threadingfrom typing import Any, BinaryIO-from .contracts import CodexAuthError, CodexCredentials+from .contracts import CatalogSnapshot, CodexAuthError, CodexCredentials_SCHEMA_VERSION = 1@@ -255,6 +256,63 @@ class CodexCredentialStore:with self._locked():_atomic_write_json(self.catalog_cache_path, payload)+ def commit_catalog_cache(self, snapshot: CatalogSnapshot) -> None:+ """Publish a response only while its credential owner and generation are current.++ Validation and publication share logout's interprocess lock. Checking+ before taking this lock would let a late 200 or 304 response recreate+ a cache cleared by logout or overwrite a newer account's version history.+ """+ with self._locked():+ generation = int(self._read_state_unlocked()["generation"])+ if generation != snapshot.generation:+ raise self._generation_changed()+ payload = self._read_json(+ self.credentials_path,+ code="credential_corrupt",+ message="Stored Codex credentials are invalid.",+ )+ if payload is None:+ raise self._generation_changed()+ credentials = CodexCredentials.from_dict(payload)+ account_hash = hashlib.sha256(credentials.account_id.encode("utf-8")).hexdigest()+ if credentials.generation != generation or account_hash != snapshot.account_hash:+ raise self._generation_changed()+ _atomic_write_json(self.catalog_cache_path, snapshot.to_dict())++ def invalidate_catalog_models(self, account_hash: str, *, generation: int) -> None:+ """Atomically invalidate matching models, retaining successful version history.++ Matching and rewriting share the existing interprocess lock with logout,+ so an in-flight auth error cannot recreate a cache that logout cleared.+ A response for an older account or generation cannot invalidate a newer+ catalog either.+ """+ with self._locked():+ try:+ payload = self._read_json(+ self.catalog_cache_path,+ code="catalog_corrupt",+ message="Stored Codex model data is invalid.",+ )+ if payload is None:+ return+ snapshot = CatalogSnapshot.from_dict(payload)+ except CodexAuthError as exc:+ if exc.code != "catalog_corrupt":+ raise+ self.catalog_cache_path.unlink(missing_ok=True)+ return+ if snapshot.account_hash != account_hash or snapshot.generation != generation:+ return+ if snapshot.client_version is None:+ self.catalog_cache_path.unlink(missing_ok=True)+ return+ _atomic_write_json(+ self.catalog_cache_path,+ replace(snapshot, models=(), etag=None, models_valid=False).to_dict(),+ )+def clear_catalog_cache(self) -> None:with self._locked():_assert_safe_regular_path(self.catalog_cache_path)diff --git a/tests/services/codex_auth/test_catalog.py b/tests/services/codex_auth/test_catalog.pyindex 66fd56723..00db9ba03 100644--- a/tests/services/codex_auth/test_catalog.py+++ b/tests/services/codex_auth/test_catalog.py@@ -1,7 +1,12 @@from __future__ import annotations+from dataclasses import replace+import hashlibimport jsonfrom pathlib import Path+import ssl+import subprocess+import sysfrom typing import Anyimport httpx@@ -13,7 +18,11 @@ from deeptutor.services.codex_auth.constants import (CODEX_MAX_CATALOG_BYTES,CODEX_MAX_MODELS,)-from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexCredentials+from deeptutor.services.codex_auth.contracts import (+ CatalogSnapshot,+ CodexAuthError,+ CodexCredentials,+)from deeptutor.services.codex_auth.storage import CodexCredentialStoreFIXTURE_PATH = Path(__file__).parent / "fixtures" / "models-response.json"@@ -39,12 +48,20 @@ def _credentials()[email protected](autouse=True)+def _persist_initial_credentials(tmp_path: Path) -> None:+ """Catalog publication, like production, requires committed credentials."""+ CodexCredentialStore(tmp_path).commit_credentials(_credentials(), expected_generation=0)++class ResponseQueue:def __init__(self, *responses: httpx.Response | Exception) -> None:self.responses = list(responses)self.requests: list[httpx.Request] = []def __call__(self, request: httpx.Request) -> httpx.Response:+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(503)self.requests.append(request)response = self.responses.pop(0)if isinstance(response, Exception):@@ -61,6 +78,7 @@ def _catalog(catalog = CodexModelCatalog(CodexCredentialStore(tmp_path),http=http,+ version_http=http,clock=lambda: clock[0],)return catalog, http@@ -122,6 +140,142 @@ def test_parse_catalog_rejects_more_than_model_limit() -> None:assert exc_info.value.code == "catalog_too_large"[email protected]("status_code", [200, 304])[email protected]("separate_process", [False, True])+async def test_late_catalog_response_does_not_restore_cache_after_logout(+ tmp_path: Path, status_code: int, separate_process: bool+) -> None:+ store = CodexCredentialStore(tmp_path)+ other_process_store = CodexCredentialStore(tmp_path)+ credentials = store.load_credentials()+ assert credentials is not None+ logout_during_response = False++ def respond(request: httpx.Request) -> httpx.Response:+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(503)+ if logout_during_response:+ assert request.headers["if-none-match"] == '"before-logout"'+ if separate_process:+ subprocess.run(+ [+ sys.executable,+ "-c",+ "import sys; from pathlib import Path; "+ "from deeptutor.services.codex_auth.storage import CodexCredentialStore; "+ "CodexCredentialStore(Path(sys.argv[1])).clear_credentials("+ "expected_generation=int(sys.argv[2]))",+ str(tmp_path),+ str(credentials.generation),+ ],+ cwd=Path(__file__).resolve().parents[3],+ check=True,+ capture_output=True,+ timeout=10,+ )+ else:+ other_process_store.clear_credentials(expected_generation=credentials.generation)+ assert other_process_store.load_catalog_cache() is None+ return httpx.Response(status_code, json=_fixture())+ return httpx.Response(200, json=_fixture(), headers={"etag": '"before-logout"'})++ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http:+ catalog = CodexModelCatalog(store, http=http, version_http=http, clock=lambda: 1_000)+ await catalog.get(credentials, force=True)+ logout_during_response = True+ error = None+ try:+ await catalog.get(credentials, force=True)+ except CodexAuthError as exc:+ error = exc++ assert store.load_credentials() is None+ assert other_process_store.load_catalog_cache() is None+ assert error is not None+ assert error.code == "generation_changed"++[email protected]("status_code", [200, 304])[email protected]("transition", ["refresh", "relogin", "switch_account"])+async def test_late_catalog_response_preserves_new_generation_cache(+ tmp_path: Path, status_code: int, transition: str+) -> None:+ store = CodexCredentialStore(tmp_path)+ other_process_store = CodexCredentialStore(tmp_path)+ credentials = store.load_credentials()+ assert credentials is not None+ change_during_response = False+ expected_cache = None+ catalog_calls = 0++ def respond(request: httpx.Request) -> httpx.Response:+ nonlocal expected_cache, catalog_calls+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(503)+ catalog_calls += 1+ if change_during_response:+ generation = credentials.generation+ if transition != "refresh":+ generation = other_process_store.clear_credentials(expected_generation=generation)+ account_id = (+ "another-account" if transition == "switch_account" else credentials.account_id+ )+ current = other_process_store.commit_credentials(+ _credentials(account_id=account_id), expected_generation=generation+ )+ newer = replace(+ previous,+ generation=current.generation,+ account_hash=hashlib.sha256(account_id.encode()).hexdigest(),+ client_version="9.9.9",+ etag='"new-generation"',+ )+ other_process_store.commit_catalog_cache(newer)+ expected_cache = newer.to_dict()+ return httpx.Response(status_code, json=_fixture())+ return httpx.Response(200, json=_fixture(), headers={"etag": '"old-generation"'})++ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http:+ catalog = CodexModelCatalog(store, http=http, version_http=http, clock=lambda: 1_000)+ previous = await catalog.get(credentials, force=True)+ change_during_response = True+ with pytest.raises(CodexAuthError) as error:+ await catalog.get(credentials, force=True)++ assert error.value.code == "generation_changed"+ assert catalog_calls == 2+ assert expected_cache is not None+ assert store.load_catalog_cache() == expected_cache+++async def test_refresh_discovers_and_persists_version_without_sending_credentials(+ tmp_path: Path,+) -> None:+ requests: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if request.url.host == "registry.npmjs.org":+ assert "authorization" not in request.headers+ assert "chatgpt-account-id" not in request.headers+ assert str(request.url) == "https://registry.npmjs.org/@openai%2Fcodex/latest"+ return httpx.Response(200, json={"name": "@openai/codex", "version": "1.2.3"})+ assert request.url.params["client_version"] == "1.2.3"+ return httpx.Response(200, json=_fixture())++ store = CodexCredentialStore(tmp_path)+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(store, http=http, version_http=http)+ live = await catalog.get(_credentials(), force=True)+ fresh = await catalog.get(_credentials(), force=False)+ assert live.client_version == fresh.client_version == "1.2.3"+ assert store.load_catalog_cache()["client_version"] == "1.2.3"+ assert len(requests) == 2++@pytest.mark.asyncioasync def test_live_catalog_uses_account_headers_and_client_version(tmp_path: Path) -> None:queue = ResponseQueue(httpx.Response(200, json=_fixture(), headers={"ETag": '"catalog-v1"'}))@@ -195,8 +349,11 @@ async def test_cache_is_partitioned_by_account(tmp_path: Path) -> None:)clock = [1_000]catalog, http = _catalog(tmp_path, queue, clock)+ credentials = CodexCredentialStore(tmp_path).commit_credentials(+ _credentials(account_id="account-a"), expected_generation=1+ )try:- await catalog.get(_credentials(account_id="account-a"), force=True)+ await catalog.get(credentials, force=True)clock[0] = 1_301with pytest.raises(CodexAuthError) as exc_info:await catalog.get(@@ -235,7 +392,11 @@ async def test_auth_errors_never_use_stale_cache(assert exc_info.value.code == error_codeassert "private error" not in str(exc_info.value)- assert CodexCredentialStore(tmp_path).load_catalog_cache() is None+ cached = CodexCredentialStore(tmp_path).load_catalog_cache()+ assert cached["models_valid"] is False+ assert cached["models"] == []+ assert cached["etag"] is None+ assert cached["client_version"] == CODEX_CLIENT_VERSION@pytest.mark.asyncio@@ -250,3 +411,279 @@ async def test_catalog_rejects_response_larger_than_eight_mib(tmp_path: Path) ->await http.aclose()assert exc_info.value.code == "catalog_too_large"++[email protected]("failure", ["schema", "version"])+async def test_new_version_falls_back_once_to_successful_version(+ tmp_path: Path, failure: str+) -> None:+ versions = iter(["1.2.3", "2.0.0"])+ requested: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(200, json={"name": "@openai/codex", "version": next(versions)})+ version = request.url.params["client_version"]+ requested.append(version)+ if version == "2.0.0":+ assert "if-none-match" not in request.headers+ if failure == "schema":+ return httpx.Response(200, json={"unexpected": []})+ return httpx.Response(400, json={"error": {"code": "unsupported_client_version"}})+ return httpx.Response(200, json=_fixture(), headers={"etag": '"old-version"'})++ store = CodexCredentialStore(tmp_path)+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(store, http=http, version_http=http)+ await catalog.get(_credentials(), force=True)+ snapshot = await catalog.get(_credentials(), force=True)+ assert requested == ["1.2.3", "2.0.0", "1.2.3"]+ assert snapshot.source == "live"+ assert store.load_catalog_cache()["client_version"] == "1.2.3"++[email protected]("status", [400, 429, 500])+async def test_manual_refresh_failure_is_not_stale_success(tmp_path: Path, status: int) -> None:+ queue = ResponseQueue(httpx.Response(200, json=_fixture()), httpx.Response(status))+ catalog, http = _catalog(tmp_path, queue, [1_000])+ try:+ original = await catalog.get(_credentials(), force=True)+ with pytest.raises(CodexAuthError):+ await catalog.get(_credentials(), force=True)+ assert CodexCredentialStore(tmp_path).load_catalog_cache() == original.to_dict()+ finally:+ await http.aclose()+++async def test_version_discovery_failure_reuses_persisted_success_after_restart(+ tmp_path: Path,+) -> None:+ npm_responses = iter(+ [+ httpx.Response(200, json={"name": "@openai/codex", "version": "1.2.3"}),+ httpx.Response(503),+ ]+ )++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.host == "registry.npmjs.org":+ return next(npm_responses)+ assert request.url.params["client_version"] == "1.2.3"+ return httpx.Response(200, json=_fixture())++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ await CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http).get(+ _credentials(), force=True+ )+ restarted = CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http)+ assert (await restarted.get(_credentials(), force=True)).client_version == "1.2.3"++[email protected]("second_status", [200, 304])+async def test_version_change_never_reuses_old_etag_or_promotes_304(+ tmp_path: Path, second_status: int+) -> None:+ versions = iter(["1.2.3", "2.0.0"])+ catalog_requests: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(200, json={"name": "@openai/codex", "version": next(versions)})+ catalog_requests.append(request)+ if len(catalog_requests) == 2:+ assert "if-none-match" not in request.headers+ return httpx.Response(second_status, json=_fixture())+ if len(catalog_requests) == 3:+ assert request.url.params["client_version"] == "1.2.3"+ assert request.headers["if-none-match"] == '"v1"'+ return httpx.Response(304)+ return httpx.Response(200, json=_fixture(), headers={"etag": '"v1"'})++ store = CodexCredentialStore(tmp_path)+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(store, http=http, version_http=http)+ original = await catalog.get(_credentials(), force=True)+ if second_status == 304:+ with pytest.raises(CodexAuthError) as error:+ await catalog.get(_credentials(), force=True)+ assert error.value.code == "catalog_invalid_response"+ assert len(catalog_requests) == 2+ assert store.load_catalog_cache() == original.to_dict()+ return+ result = await catalog.get(_credentials(), force=True)+ assert result.client_version == "2.0.0"+ assert store.load_catalog_cache()["client_version"] == result.client_version+++async def test_legacy_cache_is_readable_but_never_revalidated_as_known_version(+ tmp_path: Path,+) -> None:+ queue = ResponseQueue(+ httpx.Response(200, json=_fixture(), headers={"etag": '"v1"'}),+ httpx.Response(200, json=_fixture()),+ )+ catalog, http = _catalog(tmp_path, queue, [1_000])+ store = CodexCredentialStore(tmp_path)+ try:+ await catalog.get(_credentials(), force=True)+ legacy = store.load_catalog_cache()+ del legacy["client_version"]+ store.save_catalog_cache(legacy)+ assert CatalogSnapshot.from_dict(legacy).client_version is None+ result = await catalog.get(_credentials(), force=True)+ assert result.client_version == CODEX_CLIENT_VERSION+ assert "if-none-match" not in queue.requests[1].headers+ finally:+ await http.aclose()+++ ("failure", "code"),+ [+ (httpx.Response(401), "catalog_unauthorized"),+ (httpx.Response(403), "catalog_forbidden"),+ (httpx.Response(429), "catalog_rate_limited"),+ (httpx.Response(500), "catalog_unavailable"),+ (httpx.Response(400, json={"error": {"code": "other"}}), "catalog_unavailable"),+ (httpx.ConnectError("offline"), "catalog_unavailable"),+ ("tls", "catalog_tls_error"),+ ],+)+async def test_new_version_does_not_retry_or_hide_unrelated_failures(+ tmp_path: Path, failure: httpx.Response | Exception | str, code: str+) -> None:+ catalog_requests = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal catalog_requests+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(200, json={"name": "@openai/codex", "version": "2.0.0"})+ catalog_requests += 1+ if failure == "tls":+ raise httpx.ConnectError("private tls detail") from ssl.SSLCertVerificationError()+ if isinstance(failure, Exception):+ raise failure+ assert isinstance(failure, httpx.Response)+ return failure++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http)+ with pytest.raises(CodexAuthError) as error:+ await catalog.get(_credentials(), force=True)+ assert error.value.code == code+ assert catalog_requests == 1+ assert CodexCredentialStore(tmp_path).load_catalog_cache() is None+++async def test_failed_fallback_does_not_loop_or_overwrite_success(tmp_path: Path) -> None:+ calls = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal calls+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(200, json={"name": "@openai/codex", "version": "2.0.0"})+ calls += 1+ return httpx.Response(200, json={"invalid": []})++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http)+ with pytest.raises(CodexAuthError, match="invalid model catalog"):+ await catalog.get(_credentials(), force=True)+ assert calls == 2+ assert CodexCredentialStore(tmp_path).load_catalog_cache() is None+++async def test_credential_rotation_keeps_version_but_not_catalog_or_etag(tmp_path: Path) -> None:+ npm_calls = 0+ catalog_calls = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal npm_calls, catalog_calls+ if request.url.host == "registry.npmjs.org":+ npm_calls += 1+ if npm_calls == 1:+ return httpx.Response(200, json={"name": "@openai/codex", "version": "1.2.3"})+ return httpx.Response(503)+ catalog_calls += 1+ assert request.url.params["client_version"] == "1.2.3"+ assert "if-none-match" not in request.headers+ if catalog_calls == 1:+ return httpx.Response(200, json=_fixture(), headers={"etag": '"old-generation"'})+ raise httpx.ConnectError("offline")++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http)+ await catalog.get(_credentials(), force=True)+ with pytest.raises(CodexAuthError):+ await catalog.get(_credentials(generation=2), force=False)+ assert catalog_calls == 2+ assert npm_calls == 1+++async def test_invalid_json_does_not_retry_a_different_version(tmp_path: Path) -> None:+ calls = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal calls+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(200, json={"name": "@openai/codex", "version": "2.0.0"})+ calls += 1+ return httpx.Response(200, content=b"<html>gateway error</html>")++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http)+ with pytest.raises(CodexAuthError) as error:+ await catalog.get(_credentials(), force=True)+ assert error.value.code == "catalog_invalid_response"+ assert calls == 1+++async def test_auth_invalidation_preserves_version_history_but_no_usable_models(+ tmp_path: Path,+) -> None:+ npm_calls = 0+ catalog_calls = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal npm_calls, catalog_calls+ if request.url.host == "registry.npmjs.org":+ npm_calls += 1+ if npm_calls == 1:+ return httpx.Response(200, json={"name": "@openai/codex", "version": "1.2.3"})+ return httpx.Response(503)+ catalog_calls += 1+ assert request.url.params["client_version"] == "1.2.3"+ if catalog_calls == 1:+ return httpx.Response(200, json=_fixture(), headers={"etag": '"old"'})+ if catalog_calls == 2:+ return httpx.Response(401)+ assert "if-none-match" not in request.headers+ if catalog_calls == 3:+ raise httpx.ConnectError("offline")+ return httpx.Response(200, json=_fixture())++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ catalog = CodexModelCatalog(CodexCredentialStore(tmp_path), http=http, version_http=http)+ await catalog.get(_credentials(), force=True)+ with pytest.raises(CodexAuthError):+ await catalog.get(_credentials(), force=True)+ # The same generation must not get a fresh or stale invalidated catalog.+ with pytest.raises(CodexAuthError):+ await catalog.get(_credentials(), force=False)+ refreshed = CodexCredentialStore(tmp_path).commit_credentials(+ _credentials(), expected_generation=1+ )+ result = await catalog.get(refreshed, force=True)+ assert result.client_version == "1.2.3"+ assert result.models_valid is True+ assert result.source == "live"diff --git a/tests/services/codex_auth/test_catalog_refresh.py b/tests/services/codex_auth/test_catalog_refresh.pyindex 7db019f3a..a934a7706 100644--- a/tests/services/codex_auth/test_catalog_refresh.py+++ b/tests/services/codex_auth/test_catalog_refresh.py@@ -35,6 +35,8 @@ async def test_refresh_discovers_version_gated_model_and_preserves_selection(requests: list[httpx.Request] = []def respond(request: httpx.Request) -> httpx.Response:+ if request.url.host == "registry.npmjs.org":+ return httpx.Response(503)requests.append(request)version = request.url.params["client_version"]assert version in {"0.145.0", "0.153.4"}@@ -56,7 +58,7 @@ async def test_refresh_discovers_version_gated_model_and_preserves_selection()model_catalog = ModelCatalogService(tmp_path / "model_catalog.json")async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http:- catalog = CodexModelCatalog(store, http=http, clock=lambda: 1_000)+ catalog = CodexModelCatalog(store, http=http, version_http=http, clock=lambda: 1_000)# Seed a still-fresh pre-upgrade cache and a user's selected model.previous = CatalogSnapshot(models=parse_models_response(old_payload),@@ -75,7 +77,8 @@ async def test_refresh_discovers_version_gated_model_and_preserves_selection(before = model_catalog.load()status = await service.refresh_models()- assert requests[0].headers["if-none-match"] == '"old-catalog"'+ # Legacy caches have no request version, so their ETag cannot be reused.+ assert "if-none-match" not in requests[0].headersassert [m["model"] for m in status["models"]].count("gpt-6-astra") == 1refreshed = model_catalog.load()llm = refreshed["services"]["llm"]diff --git a/tests/services/codex_auth/test_client_version.py b/tests/services/codex_auth/test_client_version.pynew file mode 100644index 000000000..f20377307--- /dev/null+++ b/tests/services/codex_auth/test_client_version.py@@ -0,0 +1,170 @@+"""Official version discovery stays bounded and independent of OAuth."""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator++import httpx+import pytest++from deeptutor.services.codex_auth.client_version import latest_client_version+from deeptutor.services.codex_auth.constants import CODEX_MAX_VERSION_BYTES+++ "payload",+ [+ {"name": "@openai/codex", "version": "0.0.0"},+ {"name": "@openai/codex", "version": "1.23.456"},+ ],+)+async def test_stable_versions_are_accepted(payload: dict[str, str]) -> None:+ async with httpx.AsyncClient(+ transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))+ ) as http:+ assert await latest_client_version(http) == payload["version"]+++ "payload",+ [+ [],+ None,+ {"name": "codex", "version": "1.2.3"},+ {"version": "1.2.3"},+ *[+ {"name": "@openai/codex", "version": version}+ for version in [+ None,+ 123,+ True,+ "",+ "v1.2.3",+ "1.2",+ "01.2.3",+ "1.2.3\n",+ "1.2.3-alpha.1",+ "1.2.3+build",+ " 1.2.3",+ "1.2.3/path",+ ]+ ],+ ],+)+async def test_invalid_metadata_is_unavailable(payload: object) -> None:+ async with httpx.AsyncClient(+ transport=httpx.MockTransport(lambda _: httpx.Response(200, json=payload))+ ) as http:+ assert await latest_client_version(http) is None+++ "response",+ [+ httpx.Response(503),+ httpx.Response(302, headers={"location": "https://example.test/"}),+ httpx.Response(200, content=b"not json"),+ httpx.Response(200, content=b"[" * 2_000 + b"]" * 2_000),+ httpx.Response(200, headers={"content-length": str(CODEX_MAX_VERSION_BYTES + 1)}),+ httpx.Response(200, content=b" " * (CODEX_MAX_VERSION_BYTES + 1)),+ httpx.ConnectError("offline"),+ httpx.ReadTimeout("timeout"),+ TimeoutError(),+ ],+)+async def test_source_failure_is_unavailable(response: httpx.Response | Exception) -> None:+ calls = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal calls+ calls += 1+ if isinstance(response, Exception):+ raise response+ return response++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ assert await latest_client_version(http) is None+ assert calls == 1+++async def test_json_recursion_failure_is_unavailable_and_closes_response(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Exercise decoder recursion failure independently of Python's nesting limit."""++ class MetadataStream(httpx.AsyncByteStream):+ """Keep the response open until discovery explicitly closes it."""++ async def __aiter__(self) -> AsyncIterator[bytes]:+ yield b"{}"++ response = httpx.Response(200, stream=MetadataStream())+ assert not response.is_closed++ def reject_nested_json(content: object) -> object:+ raise RecursionError("JSON nesting exceeded the decoder limit")++ monkeypatch.setattr(+ "deeptutor.services.codex_auth.client_version.json.loads", reject_nested_json+ )+ async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: response)) as http:+ assert await latest_client_version(http) is None+ assert response.is_closed+++async def test_client_defaults_cannot_leak_auth_or_cookies_to_npm() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ assert "authorization" not in request.headers+ assert "cookie" not in request.headers+ assert "chatgpt-account-id" not in request.headers+ return httpx.Response(200, json={"name": "@openai/codex", "version": "1.2.3"})++ async with httpx.AsyncClient(+ transport=httpx.MockTransport(handler),+ auth=("private", "private"),+ headers={"Authorization": "Bearer private", "chatgpt-account-id": "private"},+ cookies={"session": "private"},+ ) as http:+ assert await latest_client_version(http) == "1.2.3"+++async def test_cancellation_is_not_swallowed() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise asyncio.CancelledError++ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ with pytest.raises(asyncio.CancelledError):+ await latest_client_version(http)++[email protected]("stall", [False, True])+async def test_stream_is_closed_at_size_limit_or_total_deadline(stall: bool) -> None:+ class MetadataStream(httpx.AsyncByteStream):+ """Serve slow or oversized chunks without a Content-Length header."""++ closed = False++ async def __aiter__(self) -> AsyncIterator[bytes]:+ if stall:+ await asyncio.sleep(60)+ yield b" " * CODEX_MAX_VERSION_BYTES+ yield b"x"+ pytest.fail("Metadata discovery must stop consuming the oversized body")++ async def aclose(self) -> None:+ self.closed = True++ stream = MetadataStream()+ async with httpx.AsyncClient(+ transport=httpx.MockTransport(lambda _: httpx.Response(200, stream=stream))+ ) as http:+ assert await latest_client_version(http) is None+ assert stream.closeddiff --git a/tests/services/codex_auth/test_contracts.py b/tests/services/codex_auth/test_contracts.pyindex b2316a56b..eb551a228 100644--- a/tests/services/codex_auth/test_contracts.py+++ b/tests/services/codex_auth/test_contracts.py@@ -154,6 +154,7 @@ def test_catalog_snapshot_round_trip_preserves_tuples() -> None:etag='"catalog-v1"',generation=7,account_hash="account-hash",+ client_version="1.2.3",)restored = CatalogSnapshot.from_dict(snapshot.to_dict())@@ -163,6 +164,54 @@ def test_catalog_snapshot_round_trip_preserves_tuples() -> None:assert isinstance(restored.models[0].supported_reasoning_levels, tuple)[email protected]("version", [True, 123, "", "1.2.3-beta", "1.2.3\n"])+def test_catalog_snapshot_rejects_invalid_cached_client_version(version: object) -> None:+ payload = CatalogSnapshot(+ models=(),+ source="live",+ fetched_at=1_000,+ etag=None,+ generation=1,+ account_hash="account-hash",+ ).to_dict()+ payload["client_version"] = version+ with pytest.raises(CodexAuthError) as error:+ CatalogSnapshot.from_dict(payload)+ assert error.value.code == "catalog_corrupt"+++def test_legacy_catalog_defaults_to_valid_models_without_known_version() -> None:+ payload = CatalogSnapshot(+ models=(_model(),),+ source="live",+ fetched_at=1_000,+ etag=None,+ generation=1,+ account_hash="account-hash",+ ).to_dict()+ del payload["models_valid"]+ del payload["client_version"]+ restored = CatalogSnapshot.from_dict(payload)+ assert restored.models_valid is True+ assert restored.client_version is None++[email protected]("value", [None, "false", 0, 1])+def test_cache_validity_marker_must_be_boolean(value: object) -> None:+ payload = CatalogSnapshot(+ models=(),+ source="live",+ fetched_at=1_000,+ etag=None,+ generation=1,+ account_hash="account-hash",+ ).to_dict()+ payload["models_valid"] = value+ with pytest.raises(CodexAuthError) as error:+ CatalogSnapshot.from_dict(payload)+ assert error.value.code == "catalog_corrupt"++def test_codex_model_round_trip_preserves_context_windows() -> None:model = CodexModel(slug="gpt-5.6-sol",diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.pyindex b4c7ed540..34f9f9d49 100644--- a/tests/services/codex_auth/test_service.py+++ b/tests/services/codex_auth/test_service.py@@ -8,9 +8,11 @@ from pathlib import Pathfrom typing import Anyfrom urllib.parse import parse_qs, urlsplit+import httpximport pytestfrom deeptutor.services.codex_auth import service as service_module+from deeptutor.services.codex_auth.catalog import CodexModelCatalogfrom deeptutor.services.codex_auth.contracts import (CatalogSnapshot,CodexAuthError,@@ -953,6 +955,95 @@ async def test_successful_live_login_keeps_the_existing_model_selection(}+async def test_dynamic_catalog_login_and_refresh_keep_selection_and_skip_npm_on_status(+ tmp_path: Path,+) -> None:+ """Login/refresh discover versions; token/status reads never do or select a new model."""+ npm_calls = 0+ catalog_calls = 0++ def handler(request: httpx.Request) -> httpx.Response:+ nonlocal npm_calls, catalog_calls+ if request.url.host == "registry.npmjs.org":+ npm_calls += 1+ if npm_calls > 2:+ return httpx.Response(503)+ return httpx.Response(+ 200, json={"name": "@openai/codex", "version": f"1.0.{npm_calls}"}+ )+ catalog_calls += 1+ assert request.url.params["client_version"] == ("1.0.1" if catalog_calls == 1 else "1.0.2")+ if catalog_calls <= 3:+ assert "if-none-match" not in request.headers+ if catalog_calls == 4:+ return httpx.Response(500)+ if catalog_calls == 5:+ return httpx.Response(401)+ models = [{"slug": "chosen-model", "visibility": "list", "priority": 10}]+ if catalog_calls >= 2:+ models.append({"slug": "new-first-model", "visibility": "list", "priority": 0})+ return httpx.Response(200, json={"models": models}, headers={"etag": '"catalog"'})++ store = CodexCredentialStore(tmp_path / "secrets")+ model_catalog, _ = _seeded_service(tmp_path)+ original_selection = _selection(model_catalog.load())+ callback = FakeCallback()++ async def callback_factory(expected_state: str) -> FakeCallback:+ callback.expected_state = expected_state+ return callback++ clock = [1_000]+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:+ service = CodexOAuthService(+ store,+ CodexModelCatalog(store, http=http, version_http=http, clock=lambda: clock[0]),+ model_catalog,+ oauth_client=FakeOAuthClient(),+ callback_factory=callback_factory,+ clock=lambda: clock[0],+ )+ started = await service.start_login()+ callback.complete(started["authorize_url"])+ # Real HTTP mocks need more loop turns than the existing fake catalog.+ for _ in range(100):+ if service.public_status()["operation_state"] in {"completed", "failed"}:+ break+ await asyncio.sleep(0.01)+ assert service.public_status()["operation_state"] == "completed"+ assert _selection(model_catalog.load()) == original_selection+ assert store.load_catalog_cache()["client_version"] == "1.0.1"++ selected = model_catalog.load()+ selected["services"]["llm"]["active_profile_id"] = CODEX_PROFILE_ID+ selected["services"]["llm"]["active_model_id"] = codex_model_id("chosen-model")+ model_catalog.save(selected)+ await service.refresh_models()+ assert service.public_status()["active_model"] == "chosen-model"+ assert npm_calls == catalog_calls == 2++ # A normal token renewal keeps version history but not the old ETag.+ clock[0] = store.load_credentials().expires_at - 100+ await service.get_token()+ service.public_status()+ assert npm_calls == catalog_calls == 2+ assert store.load_catalog_cache()["client_version"] == "1.0.2"+ await service.refresh_models()+ assert service.public_status()["active_model"] == "chosen-model"+ assert store.load_catalog_cache()["client_version"] == "1.0.2"+ before = model_catalog.load()+ with pytest.raises(CodexAuthError):+ await service.refresh_models()+ assert model_catalog.load() == before+ with pytest.raises(CodexAuthError) as error:+ await service.refresh_models()+ assert error.value.code == "catalog_unauthorized"+ assert service.public_status()["catalog_source"] is None+ assert store.load_catalog_cache()["models_valid"] is False+ assert store.load_catalog_cache()["client_version"] == "1.0.2"++@pytest.mark.asyncioasync def test_callback_broker_keeps_waiting_after_wrong_state_then_completes(tmp_path: Path,diff --git a/tests/services/codex_auth/test_storage.py b/tests/services/codex_auth/test_storage.pyindex 94bff2c81..d627bc497 100644--- a/tests/services/codex_auth/test_storage.py+++ b/tests/services/codex_auth/test_storage.py@@ -1,13 +1,20 @@from __future__ import annotationsfrom concurrent.futures import ThreadPoolExecutor+from dataclasses import replace+import hashlibimport osfrom pathlib import Pathimport stat+import threadingimport pytest-from deeptutor.services.codex_auth.contracts import CodexAuthError, CodexCredentials+from deeptutor.services.codex_auth.contracts import (+ CatalogSnapshot,+ CodexAuthError,+ CodexCredentials,+)from deeptutor.services.codex_auth.storage import CodexCredentialStore@@ -129,6 +136,136 @@ def test_catalog_cache_round_trip(tmp_path: Path) -> None:}+ "invalid_owner", ["missing_credentials", "wrong_account", "old_generation"]+)+def test_catalog_publication_requires_current_credentials(+ tmp_path: Path, invalid_owner: str+) -> None:+ store = CodexCredentialStore(tmp_path)+ current = store.commit_credentials(_credentials("one"), expected_generation=0)+ snapshot = CatalogSnapshot(+ models=(),+ source="live",+ fetched_at=1_000,+ etag='"v1"',+ generation=current.generation,+ account_hash=hashlib.sha256(current.account_id.encode()).hexdigest(),+ client_version="1.2.3",+ )+ store.commit_catalog_cache(snapshot)+ if invalid_owner == "missing_credentials":+ # Even a missing credential file without a generation bump must fail closed.+ store.credentials_path.unlink()+ elif invalid_owner == "wrong_account":+ snapshot = replace(snapshot, account_hash="different-account")+ else:+ snapshot = replace(snapshot, generation=current.generation - 1)+ before = store.load_catalog_cache()++ with pytest.raises(CodexAuthError) as error:+ store.commit_catalog_cache(snapshot)++ assert error.value.code == "generation_changed"+ assert store.load_catalog_cache() == before+++def test_concurrent_logout_and_catalog_publication_cannot_restore_history(tmp_path: Path) -> None:+ store = CodexCredentialStore(tmp_path)+ other_process_store = CodexCredentialStore(tmp_path)+ with ThreadPoolExecutor(max_workers=2) as pool:+ for _ in range(20):+ credentials = store.commit_credentials(+ _credentials("one"), expected_generation=store.current_generation()+ )+ snapshot = CatalogSnapshot(+ models=(),+ source="live",+ fetched_at=1_000,+ etag='"v1"',+ generation=credentials.generation,+ account_hash=hashlib.sha256(credentials.account_id.encode()).hexdigest(),+ client_version="1.2.3",+ )+ barrier = threading.Barrier(2)++ def publish() -> None:+ barrier.wait(timeout=5)+ try:+ other_process_store.commit_catalog_cache(snapshot)+ except CodexAuthError as exc:+ assert exc.code == "generation_changed"++ def logout() -> None:+ barrier.wait(timeout=5)+ store.clear_credentials(expected_generation=credentials.generation)++ published = pool.submit(publish)+ logged_out = pool.submit(logout)+ published.result(timeout=5)+ logged_out.result(timeout=5)+ assert store.load_credentials() is None+ assert store.load_catalog_cache() is None+++def test_catalog_invalidation_does_not_touch_another_account_or_generation(tmp_path: Path) -> None:+ store = CodexCredentialStore(tmp_path)+ snapshot = CatalogSnapshot(+ models=(),+ source="live",+ fetched_at=1_000,+ etag='"v1"',+ generation=1,+ account_hash="account-hash",+ client_version="1.2.3",+ )+ store.save_catalog_cache(snapshot.to_dict())+ store.invalidate_catalog_models("other-account", generation=1)+ store.invalidate_catalog_models("account-hash", generation=2)+ assert store.load_catalog_cache() == snapshot.to_dict()+ store.invalidate_catalog_models("account-hash", generation=1)+ assert store.load_catalog_cache()["models_valid"] is False+ assert store.load_catalog_cache()["client_version"] == "1.2.3"+ assert store.load_catalog_cache()["etag"] is None+++def test_concurrent_logout_and_catalog_invalidation_cannot_restore_history(tmp_path: Path) -> None:+ store = CodexCredentialStore(tmp_path)+ other_process_store = CodexCredentialStore(tmp_path)+ with ThreadPoolExecutor(max_workers=2) as pool:+ for _ in range(20):+ credentials = store.commit_credentials(+ _credentials("one"), expected_generation=store.current_generation()+ )+ snapshot = CatalogSnapshot(+ models=(),+ source="live",+ fetched_at=1_000,+ etag='"v1"',+ generation=credentials.generation,+ account_hash="account-hash",+ client_version="1.2.3",+ )+ store.save_catalog_cache(snapshot.to_dict())+ barrier = threading.Barrier(2)++ def invalidate() -> None:+ barrier.wait(timeout=5)+ other_process_store.invalidate_catalog_models(+ "account-hash", generation=credentials.generation+ )++ def logout() -> None:+ barrier.wait(timeout=5)+ store.clear_credentials(expected_generation=credentials.generation)++ invalidated = pool.submit(invalidate)+ logged_out = pool.submit(logout)+ invalidated.result(timeout=5)+ logged_out.result(timeout=5)+ assert store.load_catalog_cache() is None++def test_existing_symlink_target_is_rejected(tmp_path: Path) -> None:store = CodexCredentialStore(tmp_path)store.root.mkdir(parents=True)