DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(multi-user): let each account sign in to its own Codex (#781)
Bingxi Zhao (Frank)4041c75d8e68
diff --git a/README.md b/README.mdindex d9bd2cfed..56c230316 100644--- a/README.md+++ b/README.md@@ -629,7 +629,7 @@ Settings is the operational control plane, with a live status strip (Backend, LLMost sections use a draft-and-apply flow, so you can test a provider before committing it. Four themes ship in the box — Default, Cream, Dark, and Glass. Project-root `.env` files are intentionally ignored; runtime configuration lives under `data/user/settings/*.json` unless `DEEPTUTOR_HOME` or `deeptutor start --home` points the app elsewhere.-**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.+**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.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.diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex 146973ea1..9826140ce 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -348,6 +348,30 @@ def _require_settings_admin() -> None:)+def _require_codex_oauth_actor() -> None:+ """Gate the Codex OAuth lifecycle: personal, not administrative.++ Every one of these endpoints acts on the *caller's own* credentials —+ ``get_codex_oauth_service()`` resolves the store, the model catalog, and+ the callback route from owner scope — so requiring an administrator was+ what left ordinary users unable to use Codex at all: an owner-bound+ profile is (correctly) never grantable, and they could not sign in for+ themselves either (#781).++ A partner is refused: it is a synthetic user whose owner is a real+ account, so letting one in would mean acting on that person's login —+ including signing them out. Partners inherit the owner's login at call+ time and need no lifecycle of their own.+ """+ from deeptutor.services.partners.scope import is_partner_user_id++ if is_partner_user_id(get_current_user().id):+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail="A partner uses the Codex login of the account that owns it.",+ )++def _codex_http_exception(error: CodexAuthError) -> HTTPException:return HTTPException(status_code=error.http_status,@@ -538,7 +562,7 @@ async def get_settings():@router.post("/providers/openai-codex/oauth/start")async def start_openai_codex_oauth() -> dict[str, Any]:- _require_settings_admin()+ _require_codex_oauth_actor()try:return await get_codex_oauth_service().start_login()except CodexAuthError as exc:@@ -547,7 +571,7 @@ async def start_openai_codex_oauth() -> dict[str, Any]:@router.get("/providers/openai-codex/oauth/status")async def get_openai_codex_oauth_status() -> dict[str, Any]:- _require_settings_admin()+ _require_codex_oauth_actor()try:return get_codex_oauth_service().public_status()except CodexAuthError as exc:@@ -556,7 +580,7 @@ async def get_openai_codex_oauth_status() -> dict[str, Any]:@router.post("/providers/openai-codex/oauth/cancel")async def cancel_openai_codex_oauth() -> dict[str, Any]:- _require_settings_admin()+ _require_codex_oauth_actor()try:return await get_codex_oauth_service().cancel_login()except CodexAuthError as exc:@@ -565,7 +589,7 @@ async def cancel_openai_codex_oauth() -> dict[str, Any]:@router.post("/providers/openai-codex/oauth/logout")async def logout_openai_codex_oauth() -> dict[str, Any]:- _require_settings_admin()+ _require_codex_oauth_actor()try:return await get_codex_oauth_service().logout()except CodexAuthError as exc:@@ -574,7 +598,7 @@ async def logout_openai_codex_oauth() -> dict[str, Any]:@router.post("/providers/openai-codex/models/refresh")async def refresh_openai_codex_models() -> dict[str, Any]:- _require_settings_admin()+ _require_codex_oauth_actor()try:return await get_codex_oauth_service().refresh_models()except CodexAuthError as exc:diff --git a/deeptutor/multi_user/model_access.py b/deeptutor/multi_user/model_access.pyindex eaf06a902..e86ebebaa 100644--- a/deeptutor/multi_user/model_access.py+++ b/deeptutor/multi_user/model_access.py@@ -3,6 +3,13 @@Grants carry LLM assignments only (grant v2): embedding and search alwaysresolve from the deployment's active profiles, so per-user grants for themwere never enforced and are not stored.++Two sources reach an ordinary user, and :func:`redacted_model_access` is the+one place both are resolved: ``admin`` models assigned through a grant, and+the ``personal`` owner-bound profiles the user signed in for themselves (see+:mod:`deeptutor.multi_user.personal_models`). Everything downstream — the+option list, the capability gate, and selection validation — reads that one+function, so the three can never disagree about what a user may use."""from __future__ import annotations@@ -86,6 +93,14 @@ def redacted_model_access(user_id: str | None = None) -> dict[str, list[dict[str"available": model is not None,})+ if user_id == user.id:+ # Only ever the caller's OWN personal models. An administrator+ # inspecting somebody's grants asks for that user's id, and their+ # personal sign-in is not the administrator's business — nor is it in+ # the grant editor's gift to assign.+ from .personal_models import personal_llm_rows++ result["llm"].extend(personal_llm_rows())return result@@ -102,7 +117,7 @@ def allowed_llm_options() -> dict[str, Any]:"label": item.get("name") or item.get("model") or item.get("model_id"),"model": item.get("model") or "","provider": "",- "source": "admin",+ "source": item.get("source") or "admin","is_active_default": False,}for item in redacted_model_access(user.id).get("llm", [])diff --git a/deeptutor/multi_user/personal_models.py b/deeptutor/multi_user/personal_models.pynew file mode 100644index 000000000..1b215fceb--- /dev/null+++ b/deeptutor/multi_user/personal_models.py@@ -0,0 +1,142 @@+"""Owner-bound LLM profiles an ordinary user signed in for themselves.++An owner-bound profile — an OpenAI Codex OAuth login, today — authenticates+one *person's* subscription rather than a billable team key, so it is never+lent to another account through grants (see+:func:`~deeptutor.multi_user.model_access.is_owner_bound`). Before this+module that left ordinary users with no path to Codex at all: they could+not be granted the administrator's profile (correctly withheld) and could+not sign in for themselves either, because the OAuth endpoints were+admin-only (#781).++The rule that makes per-user sign-in safe is *where the profile lives*: an+ordinary user's Codex profile is written to that user's OWN catalog+(``data/users/<uid>/settings/model_catalog.json``), never into the shared+admin catalog. Nothing an ordinary user does can therefore appear in the+administrator's model list, in another user's options, or in the grant+editor. The profile is merged into the catalog the runtime resolves against+per request instead — which is safe because a managed Codex profile carries+no secret at all (``api_key`` is empty; the token is read from the owner's+credential store at call time by+:class:`~deeptutor.services.llm.provider_core.openai_codex_provider.OpenAICodexProvider`).++Ownership resolution is shared with the credential store via+:func:`~deeptutor.multi_user.paths.get_owner_path_service`, so a profile and+the token that authorizes it can never be resolved to different accounts —+and a partner turn keeps inheriting the login of the human who owns it.+"""++from __future__ import annotations++from typing import Any++from deeptutor.services.config.model_catalog import ModelCatalogService++from .paths import get_owner_path_service+++def owner_catalog_service() -> ModelCatalogService:+ """Model catalog of the account that owns the current scope.++ For an administrator — and for any scope with no request context, i.e.+ CLI runs and background jobs — this is the shared deployment catalog, so+ administrator behaviour is exactly what it was. For an ordinary user it+ is their own file; for a partner, its owner's.+ """+ return ModelCatalogService.get_instance(+ get_owner_path_service().get_settings_file("model_catalog")+ )+++def _personal_catalog_profiles() -> list[dict[str, Any]]:+ """Owner-bound LLM profiles from the owner's own catalog.++ Empty for an administrator: their owner-bound profiles already live in+ the shared catalog they manage, and overlaying them would duplicate+ every model in their own option list.+ """+ from .context import get_current_user_or_none+ from .model_access import is_owner_bound++ user = get_current_user_or_none()+ if user is None or user.is_admin:+ return []+ service = owner_catalog_service()+ # Checked rather than loaded blind: ``load()`` writes a default catalog+ # when the file is absent, and a user who never touched Codex should not+ # get a settings file created on every options request.+ if not service.path.exists():+ 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)+ ]+++def personal_llm_rows() -> list[dict[str, Any]]:+ """Personal models in the row shape ``redacted_model_access`` returns.++ ``source="personal"`` is what tells the frontend these came from the+ user's own sign-in rather than an administrator's grant, so it can offer+ them a connect/disconnect card instead of a read-only assignment.+ """+ rows: list[dict[str, Any]] = []+ for profile in _personal_catalog_profiles():+ profile_id = str(profile.get("id") or "")+ for model in profile.get("models", []) or []:+ if not isinstance(model, dict):+ continue+ model_id = str(model.get("id") or "")+ if not model_id:+ continue+ rows.append(+ {+ "profile_id": profile_id,+ "model_id": model_id,+ "name": model.get("name") or model_id,+ "model": model.get("model") or "",+ "source": "personal",+ "available": True,+ }+ )+ return rows+++def merge_personal_llm_profiles(catalog: dict[str, Any]) -> dict[str, Any]:+ """``catalog`` plus the current owner's personal LLM profiles.++ Used on the resolution path so a personal selection resolves to a real+ profile: the runtime otherwise looks the selection up in the shared+ catalog, where a per-user profile deliberately does not exist. Returns+ the input untouched when there is nothing to add, and never mutates it.++ A personal profile *replaces* a shared one of the same id rather than+ being skipped. Managed profile ids are per-provider constants, so an+ administrator who also signed in to Codex holds a profile under the same+ id — and that one lists the administrator's models, which the user's plan+ may not include. The owner's own profile is the authority inside their+ own scope; the token is resolved per owner regardless.+ """+ personal = _personal_catalog_profiles()+ if not personal:+ return catalog+ personal_ids = {str(profile.get("id") or "") for profile in personal}+ merged = dict(catalog)+ services = dict(merged.get("services") or {})+ llm = dict(services.get("llm") or {})+ shared = [+ profile+ for profile in llm.get("profiles") or []+ if not (isinstance(profile, dict) and str(profile.get("id") or "") in personal_ids)+ ]+ llm["profiles"] = shared + personal+ services["llm"] = llm+ merged["services"] = services+ return merged+++__all__ = [+ "merge_personal_llm_profiles",+ "owner_catalog_service",+ "personal_llm_rows",+]diff --git a/deeptutor/services/codex_auth/service.py b/deeptutor/services/codex_auth/service.pyindex 9e5c3b263..271e80a77 100644--- a/deeptutor/services/codex_auth/service.py+++ b/deeptutor/services/codex_auth/service.py@@ -16,10 +16,7 @@ from typing import Anyimport httpx-from deeptutor.services.config.model_catalog import (- ModelCatalogService,- get_model_catalog_service,-)+from deeptutor.services.config.model_catalog import ModelCatalogServicefrom deeptutor.services.config.runtime_settings import load_system_settingsfrom .catalog import CodexModelCatalog@@ -794,6 +791,22 @@ def _relocate_legacy_store(user_root: Path, secrets_root: Path) -> bool:return True+def _owner_model_catalog_service() -> ModelCatalogService:+ """The catalog a sign-in publishes its managed profile into.++ Deliberately NOT :func:`get_model_catalog_service`, which resolves an+ ordinary user to the *administrator's* catalog: a non-admin sign-in would+ then write their personal Codex profile into the shared catalog, where it+ would show up in the administrator's model list and in every other user's+ resolution path. Owner scope keys this to the same account as the+ credential store, so a login and its profile can never land in different+ places (#781).+ """+ from deeptutor.multi_user.personal_models import owner_catalog_service++ return owner_catalog_service()++def get_codex_oauth_service() -> CodexOAuthService:secrets_root = _codex_secrets_root()key = str(secrets_root)@@ -806,7 +819,7 @@ def get_codex_oauth_service() -> CodexOAuthService:service = CodexOAuthService(store,catalog,- get_model_catalog_service(),+ _owner_model_catalog_service(),oauth_client=CodexOAuthClient(http),callback_forward_port=callback_forward_port,)diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.pyindex c15c0d0c8..da2058828 100644--- a/deeptutor/services/config/provider_runtime.py+++ b/deeptutor/services/config/provider_runtime.py@@ -541,6 +541,24 @@ def _load_catalog(catalog: dict[str, Any] | None) -> dict[str, Any]:return get_model_catalog_service().load()+def _with_personal_llm_profiles(catalog: dict[str, Any]) -> dict[str, Any]:+ """Add the current owner's own owner-bound LLM profiles to *catalog*.++ An ordinary user's Codex profile lives in their own catalog rather than+ the shared one (see :mod:`deeptutor.multi_user.personal_models`), so+ resolving a personal selection against the shared catalog alone would+ fail to find the profile it names. Imported lazily and guarded: the LLM+ layer must keep resolving in contexts where multi-user state is absent+ (CLI, tests, background jobs).+ """+ try:+ from deeptutor.multi_user.personal_models import merge_personal_llm_profiles++ return merge_personal_llm_profiles(catalog)+ except Exception:+ return catalog++def _active_profile_and_model(catalog: dict[str, Any],service: ModelCatalogService,@@ -626,7 +644,7 @@ def resolve_llm_runtime_config() -> ResolvedLLMConfig:"""Resolve active LLM config with TutorBot-style provider matching."""catalog_service = service or get_model_catalog_service()- loaded = _load_catalog(catalog)+ loaded = _with_personal_llm_profiles(_load_catalog(catalog))loaded = apply_llm_selection_to_catalog(loaded, llm_selection)profile, model = _active_profile_and_model(loaded, catalog_service, "llm")diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pyindex bd75f9015..f2926a0e8 100644--- a/deeptutor/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -744,6 +744,7 @@ class TurnRuntimeManager:"model_id": assigned_llms[0].get("model_id"),}if llm_selection:+ from deeptutor.multi_user.personal_models import merge_personal_llm_profilesfrom deeptutor.services.config import get_model_catalog_servicefrom deeptutor.services.model_selection import (LLMSelection,@@ -751,8 +752,12 @@ class TurnRuntimeManager:)try:+ # Personal (owner-bound) profiles live in the user's own+ # catalog, so validating against the shared one alone would+ # reject a Codex model the user signed in for themselves —+ # the same merge the resolution path performs (#781).apply_llm_selection_to_catalog(- get_model_catalog_service().load(),+ merge_personal_llm_profiles(get_model_catalog_service().load()),LLMSelection.from_payload(llm_selection),)except ValueError as exc:diff --git a/tests/api/test_codex_oauth_scope.py b/tests/api/test_codex_oauth_scope.pynew file mode 100644index 000000000..0a682451f--- /dev/null+++ b/tests/api/test_codex_oauth_scope.py@@ -0,0 +1,105 @@+"""Who may drive the Codex OAuth lifecycle (issue #781).++These five endpoints act on the *caller's own* credentials — the store, the+model catalog, and the callback route are all resolved from owner scope — so+the administrator gate that used to sit on them was what left ordinary users+unable to use Codex at all: an owner-bound profile is never grantable, and+they could not sign in for themselves either.++What replaces it is narrower, not absent: a partner is refused. A partner is+a synthetic user whose owner is a real account, so admitting one would mean+acting on that person's login — including signing them out.+"""++from __future__ import annotations++from typing import Any++from fastapi import FastAPI+from fastapi.testclient import TestClient+import pytest++from deeptutor.api.routers import settings as settings_router+from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.partners.scope import PARTNER_USER_PREFIX++CODEX_ROUTES = [+ ("post", "/api/v1/settings/providers/openai-codex/oauth/start"),+ ("get", "/api/v1/settings/providers/openai-codex/oauth/status"),+ ("post", "/api/v1/settings/providers/openai-codex/oauth/cancel"),+ ("post", "/api/v1/settings/providers/openai-codex/oauth/logout"),+ ("post", "/api/v1/settings/providers/openai-codex/models/refresh"),+]+++class _Service:+ """Stand-in for the per-owner ``CodexOAuthService``."""++ def __init__(self) -> None:+ self.calls: list[str] = []++ async def start_login(self) -> dict[str, Any]:+ self.calls.append("start")+ return {"operation_id": "op-1"}++ def public_status(self) -> dict[str, Any]:+ self.calls.append("status")+ return {"connection": "disconnected"}++ async def cancel_login(self) -> dict[str, Any]:+ self.calls.append("cancel")+ return {"connection": "disconnected"}++ async def logout(self) -> dict[str, Any]:+ self.calls.append("logout")+ return {"connection": "disconnected"}++ async def refresh_models(self) -> dict[str, Any]:+ self.calls.append("refresh")+ return {"connection": "connected"}+++def _user(uid: str, *, role: str, root) -> CurrentUser:+ return CurrentUser(+ id=uid,+ username=uid,+ role=role,+ scope=UserScope(kind="user", user_id=uid, root=root),+ )+++def client(tmp_path, monkeypatch) -> tuple[TestClient, _Service, dict[str, CurrentUser]]:+ service = _Service()+ monkeypatch.setattr(settings_router, "get_codex_oauth_service", lambda: service)+ current: dict[str, CurrentUser] = {+ "user": _user("u_alice", role="user", root=tmp_path / "alice")+ }+ monkeypatch.setattr(settings_router, "get_current_user", lambda: current["user"])++ app = FastAPI()+ app.include_router(settings_router.router, prefix="/api/v1/settings")+ return TestClient(app), service, current++[email protected](("method", "path"), CODEX_ROUTES)+def test_an_ordinary_user_drives_their_own_codex_lifecycle(client, method, path) -> None:+ test_client, service, _current = client++ response = getattr(test_client, method)(path)++ assert response.status_code == 200+ assert service.calls, "the request must reach the owner-scoped service"++[email protected](("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+ would let it sign that person out."""+ test_client, service, current = client+ current["user"] = _user(f"{PARTNER_USER_PREFIX}ada", role="user", root=tmp_path / "partner-ada")++ response = getattr(test_client, method)(path)++ assert response.status_code == 403+ assert service.calls == []diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.pyindex 8f628526a..048b9c569 100644--- a/tests/api/test_settings_router.py+++ b/tests/api/test_settings_router.py@@ -868,27 +868,33 @@ def test_codex_provider_choice_is_advertised_as_oauth() -> None:@pytest.mark.asyncio-async def test_codex_oauth_status_is_admin_only(+async def test_codex_oauth_status_is_reachable_by_an_ordinary_user(monkeypatch: pytest.MonkeyPatch,) -> None:- from fastapi import HTTPException-+ """Codex OAuth is personal, not administrative (#781).++ This route used to be administrator-gated, which left ordinary users with+ no path to Codex at all: an owner-bound profile is never grantable, so+ they could neither be given one nor sign in for themselves. Everything it+ touches — credential store, model catalog, callback route — resolves from+ owner scope, so it is the caller's own login either way. The full+ authorization contract, including the partner refusal that replaced the+ admin gate, lives in ``tests/api/test_codex_oauth_scope.py``.+ """+ fake = _FakeCodexOAuthService()monkeypatch.setattr(settings_router,"get_current_user",- lambda: SimpleNamespace(is_admin=False),+ lambda: SimpleNamespace(id="u_alice", is_admin=False),)monkeypatch.setattr(settings_router,"get_codex_oauth_service",- lambda: (_ for _ in ()).throw(AssertionError("service must not be accessed")),+ lambda: fake,raising=False,)- with pytest.raises(HTTPException) as exc_info:- await settings_router.get_openai_codex_oauth_status()-- assert exc_info.value.status_code == 403+ assert await settings_router.get_openai_codex_oauth_status() == fake.public_status()@pytest.mark.asyncio@@ -899,7 +905,7 @@ async def test_codex_oauth_routes_return_only_public_service_payloads(monkeypatch.setattr(settings_router,"get_current_user",- lambda: SimpleNamespace(is_admin=True),+ lambda: SimpleNamespace(id="root", is_admin=True),)monkeypatch.setattr(settings_router,@@ -948,7 +954,7 @@ async def test_codex_oauth_error_maps_to_sanitized_http_detail(monkeypatch.setattr(settings_router,"get_current_user",- lambda: SimpleNamespace(is_admin=True),+ lambda: SimpleNamespace(id="root", is_admin=True),)monkeypatch.setattr(settings_router,diff --git a/tests/multi_user/test_personal_codex_models.py b/tests/multi_user/test_personal_codex_models.pynew file mode 100644index 000000000..8ffd7796f--- /dev/null+++ b/tests/multi_user/test_personal_codex_models.py@@ -0,0 +1,189 @@+"""Per-user Codex sign-in in an authenticated deployment (issue #781).++An owner-bound profile authenticates one person's ChatGPT plan, so it is+never grantable — which used to leave ordinary users with no path to Codex+at all, because the OAuth endpoints were admin-only too. They can now sign+in for themselves, and the isolation that makes it safe is asserted here:++* the profile is written to the user's OWN catalog, never the shared one;+* it reaches that user's options, capability gate, and selection validation;+* it reaches nobody else's — not another user's, not the administrator's,+ and not the grant editor's view of that user.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from deeptutor.multi_user import model_access, personal_models++CODEX_PROFILE = "llm-profile-openai-codex-managed"+SHARED_PROFILE = "llm-profile-shared-key"+++def _codex_profile(model_id: str, model: str) -> dict[str, Any]:+ """The shape ``sync_codex_catalog`` publishes — note the empty api_key:+ a managed Codex profile carries no secret, the token lives in the+ owner's credential store."""+ return {+ "id": CODEX_PROFILE,+ "name": "OpenAI Codex",+ "binding": "openai_codex",+ "api_key": "",+ "owner_bound": True,+ "read_only": True,+ "managed_by": "openai_codex_oauth",+ "models": [{"id": model_id, "name": model_id, "model": model}],+ }+++def _write_catalog(path: Path, profiles: list[dict[str, Any]]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps({"version": 1, "services": {"llm": {"profiles": profiles}}}),+ encoding="utf-8",+ )+++def _sign_in_codex(as_user, uid: str, model_id: str, model: str) -> None:+ """Simulate a completed OAuth sign-in for *uid* by writing the profile+ exactly where the service publishes it: that owner's own catalog."""+ with as_user(uid):+ _write_catalog(+ personal_models.owner_catalog_service().path, [_codex_profile(model_id, model)]+ )+++def _admin_catalog(profiles: list[dict[str, Any]]) -> dict[str, Any]:+ return {"services": {"llm": {"profiles": profiles}}}+++def no_grants(monkeypatch):+ monkeypatch.setattr(model_access, "load_grant", lambda _uid=None: {"models": {"llm": []}})+++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 can+ reach the catalog the administrator manages."""+ with as_user("u_alice"):+ alice_path = personal_models.owner_catalog_service().path+ with as_user("root", role="admin"):+ admin_path = personal_models.owner_catalog_service().path++ assert alice_path != admin_path+ assert "users/u_alice" in alice_path.as_posix()+ assert alice_path.is_relative_to((mu_isolated_root / "data" / "users" / "u_alice").resolve())+++def test_signed_in_user_sees_their_own_codex_models(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")++ with as_user("u_alice"):+ rows = model_access.redacted_model_access()["llm"]+ assert [(r["model_id"], r["source"], r["available"]) for r in rows] == [+ ("m-sol", "personal", True)+ ]+ # The option list, the gate, and selection validation all read that+ # same function, so a personal model works end to end without a grant.+ options = model_access.allowed_llm_options()["options"]+ assert [(o["model_id"], o["source"]) for o in options] == [("m-sol", "personal")]+ assert model_access.has_capability_access("llm") is True+ assert model_access.apply_allowed_llm_selection(+ {"profile_id": CODEX_PROFILE, "model_id": "m-sol"}+ ) == {"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")++ with as_user("u_bob"):+ 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_two_users_connect_different_accounts_without_crossover(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")+ _sign_in_codex(as_user, "u_bob", "m-mini", "gpt-5.6-mini")++ with as_user("u_alice"):+ assert [r["model_id"] for r in model_access.redacted_model_access()["llm"]] == ["m-sol"]+ with as_user("u_bob"):+ assert [r["model_id"] for r in model_access.redacted_model_access()["llm"]] == ["m-mini"]+++def test_administrator_never_sees_a_users_personal_sign_in(as_user, monkeypatch, no_grants):+ """Two claims at once: the admin's own view is unchanged (it resolves+ straight from the catalog they manage), and asking for a user's grants+ does not surface that user's personal login."""+ monkeypatch.setattr(model_access, "admin_catalog", lambda: _admin_catalog([]))+ _sign_in_codex(as_user, "u_alice", "m-sol", "gpt-5.6-sol")++ with as_user("root", role="admin"):+ assert model_access.redacted_model_access("u_alice")["llm"] == []+ assert personal_models.personal_llm_rows() == []+++def test_granted_admin_models_and_personal_models_coexist(as_user, monkeypatch):+ shared = {+ "id": SHARED_PROFILE,+ "name": "Team key",+ "models": [{"id": "m-team", "name": "Team model", "model": "gpt-4o"}],+ }+ monkeypatch.setattr(model_access, "admin_catalog", lambda: _admin_catalog([shared]))+ monkeypatch.setattr(+ model_access,+ "load_grant",+ lambda _uid=None: {+ "models": {"llm": [{"profile_id": SHARED_PROFILE, "model_ids": ["m-team"]}]}+ },+ )+ _sign_in_codex(as_user, "u_alice", "m-sol", "gpt-5.6-sol")++ with as_user("u_alice"):+ rows = model_access.redacted_model_access()["llm"]+ assert [(r["model_id"], r["source"]) for r in rows] == [+ ("m-team", "admin"),+ ("m-sol", "personal"),+ ]+++def test_merge_lets_the_owners_profile_win_over_the_shared_one(as_user, monkeypatch, no_grants):+ """A managed profile id is a constant, so an administrator who also signed+ in holds one under the same id — listing *their* models. Resolving a user's+ selection against that would fail for any model their own plan added."""+ admin_side = _codex_profile("m-admin-only", "gpt-5.6-admin")+ _sign_in_codex(as_user, "u_alice", "m-sol", "gpt-5.6-sol")++ with as_user("u_alice"):+ merged = personal_models.merge_personal_llm_profiles(_admin_catalog([admin_side]))+ profiles = merged["services"]["llm"]["profiles"]+ assert [p["id"] for p in profiles] == [CODEX_PROFILE]+ assert [m["id"] for m in profiles[0]["models"]] == ["m-sol"]+++def test_merge_is_a_no_op_without_a_personal_sign_in(as_user, monkeypatch, no_grants):+ catalog = _admin_catalog([{"id": SHARED_PROFILE, "models": []}])+ with as_user("u_alice"):+ assert personal_models.merge_personal_llm_profiles(catalog) is catalog+++def test_reading_options_does_not_create_a_catalog_file(as_user, monkeypatch, no_grants):+ """A user who never touched Codex must not get a settings file written on+ every options request."""+ monkeypatch.setattr(model_access, "admin_catalog", lambda: _admin_catalog([]))+ with as_user("u_alice"):+ catalog_path = personal_models.owner_catalog_service().path+ assert model_access.redacted_model_access()["llm"] == []+ assert not catalog_path.exists()diff --git a/tests/services/codex_auth/test_service.py b/tests/services/codex_auth/test_service.pyindex 128d150d8..def6aa93d 100644--- a/tests/services/codex_auth/test_service.py+++ b/tests/services/codex_auth/test_service.py@@ -148,7 +148,9 @@ def test_service_singleton_reads_frontend_port_only_when_created(lambda _store, *, http: object(),)monkeypatch.setattr(service_module, "CodexOAuthClient", lambda _http: object())- monkeypatch.setattr(service_module, "get_model_catalog_service", lambda: object())+ # A sign-in publishes into the OWNER's catalog, never the shared one that+ # ``get_model_catalog_service`` resolves an ordinary user to (#781).+ monkeypatch.setattr(service_module, "_owner_model_catalog_service", lambda: object())monkeypatch.setattr(service_module, "CodexOAuthService", CapturingService)first = service_module.get_codex_oauth_service()diff --git a/web/components/settings/CodexOAuthCard.tsx b/web/components/settings/CodexOAuthCard.tsxindex a02020ba6..52f2092c9 100644--- a/web/components/settings/CodexOAuthCard.tsx+++ b/web/components/settings/CodexOAuthCard.tsx@@ -5,6 +5,7 @@ import { ExternalLink, RefreshCw, ShieldCheck, Unplug } from "lucide-react";import { useTranslation } from "react-i18next";import Button from "@/components/ui/Button";+import { invalidateLLMOptionsCache } from "@/lib/llm-options";import {buildSshForwardCommand,cancelCodexLogin,@@ -120,6 +121,12 @@ export function CodexOAuthCard() {// Reloading replaces the whole catalog draft, so this must never run behind// the operator's back while they have unsaved edits open on another provider.const syncCatalog = useCallback(async () => {+ // Every model picker reads a cached option list — derived from the catalog+ // for an administrator, from /settings/llm-options for an ordinary user —+ // and a sign-in, logout, or model refresh changes what belongs in it. Drop+ // the cache first, and unconditionally: the server has already changed+ // even when the catalog reload below is deferred.+ invalidateLLMOptionsCache();if (hasUnsavedChanges) {setToast(t("codex.oauth.reloadDeferred"));return;diff --git a/web/components/settings/ServiceConfigEditor.tsx b/web/components/settings/ServiceConfigEditor.tsxindex aae8ad702..9dde6b2f1 100644--- a/web/components/settings/ServiceConfigEditor.tsx+++ b/web/components/settings/ServiceConfigEditor.tsx@@ -206,10 +206,18 @@ export function ServiceConfigEditor({ service }: { service: ServiceName }) {);}return (- <div className="rounded-xl border border-dashed border-[var(--border)] px-5 py-10 text-center text-[13px] text-[var(--muted-foreground)]">- {t(- "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",- )}+ <div className="space-y-4">+ <div className="rounded-xl border border-dashed border-[var(--border)] px-5 py-10 text-center text-[13px] text-[var(--muted-foreground)]">+ {t(+ "Model endpoints are assigned by your administrator. You can still personalize theme and language here.",+ )}+ </div>+ {/* One thing an ordinary user CAN configure for themselves: an+ owner-bound Codex login. It authenticates their own ChatGPT plan,+ so it is never something an administrator can grant them — the+ account has to sign in for itself (#781). The card talks only to+ the per-user OAuth endpoints and exposes no catalog. */}+ {service === "llm" && <CodexOAuthCard />}</div>);}