fix(webui): surface OAuth model catalog authorization failures

This commit is contained in:
Xubin Ren committed 2026-09-21 00:13:46 +08:00
1 parent a478c96bde
commit 024fe8f636
26 files changed
+585 -34

No files matched your search

@@ -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.")}
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -515,6 +515,10 @@
"installing": "必要なパッケージをインストール中…"
},
"models": {
"catalogAuthRequired": "認証が失効しました。再度ログインしてください。",
"catalogUnavailable": "モデルを更新できません。しばらくしてから再試行してください。",
"catalogStale": "キャッシュ済みのモデルを表示しています。最新ではない可能性があります。",
"catalogFallback": "組み込みのモデルを表示しています。最新ではない可能性があります。",
"selectModel": "モデルを選択",
"addConfiguration": "設定を追加",
"newConfiguration": "新しいモデル設定",
+4
View File
@@ -515,6 +515,10 @@
"installing": "필수 패키지 설치 중…"
},
"models": {
"catalogAuthRequired": "인증이 만료되었습니다. 다시 로그인해 주세요.",
"catalogUnavailable": "모델 목록을 갱신할 수 없습니다. 나중에 다시 시도해 주세요.",
"catalogStale": "캐시된 모델을 표시합니다. 최신 목록이 아닐 수 있습니다.",
"catalogFallback": "기본 제공 모델을 표시합니다. 최신 목록이 아닐 수 있습니다.",
"selectModel": "모델 선택",
"addConfiguration": "설정 추가",
"newConfiguration": "새 모델 설정",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -401,6 +401,10 @@
"voiceInput": "语音识别"
},
"models": {
"catalogAuthRequired": "授权已失效,请重新登录。",
"catalogUnavailable": "暂时无法刷新模型,请稍后重试。",
"catalogStale": "当前显示缓存的模型列表,可能不是最新。",
"catalogFallback": "当前显示内置模型列表,可能不是最新。",
"selectModel": "选择模型",
"addConfiguration": "添加配置",
"newConfiguration": "新建模型配置",
+4
View File
@@ -515,6 +515,10 @@
"installing": "正在安裝所需套件…"
},
"models": {
"catalogAuthRequired": "授權已失效,請重新登入。",
"catalogUnavailable": "暫時無法更新模型,請稍後重試。",
"catalogStale": "目前顯示快取的模型清單,可能不是最新。",
"catalogFallback": "目前顯示內建模型清單,可能不是最新。",
"selectModel": "選擇模型",
"addConfiguration": "新增設定",
"newConfiguration": "新增模型設定",
+1
View File
@@ -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);
}
});
});
+55
View File
@@ -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] = {