fix(webui): surface OAuth model catalog authorization failures
This commit is contained in:
1 parent
a478c96bde
commit
024fe8f636
26 files changed
+585
-34
No files matched your search
@@ -4,6 +4,15 @@ Use this page when the first reply fails because of provider/model mismatch, or
|
||||
|
||||
For normal local setup, open **Settings → Models** in the WebUI to add provider credentials, create a model preset, and select the active model. Use the JSON below for manual deployments, local endpoints, provider-specific fields, or diagnosis.
|
||||
|
||||
The model picker fetches online catalogs for OpenAI Codex, xAI Grok, and GitHub
|
||||
Copilot. If a refresh fails, it labels cached or built-in lists as potentially
|
||||
out of date. An explicit authorization failure offers **Sign in again** using
|
||||
the existing provider login flow; successful WebUI sign-in clears the catalog
|
||||
cache. Network, rate-limit, and service failures instead ask you to try again
|
||||
later (failed refreshes are cached briefly). Existing presets and manual model
|
||||
IDs remain available. A successful chat may have used a fallback preset and
|
||||
does not prove that the selected provider's authorization is still valid.
|
||||
|
||||
For every setup, answer three questions:
|
||||
|
||||
1. Which provider owns the credential or endpoint?
|
||||
|
||||
@@ -19,6 +19,7 @@ from oauth_cli_kit.storage import FileTokenStorage
|
||||
|
||||
from nanobot.providers.base import LLMResponse, ProviderCallContext
|
||||
from nanobot.providers.oauth_model_catalog import (
|
||||
OAuthCatalogAuthRequiredError,
|
||||
OAuthModelCatalog,
|
||||
OAuthModelCatalogSnapshot,
|
||||
)
|
||||
@@ -326,7 +327,7 @@ def invalidate_github_copilot_model_catalog() -> None:
|
||||
def _fetch_github_copilot_models(proxy: str | None) -> tuple[ProviderModelSpec, ...]:
|
||||
github_token = get_storage().load()
|
||||
if not github_token or not github_token.access:
|
||||
raise RuntimeError("GitHub Copilot is not logged in")
|
||||
raise OAuthCatalogAuthRequiredError()
|
||||
|
||||
common_headers = {
|
||||
"Accept": "application/json",
|
||||
|
||||
@@ -6,13 +6,48 @@ import threading
|
||||
import time
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Literal
|
||||
from typing import Literal, cast
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.providers.registry import ProviderModelSpec
|
||||
|
||||
CatalogSource = Literal["remote", "cache", "stale", "fallback"]
|
||||
CatalogErrorKind = Literal["auth_required", "unavailable"]
|
||||
|
||||
|
||||
class OAuthCatalogAuthRequiredError(RuntimeError):
|
||||
"""The provider's credentials are missing or were explicitly rejected."""
|
||||
|
||||
|
||||
def oauth_catalog_auth_rejected(status: int, payload: object = None) -> bool:
|
||||
"""Classify only explicit credential failures, never arbitrary response text."""
|
||||
if status == 401:
|
||||
return True
|
||||
if status not in {400, 403} or not isinstance(payload, dict):
|
||||
return False
|
||||
error = cast(dict[object, object], payload).get("error")
|
||||
code = cast(dict[object, object], error).get("code") if isinstance(error, dict) else error
|
||||
return isinstance(code, str) and code in {
|
||||
"invalid_grant", "invalid_token", "token_revoked", "refresh_token_expired",
|
||||
"refresh_token_reused", "refresh_token_invalidated",
|
||||
}
|
||||
|
||||
|
||||
def _catalog_error_kind(exc: Exception) -> CatalogErrorKind:
|
||||
if isinstance(exc, OAuthCatalogAuthRequiredError):
|
||||
return "auth_required"
|
||||
if isinstance(exc, httpx.HTTPStatusError):
|
||||
payload: object = None
|
||||
if len(exc.response.content) <= 16_384:
|
||||
try:
|
||||
payload = exc.response.json()
|
||||
except ValueError:
|
||||
pass
|
||||
if oauth_catalog_auth_rejected(exc.response.status_code, payload):
|
||||
return "auth_required"
|
||||
return "unavailable"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -23,6 +58,7 @@ class OAuthModelCatalogSnapshot:
|
||||
source: CatalogSource
|
||||
fetched_at: float
|
||||
message: str | None = None
|
||||
error_kind: CatalogErrorKind | None = None
|
||||
|
||||
def find(self, model: str) -> ProviderModelSpec | None:
|
||||
wire_id = model.split("/", 1)[-1]
|
||||
@@ -38,6 +74,12 @@ class _CacheEntry:
|
||||
stored_at: float
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _FailureEntry:
|
||||
retry_at: float
|
||||
error_kind: CatalogErrorKind
|
||||
|
||||
|
||||
class OAuthModelCatalog:
|
||||
"""Cache one provider's discovery behind a small failure-tolerant interface."""
|
||||
|
||||
@@ -67,7 +109,7 @@ class OAuthModelCatalog:
|
||||
self._wall_clock = wall_clock
|
||||
self._condition = threading.Condition()
|
||||
self._entries: dict[str, _CacheEntry] = {}
|
||||
self._failures: dict[str, float] = {}
|
||||
self._failures: dict[str, _FailureEntry] = {}
|
||||
self._inflight: set[str] = set()
|
||||
self._generation = 0
|
||||
|
||||
@@ -92,12 +134,13 @@ class OAuthModelCatalog:
|
||||
if not models:
|
||||
raise ValueError("provider returned an empty model catalog")
|
||||
except Exception as exc:
|
||||
logger.warning("OAuth model catalog refresh failed: type={}", type(exc).__name__)
|
||||
error_kind = _catalog_error_kind(exc)
|
||||
logger.warning("OAuth model catalog refresh failed: kind={}", error_kind)
|
||||
with self._condition:
|
||||
result = (
|
||||
self._stale_or_fallback(None, self._monotonic())
|
||||
if generation != self._generation
|
||||
else self._failure_result(cache_key)
|
||||
else self._failure_result(cache_key, error_kind)
|
||||
)
|
||||
else:
|
||||
now = self._monotonic()
|
||||
@@ -132,35 +175,40 @@ class OAuthModelCatalog:
|
||||
entry = self._entries.get(cache_key)
|
||||
if entry is not None and now - entry.stored_at < self._fresh_ttl_s:
|
||||
return replace(entry.snapshot, source="cache")
|
||||
failure_until = self._failures.get(cache_key)
|
||||
if failure_until is not None and failure_until <= now:
|
||||
failure = self._failures.get(cache_key)
|
||||
if failure is not None and failure.retry_at <= now:
|
||||
self._failures.pop(cache_key, None)
|
||||
elif failure_until is not None:
|
||||
return self._stale_or_fallback(entry, now)
|
||||
elif failure is not None:
|
||||
return self._stale_or_fallback(entry, now, failure.error_kind)
|
||||
return None
|
||||
|
||||
def _failure_result(self, cache_key: str) -> OAuthModelCatalogSnapshot:
|
||||
def _failure_result(
|
||||
self, cache_key: str, error_kind: CatalogErrorKind,
|
||||
) -> OAuthModelCatalogSnapshot:
|
||||
now = self._monotonic()
|
||||
self._reserve(cache_key)
|
||||
self._failures[cache_key] = now + self._failure_ttl_s
|
||||
return self._stale_or_fallback(self._entries.get(cache_key), now)
|
||||
self._failures[cache_key] = _FailureEntry(now + self._failure_ttl_s, error_kind)
|
||||
return self._stale_or_fallback(self._entries.get(cache_key), now, error_kind)
|
||||
|
||||
def _stale_or_fallback(
|
||||
self,
|
||||
entry: _CacheEntry | None,
|
||||
now: float,
|
||||
error_kind: CatalogErrorKind = "unavailable",
|
||||
) -> OAuthModelCatalogSnapshot:
|
||||
if entry is not None and now - entry.stored_at < self._stale_ttl_s:
|
||||
return replace(
|
||||
entry.snapshot,
|
||||
source="stale",
|
||||
message="Could not refresh the online model list; showing cached models.",
|
||||
error_kind=error_kind,
|
||||
)
|
||||
return OAuthModelCatalogSnapshot(
|
||||
models=self._fallback_models,
|
||||
source="fallback",
|
||||
fetched_at=self._wall_clock(),
|
||||
message="Could not load the online model list; showing built-in fallback models.",
|
||||
error_kind=error_kind,
|
||||
)
|
||||
|
||||
def _store(self, cache_key: str, entry: _CacheEntry) -> None:
|
||||
@@ -176,7 +224,7 @@ class OAuthModelCatalog:
|
||||
key=lambda key: (
|
||||
self._entries[key].stored_at
|
||||
if key in self._entries
|
||||
else self._failures[key] - self._failure_ttl_s
|
||||
else self._failures[key].retry_at - self._failure_ttl_s
|
||||
),
|
||||
)
|
||||
self._entries.pop(oldest, None)
|
||||
|
||||
@@ -26,8 +26,10 @@ from nanobot.providers.base import (
|
||||
resolve_stream_idle_timeout_s,
|
||||
)
|
||||
from nanobot.providers.oauth_model_catalog import (
|
||||
OAuthCatalogAuthRequiredError,
|
||||
OAuthModelCatalog,
|
||||
OAuthModelCatalogSnapshot,
|
||||
oauth_catalog_auth_rejected,
|
||||
)
|
||||
from nanobot.providers.openai_responses import (
|
||||
ResponsesStreamCapture,
|
||||
@@ -655,7 +657,26 @@ def invalidate_openai_codex_model_catalog() -> None:
|
||||
|
||||
|
||||
def _fetch_openai_codex_models(proxy: str | None) -> tuple[ProviderModelSpec, ...]:
|
||||
token = get_codex_token(proxy=proxy)
|
||||
try:
|
||||
token = get_codex_token(proxy=proxy)
|
||||
except RuntimeError as exc:
|
||||
# oauth-cli-kit exposes refresh failures as strings, not typed HTTP errors.
|
||||
# Interpret only its exact envelope; never propagate the raw token response.
|
||||
detail = str(exc)
|
||||
if detail == "OAuth credentials not found. Please run the login command.":
|
||||
raise OAuthCatalogAuthRequiredError() from None
|
||||
prefix = "Token refresh failed: "
|
||||
if detail.startswith(prefix):
|
||||
status, _, body = detail[len(prefix):].partition(" ")
|
||||
payload: object = None
|
||||
if len(body) <= 16_384:
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except ValueError:
|
||||
pass
|
||||
if status.isdecimal() and oauth_catalog_auth_rejected(int(status), payload):
|
||||
raise OAuthCatalogAuthRequiredError() from None
|
||||
raise
|
||||
account_id = getattr(token, "account_id", None)
|
||||
if not isinstance(account_id, str) or not account_id:
|
||||
raise RuntimeError("OpenAI Codex OAuth token has no account ID")
|
||||
|
||||
@@ -22,7 +22,11 @@ from nanobot.providers.base import (
|
||||
ToolCallRequest,
|
||||
resolve_stream_idle_timeout_s,
|
||||
)
|
||||
from nanobot.providers.oauth_model_catalog import OAuthModelCatalog, OAuthModelCatalogSnapshot
|
||||
from nanobot.providers.oauth_model_catalog import (
|
||||
OAuthCatalogAuthRequiredError,
|
||||
OAuthModelCatalog,
|
||||
OAuthModelCatalogSnapshot,
|
||||
)
|
||||
from nanobot.providers.openai_responses import (
|
||||
consume_sse_with_reasoning,
|
||||
convert_messages,
|
||||
@@ -661,7 +665,12 @@ def invalidate_xai_grok_model_catalog() -> None:
|
||||
|
||||
|
||||
def _fetch_xai_grok_models(proxy: str | None) -> tuple[ProviderModelSpec, ...]:
|
||||
token = get_xai_oauth_token(proxy=proxy)
|
||||
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError
|
||||
|
||||
try:
|
||||
token = get_xai_oauth_token(proxy=proxy)
|
||||
except XAIOAuthReauthRequiredError:
|
||||
raise OAuthCatalogAuthRequiredError() from None
|
||||
client_kwargs: dict[str, Any] = {"timeout": 10.0, "follow_redirects": False}
|
||||
if proxy:
|
||||
client_kwargs.update(proxy=proxy, trust_env=False)
|
||||
|
||||
@@ -60,6 +60,10 @@ class XAIOAuthError(RuntimeError):
|
||||
"""An actionable xAI OAuth failure with no credential material."""
|
||||
|
||||
|
||||
class XAIOAuthReauthRequiredError(XAIOAuthError):
|
||||
"""No usable login remains; an explicit sign-in is required."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XAIToken:
|
||||
"""Persisted xAI OAuth token material."""
|
||||
@@ -357,7 +361,7 @@ def get_xai_oauth_token(
|
||||
"""Load a usable token, refreshing it under an inter-process lock when needed."""
|
||||
token = _load_token()
|
||||
if token is None:
|
||||
raise XAIOAuthError(
|
||||
raise XAIOAuthReauthRequiredError(
|
||||
"xAI is not signed in. Run `nanobot provider login xai-grok` first."
|
||||
)
|
||||
if not force_refresh and _token_is_fresh(token, min_ttl_ms):
|
||||
@@ -365,7 +369,7 @@ def get_xai_oauth_token(
|
||||
if not token.refresh:
|
||||
if not force_refresh and token.expires > _now_ms():
|
||||
return token
|
||||
raise XAIOAuthError(
|
||||
raise XAIOAuthReauthRequiredError(
|
||||
"The xAI login has expired and cannot be refreshed. "
|
||||
"Run `nanobot provider login xai-grok` again."
|
||||
)
|
||||
@@ -373,13 +377,13 @@ def get_xai_oauth_token(
|
||||
with _token_lock():
|
||||
latest = _load_token()
|
||||
if latest is None:
|
||||
raise XAIOAuthError(
|
||||
raise XAIOAuthReauthRequiredError(
|
||||
"xAI is not signed in. Run `nanobot provider login xai-grok` first."
|
||||
)
|
||||
if not force_refresh and _token_is_fresh(latest, min_ttl_ms):
|
||||
return latest
|
||||
if not latest.refresh:
|
||||
raise XAIOAuthError(
|
||||
raise XAIOAuthReauthRequiredError(
|
||||
"The xAI login has expired and cannot be refreshed. "
|
||||
"Run `nanobot provider login xai-grok` again."
|
||||
)
|
||||
@@ -705,6 +709,11 @@ def _oauth_http_error(response: httpx.Response, action: str) -> XAIOAuthError:
|
||||
description = raw_description[:200] if isinstance(raw_description, str) else None
|
||||
detail = ": ".join(value for value in (code, description) if value)
|
||||
suffix = f" ({detail})" if detail else ""
|
||||
if action == "token refresh" and (
|
||||
response.status_code == 401
|
||||
or (response.status_code in {400, 403} and code in {"invalid_grant", "invalid_token"})
|
||||
):
|
||||
return XAIOAuthReauthRequiredError("The xAI login has expired. Please sign in again.")
|
||||
return XAIOAuthError(f"xAI OAuth {action} failed with HTTP {response.status_code}{suffix}.")
|
||||
|
||||
|
||||
|
||||
@@ -685,6 +685,7 @@ def provider_models_payload(
|
||||
**base_payload,
|
||||
"status": "available",
|
||||
"source": catalog.source,
|
||||
"error_kind": catalog.error_kind,
|
||||
"models": rows,
|
||||
"model_count": len(rows),
|
||||
"message": catalog.message,
|
||||
@@ -1591,15 +1592,13 @@ def login_oauth_provider(
|
||||
if spec.name == "github_copilot":
|
||||
try:
|
||||
from nanobot.providers.github_copilot_provider import (
|
||||
get_github_copilot_login_status,
|
||||
login_github_copilot,
|
||||
)
|
||||
except ImportError:
|
||||
raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None
|
||||
|
||||
token = get_github_copilot_login_status()
|
||||
if not token:
|
||||
token = login_github_copilot(print_fn=lambda _message: None)
|
||||
# An existing token can be revoked; an explicit sign-in must replace it.
|
||||
token = login_github_copilot(print_fn=lambda _message: None)
|
||||
if not (token and token.access):
|
||||
raise WebUISettingsError("OAuth login failed", status=401)
|
||||
invalidate_oauth_model_catalog(spec.name)
|
||||
|
||||
@@ -12,6 +12,7 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.providers.oauth_model_catalog import (
|
||||
OAuthCatalogAuthRequiredError,
|
||||
OAuthModelCatalog,
|
||||
get_oauth_model_catalog,
|
||||
invalidate_oauth_model_catalog,
|
||||
@@ -513,3 +514,125 @@ def test_catalog_treats_empty_remote_list_as_failure_and_can_be_invalidated() ->
|
||||
assert refreshed.source == "remote"
|
||||
assert refreshed.models[0].id == "provider/new"
|
||||
assert calls == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_cache", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
("status", "body", "expected"),
|
||||
[
|
||||
(401, {"error": {"code": "token_revoked"}}, "auth_required"),
|
||||
(401, "non-json", "auth_required"),
|
||||
(400, {"error": "invalid_grant"}, "auth_required"),
|
||||
(403, {"error": {"code": "token_revoked"}}, "auth_required"),
|
||||
(403, {"error": "insufficient_scope"}, "unavailable"),
|
||||
(429, {"error": "invalid_grant"}, "unavailable"),
|
||||
(503, {}, "unavailable"),
|
||||
],
|
||||
)
|
||||
def test_catalog_retains_safe_error_kind_until_reauthentication(
|
||||
with_cache: bool, status: int, body: object, expected: str,
|
||||
) -> None:
|
||||
from loguru import logger
|
||||
|
||||
now = [0.0]
|
||||
failing = [not with_cache]
|
||||
calls = 0
|
||||
sentinel = "private-token-and-account-fixture"
|
||||
logs: list[str] = []
|
||||
|
||||
def fetch(_proxy):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
if failing[0]:
|
||||
request = httpx.Request("GET", f"https://example.com/{sentinel}")
|
||||
response = httpx.Response(status, json=body, request=request)
|
||||
raise httpx.HTTPStatusError(sentinel, request=request, response=response)
|
||||
return (ProviderModelSpec(id="provider/new"),)
|
||||
|
||||
catalog = OAuthModelCatalog(
|
||||
fallback_models=(_fallback_model(),), fetch=fetch,
|
||||
fresh_ttl_s=10, stale_ttl_s=100, monotonic=lambda: now[0],
|
||||
)
|
||||
if with_cache:
|
||||
assert catalog.get(cache_key="same-account").error_kind is None
|
||||
now[0] = 11
|
||||
failing[0] = True
|
||||
sink = logger.add(lambda message: logs.append(str(message)))
|
||||
try:
|
||||
first = catalog.get(cache_key="same-account")
|
||||
second = catalog.get(cache_key="same-account")
|
||||
finally:
|
||||
logger.remove(sink)
|
||||
assert first.source == ("stale" if with_cache else "fallback")
|
||||
assert first.error_kind == second.error_kind == expected
|
||||
assert calls == (2 if with_cache else 1)
|
||||
assert sentinel not in repr(first) + "".join(logs)
|
||||
# Same account re-login must bypass both the stale list and negative cache.
|
||||
failing[0] = False
|
||||
catalog.invalidate()
|
||||
recovered = catalog.get(cache_key="same-account")
|
||||
assert recovered.source == "remote"
|
||||
assert recovered.error_kind is None
|
||||
assert recovered.message is None
|
||||
assert recovered.models[0].id == "provider/new"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure", [httpx.ConnectError("offline"), httpx.ReadTimeout("slow")])
|
||||
def test_catalog_network_errors_do_not_request_sign_in(failure: Exception) -> None:
|
||||
def fetch(_proxy):
|
||||
raise failure
|
||||
|
||||
catalog = OAuthModelCatalog(fallback_models=(_fallback_model(),), fetch=fetch)
|
||||
assert catalog.get(cache_key="one").error_kind == "unavailable"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("message", "reauth"),
|
||||
[
|
||||
('Token refresh failed: 400 {"error":"invalid_grant","token":"private"}', True),
|
||||
('Token refresh failed: 401 private', True),
|
||||
('Token refresh failed: 429 {"error":"invalid_grant"}', False),
|
||||
('Token refresh failed: 503 private', False),
|
||||
('network error mentions invalid_grant', False),
|
||||
('OAuth credentials not found. Please run the login command.', True),
|
||||
],
|
||||
)
|
||||
def test_codex_catalog_classifies_sdk_refresh_envelope(monkeypatch, message, reauth):
|
||||
from nanobot.providers.openai_codex_provider import _fetch_openai_codex_models
|
||||
|
||||
def fail(**_kwargs):
|
||||
raise RuntimeError(message)
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider.get_codex_token", fail)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
_fetch_openai_codex_models(None)
|
||||
assert isinstance(error.value, OAuthCatalogAuthRequiredError) is reauth
|
||||
if reauth:
|
||||
assert "private" not in str(error.value)
|
||||
|
||||
|
||||
def test_xai_catalog_classifies_expired_refresh_credentials(monkeypatch):
|
||||
from nanobot.providers.xai_grok_provider import _fetch_xai_grok_models
|
||||
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError, _oauth_http_error
|
||||
|
||||
failure = _oauth_http_error(
|
||||
httpx.Response(400, json={"error": "invalid_grant", "error_description": "private"}),
|
||||
"token refresh",
|
||||
)
|
||||
assert isinstance(failure, XAIOAuthReauthRequiredError)
|
||||
assert "private" not in str(failure)
|
||||
|
||||
def fail(**_kwargs):
|
||||
raise failure
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.xai_grok_provider.get_xai_oauth_token", fail)
|
||||
with pytest.raises(OAuthCatalogAuthRequiredError):
|
||||
_fetch_xai_grok_models(None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [403, 429, 503])
|
||||
def test_xai_oauth_other_failures_are_not_reauthentication(status):
|
||||
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError, _oauth_http_error
|
||||
|
||||
failure = _oauth_http_error(httpx.Response(status, json={}), "token refresh")
|
||||
assert not isinstance(failure, XAIOAuthReauthRequiredError)
|
||||
@@ -2120,6 +2120,89 @@ def test_provider_models_payload_returns_online_openai_codex_models(
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["stale", "fallback"])
|
||||
@pytest.mark.parametrize("error_kind", ["auth_required", "unavailable"])
|
||||
def test_provider_models_payload_exposes_catalog_failure_with_usable_models(
|
||||
monkeypatch, source, error_kind,
|
||||
):
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_models.get_oauth_model_catalog",
|
||||
lambda *_args, **_kwargs: OAuthModelCatalogSnapshot(
|
||||
models=(ProviderModelSpec(id="openai-codex/offline-model"),),
|
||||
source=source, fetched_at=123, error_kind=error_kind,
|
||||
),
|
||||
)
|
||||
payload = provider_models_payload({"provider": ["openai_codex"]})
|
||||
assert payload["status"] == "available"
|
||||
assert payload["source"] == source
|
||||
assert payload["error_kind"] == error_kind
|
||||
assert payload["models"][0]["id"] == "openai-codex/offline-model"
|
||||
|
||||
|
||||
def test_copilot_explicit_login_does_not_reuse_revoked_credentials(monkeypatch, oauth_flows):
|
||||
from unittest.mock import Mock
|
||||
|
||||
login = Mock(return_value=SimpleNamespace(access="new-token"))
|
||||
invalidate = Mock()
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.github_copilot_provider.get_github_copilot_login_status",
|
||||
lambda: SimpleNamespace(access="revoked-token"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_provider.login_github_copilot", login)
|
||||
monkeypatch.setattr("nanobot.webui.settings_models.invalidate_oauth_model_catalog", invalidate)
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
|
||||
assert login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows) == {"ready": True}
|
||||
login.assert_called_once()
|
||||
invalidate.assert_called_once_with("github_copilot")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("provider", ["openai_codex", "xai_grok"])
|
||||
def test_oauth_completion_clears_same_account_catalog_failure(monkeypatch, oauth_flows, provider):
|
||||
from nanobot.providers.oauth_model_catalog import OAuthModelCatalog
|
||||
|
||||
signed_in = [False]
|
||||
|
||||
def fetch(_proxy):
|
||||
if not signed_in[0]:
|
||||
request = httpx.Request("GET", "https://example.com/models")
|
||||
raise httpx.HTTPStatusError("revoked", request=request, response=httpx.Response(401))
|
||||
return (ProviderModelSpec(id="provider/new-model"),)
|
||||
|
||||
catalog = OAuthModelCatalog(fallback_models=(), fetch=fetch)
|
||||
module = f"nanobot.providers.{provider}_provider"
|
||||
monkeypatch.setattr(f"{module}._{provider.upper()}_MODEL_CATALOG", catalog)
|
||||
monkeypatch.setattr(
|
||||
"nanobot.webui.settings_models.get_oauth_model_catalog",
|
||||
lambda *_args, **_kwargs: catalog.get(cache_key="same-account"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
|
||||
|
||||
class Flow:
|
||||
expired = False
|
||||
|
||||
def cancel(self):
|
||||
pass
|
||||
|
||||
def complete(*_args):
|
||||
signed_in[0] = True
|
||||
return SimpleNamespace(access="fixture")
|
||||
|
||||
owner = "openai_codex_oauth" if provider == "openai_codex" else "xai_oauth"
|
||||
completion = "complete_openai_codex_oauth_login" if provider == "openai_codex" else "complete_xai_oauth_login"
|
||||
monkeypatch.setattr(f"nanobot.providers.{owner}.{completion}", complete)
|
||||
oauth_flows.register(provider, "flow-test", Flow())
|
||||
before = provider_models_payload({"provider": [provider]})
|
||||
assert before["error_kind"] == "auth_required"
|
||||
assert complete_oauth_provider(
|
||||
{"provider": [provider], "flow_id": ["flow-test"]},
|
||||
"synthetic-callback", oauth_flows=oauth_flows,
|
||||
) == {"ready": True}
|
||||
after = provider_models_payload({"provider": [provider]})
|
||||
assert after["source"] == "remote"
|
||||
assert after["error_kind"] is None
|
||||
assert after["models"][0]["id"] == "provider/new-model"
|
||||
|
||||
|
||||
def test_provider_models_payload_returns_online_github_copilot_models(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
|
||||
@@ -483,6 +483,8 @@ export function ModelsSettings({
|
||||
provider={form.provider}
|
||||
value={form.model}
|
||||
showProviderLogos={showBrandLogos}
|
||||
onProviderOAuthLogin={onProviderOAuthLogin}
|
||||
providerSigningIn={selectedProviderSigningIn}
|
||||
onChange={(model) => {
|
||||
const canSuggestName =
|
||||
creating &&
|
||||
|
||||
@@ -501,14 +501,12 @@ export function useModelSettingsActions({
|
||||
setProviderOAuthFlow(payload);
|
||||
setProviderOAuthResponse("");
|
||||
setProviderOAuthDialogError(null);
|
||||
setExpandedProvider(providerName);
|
||||
setError(null);
|
||||
return;
|
||||
}
|
||||
popup?.close();
|
||||
closeProviderOAuthFlow();
|
||||
applyPayload(payload);
|
||||
setExpandedProvider(providerName);
|
||||
applyPayload(payload, { preserveAgentForm: action === "login" });
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
popup?.close();
|
||||
@@ -533,8 +531,7 @@ export function useModelSettingsActions({
|
||||
);
|
||||
if (providerOAuthFlowRef.current?.flow_id !== flow.flow_id) return;
|
||||
if (isProviderOAuthPending(payload)) return;
|
||||
applyPayload(payload);
|
||||
setExpandedProvider(flow.provider);
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
setError(null);
|
||||
closeProviderOAuthFlow();
|
||||
} catch (err) {
|
||||
|
||||
@@ -35,7 +35,6 @@ export function useProviderOAuthPolling({
|
||||
const {
|
||||
providerOAuthFlow,
|
||||
providerOAuthFlowRef,
|
||||
setExpandedProvider,
|
||||
} = state;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -57,8 +56,7 @@ export function useProviderOAuthPolling({
|
||||
timer = window.setTimeout(() => void poll(), 1000);
|
||||
return;
|
||||
}
|
||||
applyPayload(payload);
|
||||
setExpandedProvider(providerOAuthFlow.provider);
|
||||
applyPayload(payload, { preserveAgentForm: true });
|
||||
setError(null);
|
||||
closeProviderOAuthFlow();
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import { useEffect, useId, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import {
|
||||
Bot,
|
||||
Brain,
|
||||
@@ -160,6 +160,8 @@ export function ModelIdPicker({
|
||||
emptyLabel,
|
||||
searchPlaceholder,
|
||||
emptyMessage,
|
||||
onProviderOAuthLogin,
|
||||
providerSigningIn = false,
|
||||
onChange,
|
||||
}: {
|
||||
token: string;
|
||||
@@ -171,6 +173,8 @@ export function ModelIdPicker({
|
||||
emptyLabel?: string;
|
||||
searchPlaceholder?: string;
|
||||
emptyMessage?: string;
|
||||
onProviderOAuthLogin?: (provider: string) => void;
|
||||
providerSigningIn?: boolean;
|
||||
onChange: (model: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -182,6 +186,7 @@ export function ModelIdPicker({
|
||||
const [payload, setPayload] = useState<ProviderModelsPayload | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const catalogNoticeId = useId();
|
||||
const effectiveProvider =
|
||||
provider === "auto" ? settings.agent.resolved_provider ?? provider : provider;
|
||||
const hasConcreteProvider = Boolean(effectiveProvider && effectiveProvider !== "auto");
|
||||
@@ -239,6 +244,9 @@ export function ModelIdPicker({
|
||||
);
|
||||
const providerModelCount = payload?.model_count ?? providerModels.length;
|
||||
const modelUnconfigured = !value.trim() || !providerConfigured;
|
||||
const showCatalogNotice = !loading && payload?.status === "available"
|
||||
&& (payload.source === "stale" || payload.source === "fallback");
|
||||
const catalogNeedsSignIn = payload?.error_kind === "auth_required";
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -269,7 +277,8 @@ export function ModelIdPicker({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [effectiveProvider, open, shouldFetchModels]);
|
||||
// Successful OAuth completion replaces the settings row even for the same account.
|
||||
}, [effectiveProvider, open, shouldFetchModels, providerRow]);
|
||||
|
||||
const selectModel = (model: string) => {
|
||||
onChange(model);
|
||||
@@ -377,11 +386,46 @@ export function ModelIdPicker({
|
||||
aria-label={
|
||||
searchPlaceholder || tx("settings.models.searchModels", "Search or type model ID")
|
||||
}
|
||||
aria-describedby={showCatalogNotice ? catalogNoticeId : undefined}
|
||||
className="h-8 rounded-full pl-8 pr-3 text-[12px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showCatalogNotice ? (
|
||||
<div className="mx-1 mb-1.5 rounded-control bg-muted/60 px-2.5 py-2 text-[11px] leading-4">
|
||||
<div id={catalogNoticeId} role="status">
|
||||
<p className="font-medium text-foreground">
|
||||
{catalogNeedsSignIn
|
||||
? tx("settings.models.catalogAuthRequired", "Authorization expired. Please sign in again.")
|
||||
: tx("settings.models.catalogUnavailable", "Could not refresh models. Try again later.")}
|
||||
</p>
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
{payload.source === "stale"
|
||||
? tx("settings.models.catalogStale", "Showing cached models; the list may be out of date.")
|
||||
: tx("settings.models.catalogFallback", "Showing built-in models; the list may be out of date.")}
|
||||
</p>
|
||||
</div>
|
||||
{catalogNeedsSignIn && onProviderOAuthLogin && providerRow?.oauth_login_supported ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="mt-2 h-7 rounded-full px-2.5 text-[11px]"
|
||||
disabled={providerSigningIn}
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
onProviderOAuthLogin(effectiveProvider);
|
||||
}}
|
||||
>
|
||||
{providerSigningIn
|
||||
? tx("settings.oauth.signingIn", "Signing in...")
|
||||
: tx("settings.oauth.signInAgain", "Sign in again")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{providerRequiresConfiguration ? (
|
||||
<div className="px-2 py-1.5 text-[11px] leading-4 text-muted-foreground">
|
||||
{tx("settings.models.providerNotConfigured", "Configure this provider before loading models.")}
|
||||
|
||||
@@ -401,6 +401,10 @@
|
||||
"voiceInput": "Voice input"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "Authorization expired. Please sign in again.",
|
||||
"catalogUnavailable": "Could not refresh models. Try again later.",
|
||||
"catalogStale": "Showing cached models; the list may be out of date.",
|
||||
"catalogFallback": "Showing built-in models; the list may be out of date.",
|
||||
"selectModel": "Select model",
|
||||
"addConfiguration": "Add configuration",
|
||||
"newConfiguration": "New model configuration",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "Instalando dependencias…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "La autorización ha caducado. Inicia sesión de nuevo.",
|
||||
"catalogUnavailable": "No se pudieron actualizar los modelos. Inténtalo más tarde.",
|
||||
"catalogStale": "Se muestran modelos en caché; la lista puede estar desactualizada.",
|
||||
"catalogFallback": "Se muestran modelos integrados; la lista puede estar desactualizada.",
|
||||
"selectModel": "Seleccionar modelo",
|
||||
"addConfiguration": "Agregar configuración",
|
||||
"newConfiguration": "Nueva configuración de modelo",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "Installation des dépendances…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "L’autorisation a expiré. Veuillez vous reconnecter.",
|
||||
"catalogUnavailable": "Impossible d’actualiser les modèles. Réessayez plus tard.",
|
||||
"catalogStale": "Modèles en cache affichés ; la liste peut ne pas être à jour.",
|
||||
"catalogFallback": "Modèles intégrés affichés ; la liste peut ne pas être à jour.",
|
||||
"selectModel": "Choisir un modèle",
|
||||
"addConfiguration": "Ajouter une configuration",
|
||||
"newConfiguration": "Nouvelle configuration de modèle",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "Memasang paket yang diperlukan…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "Otorisasi kedaluwarsa. Silakan masuk lagi.",
|
||||
"catalogUnavailable": "Model tidak dapat diperbarui. Coba lagi nanti.",
|
||||
"catalogStale": "Menampilkan model dari cache; daftar mungkin belum terbaru.",
|
||||
"catalogFallback": "Menampilkan model bawaan; daftar mungkin belum terbaru.",
|
||||
"selectModel": "Pilih model",
|
||||
"addConfiguration": "Tambah konfigurasi",
|
||||
"newConfiguration": "Konfigurasi model baru",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "必要なパッケージをインストール中…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "認証が失効しました。再度ログインしてください。",
|
||||
"catalogUnavailable": "モデルを更新できません。しばらくしてから再試行してください。",
|
||||
"catalogStale": "キャッシュ済みのモデルを表示しています。最新ではない可能性があります。",
|
||||
"catalogFallback": "組み込みのモデルを表示しています。最新ではない可能性があります。",
|
||||
"selectModel": "モデルを選択",
|
||||
"addConfiguration": "設定を追加",
|
||||
"newConfiguration": "新しいモデル設定",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "필수 패키지 설치 중…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "인증이 만료되었습니다. 다시 로그인해 주세요.",
|
||||
"catalogUnavailable": "모델 목록을 갱신할 수 없습니다. 나중에 다시 시도해 주세요.",
|
||||
"catalogStale": "캐시된 모델을 표시합니다. 최신 목록이 아닐 수 있습니다.",
|
||||
"catalogFallback": "기본 제공 모델을 표시합니다. 최신 목록이 아닐 수 있습니다.",
|
||||
"selectModel": "모델 선택",
|
||||
"addConfiguration": "설정 추가",
|
||||
"newConfiguration": "새 모델 설정",
|
||||
|
||||
@@ -215,6 +215,10 @@
|
||||
"voiceInput": "Entrada de voz"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "A autorização expirou. Entre novamente.",
|
||||
"catalogUnavailable": "Não foi possível atualizar os modelos. Tente mais tarde.",
|
||||
"catalogStale": "Exibindo modelos em cache; a lista pode estar desatualizada.",
|
||||
"catalogFallback": "Exibindo modelos integrados; a lista pode estar desatualizada.",
|
||||
"selectModel": "Selecionar modelo",
|
||||
"addConfiguration": "Adicionar configuração",
|
||||
"newConfiguration": "Nova configuração de modelo",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "Đang cài các gói cần thiết…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "Quyền truy cập đã hết hạn. Vui lòng đăng nhập lại.",
|
||||
"catalogUnavailable": "Không thể cập nhật mô hình. Vui lòng thử lại sau.",
|
||||
"catalogStale": "Đang hiển thị mô hình đã lưu đệm; danh sách có thể chưa được cập nhật.",
|
||||
"catalogFallback": "Đang hiển thị mô hình tích hợp sẵn; danh sách có thể chưa được cập nhật.",
|
||||
"selectModel": "Chọn mô hình",
|
||||
"addConfiguration": "Thêm cấu hình",
|
||||
"newConfiguration": "Cấu hình mô hình mới",
|
||||
|
||||
@@ -401,6 +401,10 @@
|
||||
"voiceInput": "语音识别"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "授权已失效,请重新登录。",
|
||||
"catalogUnavailable": "暂时无法刷新模型,请稍后重试。",
|
||||
"catalogStale": "当前显示缓存的模型列表,可能不是最新。",
|
||||
"catalogFallback": "当前显示内置模型列表,可能不是最新。",
|
||||
"selectModel": "选择模型",
|
||||
"addConfiguration": "添加配置",
|
||||
"newConfiguration": "新建模型配置",
|
||||
|
||||
@@ -515,6 +515,10 @@
|
||||
"installing": "正在安裝所需套件…"
|
||||
},
|
||||
"models": {
|
||||
"catalogAuthRequired": "授權已失效,請重新登入。",
|
||||
"catalogUnavailable": "暫時無法更新模型,請稍後重試。",
|
||||
"catalogStale": "目前顯示快取的模型清單,可能不是最新。",
|
||||
"catalogFallback": "目前顯示內建模型清單,可能不是最新。",
|
||||
"selectModel": "選擇模型",
|
||||
"addConfiguration": "新增設定",
|
||||
"newConfiguration": "新增模型設定",
|
||||
|
||||
@@ -564,6 +564,7 @@ export interface ProviderModelsPayload {
|
||||
| "custom"
|
||||
| "unsupported";
|
||||
source?: "remote" | "cache" | "stale" | "fallback";
|
||||
error_kind?: "auth_required" | "unavailable" | null;
|
||||
models: ProviderModelInfo[];
|
||||
model_count: number;
|
||||
message?: string | null;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ModelIdPicker } from "@/components/settings/shared/ModelControls";
|
||||
import type { ProviderModelsPayload } from "@/lib/types";
|
||||
import { installSettingsViewTestHooks, jsonResponse, openPopover, settingsPayload } from "@/tests/settings-test-utils";
|
||||
import en from "@/i18n/locales/en/common.json";
|
||||
import zhCN from "@/i18n/locales/zh-CN/common.json";
|
||||
|
||||
function settings() {
|
||||
return {
|
||||
...settingsPayload(),
|
||||
providers: [{
|
||||
name: "openai_codex", label: "OpenAI Codex", configured: true,
|
||||
auth_type: "oauth" as const, model_catalog: "hybrid" as const,
|
||||
oauth_login_supported: true,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
function catalog(
|
||||
source: ProviderModelsPayload["source"],
|
||||
error_kind: ProviderModelsPayload["error_kind"],
|
||||
): ProviderModelsPayload {
|
||||
return {
|
||||
provider: "openai_codex", label: "OpenAI Codex", status: "available",
|
||||
catalog_kind: "hybrid", source, error_kind,
|
||||
models: [{ id: "openai-codex/offline-model", label: "Offline model" }],
|
||||
model_count: 1,
|
||||
// Never use raw provider text as a translated, user-facing catalog notice.
|
||||
message: "private upstream response fixture",
|
||||
};
|
||||
}
|
||||
|
||||
describe("OAuth catalog feedback", () => {
|
||||
installSettingsViewTestHooks();
|
||||
|
||||
it.each(["stale", "fallback"] as const)("explains %s auth failures without hiding models or manual IDs", async (source) => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(catalog(source, "auth_required"))));
|
||||
const onChange = vi.fn();
|
||||
const login = vi.fn();
|
||||
render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex"
|
||||
value="" showProviderLogos onChange={onChange} onProviderOAuthLogin={login} />);
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
const notice = await screen.findByRole("status");
|
||||
expect(notice).toHaveTextContent("Authorization expired. Please sign in again.");
|
||||
expect(notice).toHaveTextContent(source === "stale" ? "cached models" : "built-in models");
|
||||
expect(notice).toHaveTextContent("out of date");
|
||||
expect(screen.queryByText(/private upstream/)).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: /Offline model/ })).toBeVisible();
|
||||
const search = screen.getByRole("combobox");
|
||||
expect(search).toHaveAttribute("aria-describedby", notice.id);
|
||||
fireEvent.change(search, { target: { value: "openai-codex/custom-model" } });
|
||||
fireEvent.click(screen.getByRole("option", { name: /Use.*custom-model/ }));
|
||||
expect(onChange).toHaveBeenCalledWith("openai-codex/custom-model");
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Sign in again" }));
|
||||
expect(login).toHaveBeenCalledWith("openai_codex");
|
||||
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each(["unavailable", undefined] as const)("does not request login for temporary or legacy failures (%s)", async (kind) => {
|
||||
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(catalog("fallback", kind))));
|
||||
render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex"
|
||||
value="" showProviderLogos onChange={vi.fn()} onProviderOAuthLogin={vi.fn()} />);
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
expect(await screen.findByRole("status")).toHaveTextContent("Could not refresh models. Try again later.");
|
||||
expect(screen.queryByRole("button", { name: "Sign in again" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: /Offline model/ })).toBeVisible();
|
||||
});
|
||||
|
||||
it("reloads an open picker on successful same-account login and clears stale feedback", async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(jsonResponse(catalog("stale", "auth_required")))
|
||||
.mockResolvedValueOnce(jsonResponse({
|
||||
...catalog("remote", null), message: null,
|
||||
models: [{ id: "openai-codex/new-model", label: "New model" }],
|
||||
}));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const props = { token: "tok", provider: "openai_codex", value: "", showProviderLogos: true, onChange: vi.fn() };
|
||||
const view = render(<ModelIdPicker {...props} settings={settings()} />);
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
expect(await screen.findByRole("status")).toHaveTextContent("Authorization expired");
|
||||
// Login produces a new settings snapshot, even when the account is unchanged.
|
||||
view.rerender(<ModelIdPicker {...props} settings={settings()} />);
|
||||
expect(await screen.findByRole("option", { name: /New model/ })).toBeVisible();
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("ignores an old auth failure arriving after refreshed settings", async () => {
|
||||
let finishOld!: (response: Response) => void;
|
||||
const fetchMock = vi.fn()
|
||||
.mockImplementationOnce(() => new Promise<Response>((resolve) => { finishOld = resolve; }))
|
||||
.mockResolvedValueOnce(jsonResponse(catalog("remote", null)));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const props = { token: "tok", provider: "openai_codex", value: "", showProviderLogos: true, onChange: vi.fn() };
|
||||
const view = render(<ModelIdPicker {...props} settings={settings()} />);
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
||||
view.rerender(<ModelIdPicker {...props} settings={settings()} />);
|
||||
await screen.findByRole("option", { name: /Offline model/ });
|
||||
await act(async () => { finishOld(jsonResponse(catalog("fallback", "auth_required"))); });
|
||||
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([en, zhCN])("includes localized notices", (locale) => {
|
||||
for (const key of ["catalogAuthRequired", "catalogUnavailable", "catalogStale", "catalogFallback"] as const) {
|
||||
expect(locale.settings.models[key].length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -89,6 +89,61 @@ async function togglePresetEditor(name = "primary") {
|
||||
describe("Settings models", () => {
|
||||
installSettingsViewTestHooks();
|
||||
|
||||
it.each(["manual", "poll", "direct"])("reauthenticates from the catalog and preserves the preset draft (%s)", async (mode) => {
|
||||
const payload = settingsPayload();
|
||||
payload.providers = [{
|
||||
name: "openai_codex", label: "OpenAI Codex", configured: true,
|
||||
auth_type: "oauth", model_catalog: "hybrid", oauth_login_supported: true,
|
||||
}];
|
||||
let recovered = false;
|
||||
const signedIn = () => {
|
||||
recovered = true;
|
||||
return { ...payload, providers: payload.providers.map((row) => ({ ...row })) };
|
||||
};
|
||||
requestMutationMock.mockImplementation(async (action, args) => {
|
||||
if (action === "settings.provider.oauth_login") {
|
||||
return mode === "direct" ? signedIn() : {
|
||||
status: "authorization_required", provider: "openai_codex", flow_id: "flow-test",
|
||||
authorization_url: "https://example.com/authorize", expires_in: 600,
|
||||
completion_input: "callback_url",
|
||||
};
|
||||
}
|
||||
if (action === "settings.provider.oauth_complete") {
|
||||
return mode === "manual" && !args.authorization_response
|
||||
? { status: "pending", provider: "openai_codex", flow_id: "flow-test" }
|
||||
: signedIn();
|
||||
}
|
||||
throw new Error(`Unexpected mutation: ${action}`);
|
||||
});
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).includes("/provider-models?")) return jsonResponse({
|
||||
provider: "openai_codex", label: "OpenAI Codex", status: "available", catalog_kind: "hybrid",
|
||||
source: recovered ? "remote" : "fallback", error_kind: recovered ? null : "auth_required",
|
||||
models: [{ id: recovered ? "openai-codex/new-model" : "openai-codex/offline-model" }], model_count: 1,
|
||||
});
|
||||
return jsonResponse(payload);
|
||||
}));
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
fireEvent.click(await screen.findByRole("button", { name: "New model preset" }));
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Preset name" }), {
|
||||
target: { value: "My unsaved preset" },
|
||||
});
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Sign in again" }));
|
||||
if (mode === "manual") {
|
||||
fireEvent.change(await screen.findByRole("textbox", { name: "Full callback URL" }), {
|
||||
target: { value: "http://localhost:1455/auth/callback?code=fixture&state=test" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Finish sign-in" }));
|
||||
}
|
||||
await waitFor(() => expect(recovered).toBe(true), { timeout: 3000 });
|
||||
expect(screen.getByRole("textbox", { name: "Preset name" })).toHaveValue("My unsaved preset");
|
||||
await openPopover(screen.getByRole("button", { name: "Select model" }));
|
||||
expect(await screen.findByRole("option", { name: /openai-codex\/new-model/ })).toBeVisible();
|
||||
expect(screen.queryByText("Authorization expired. Please sign in again.")).not.toBeInTheDocument();
|
||||
expect(requestMutationMock.mock.calls.every(([action]) => action.startsWith("settings.provider.oauth_"))).toBe(true);
|
||||
});
|
||||
|
||||
it("uses the preset name as the canonical identity", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_presets[0] = {
|
||||
|
||||
Reference in new issue
Block a user