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:
1 parent
aca59431fe
commit
a44f28e656
24 files changed
+563
-39
No files matched your search
@@ -620,6 +620,15 @@ xAI may change that upstream contract independently of nanobot.
|
||||
|
||||
For GitHub Copilot:
|
||||
|
||||
You can also sign in from the WebUI's model settings. The sign-in dialog shows a
|
||||
device code: copy it, select **Open GitHub**, and enter the code on GitHub. Keep
|
||||
the dialog open; nanobot detects approval and refreshes the model catalog
|
||||
automatically. Closing the dialog cancels the pending sign-in without replacing
|
||||
your saved credentials. This works from a remote browser too; no browser needs
|
||||
to open on the gateway machine.
|
||||
|
||||
For terminal sign-in:
|
||||
|
||||
```bash
|
||||
nanobot provider login github-copilot --set-main
|
||||
```
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Nonblocking GitHub device authorization for gateway settings clients."""
|
||||
|
||||
# pyright: reportMissingTypeStubs=false
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from oauth_cli_kit.models import OAuthToken
|
||||
|
||||
from nanobot.providers import github_copilot_provider
|
||||
from nanobot.providers.github_copilot_provider import login_github_copilot
|
||||
|
||||
|
||||
class GitHubCopilotOAuthFlow:
|
||||
"""Expose the device prompt while the existing login worker waits for approval."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.authorization_url = ""
|
||||
self.user_code = ""
|
||||
self._deadline = time.monotonic() + 900
|
||||
self._ready = threading.Event()
|
||||
self._done = threading.Event()
|
||||
self._cancelled = threading.Event()
|
||||
self._token: OAuthToken | None = None
|
||||
self._error: Exception | None = None
|
||||
self._commit_lock = threading.Lock()
|
||||
self._saved = False
|
||||
|
||||
@property
|
||||
def remaining_seconds(self) -> int:
|
||||
return max(0, int(self._deadline - time.monotonic()))
|
||||
|
||||
@property
|
||||
def expired(self) -> bool:
|
||||
return self._cancelled.is_set() or self.remaining_seconds <= 0
|
||||
|
||||
def cancel(self) -> None:
|
||||
with self._commit_lock:
|
||||
self._cancelled.set()
|
||||
|
||||
def _authorize(self, url: str, code: str, expires_in: int) -> None:
|
||||
self.authorization_url = url
|
||||
self.user_code = code
|
||||
self._deadline = time.monotonic() + expires_in
|
||||
self._ready.set()
|
||||
|
||||
def _run(self) -> None:
|
||||
try:
|
||||
self._token = login_github_copilot(
|
||||
print_fn=lambda _message: None,
|
||||
on_authorization=self._authorize,
|
||||
cancelled=self._cancelled,
|
||||
open_browser=False,
|
||||
persist=False,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._error = exc
|
||||
finally:
|
||||
self._done.set()
|
||||
self._ready.set()
|
||||
|
||||
def start(self) -> None:
|
||||
threading.Thread(target=self._run, daemon=True, name="github-device-login").start()
|
||||
if not self._ready.wait(timeout=15):
|
||||
self.cancel()
|
||||
raise RuntimeError("GitHub sign-in timed out. Start again.")
|
||||
if self._error is not None:
|
||||
raise RuntimeError("GitHub sign-in failed. Start again.") from None
|
||||
|
||||
def complete(self) -> OAuthToken | None:
|
||||
# Approval alone must not change credentials after the UI was closed.
|
||||
# Commit only through the live flow's completion endpoint, serialized
|
||||
# with cancellation (including sign-out).
|
||||
with self._commit_lock:
|
||||
if self.expired:
|
||||
raise RuntimeError("GitHub sign-in expired or cancelled. Start again.")
|
||||
if not self._done.is_set():
|
||||
return None
|
||||
if self._error is not None or self._token is None or not self._token.access:
|
||||
raise RuntimeError("GitHub sign-in failed. Start again.") from None
|
||||
if not self._saved:
|
||||
github_copilot_provider.get_storage().save(self._token)
|
||||
self._saved = True
|
||||
return self._token
|
||||
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import hashlib
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from collections.abc import Awaitable, Callable
|
||||
@@ -81,10 +82,27 @@ def get_github_copilot_login_status() -> OAuthToken | None:
|
||||
def login_github_copilot(
|
||||
print_fn: Callable[[str], None] | None = None,
|
||||
prompt_fn: Callable[[str], str] | None = None,
|
||||
*,
|
||||
on_authorization: Callable[[str, str, int], None] | None = None,
|
||||
cancelled: threading.Event | None = None,
|
||||
open_browser: bool = True,
|
||||
persist: bool = True,
|
||||
) -> OAuthToken:
|
||||
"""Run GitHub device flow and persist the GitHub OAuth token used for Copilot."""
|
||||
del prompt_fn
|
||||
printer = print_fn or print
|
||||
|
||||
def check_cancelled() -> None:
|
||||
if cancelled is not None and cancelled.is_set():
|
||||
raise RuntimeError("GitHub sign-in cancelled.")
|
||||
|
||||
def wait(seconds: int) -> None:
|
||||
if cancelled is None:
|
||||
time.sleep(seconds)
|
||||
else:
|
||||
cancelled.wait(seconds)
|
||||
check_cancelled()
|
||||
|
||||
timeout = httpx.Timeout(20.0, connect=20.0)
|
||||
|
||||
client_id = _resolve("NANOBOT_GITHUB_COPILOT_CLIENT_ID", GITHUB_COPILOT_CLIENT_ID)
|
||||
@@ -112,7 +130,10 @@ def login_github_copilot(
|
||||
|
||||
printer(f"Open: {verify_url}")
|
||||
printer(f"Code: {user_code}")
|
||||
if verify_complete:
|
||||
check_cancelled()
|
||||
if on_authorization is not None:
|
||||
on_authorization(verify_complete, user_code, expires_in)
|
||||
if verify_complete and open_browser:
|
||||
with suppress(Exception):
|
||||
webbrowser.open(verify_complete)
|
||||
|
||||
@@ -121,6 +142,7 @@ def login_github_copilot(
|
||||
access_token = None
|
||||
token_expires_in = _LONG_LIVED_TOKEN_SECONDS
|
||||
while time.time() < deadline:
|
||||
check_cancelled()
|
||||
poll = client.post(
|
||||
access_token_url,
|
||||
headers={"Accept": "application/json", "User-Agent": USER_AGENT},
|
||||
@@ -140,11 +162,11 @@ def login_github_copilot(
|
||||
|
||||
error = poll_payload.get("error")
|
||||
if error == "authorization_pending":
|
||||
time.sleep(current_interval)
|
||||
wait(current_interval)
|
||||
continue
|
||||
if error == "slow_down":
|
||||
current_interval += 5
|
||||
time.sleep(current_interval)
|
||||
wait(current_interval)
|
||||
continue
|
||||
if error == "expired_token":
|
||||
raise RuntimeError("GitHub device code expired. Please run login again.")
|
||||
@@ -153,7 +175,7 @@ def login_github_copilot(
|
||||
if error:
|
||||
desc = poll_payload.get("error_description") or error
|
||||
raise RuntimeError(str(desc))
|
||||
time.sleep(current_interval)
|
||||
wait(current_interval)
|
||||
else:
|
||||
raise RuntimeError("GitHub device flow timed out.")
|
||||
|
||||
@@ -176,7 +198,9 @@ def login_github_copilot(
|
||||
expires=expires_ms,
|
||||
account_id=str(account_id) if account_id else None,
|
||||
)
|
||||
get_storage().save(token)
|
||||
check_cancelled()
|
||||
if persist:
|
||||
get_storage().save(token)
|
||||
return token
|
||||
|
||||
|
||||
|
||||
@@ -1591,18 +1591,30 @@ def login_oauth_provider(
|
||||
|
||||
if spec.name == "github_copilot":
|
||||
try:
|
||||
from nanobot.providers.github_copilot_provider import (
|
||||
login_github_copilot,
|
||||
)
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
except ImportError:
|
||||
raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from 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)
|
||||
return settings_payload(config_path=config_path)
|
||||
# An existing token can be revoked. Expose the device prompt immediately
|
||||
# instead of waiting for approval inside a blocking CLI login request.
|
||||
oauth_flows.clear(spec.name)
|
||||
copilot_flow = GitHubCopilotOAuthFlow()
|
||||
try:
|
||||
copilot_flow.start()
|
||||
except Exception:
|
||||
copilot_flow.cancel()
|
||||
raise WebUISettingsError("GitHub sign-in failed. Start again.", status=502) from None
|
||||
flow_id = secrets.token_urlsafe(24)
|
||||
oauth_flows.register(spec.name, flow_id, copilot_flow)
|
||||
return {
|
||||
"status": "authorization_required",
|
||||
"provider": spec.name,
|
||||
"flow_id": flow_id,
|
||||
"authorization_url": copilot_flow.authorization_url,
|
||||
"user_code": copilot_flow.user_code,
|
||||
"expires_in": copilot_flow.remaining_seconds,
|
||||
"completion_input": "device_code",
|
||||
}
|
||||
|
||||
if spec.name == "xai_grok":
|
||||
from nanobot.providers.xai_oauth import start_xai_oauth_login
|
||||
@@ -1646,7 +1658,7 @@ def complete_oauth_provider(
|
||||
provider_name = (query_first(query, "provider") or "").strip()
|
||||
flow_id = (query_first(query, "flow_id") or "").strip()
|
||||
spec = find_by_name(provider_name)
|
||||
if spec is None or spec.name not in {"openai_codex", "xai_grok"}:
|
||||
if spec is None or spec.name not in {"openai_codex", "xai_grok", "github_copilot"}:
|
||||
raise WebUISettingsError("OAuth completion is not supported for this provider")
|
||||
if not flow_id:
|
||||
raise WebUISettingsError("flow_id is required")
|
||||
@@ -1655,6 +1667,11 @@ def complete_oauth_provider(
|
||||
if flow is None:
|
||||
raise WebUISettingsError(f"{spec.label} sign-in expired. Start again.", status=410)
|
||||
|
||||
cancel = query_first(query, "cancel")
|
||||
if cancel is not None and parse_bool(cancel, "cancel"):
|
||||
oauth_flows.remove(spec.name, flow_id, flow)
|
||||
return {"status": "cancelled", "provider": spec.name, "flow_id": flow_id}
|
||||
|
||||
try:
|
||||
if spec.name == "openai_codex":
|
||||
from nanobot.providers.openai_codex_oauth import (
|
||||
@@ -1666,6 +1683,12 @@ def complete_oauth_provider(
|
||||
token = complete_openai_codex_oauth_login(flow, authorization_response)
|
||||
except OpenAICodexOAuthInputError as exc:
|
||||
raise WebUISettingsError(str(exc), status=400) from exc
|
||||
elif spec.name == "github_copilot":
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
|
||||
if not isinstance(flow, GitHubCopilotOAuthFlow):
|
||||
raise WebUISettingsError("Invalid GitHub sign-in session. Start again.")
|
||||
token = flow.complete()
|
||||
else:
|
||||
from nanobot.providers.xai_oauth import complete_xai_oauth_login
|
||||
|
||||
@@ -1720,6 +1743,7 @@ def logout_oauth_provider(
|
||||
from nanobot.providers.github_copilot_provider import get_storage
|
||||
except ImportError:
|
||||
raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None
|
||||
oauth_flows.clear(spec.name)
|
||||
token_path = get_storage().get_token_path()
|
||||
elif spec.name == "xai_grok":
|
||||
from nanobot.providers.xai_oauth import logout_xai_oauth
|
||||
@@ -1854,6 +1878,6 @@ class ModelSettingsHandler:
|
||||
except WebUISettingsError as exc:
|
||||
return SettingsRouteResult.failure(exc.status, exc.message)
|
||||
|
||||
if payload.get("status") in {"authorization_required", "pending"}:
|
||||
if payload.get("status") in {"authorization_required", "pending", "cancelled"}:
|
||||
return SettingsRouteResult.success(payload)
|
||||
return SettingsRouteResult.success(payload, decorate_restart=True)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Device authorization exposes its prompt before waiting for browser approval."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from nanobot.providers import github_copilot_provider as provider
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
|
||||
|
||||
def test_device_prompt_precedes_approval_and_success_persists_token(monkeypatch):
|
||||
saved = []
|
||||
approved = False
|
||||
|
||||
def respond(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path.endswith("/device/code"):
|
||||
return httpx.Response(200, json={
|
||||
"device_code": "device-secret", "user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://github.com/login/device",
|
||||
"interval": 1, "expires_in": 60,
|
||||
})
|
||||
if request.url.path.endswith("/access_token"):
|
||||
return httpx.Response(200, json={"access_token": "account-secret"} if approved
|
||||
else {"error": "authorization_pending"})
|
||||
return httpx.Response(200, json={"login": "test-account"})
|
||||
|
||||
client = httpx.Client(transport=httpx.MockTransport(respond))
|
||||
monkeypatch.setattr(provider.httpx, "Client", lambda **_kwargs: client)
|
||||
monkeypatch.setattr(provider, "get_storage", lambda: SimpleNamespace(save=saved.append))
|
||||
monkeypatch.setattr(provider.webbrowser, "open", lambda *_args: (_ for _ in ()).throw(
|
||||
AssertionError("The gateway must not open the user's browser")
|
||||
))
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
try:
|
||||
flow.start()
|
||||
assert flow.user_code == "ABCD-EFGH"
|
||||
assert flow.authorization_url == "https://github.com/login/device"
|
||||
assert flow.complete() is None
|
||||
assert saved == []
|
||||
approved = True
|
||||
deadline = time.monotonic() + 3
|
||||
token = flow.complete()
|
||||
while token is None and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
token = flow.complete()
|
||||
assert token is not None
|
||||
assert token.account_id == "test-account"
|
||||
assert saved == [token]
|
||||
finally:
|
||||
flow.cancel()
|
||||
|
||||
|
||||
def test_cancelling_device_flow_interrupts_polling_without_saving(monkeypatch):
|
||||
saved = []
|
||||
|
||||
def respond(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path.endswith("/device/code"):
|
||||
return httpx.Response(200, json={
|
||||
"device_code": "device-secret", "user_code": "ABCD-EFGH",
|
||||
"verification_uri": "https://github.com/login/device",
|
||||
"interval": 30, "expires_in": 60,
|
||||
})
|
||||
return httpx.Response(200, json={"error": "authorization_pending"})
|
||||
|
||||
client = httpx.Client(transport=httpx.MockTransport(respond))
|
||||
monkeypatch.setattr(provider.httpx, "Client", lambda **_kwargs: client)
|
||||
monkeypatch.setattr(provider, "get_storage", lambda: SimpleNamespace(save=saved.append))
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
flow.start()
|
||||
flow.cancel()
|
||||
deadline = time.monotonic() + 2
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
flow.complete()
|
||||
except RuntimeError as exc:
|
||||
assert "cancelled" in str(exc)
|
||||
break
|
||||
time.sleep(0.01)
|
||||
else:
|
||||
raise AssertionError("Device polling did not stop after cancellation")
|
||||
assert saved == []
|
||||
assert flow.expired
|
||||
|
||||
|
||||
def test_approval_after_cancellation_cannot_overwrite_saved_credentials(monkeypatch):
|
||||
from nanobot.providers import github_copilot_oauth as oauth
|
||||
|
||||
approved = threading.Event()
|
||||
finished = threading.Event()
|
||||
saved = []
|
||||
|
||||
def login(*, on_authorization, persist, **_kwargs):
|
||||
assert persist is False
|
||||
on_authorization("https://github.com/login/device", "ABCD-EFGH", 60)
|
||||
approved.wait(2)
|
||||
finished.set()
|
||||
return SimpleNamespace(access="new-account-secret")
|
||||
|
||||
monkeypatch.setattr(oauth, "login_github_copilot", login)
|
||||
monkeypatch.setattr(provider, "get_storage", lambda: SimpleNamespace(save=saved.append))
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
try:
|
||||
flow.start()
|
||||
flow.cancel()
|
||||
approved.set()
|
||||
assert finished.wait(1)
|
||||
with pytest.raises(RuntimeError, match="cancelled"):
|
||||
flow.complete()
|
||||
assert saved == []
|
||||
finally:
|
||||
approved.set()
|
||||
flow.cancel()
|
||||
|
||||
|
||||
def test_device_flow_does_not_expose_upstream_failure_details(monkeypatch):
|
||||
from nanobot.providers import github_copilot_oauth as oauth
|
||||
|
||||
def login(**_kwargs):
|
||||
raise RuntimeError("upstream echoed synthetic-secret")
|
||||
|
||||
monkeypatch.setattr(oauth, "login_github_copilot", login)
|
||||
flow = GitHubCopilotOAuthFlow()
|
||||
with pytest.raises(RuntimeError, match="GitHub sign-in failed") as failure:
|
||||
flow.start()
|
||||
assert "synthetic-secret" not in str(failure.value)
|
||||
with pytest.raises(RuntimeError, match="GitHub sign-in failed"):
|
||||
flow.complete()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The WebUI exposes only user-facing device data and owns cancellation."""
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.config.schema import Config
|
||||
from nanobot.webui.settings_models import complete_oauth_provider, login_oauth_provider
|
||||
from nanobot.webui.settings_services import WebUIOAuthFlowRegistry
|
||||
|
||||
|
||||
def test_copilot_prompt_poll_and_owned_cancellation(monkeypatch):
|
||||
stopped = threading.Event()
|
||||
|
||||
def login(*, on_authorization, cancelled, persist, **_kwargs):
|
||||
assert persist is False
|
||||
on_authorization("https://github.com/login/device", "ABCD-EFGH", 60)
|
||||
cancelled.wait(2)
|
||||
stopped.set()
|
||||
raise RuntimeError("cancelled")
|
||||
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_oauth.login_github_copilot", login)
|
||||
registry = WebUIOAuthFlowRegistry()
|
||||
payload = login_oauth_provider(
|
||||
Config(), {"provider": ["github_copilot"]}, oauth_flows=registry,
|
||||
config_path=None, settings_payload=lambda **_: {},
|
||||
)
|
||||
assert set(payload) == {
|
||||
"status", "provider", "flow_id", "authorization_url", "user_code",
|
||||
"expires_in", "completion_input",
|
||||
}
|
||||
assert payload["user_code"] == "ABCD-EFGH"
|
||||
assert payload["completion_input"] == "device_code"
|
||||
query = {"provider": ["github_copilot"], "flow_id": [payload["flow_id"]]}
|
||||
kwargs = dict(oauth_flows=registry, config_path=None, settings_payload=lambda **_: {})
|
||||
try:
|
||||
assert complete_oauth_provider(query, **kwargs)["status"] == "pending"
|
||||
with pytest.raises(ValueError, match="expired"):
|
||||
complete_oauth_provider({**query, "provider": ["openai_codex"], "cancel": ["true"]}, **kwargs)
|
||||
assert registry.get("github_copilot", payload["flow_id"]) is not None
|
||||
result = complete_oauth_provider({**query, "cancel": ["true"]}, **kwargs)
|
||||
assert result["status"] == "cancelled"
|
||||
assert registry.get("github_copilot", payload["flow_id"]) is None
|
||||
assert stopped.wait(1)
|
||||
finally:
|
||||
registry.clear("github_copilot")
|
||||
@@ -1904,7 +1904,7 @@ def test_github_copilot_oauth_login_reports_missing_oauth_cli_kit(
|
||||
real_import = builtins.__import__
|
||||
|
||||
def fake_import(name, *args, **kwargs):
|
||||
if name == "nanobot.providers.github_copilot_provider":
|
||||
if name == "nanobot.providers.github_copilot_oauth":
|
||||
raise ImportError("missing")
|
||||
return real_import(name, *args, **kwargs)
|
||||
|
||||
@@ -2142,17 +2142,27 @@ def test_provider_models_payload_exposes_catalog_failure_with_usable_models(
|
||||
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"))
|
||||
from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
|
||||
|
||||
start = Mock()
|
||||
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(GitHubCopilotOAuthFlow, "start", start)
|
||||
monkeypatch.setattr(GitHubCopilotOAuthFlow, "complete", lambda _: SimpleNamespace(access="new-token"))
|
||||
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()
|
||||
payload = login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows)
|
||||
assert payload["status"] == "authorization_required"
|
||||
assert payload["completion_input"] == "device_code"
|
||||
start.assert_called_once()
|
||||
invalidate.assert_not_called()
|
||||
assert complete_oauth_provider(
|
||||
{"provider": ["github-copilot"], "flow_id": [payload["flow_id"]]},
|
||||
oauth_flows=oauth_flows,
|
||||
) == {"ready": True}
|
||||
invalidate.assert_called_once_with("github_copilot")
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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...",
|
||||
|
||||
@@ -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...",
|
||||
|
||||
@@ -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...",
|
||||
|
||||
@@ -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...",
|
||||
|
||||
@@ -1060,6 +1060,10 @@
|
||||
}
|
||||
},
|
||||
"oauth": {
|
||||
"deviceCode": "デバイスコード",
|
||||
"deviceCodeHelp": "このコードをコピーして GitHub で入力し、認証してください。完了すると、この画面は自動的に更新されます。",
|
||||
"waitingForDeviceApproval": "GitHub の認証を待っています…",
|
||||
"openGitHub": "GitHub を開く",
|
||||
"authentication": "OAuth 認証",
|
||||
"signIn": "サインイン",
|
||||
"signingIn": "サインイン中...",
|
||||
|
||||
@@ -1060,6 +1060,10 @@
|
||||
}
|
||||
},
|
||||
"oauth": {
|
||||
"deviceCode": "기기 코드",
|
||||
"deviceCodeHelp": "이 코드를 복사하여 GitHub에 입력하고 인증하세요. 완료되면 이 창이 자동으로 업데이트됩니다.",
|
||||
"waitingForDeviceApproval": "GitHub 인증을 기다리는 중…",
|
||||
"openGitHub": "GitHub 열기",
|
||||
"authentication": "OAuth 인증",
|
||||
"signIn": "로그인",
|
||||
"signingIn": "로그인 중...",
|
||||
|
||||
@@ -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...",
|
||||
|
||||
@@ -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...",
|
||||
|
||||
@@ -1260,6 +1260,10 @@
|
||||
}
|
||||
},
|
||||
"oauth": {
|
||||
"deviceCode": "设备码",
|
||||
"deviceCodeHelp": "复制此设备码,前往 GitHub 输入并授权。完成后此窗口会自动更新。",
|
||||
"waitingForDeviceApproval": "等待 GitHub 授权…",
|
||||
"openGitHub": "前往 GitHub",
|
||||
"authentication": "OAuth 认证",
|
||||
"signIn": "登录",
|
||||
"signingIn": "登录中...",
|
||||
|
||||
@@ -1060,6 +1060,10 @@
|
||||
}
|
||||
},
|
||||
"oauth": {
|
||||
"deviceCode": "裝置碼",
|
||||
"deviceCodeHelp": "複製此裝置碼,前往 GitHub 輸入並授權。完成後此視窗會自動更新。",
|
||||
"waitingForDeviceApproval": "等待 GitHub 授權…",
|
||||
"openGitHub": "前往 GitHub",
|
||||
"authentication": "OAuth 認證",
|
||||
"signIn": "登入",
|
||||
"signingIn": "登入中…",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user