fix(webui): hide model choices when OAuth authorization expires

This commit is contained in:
Xubin Ren committed 2026-09-21 00:13:46 +08:00
1 parent 1bfb4f6fc7
commit eaa0e290d0
3 files changed
+103 -57

No files matched your search

+8 -6
View File
@@ -5,12 +5,14 @@ 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. 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 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 Copilot. An explicit authorization failure hides the picker’s search and model
out of date. An explicit authorization failure offers **Sign in again** using list and offers **Sign in again** using the existing provider login flow.
the existing provider login flow; successful WebUI sign-in clears the catalog Successful WebUI sign-in clears the catalog cache and restores model selection.
cache. Network, rate-limit, and service failures instead ask you to try again Existing presets, selected models, and unsaved preset details are preserved.
later (failed refreshes are cached briefly). Existing presets and manual model Network, rate-limit, and service failures instead keep cached or built-in lists
IDs remain available. A successful chat may have used a fallback preset and available, label them as potentially out of date, and ask you to try again later
(failed refreshes are cached briefly). Manual model IDs remain available for
these temporary failures. A successful chat may have used a fallback preset and
does not prove that the selected provider's authorization is still valid. 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 When a live chat uses a fallback model, a dismissible notice above the composer
names that model and links to model settings. If the provider explicitly rejected names that model and links to model settings. If the provider explicitly rejected
@@ -187,6 +187,7 @@ export function ModelIdPicker({
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const catalogNoticeId = useId(); const catalogNoticeId = useId();
const catalogSignInRef = useRef<HTMLButtonElement>(null);
const effectiveProvider = const effectiveProvider =
provider === "auto" ? settings.agent.resolved_provider ?? provider : provider; provider === "auto" ? settings.agent.resolved_provider ?? provider : provider;
const hasConcreteProvider = Boolean(effectiveProvider && effectiveProvider !== "auto"); const hasConcreteProvider = Boolean(effectiveProvider && effectiveProvider !== "auto");
@@ -233,20 +234,25 @@ export function ModelIdPicker({
const waitingForModelSearch = const waitingForModelSearch =
open && canFetchModels && defersModelList && !hasDeferredSearchQuery; open && canFetchModels && defersModelList && !hasDeferredSearchQuery;
const hasModelList = hasStaticModels || payload?.status === "available"; const hasModelList = hasStaticModels || payload?.status === "available";
const catalogNeedsSignIn = !hasStaticModels && payload?.error_kind === "auth_required";
const showModels = Boolean( const showModels = Boolean(
hasModelList && (hasStaticModels || (payload && (!isCatalog || normalizedQuery))), !catalogNeedsSignIn && hasModelList
&& (hasStaticModels || (payload && (!isCatalog || normalizedQuery))),
); );
const customCandidate = query.trim(); const customCandidate = query.trim();
const allowCustomModel = !providerRequiresConfiguration; const allowCustomModel = !providerRequiresConfiguration && !catalogNeedsSignIn;
const exactQueryMatch = providerModels.some((model) => model.id === customCandidate); const exactQueryMatch = providerModels.some((model) => model.id === customCandidate);
const showCustomModel = Boolean( const showCustomModel = Boolean(
allowCustomModel && customCandidate && !exactQueryMatch && customCandidate !== value, allowCustomModel && customCandidate && !exactQueryMatch && customCandidate !== value,
); );
const providerModelCount = payload?.model_count ?? providerModels.length; const providerModelCount = payload?.model_count ?? providerModels.length;
const modelUnconfigured = !value.trim() || !providerConfigured; const modelUnconfigured = !value.trim() || !providerConfigured;
const showCatalogNotice = !loading && payload?.status === "available" const showCatalogNotice = !loading && payload && (catalogNeedsSignIn
&& (payload.source === "stale" || payload.source === "fallback"); || (payload.status === "available" && (payload.source === "stale" || payload.source === "fallback")));
const catalogNeedsSignIn = payload?.error_kind === "auth_required";
useEffect(() => {
if (open && catalogNeedsSignIn && !loading) catalogSignInRef.current?.focus();
}, [open, catalogNeedsSignIn, loading]);
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) return;
@@ -370,7 +376,7 @@ export function ModelIdPicker({
align="end" align="end"
className="w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-2rem)] p-1.5" className="w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-2rem)] p-1.5"
> >
<div className="p-1 pb-1.5"> {!catalogNeedsSignIn ? <div className="p-1 pb-1.5">
<div className="relative"> <div className="relative">
<Search <Search
className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"
@@ -390,43 +396,51 @@ export function ModelIdPicker({
className="h-8 rounded-full pl-8 pr-3 text-[12px]" className="h-8 rounded-full pl-8 pr-3 text-[12px]"
/> />
</div> </div>
</div> </div> : null}
{showCatalogNotice ? ( {showCatalogNotice ? (
<div className="mx-1 mb-1.5 rounded-control bg-muted/60 px-2.5 py-2 text-[11px] leading-4"> <div className="mx-1 mb-1.5 flex items-start gap-2 rounded-control bg-muted/60 px-2.5 py-2 text-[11px] leading-4">
<div id={catalogNoticeId} role="status"> {catalogNeedsSignIn ? <ProviderPickerIcon
<p className="font-medium text-foreground"> provider={effectiveProvider}
{catalogNeedsSignIn showBrandLogos={showProviderLogos}
? tx("settings.models.catalogAuthRequired", "Authorization expired. Please sign in again.") /> : null}
: tx("settings.models.catalogUnavailable", "Could not refresh models. Try again later.")} <div className="min-w-0 flex-1">
</p> <div id={catalogNoticeId} role="status">
<p className="mt-1 text-muted-foreground"> <p className="font-medium text-foreground">
{payload.source === "stale" {catalogNeedsSignIn
? tx("settings.models.catalogStale", "Showing cached models; the list may be out of date.") ? tx("settings.models.catalogAuthRequired", "Authorization expired. Please sign in again.")
: tx("settings.models.catalogFallback", "Showing built-in models; the list may be out of date.")} : tx("settings.models.catalogUnavailable", "Could not refresh models. Try again later.")}
</p> </p>
{!catalogNeedsSignIn ? <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> : null}
</div>
{catalogNeedsSignIn && onProviderOAuthLogin && providerRow?.oauth_login_supported ? (
<Button
ref={catalogSignInRef}
type="button"
size="sm"
variant="outline"
className="mt-2 h-7 rounded-full px-2.5 text-[11px]"
disabled={providerSigningIn}
aria-describedby={catalogNoticeId}
onClick={() => {
setOpen(false);
onProviderOAuthLogin(effectiveProvider);
}}
>
{providerSigningIn
? tx("settings.oauth.signingIn", "Signing in...")
: tx("settings.oauth.signInAgain", "Sign in again")}
</Button>
) : null}
</div> </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> </div>
) : null} ) : null}
{providerRequiresConfiguration ? ( {catalogNeedsSignIn ? null : providerRequiresConfiguration ? (
<div className="px-2 py-1.5 text-[11px] leading-4 text-muted-foreground"> <div className="px-2 py-1.5 text-[11px] leading-4 text-muted-foreground">
{tx("settings.models.providerNotConfigured", "Configure this provider before loading models.")} {tx("settings.models.providerNotConfigured", "Configure this provider before loading models.")}
</div> </div>
+44 -14
View File
@@ -35,38 +35,65 @@ function catalog(
describe("OAuth catalog feedback", () => { describe("OAuth catalog feedback", () => {
installSettingsViewTestHooks(); installSettingsViewTestHooks();
it.each(["stale", "fallback"] as const)("explains %s auth failures without hiding models or manual IDs", async (source) => { it.each(["stale", "fallback"] as const)("replaces %s models and search with sign-in after auth fails", async (source) => {
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(catalog(source, "auth_required")))); vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(catalog(source, "auth_required"))));
const onChange = vi.fn(); const onChange = vi.fn();
const login = vi.fn(); const login = vi.fn();
render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex" render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex"
value="" showProviderLogos onChange={onChange} onProviderOAuthLogin={login} />); value="openai-codex/saved-model" showProviderLogos onChange={onChange} onProviderOAuthLogin={login} />);
await openPopover(screen.getByRole("button", { name: "Select model" })); await openPopover(screen.getByRole("button", { name: "openai-codex/saved-model" }));
const notice = await screen.findByRole("status"); const notice = await screen.findByRole("status");
expect(notice).toHaveTextContent("Authorization expired. Please sign in again."); expect(notice).toHaveTextContent("Authorization expired. Please sign in again.");
expect(notice).not.toHaveTextContent("out of date");
expect(screen.queryByText(/private upstream/)).not.toBeInTheDocument();
expect(screen.queryByRole("option")).not.toBeInTheDocument();
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "openai-codex/saved-model" })).toBeVisible();
expect(onChange).not.toHaveBeenCalled();
const signIn = screen.getByRole("button", { name: "Sign in again" });
expect(signIn).toHaveAttribute("aria-describedby", notice.id);
expect(signIn).toHaveFocus();
fireEvent.click(signIn);
expect(login).toHaveBeenCalledWith("openai_codex");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
it.each([
["fallback", "unavailable"], ["fallback", undefined], ["stale", "unavailable"],
] as const)("keeps %s models for temporary or legacy failures (%s)", async (source, kind) => {
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(catalog(source, kind))));
const onChange = vi.fn();
render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex"
value="" showProviderLogos onChange={onChange} onProviderOAuthLogin={vi.fn()} />);
await openPopover(screen.getByRole("button", { name: "Select model" }));
const notice = await screen.findByRole("status");
expect(notice).toHaveTextContent("Could not refresh models. Try again later.");
expect(notice).toHaveTextContent(source === "stale" ? "cached models" : "built-in models"); expect(notice).toHaveTextContent(source === "stale" ? "cached models" : "built-in models");
expect(notice).toHaveTextContent("out of date"); expect(notice).toHaveTextContent("out of date");
expect(screen.queryByText(/private upstream/)).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Sign in again" })).not.toBeInTheDocument();
expect(screen.getByRole("option", { name: /Offline model/ })).toBeVisible(); expect(screen.getByRole("option", { name: /Offline model/ })).toBeVisible();
const search = screen.getByRole("combobox"); const search = screen.getByRole("combobox");
expect(search).toHaveAttribute("aria-describedby", notice.id); expect(search).toHaveAttribute("aria-describedby", notice.id);
fireEvent.change(search, { target: { value: "openai-codex/custom-model" } }); fireEvent.change(search, { target: { value: "openai-codex/custom-model" } });
fireEvent.click(screen.getByRole("option", { name: /Use.*custom-model/ })); fireEvent.click(screen.getByRole("option", { name: /Use.*custom-model/ }));
expect(onChange).toHaveBeenCalledWith("openai-codex/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) => { it("removes a pending custom choice when an auth failure arrives", async () => {
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(catalog("fallback", kind)))); let finish!: (response: Response) => void;
vi.stubGlobal("fetch", vi.fn(() => new Promise<Response>((resolve) => { finish = resolve; })));
const onChange = vi.fn();
render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex" render(<ModelIdPicker token="tok" settings={settings()} provider="openai_codex"
value="" showProviderLogos onChange={vi.fn()} onProviderOAuthLogin={vi.fn()} />); value="" showProviderLogos onChange={onChange} onProviderOAuthLogin={vi.fn()} />);
await openPopover(screen.getByRole("button", { name: "Select model" })); await openPopover(screen.getByRole("button", { name: "Select model" }));
expect(await screen.findByRole("status")).toHaveTextContent("Could not refresh models. Try again later."); fireEvent.change(screen.getByRole("combobox"), { target: { value: "openai-codex/custom-model" } });
expect(screen.queryByRole("button", { name: "Sign in again" })).not.toBeInTheDocument(); expect(screen.getByRole("option", { name: /Use.*custom-model/ })).toBeVisible();
expect(screen.getByRole("option", { name: /Offline model/ })).toBeVisible(); await act(async () => { finish(jsonResponse(catalog("stale", "auth_required"))); });
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.queryByRole("option")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Sign in again" })).toHaveFocus();
expect(onChange).not.toHaveBeenCalled();
}); });
it("reloads an open picker on successful same-account login and clears stale feedback", async () => { it("reloads an open picker on successful same-account login and clears stale feedback", async () => {
@@ -81,9 +108,12 @@ describe("OAuth catalog feedback", () => {
const view = render(<ModelIdPicker {...props} settings={settings()} />); const view = render(<ModelIdPicker {...props} settings={settings()} />);
await openPopover(screen.getByRole("button", { name: "Select model" })); await openPopover(screen.getByRole("button", { name: "Select model" }));
expect(await screen.findByRole("status")).toHaveTextContent("Authorization expired"); expect(await screen.findByRole("status")).toHaveTextContent("Authorization expired");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.queryByRole("option")).not.toBeInTheDocument();
// Login produces a new settings snapshot, even when the account is unchanged. // Login produces a new settings snapshot, even when the account is unchanged.
view.rerender(<ModelIdPicker {...props} settings={settings()} />); view.rerender(<ModelIdPicker {...props} settings={settings()} />);
expect(await screen.findByRole("option", { name: /New model/ })).toBeVisible(); expect(await screen.findByRole("option", { name: /New model/ })).toBeVisible();
expect(screen.getByRole("combobox")).toBeVisible();
expect(screen.queryByRole("status")).not.toBeInTheDocument(); expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(fetchMock).toHaveBeenCalledTimes(2); expect(fetchMock).toHaveBeenCalledTimes(2);
}); });