fix(webui): identify OAuth reauthentication behind fallback replies

This commit is contained in:
Xubin Ren committed 2026-09-21 00:13:46 +08:00
1 parent a05f11ba10
commit 448767d147
28 files changed
+269 -40

No files matched your search

+5 -2
View File
@@ -13,8 +13,11 @@ 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.
When a live chat uses a fallback model, a dismissible notice above the composer
names that model and links to model settings. It does not change your selected
preset or assume that every fallback means the login expired.
names that model and links to model settings. If the provider explicitly rejected
OAuth credentials, the notice instead names the provider that needs a new login,
with fallback completion as secondary information. Network errors, ordinary
permission denials, and rate limits do not request reauthentication. The notice
does not change your selected preset.
For every setup, answer three questions:
+1
View File
@@ -109,6 +109,7 @@ class TurnModelUpdatedEvent(AgentEvent):
model_preset: str | None = None
context_window_tokens: int | None = None
fallback: bool = False
reauth_provider: str | None = None
def outbound_message_for_event(
+3
View File
@@ -1531,6 +1531,7 @@ class WebSocketChannel(BaseChannel):
model_preset: Any = None,
context_window_tokens: Any = None,
fallback: bool = False,
reauth_provider: str | None = None,
) -> None:
"""Notify one chat's subscribers which model is handling its current request."""
conns = list(self._subs.get(chat_id, ()))
@@ -1551,6 +1552,8 @@ class WebSocketChannel(BaseChannel):
body["context_window_tokens"] = context_window_tokens
if fallback:
body["fallback"] = True
if reauth_provider:
body["reauth_provider"] = reauth_provider
raw = json.dumps(body, ensure_ascii=False)
for connection in conns:
await self._safe_send_to(connection, raw, label=" turn_model_updated ")
@@ -2309,11 +2309,13 @@ async def test_send_scopes_turn_model_updates_to_the_subscribed_chat() -> None:
model="deepseek/deepseek-chat",
model_preset="Deep Research",
fallback=True,
reauth_provider="openai_codex",
),
)
)
fallback_payload = json.loads(chat_one.send.call_args.args[0])
assert fallback_payload["fallback"] is True
assert fallback_payload["reauth_provider"] == "openai_codex"
chat_two.send.assert_not_awaited()
+29 -5
View File
@@ -7,7 +7,7 @@ from __future__ import annotations
import asyncio
import time
from collections.abc import Awaitable, Callable
from dataclasses import replace
from dataclasses import dataclass, replace
from typing import Any
from loguru import logger
@@ -23,6 +23,8 @@ from nanobot.providers.base import (
RetryEventCallback,
RetryStatusCallback,
)
from nanobot.providers.oauth_model_catalog import oauth_catalog_auth_rejected
from nanobot.providers.registry import find_by_name
# Circuit breaker tuned to match OpenAICompatProvider's Responses API breaker.
_PRIMARY_FAILURE_THRESHOLD = 3
@@ -35,6 +37,7 @@ _FALLBACK_ERROR_KINDS = frozenset({
"overloaded",
})
_AUTHENTICATION_ERROR_KINDS = frozenset({
"oauth_auth_required",
"authentication",
"auth",
"permission",
@@ -96,7 +99,15 @@ _FALLBACK_ERROR_TOKENS = (
)
FallbackModelObserver = Callable[[str], Awaitable[None]]
@dataclass(frozen=True)
class FallbackModelSelection:
"""Display-safe fallback result; no upstream error text or credentials."""
model: str
reauth_provider: str | None = None
FallbackModelObserver = Callable[[FallbackModelSelection], Awaitable[None]]
class FallbackProvider(LLMProvider):
@@ -611,7 +622,7 @@ class FallbackProvider(LLMProvider):
# attempted. A fallback can fail just like the primary, and
# the WebUI would otherwise show a misleading success signal.
# Publish only after this response is known to be usable.
await self._notify_fallback_model(fallback_model)
await self._notify_fallback_model(fallback_model, primary_response)
logger.info(
"Fallback '{}' succeeded after primary '{}' failed",
fallback_model, primary_model,
@@ -673,11 +684,22 @@ class FallbackProvider(LLMProvider):
response.error_kind = "authentication"
return response, exc
async def _notify_fallback_model(self, model: str) -> None:
async def _notify_fallback_model(self, model: str, primary_response: LLMResponse | None) -> None:
if self._fallback_model_observer is None:
return
reauth_provider = None
spec = find_by_name(self._primary.provider_name)
if spec is not None and spec.is_oauth and primary_response is not None:
# Plain 403, rate limits, transport errors, and message substrings are
# not evidence of revoked credentials. A skipped circuit has no new
# auth result either; never retain credential state on this wrapper.
if primary_response.error_kind == "oauth_auth_required" or oauth_catalog_auth_rejected(
primary_response.error_status_code or 0,
{"error": {"code": primary_response.error_code}},
):
reauth_provider = spec.name
try:
await self._fallback_model_observer(model)
await self._fallback_model_observer(FallbackModelSelection(model, reauth_provider))
except Exception:
logger.exception("fallback model observer failed for '{}'", model)
@@ -692,6 +714,8 @@ class FallbackProvider(LLMProvider):
text = (response.content or "").lower()
structured_values = (kind, error_type, code)
if oauth_catalog_auth_rejected(status or 0, {"error": {"code": code}}):
return True
if kind in _AUTHENTICATION_ERROR_KINDS:
return True
if any(
+27 -15
View File
@@ -554,6 +554,13 @@ def _friendly_error(status_code: int, raw: str) -> str:
def _codex_error_response(exc: Exception) -> LLMResponse:
"""Convert Codex transport/API failures into actionable, retryable metadata."""
if isinstance(exc, RuntimeError) and _codex_login_required(exc):
return LLMResponse(
content="OpenAI Codex authorization expired. Please sign in again.",
finish_reason="error",
error_kind="oauth_auth_required",
error_should_retry=False,
)
exc_type = "CodexHTTPError" if isinstance(exc, _CodexHTTPError) else type(exc).__name__
detail = str(exc).strip()
@@ -656,26 +663,31 @@ def invalidate_openai_codex_model_catalog() -> None:
_OPENAI_CODEX_MODEL_CATALOG.invalidate()
def _codex_login_required(exc: RuntimeError) -> bool:
# 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.":
return True
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
return status.isdecimal() and oauth_catalog_auth_rejected(int(status), payload)
return False
def _fetch_openai_codex_models(proxy: str | None) -> tuple[ProviderModelSpec, ...]:
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.":
if _codex_login_required(exc):
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:
+8 -2
View File
@@ -35,6 +35,7 @@ from nanobot.providers.openai_responses import (
from nanobot.providers.registry import ProviderModelSpec, find_by_name
from nanobot.providers.xai_oauth import (
XAI_CLIENT_VERSION,
XAIOAuthReauthRequiredError,
get_xai_oauth_login_status,
get_xai_oauth_storage_path,
get_xai_oauth_token,
@@ -597,6 +598,13 @@ def _friendly_error(status_code: int, response_body: str | None = None) -> str:
def _xai_error_response(exc: Exception) -> LLMResponse:
if isinstance(exc, XAIOAuthReauthRequiredError):
return LLMResponse(
content="xAI authorization expired. Please sign in again.",
finish_reason="error",
error_kind="oauth_auth_required",
error_should_retry=False,
)
status_code = getattr(exc, "status_code", None)
should_retry = getattr(exc, "should_retry", None)
error_kind: str | None = None
@@ -665,8 +673,6 @@ def invalidate_xai_grok_model_catalog() -> None:
def _fetch_xai_grok_models(proxy: str | None) -> tuple[ProviderModelSpec, ...]:
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError
try:
token = get_xai_oauth_token(proxy=proxy)
except XAIOAuthReauthRequiredError:
+4 -3
View File
@@ -38,7 +38,7 @@ from nanobot.bus.runtime_events import (
)
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import LLMProvider, LLMUsage
from nanobot.providers.fallback_provider import FallbackModelObserver
from nanobot.providers.fallback_provider import FallbackModelObserver, FallbackModelSelection
from nanobot.runtime_context import public_history_message
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.history_visibility import is_hidden_history_message
@@ -523,7 +523,7 @@ class WebuiTurnRoutePolicy:
def build_webui_fallback_model_observer(bus: MessageBus) -> FallbackModelObserver:
"""Translate provider fallback choices into chat-scoped WebUI events."""
async def _publish(model: str) -> None:
async def _publish(selection: FallbackModelSelection) -> None:
context = current_request_context()
if context is None or context.channel != "websocket":
return
@@ -535,13 +535,14 @@ def build_webui_fallback_model_observer(bus: MessageBus) -> FallbackModelObserve
channel=context.channel,
chat_id=chat_id,
event=TurnModelUpdatedEvent(
model=model,
model=selection.model,
model_preset=(
context.runtime.model_preset
if context.runtime is not None
else None
),
fallback=True,
reauth_provider=selection.reauth_provider,
),
metadata=context.metadata,
)
+2
View File
@@ -59,6 +59,7 @@ class WebUIOutboundTransport(Protocol):
model_preset: str | None = None,
context_window_tokens: int | None = None,
fallback: bool = False,
reauth_provider: str | None = None,
) -> None: ...
async def send_user_input(
@@ -173,6 +174,7 @@ class WebUIOutboundProjector:
model_preset=event.model_preset,
context_window_tokens=event.context_window_tokens,
fallback=event.fallback,
reauth_provider=event.reauth_provider,
)
return
if isinstance(event, UserInputEvent):
+64 -3
View File
@@ -19,7 +19,7 @@ from nanobot.providers.base import (
ProviderConversationState,
)
from nanobot.providers.conversation_state import ProviderConversationStateController
from nanobot.providers.fallback_provider import FallbackProvider
from nanobot.providers.fallback_provider import FallbackModelSelection, FallbackProvider
from nanobot.providers.openai_responses import resolve_compact_threshold
@@ -897,8 +897,9 @@ class TestFallbackOnPrimaryError:
successful_fallback = _FakeProvider("fallback", _make_response("fallback ok"))
fallback_models: list[str] = []
async def _observe(model: str) -> None:
fallback_models.append(model)
async def _observe(selection: FallbackModelSelection) -> None:
fallback_models.append(selection.model)
assert selection.reauth_provider is None
fb = FallbackProvider(
primary=primary,
@@ -918,6 +919,66 @@ class TestFallbackOnPrimaryError:
assert result.content == "fallback ok"
assert fallback_models == ["fallback-b"]
@pytest.mark.asyncio
@pytest.mark.parametrize(("provider_name", "status", "code", "kind", "expected"), [
("openai_codex", 401, "token_revoked", "http", "openai_codex"),
("xai_grok", 401, None, "http", "xai_grok"),
("github_copilot", 401, None, "http", "github_copilot"),
("openai_codex", 400, "invalid_grant", "http", "openai_codex"),
("openai_codex", 403, "token_revoked", "http", "openai_codex"),
("openai_codex", None, None, "oauth_auth_required", "openai_codex"),
("openai_codex", 403, "insufficient_scope", "permission", None),
("openai_codex", 429, None, "rate_limit", None),
("openai_codex", 503, None, "server_error", None),
("openai_codex", None, None, "timeout", None),
("openai_codex", None, None, "authentication", None),
("openai", 401, "invalid_api_key", "authentication", None),
])
async def test_reports_only_confirmed_oauth_rejections(
self, provider_name, status, code, kind, expected,
) -> None:
observer = AsyncMock()
primary = _FakeProvider(provider_name, _make_response(
"synthetic-secret invalid_token", "error", error_status_code=status,
error_code=code, error_kind=kind,
))
provider = FallbackProvider(
primary=primary, fallback_presets=[_fallback("backup")],
provider_factory=MagicMock(return_value=_FakeProvider("backup")),
fallback_model_observer=observer,
)
await provider.chat(messages=[{"role": "user", "content": "hi"}])
observer.assert_awaited_once_with(FallbackModelSelection("backup", expected))
assert "synthetic-secret" not in repr(observer.await_args)
@pytest.mark.asyncio
async def test_does_not_reuse_auth_diagnosis_when_circuit_skips_primary(self) -> None:
observer = AsyncMock()
provider = FallbackProvider(
primary=_FakeProvider("openai_codex", _make_response("revoked", "error", error_status_code=401)),
fallback_presets=[_fallback("backup")],
provider_factory=MagicMock(return_value=_FakeProvider("backup")),
fallback_model_observer=observer,
)
for _ in range(4):
await provider.chat(messages=[{"role": "user", "content": "hi"}])
assert [call.args[0].reauth_provider for call in observer.await_args_list] == [
"openai_codex", "openai_codex", "openai_codex", None,
]
@pytest.mark.asyncio
async def test_no_reauth_notice_when_all_fallbacks_fail(self) -> None:
observer = AsyncMock()
provider = FallbackProvider(
primary=_FakeProvider("openai_codex", _make_response("revoked", "error", error_status_code=401)),
fallback_presets=[_fallback("backup")],
provider_factory=MagicMock(return_value=_FakeProvider("backup", _error_response())),
fallback_model_observer=observer,
)
result = await provider.chat(messages=[{"role": "user", "content": "hi"}])
assert result.finish_reason == "error"
observer.assert_not_awaited()
@pytest.mark.asyncio
async def test_logs_primary_error_before_fallback(self) -> None:
primary = _FakeProvider("primary", _error_response("primary overloaded"))
@@ -231,6 +231,29 @@ def test_openai_codex_catalog_uses_account_catalog_and_filters_hidden_models(
assert request.headers["chatgpt-account-id"] == "account-42"
@pytest.mark.parametrize("detail", [
'Token refresh failed: 400 {"error":"invalid_grant","access_token":"synthetic-secret"}',
"OAuth credentials not found. Please run the login command.",
])
def test_codex_inference_classifies_sdk_reauth_without_exposing_response(detail: str) -> None:
from nanobot.providers.openai_codex_provider import _codex_error_response
response = _codex_error_response(RuntimeError(detail))
assert response.error_kind == "oauth_auth_required"
assert response.error_should_retry is False
assert "synthetic-secret" not in str(response)
def test_xai_inference_classifies_typed_reauth() -> None:
from nanobot.providers.xai_grok_provider import _xai_error_response
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError
response = _xai_error_response(XAIOAuthReauthRequiredError("synthetic-secret"))
assert response.error_kind == "oauth_auth_required"
assert response.error_should_retry is False
assert "synthetic-secret" not in str(response)
def test_github_copilot_catalog_only_lists_compatible_chat_models(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
+4 -2
View File
@@ -21,6 +21,7 @@ from nanobot.bus.runtime_events import (
UserInputAccepted,
)
from nanobot.providers.base import GenerationSettings
from nanobot.providers.fallback_provider import FallbackModelSelection
from nanobot.session import webui_turns as wth
from nanobot.session.manager import SessionManager
from nanobot.session.session_handles import session_handle_for_name
@@ -177,7 +178,7 @@ async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:
metadata={"webui": True},
)
):
await observer("deepseek/deepseek-chat")
await observer(FallbackModelSelection("deepseek/deepseek-chat", "openai_codex"))
outbound = bus.publish_outbound.await_args.args[0]
assert outbound.channel == "websocket"
@@ -186,6 +187,7 @@ async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:
assert isinstance(outbound.event, TurnModelUpdatedEvent)
assert outbound.event.model == "deepseek/deepseek-chat"
assert outbound.event.model_preset == "Deep Research"
assert outbound.event.reauth_provider == "openai_codex"
@pytest.mark.asyncio
@@ -343,6 +345,6 @@ async def test_fallback_model_ignores_non_websocket_requests() -> None:
observer = wth.build_webui_fallback_model_observer(bus)
with request_context(RequestContext(channel="telegram", chat_id="chat-model")):
await observer("fallback")
await observer(FallbackModelSelection("fallback", "openai_codex"))
bus.publish_outbound.assert_not_awaited()
@@ -1,11 +1,12 @@
import { ArrowRightLeft, X } from "lucide-react";
import { ArrowRightLeft, KeyRound, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
/** A live fallback is informative, not a failed message or a changed preset. */
export function ModelFallbackNotice({ model, onDismiss, onOpenSettings }: {
export function ModelFallbackNotice({ model, reauthProviderLabel, onDismiss, onOpenSettings }: {
model: string;
reauthProviderLabel?: string;
onDismiss: () => void;
onOpenSettings?: () => void;
}) {
@@ -15,17 +16,29 @@ export function ModelFallbackNotice({ model, onDismiss, onOpenSettings }: {
role="status"
className="mx-auto mb-2 flex w-full max-w-[49.5rem] items-start gap-2 rounded-control border border-border/60 bg-muted/40 px-3 py-2 text-xs text-foreground/80 animate-in fade-in-0 slide-in-from-bottom-1 motion-reduce:animate-none"
>
<ArrowRightLeft className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" aria-hidden />
{reauthProviderLabel
? <KeyRound className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" aria-hidden />
: <ArrowRightLeft className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-400" aria-hidden />}
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-1 leading-5">
<span className="min-w-0 break-words [overflow-wrap:anywhere]">
{t("thread.composer.fallbackNotice", {
{reauthProviderLabel ? <>
<span className="font-medium text-foreground">{t("thread.composer.reauthNotice", {
provider: reauthProviderLabel,
defaultValue: "{{provider}} authorization expired. Please sign in again.",
})}</span>
<span className="ml-1.5 text-muted-foreground">{t("thread.composer.reauthFallback", {
defaultValue: "A fallback model handled this response.",
})}</span>
</> : t("thread.composer.fallbackNotice", {
model,
defaultValue: "This response used a fallback model: {{model}}.",
})}
</span>
{onOpenSettings ? (
<button type="button" onClick={onOpenSettings} className="shrink-0 rounded-sm font-medium text-foreground underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{t("thread.composer.checkModelSettings", { defaultValue: "Check model settings" })}
{reauthProviderLabel
? t("thread.composer.reauthSettings", { defaultValue: "Open sign-in settings" })
: t("thread.composer.checkModelSettings", { defaultValue: "Check model settings" })}
</button>
) : null}
</div>
+16 -3
View File
@@ -57,6 +57,7 @@ import type {
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
@@ -694,6 +695,7 @@ export function ThreadShell({
const [modelFallback, setModelFallback] = useState<{
chatId: string;
model: string;
reauthProvider?: string;
dismissed: boolean;
} | null>(null);
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
@@ -982,11 +984,19 @@ export function ThreadShell({
}
const model = event.model_name.trim();
if (!model) return;
const reauthProvider = typeof event.reauth_provider === "string"
? event.reauth_provider.trim() || undefined : undefined;
// A tool loop may report the same fallback repeatedly. Closing the notice
// lasts until the next turn/model change, without changing the actual preset.
setModelFallback((current) => current?.chatId === chatId && current.model === model
? current
: { chatId, model, dismissed: false });
setModelFallback((current) => {
if (current?.chatId === chatId && current.model === model) {
// An explicit auth rejection is actionable even after dismissing a
// generic fallback. A circuit-skipped call must not erase that reason.
return reauthProvider && reauthProvider !== current.reauthProvider
? { ...current, reauthProvider, dismissed: false } : current;
}
return { chatId, model, reauthProvider, dismissed: false };
});
});
}, [activeModelPreset, chatId, client]);
const handleModelPresetChange = useCallback((name: string) => {
@@ -1549,6 +1559,9 @@ export function ThreadShell({
{modelFallback?.chatId === chatId && !modelFallback.dismissed ? (
<ModelFallbackNotice
model={modelFallback.model}
reauthProviderLabel={modelFallback.reauthProvider
? providerDisplayLabel(settings?.providers ?? [], modelFallback.reauthProvider)
: undefined}
onOpenSettings={onOpenModelSettings}
onDismiss={() => setModelFallback((current) => current && { ...current, dismissed: true })}
/>
+3
View File
@@ -1585,6 +1585,9 @@
"manageModels": "Manage models",
"fallbackNotice": "This response used a fallback model: {{model}}.",
"checkModelSettings": "Check model settings",
"reauthNotice": "{{provider}} authorization expired. Please sign in again.",
"reauthFallback": "A fallback model handled this response.",
"reauthSettings": "Open sign-in settings",
"context": {
"tooltip": "Context {{percent}}%",
"detailsLabel": "Open context usage",
+3
View File
@@ -1386,6 +1386,9 @@
"manageModels": "Gestionar modelos",
"fallbackNotice": "Esta respuesta usó un modelo alternativo: {{model}}.",
"checkModelSettings": "Revisar ajustes del modelo",
"reauthNotice": "La autorización de {{provider}} caducó. Vuelve a iniciar sesión.",
"reauthFallback": "Un modelo alternativo respondió esta vez.",
"reauthSettings": "Abrir ajustes de inicio de sesión",
"context": {
"tooltip": "Contexto {{percent}}%",
"detailsLabel": "Abrir uso del contexto",
+3
View File
@@ -1385,6 +1385,9 @@
"manageModels": "Gérer les modèles",
"fallbackNotice": "Cette réponse a utilisé un modèle de secours : {{model}}.",
"checkModelSettings": "Vérifier les paramètres du modèle",
"reauthNotice": "L’autorisation de {{provider}} a expiré. Veuillez vous reconnecter.",
"reauthFallback": "Un modèle de secours a traité cette réponse.",
"reauthSettings": "Ouvrir les paramètres de connexion",
"context": {
"tooltip": "Contexte {{percent}} %",
"detailsLabel": "Ouvrir l’utilisation du contexte",
+3
View File
@@ -1385,6 +1385,9 @@
"manageModels": "Kelola model",
"fallbackNotice": "Respons ini menggunakan model cadangan: {{model}}.",
"checkModelSettings": "Periksa pengaturan model",
"reauthNotice": "Otorisasi {{provider}} kedaluwarsa. Silakan masuk kembali.",
"reauthFallback": "Model cadangan menangani respons ini.",
"reauthSettings": "Buka pengaturan masuk",
"context": {
"tooltip": "Konteks {{percent}}%",
"detailsLabel": "Buka penggunaan konteks",
+3
View File
@@ -1385,6 +1385,9 @@
"manageModels": "モデルを管理",
"fallbackNotice": "この応答では代替モデルを使用しました:{{model}}。",
"checkModelSettings": "モデル設定を確認",
"reauthNotice": "{{provider}} の認証が失効しました。再ログインしてください。",
"reauthFallback": "今回の応答には代替モデルを使用しました。",
"reauthSettings": "ログイン設定を開く",
"context": {
"tooltip": "コンテキスト {{percent}}%",
"detailsLabel": "コンテキスト使用量を開く",
+3
View File
@@ -1385,6 +1385,9 @@
"manageModels": "모델 관리",
"fallbackNotice": "이 응답은 대체 모델을 사용했습니다: {{model}}.",
"checkModelSettings": "모델 설정 확인",
"reauthNotice": "{{provider}} 인증이 만료되었습니다. 다시 로그인해 주세요.",
"reauthFallback": "이번 응답은 대체 모델이 처리했습니다.",
"reauthSettings": "로그인 설정 열기",
"context": {
"tooltip": "컨텍스트 {{percent}}%",
"detailsLabel": "컨텍스트 사용량 열기",
+3
View File
@@ -1399,6 +1399,9 @@
"manageModels": "Gerenciar modelos",
"fallbackNotice": "Esta resposta usou um modelo alternativo: {{model}}.",
"checkModelSettings": "Verificar configurações do modelo",
"reauthNotice": "A autorização de {{provider}} expirou. Entre novamente.",
"reauthFallback": "Um modelo alternativo respondeu desta vez.",
"reauthSettings": "Abrir configurações de login",
"context": {
"tooltip": "Contexto {{percent}}%",
"detailsLabel": "Abrir uso do contexto",
+3
View File
@@ -1385,6 +1385,9 @@
"manageModels": "Quản lý mô hình",
"fallbackNotice": "Phản hồi này đã sử dụng mô hình dự phòng: {{model}}.",
"checkModelSettings": "Kiểm tra cài đặt mô hình",
"reauthNotice": "Quyền truy cập {{provider}} đã hết hạn. Vui lòng đăng nhập lại.",
"reauthFallback": "Mô hình dự phòng đã xử lý phản hồi này.",
"reauthSettings": "Mở cài đặt đăng nhập",
"context": {
"tooltip": "Ngữ cảnh {{percent}}%",
"detailsLabel": "Mở mức sử dụng ngữ cảnh",
+3
View File
@@ -1584,6 +1584,9 @@
"manageModels": "管理模型预设",
"fallbackNotice": "本次已使用备用模型:{{model}}。",
"checkModelSettings": "检查模型设置",
"reauthNotice": "{{provider}} 授权已失效,请重新登录。",
"reauthFallback": "本次已由备用模型继续回复。",
"reauthSettings": "前往登录设置",
"context": {
"tooltip": "上下文 {{percent}}%",
"detailsLabel": "打开上下文用量",
+3
View File
@@ -1385,6 +1385,9 @@
"manageModels": "管理模型預設",
"fallbackNotice": "本次已使用備用模型:{{model}}。",
"checkModelSettings": "檢查模型設定",
"reauthNotice": "{{provider}} 授權已失效,請重新登入。",
"reauthFallback": "本次已由備用模型繼續回覆。",
"reauthSettings": "前往登入設定",
"context": {
"tooltip": "上下文 {{percent}}%",
"detailsLabel": "開啟上下文用量",
+1
View File
@@ -1455,6 +1455,7 @@ export type InboundEvent =
model_name: string;
model_preset?: string | null;
fallback?: boolean;
reauth_provider?: string;
}
| ({
event: "turn_end";
@@ -17,6 +17,7 @@ describe("chat translation resources", () => {
"chat.fallbackTitle", "chat.activity.running", "chat.rename", "chat.loading",
"message.fallbackResponse",
"thread.composer.fallbackNotice", "thread.composer.checkModelSettings",
"thread.composer.reauthNotice", "thread.composer.reauthFallback", "thread.composer.reauthSettings",
]) {
expect(i18n.exists(key), key).toBe(true);
expect(i18n.t(key), key).not.toBe(key);
+2
View File
@@ -1725,6 +1725,7 @@ describe("NanobotClient", () => {
model_name: "deepseek/deepseek-chat",
model_preset: "Deep Research",
fallback: true,
reauth_provider: "openai_codex",
});
expect(chatHandler).toHaveBeenCalledWith({
@@ -1733,6 +1734,7 @@ describe("NanobotClient", () => {
model_name: "deepseek/deepseek-chat",
model_preset: "Deep Research",
fallback: true,
reauth_provider: "openai_codex",
});
});
+29
View File
@@ -1227,6 +1227,35 @@ describe("ThreadShell", () => {
expect(notice()).not.toBeInTheDocument();
});
it("prioritizes the rejected provider's login over fallback details", async () => {
const client = makeClient();
const openSettings = vi.fn();
render(wrap(client, <ThreadShell session={session("reauth")}
title="Auth notice" onToggleSidebar={() => {}} onOpenModelSettings={openSettings}
settingsSnapshot={modelSettings("openai-codex/gpt-5.5", "openai_codex")} />));
await screen.findByTestId("composer-model-logo-openai_codex");
const emit = (reauth_provider?: string) => act(() => client._emitChat("reauth", {
event: "turn_model_updated", chat_id: "reauth", model_name: "xai-grok/grok-4.5",
fallback: true, reauth_provider,
}));
emit();
const generic = screen.getByText(/This response used a fallback model/).closest('[role="status"]')!;
fireEvent.click(within(generic as HTMLElement).getByRole("button", { name: "Dismiss" }));
emit("openai_codex");
const title = screen.getByText("OpenAI Codex authorization expired. Please sign in again.");
expect(title).toBeVisible();
expect(screen.getByText("A fallback model handled this response.")).toBeVisible();
expect(screen.queryByText(/This response used a fallback model/)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Open sign-in settings" }));
expect(openSettings).toHaveBeenCalledOnce();
fireEvent.click(within(title.closest('[role="status"]') as HTMLElement).getByRole("button", { name: "Dismiss" }));
emit("openai_codex");
emit();
expect(screen.queryByText(/authorization expired/)).not.toBeInTheDocument();
expect(screen.getByTestId("composer-model-logo-openai_codex")).toBeInTheDocument();
expect(client.sendSystemCommand).not.toHaveBeenCalled();
});
it("does not show a live fallback notice just from replayed response attribution", async () => {
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => Promise.resolve(
String(input).includes("/webui-thread") ? httpJson({