fix(webui): complete Copilot device sign-in in the browser

Reuse the device-flow adapter from #5498, expose its prompt in the existing OAuth dialog, and keep credential persistence scoped to uncancelled completion.

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
Xubin Renandchengyongru committed 2026-09-21 00:13:46 +08:00
1 parent aca59431fe
commit a44f28e656
24 files changed
+563 -39

No files matched your search

@@ -51,6 +51,7 @@ import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { providerBrand } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { copyTextToClipboard } from "@/lib/clipboard";
import type {
NanobotFeaturesPayload,
ProviderOAuthAuthorizationRequired,
@@ -272,6 +273,8 @@ export function ProviderOAuthLoginDialog({
}) {
const { t } = useTranslation();
const expectsCallbackUrl = flow?.completion_input === "callback_url";
const isDeviceCode = flow?.completion_input === "device_code";
const [copiedCode, setCopiedCode] = useState<string | null>(null);
const inputId = expectsCallbackUrl ? "provider-oauth-callback" : "provider-oauth-code";
const inputLabel = expectsCallbackUrl
? t("settings.oauth.callbackUrl")
@@ -295,7 +298,9 @@ export function ProviderOAuthLoginDialog({
<DialogHeader>
<DialogTitle>{providerLabel}</DialogTitle>
<DialogDescription>
{expectsCallbackUrl
{isDeviceCode
? t("settings.oauth.deviceCodeHelp")
: expectsCallbackUrl
? remoteBrowserAccess
? t("settings.oauth.remoteCallbackHelp")
: t("settings.oauth.localCallbackHelp")
@@ -311,12 +316,37 @@ export function ProviderOAuthLoginDialog({
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin" aria-hidden />
)}
<span>
{expectsCallbackUrl && remoteBrowserAccess
{isDeviceCode
? t("settings.oauth.waitingForDeviceApproval")
: expectsCallbackUrl && remoteBrowserAccess
? t("settings.oauth.pasteCallbackToContinue")
: t("settings.oauth.waitingForCallback")}
</span>
</div>
<div className="space-y-2">
{isDeviceCode ? (
<div className="space-y-2">
<label htmlFor="provider-device-code" className="block text-xs font-medium text-foreground">
{t("settings.oauth.deviceCode")}
</label>
<div className="flex items-center gap-2">
<Input
id="provider-device-code"
value={flow?.user_code ?? ""}
readOnly
onFocus={(event) => event.target.select()}
className="h-12 text-center font-mono text-xl tracking-widest"
/>
<Button type="button" variant="outline" onClick={async () => {
if (flow?.user_code && await copyTextToClipboard(flow.user_code)) {
setCopiedCode(flow.flow_id);
}
}}>
<Clipboard className="mr-2 h-4 w-4" aria-hidden />
{copiedCode === flow?.flow_id ? t("code.copied") : t("code.copy")}
</Button>
</div>
</div>
) : <div className="space-y-2">
<label
htmlFor={inputId}
className="block text-xs font-medium text-foreground"
@@ -345,7 +375,7 @@ export function ProviderOAuthLoginDialog({
spellCheck={false}
/>
)}
</div>
</div>}
{error ? (
<p
role="alert"
@@ -357,13 +387,15 @@ export function ProviderOAuthLoginDialog({
<DialogFooter>
<Button type="button" variant="outline" onClick={onOpenAuthorization}>
<ExternalLink className="mr-2 h-4 w-4" aria-hidden />
{expectsCallbackUrl
{isDeviceCode
? t("settings.oauth.openGitHub")
: expectsCallbackUrl
? t("settings.oauth.openChatGPT")
: t("settings.oauth.signIn")}
</Button>
<Button type="submit" disabled={!authorizationResponse.trim() || completing}>
{!isDeviceCode ? <Button type="submit" disabled={!authorizationResponse.trim() || completing}>
{completing ? t("settings.oauth.signingIn") : t("settings.oauth.finishSignIn")}
</Button>
</Button> : null}
</DialogFooter>
</form>
</DialogContent>
@@ -1,4 +1,4 @@
import { useCallback, type Dispatch, type SetStateAction } from "react";
import { useCallback, useEffect, useRef, type Dispatch, type SetStateAction } from "react";
import type { TFunction } from "i18next";
import type {
@@ -16,6 +16,7 @@ import type { ModelSettingsState } from "@/components/settings/models/useModelSe
import { normalizeContextWindowTokens } from "@/components/settings/shared/ModelControls";
import {
ApiError,
cancelProviderOAuth,
completeProviderOAuth,
createModelConfiguration,
createProviderSettings,
@@ -60,7 +61,7 @@ interface ModelSettingsActionsOptions {
setError: Dispatch<SetStateAction<string | null>>;
onModelNameChange: (modelName: string | null) => void;
remoteBrowserAccess: boolean;
closeProviderOAuthFlow: () => void;
closeProviderOAuthFlow: (cancelPending?: boolean) => void;
installCapabilities: (names: string[]) => Promise<boolean>;
modelDirty: boolean;
configuredModelProviderOptions: Array<{ name: string; label: string }>;
@@ -82,6 +83,11 @@ export function useModelSettingsActions({
modelDirty,
configuredModelProviderOptions,
}: ModelSettingsActionsOptions) {
const oauthMounted = useRef(true);
useEffect(() => {
oauthMounted.current = true;
return () => { oauthMounted.current = false; };
}, []);
const {
expandedProvider,
form,
@@ -492,6 +498,10 @@ export function useModelSettingsActions({
)
: await logoutProviderOAuth(client, providerName);
if (isProviderOAuthAuthorizationRequired(payload)) {
if (payload.completion_input === "device_code" && !oauthMounted.current) {
await cancelProviderOAuth(client, payload.provider, payload.flow_id).catch(() => {});
return;
}
try {
if (popup && !popup.closed) popup.location.href = payload.authorization_url;
} catch {
@@ -505,7 +515,7 @@ export function useModelSettingsActions({
return;
}
popup?.close();
closeProviderOAuthFlow();
closeProviderOAuthFlow(false);
applyPayload(payload, { preserveAgentForm: action === "login" });
setError(null);
} catch (err) {
@@ -533,7 +543,7 @@ export function useModelSettingsActions({
if (isProviderOAuthPending(payload)) return;
applyPayload(payload, { preserveAgentForm: true });
setError(null);
closeProviderOAuthFlow();
closeProviderOAuthFlow(false);
} catch (err) {
if (providerOAuthFlowRef.current?.flow_id === flow.flow_id) {
setProviderOAuthDialogError((err as Error).message);
@@ -3,7 +3,7 @@ import { useEffect, type Dispatch, type SetStateAction } from "react";
import type { ApplySettingsPayload } from "@/components/settings/contracts";
import { providerFormFromRow } from "@/components/settings/models/ProviderSettings";
import type { ModelSettingsState } from "@/components/settings/models/useModelSettingsState";
import { completeProviderOAuth } from "@/lib/api";
import { cancelProviderOAuth, completeProviderOAuth } from "@/lib/api";
import type { NanobotClient } from "@/lib/nanobot-client";
import type {
ProviderOAuthCompletionResult,
@@ -22,7 +22,7 @@ interface ProviderOAuthPollingOptions {
client: NanobotClient;
applyPayload: ApplySettingsPayload;
setError: Dispatch<SetStateAction<string | null>>;
closeProviderOAuthFlow: () => void;
closeProviderOAuthFlow: (cancelPending?: boolean) => void;
}
export function useProviderOAuthPolling({
@@ -58,7 +58,7 @@ export function useProviderOAuthPolling({
}
applyPayload(payload, { preserveAgentForm: true });
setError(null);
closeProviderOAuthFlow();
closeProviderOAuthFlow(false);
} catch (err) {
if (
cancelled
@@ -72,6 +72,12 @@ export function useProviderOAuthPolling({
return () => {
cancelled = true;
if (timer !== null) window.clearTimeout(timer);
if (providerOAuthFlow.completion_input === "device_code"
&& providerOAuthFlowRef.current?.flow_id === providerOAuthFlow.flow_id) {
providerOAuthFlowRef.current = null;
void cancelProviderOAuth(client, providerOAuthFlow.provider, providerOAuthFlow.flow_id)
.catch(() => {});
}
};
}, [applyPayload, client, closeProviderOAuthFlow, providerOAuthFlow]);
}
@@ -33,7 +33,7 @@ import { useSystemSettingsEffects } from "@/components/settings/system/useSystem
import { useSystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { fetchSettings, fetchSettingsUsage } from "@/lib/api";
import { cancelProviderOAuth, fetchSettings, fetchSettingsUsage } from "@/lib/api";
import {
readLocalPreferences,
writeLocalPreferences,
@@ -174,13 +174,17 @@ export function useSettingsController({
const runtimeConfigState = useRuntimeConfigSettings(settings, client, applyPayload);
const closeProviderOAuthFlow = useCallback(() => {
const closeProviderOAuthFlow = useCallback((cancelPending = true) => {
const flow = providerOAuthFlowRef.current;
providerOAuthFlowRef.current = null;
if (cancelPending && flow?.completion_input === "device_code") {
void cancelProviderOAuth(client, flow.provider, flow.flow_id).catch(() => {});
}
setProviderOAuthFlow(null);
setProviderOAuthResponse("");
setProviderOAuthCompleting(false);
setProviderOAuthDialogError(null);
}, []);
}, [client]);
useProviderOAuthPolling({
state: modelState,
client,
+4
View File
@@ -1260,6 +1260,10 @@
}
},
"oauth": {
"deviceCode": "Device code",
"deviceCodeHelp": "Copy this code and enter it on GitHub. This window will update automatically after authorization.",
"waitingForDeviceApproval": "Waiting for GitHub authorization…",
"openGitHub": "Open GitHub",
"authentication": "OAuth authentication",
"signIn": "Sign in",
"signingIn": "Signing in...",
+4
View File
@@ -1061,6 +1061,10 @@
}
},
"oauth": {
"deviceCode": "Código de dispositivo",
"deviceCodeHelp": "Copia este código e introdúcelo en GitHub. Esta ventana se actualizará automáticamente tras la autorización.",
"waitingForDeviceApproval": "Esperando la autorización de GitHub…",
"openGitHub": "Abrir GitHub",
"authentication": "Autenticación OAuth",
"signIn": "Iniciar sesión",
"signingIn": "Iniciando sesión...",
+4
View File
@@ -1060,6 +1060,10 @@
}
},
"oauth": {
"deviceCode": "Code de l’appareil",
"deviceCodeHelp": "Copiez ce code et saisissez-le sur GitHub. Cette fenêtre se mettra à jour automatiquement après l’autorisation.",
"waitingForDeviceApproval": "En attente de l’autorisation GitHub…",
"openGitHub": "Ouvrir GitHub",
"authentication": "Authentification OAuth",
"signIn": "Se connecter",
"signingIn": "Connexion...",
+4
View File
@@ -1060,6 +1060,10 @@
}
},
"oauth": {
"deviceCode": "Kode perangkat",
"deviceCodeHelp": "Salin kode ini dan masukkan di GitHub. Jendela ini akan diperbarui secara otomatis setelah otorisasi.",
"waitingForDeviceApproval": "Menunggu otorisasi GitHub…",
"openGitHub": "Buka GitHub",
"authentication": "Autentikasi OAuth",
"signIn": "Masuk",
"signingIn": "Masuk...",
+4
View File
@@ -1060,6 +1060,10 @@
}
},
"oauth": {
"deviceCode": "デバイスコード",
"deviceCodeHelp": "このコードをコピーして GitHub で入力し、認証してください。完了すると、この画面は自動的に更新されます。",
"waitingForDeviceApproval": "GitHub の認証を待っています…",
"openGitHub": "GitHub を開く",
"authentication": "OAuth 認証",
"signIn": "サインイン",
"signingIn": "サインイン中...",
+4
View File
@@ -1060,6 +1060,10 @@
}
},
"oauth": {
"deviceCode": "기기 코드",
"deviceCodeHelp": "이 코드를 복사하여 GitHub에 입력하고 인증하세요. 완료되면 이 창이 자동으로 업데이트됩니다.",
"waitingForDeviceApproval": "GitHub 인증을 기다리는 중…",
"openGitHub": "GitHub 열기",
"authentication": "OAuth 인증",
"signIn": "로그인",
"signingIn": "로그인 중...",
+4
View File
@@ -1074,6 +1074,10 @@
}
},
"oauth": {
"deviceCode": "Código do dispositivo",
"deviceCodeHelp": "Copie este código e insira-o no GitHub. Esta janela será atualizada automaticamente após a autorização.",
"waitingForDeviceApproval": "Aguardando autorização do GitHub…",
"openGitHub": "Abrir GitHub",
"authentication": "Autenticação OAuth",
"signIn": "Entrar",
"signingIn": "Entrando...",
+4
View File
@@ -1060,6 +1060,10 @@
}
},
"oauth": {
"deviceCode": "Mã thiết bị",
"deviceCodeHelp": "Sao chép mã này và nhập trên GitHub. Cửa sổ này sẽ tự động cập nhật sau khi ủy quyền.",
"waitingForDeviceApproval": "Đang chờ ủy quyền GitHub…",
"openGitHub": "Mở GitHub",
"authentication": "Xác thực OAuth",
"signIn": "Đăng nhập",
"signingIn": "Đang đăng nhập...",
+4
View File
@@ -1260,6 +1260,10 @@
}
},
"oauth": {
"deviceCode": "设备码",
"deviceCodeHelp": "复制此设备码,前往 GitHub 输入并授权。完成后此窗口会自动更新。",
"waitingForDeviceApproval": "等待 GitHub 授权…",
"openGitHub": "前往 GitHub",
"authentication": "OAuth 认证",
"signIn": "登录",
"signingIn": "登录中...",
+4
View File
@@ -1060,6 +1060,10 @@
}
},
"oauth": {
"deviceCode": "裝置碼",
"deviceCodeHelp": "複製此裝置碼,前往 GitHub 輸入並授權。完成後此視窗會自動更新。",
"waitingForDeviceApproval": "等待 GitHub 授權…",
"openGitHub": "前往 GitHub",
"authentication": "OAuth 認證",
"signIn": "登入",
"signingIn": "登入中…",
+10
View File
@@ -1202,6 +1202,16 @@ export async function completeProviderOAuth(
);
}
export async function cancelProviderOAuth(
transport: WebUIMutationTransport,
provider: string,
flowId: string,
): Promise<void> {
await mutation(transport, "settings.provider.oauth_complete", {
provider, flow_id: flowId, cancel: true,
});
}
export async function logoutProviderOAuth(
transport: WebUIMutationTransport,
provider: string,
+2 -1
View File
@@ -577,7 +577,8 @@ export interface ProviderOAuthAuthorizationRequired {
flow_id: string;
authorization_url: string;
expires_in: number;
completion_input?: "authorization_code" | "callback_url";
completion_input?: "authorization_code" | "callback_url" | "device_code";
user_code?: string;
}
export interface ProviderOAuthPending {
@@ -0,0 +1,92 @@
import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import * as clipboard from "@/lib/clipboard";
import {
installSettingsViewTestHooks, jsonResponse, openPopover, renderSettingsView,
requestMutationMock, settingsPayload,
} from "@/tests/settings-test-utils";
describe("Copilot device sign-in", () => {
installSettingsViewTestHooks();
it.each(["approve", "close", "unmount", "close-before-start"])("handles %s without losing the preset draft", async (ending) => {
const payload = settingsPayload();
payload.providers = [{
name: "github_copilot", label: "GitHub Copilot", configured: true,
auth_type: "oauth", model_catalog: "hybrid", oauth_login_supported: true,
}];
const flow = {
status: "authorization_required", provider: "github_copilot", flow_id: "device-flow",
authorization_url: "https://github.com/login/device", user_code: "ABCD-EFGH",
completion_input: "device_code", expires_in: 600,
};
let approved = false;
let recovered = false;
let resolveStart!: (value: typeof flow) => void;
requestMutationMock.mockImplementation(async (action, args) => {
if (action === "settings.provider.oauth_login") {
return ending === "close-before-start"
? new Promise((resolve) => { resolveStart = resolve; }) : flow;
}
if (action === "settings.provider.oauth_complete") {
if (args.cancel) return { status: "cancelled", provider: flow.provider, flow_id: flow.flow_id };
if (!approved) return { status: "pending", provider: flow.provider, flow_id: flow.flow_id };
recovered = true;
return { ...payload, providers: payload.providers.map((row) => ({ ...row })) };
}
throw new Error(`Unexpected mutation: ${action}`);
});
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
if (String(input).includes("/provider-models?")) return jsonResponse({
provider: "github_copilot", status: "available", catalog_kind: "hybrid",
source: recovered ? "remote" : "fallback", error_kind: recovered ? null : "auth_required",
models: [{ id: "github-copilot/new-model" }],
});
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: "Draft" } });
await openPopover(screen.getByRole("button", { name: "Select model" }));
fireEvent.click(await screen.findByRole("button", { name: "Sign in again" }));
if (ending === "close-before-start") {
cleanup();
await act(async () => { resolveStart(flow); });
} else {
const dialog = await screen.findByRole("dialog", { name: "GitHub Copilot" });
expect(within(dialog).getByRole("textbox", { name: "Device code" })).toHaveValue("ABCD-EFGH");
expect(within(dialog).queryByRole("button", { name: "Finish sign-in" })).not.toBeInTheDocument();
expect(within(dialog).queryByRole("textbox", { name: "Authorization code" })).not.toBeInTheDocument();
if (ending === "approve") {
const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);
const open = vi.spyOn(window, "open").mockReturnValue(null);
try {
fireEvent.click(within(dialog).getByRole("button", { name: "Copy" }));
await within(dialog).findByRole("button", { name: "Copied" });
expect(copy).toHaveBeenCalledWith("ABCD-EFGH");
fireEvent.click(within(dialog).getByRole("button", { name: "Open GitHub" }));
expect(open).toHaveBeenCalledWith(flow.authorization_url, "_blank", "noopener,noreferrer");
approved = true;
await waitFor(() => expect(recovered).toBe(true), { timeout: 3000 });
expect(screen.queryByRole("dialog", { name: "GitHub Copilot" })).not.toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Preset name" })).toHaveValue("Draft");
await openPopover(screen.getByRole("button", { name: "Select model" }));
expect(await screen.findByRole("option", { name: /new-model/ })).toBeVisible();
expect(requestMutationMock.mock.calls.some(([, args]) => args.cancel)).toBe(false);
} finally {
copy.mockRestore();
open.mockRestore();
}
return;
}
if (ending === "unmount") cleanup();
else fireEvent.keyDown(dialog, { key: "Escape" });
}
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
"settings.provider.oauth_complete",
{ provider: "github_copilot", flow_id: "device-flow", cancel: true },
expect.any(Number),
));
expect(recovered).toBe(false);
});
});