Agent Zero AI framework
Honor GitHub device-flow polling intervals
Alessandro85e28d0799b3
diff --git a/plugins/_oauth/AGENTS.md b/plugins/_oauth/AGENTS.mdindex 02f807262..1bbf87f9e 100644--- a/plugins/_oauth/AGENTS.md+++ b/plugins/_oauth/AGENTS.md@@ -26,6 +26,7 @@- Provider cards and model slot actions must be driven by backend provider status. Do not reintroduce hardcoded frontend provider lists or fallback provider catalogs.- OAuth account surfaces in settings, discovery, and onboarding must use the provider registry/status summary rather than Codex-only frontend state.- OAuth settings pending-auth controls such as device codes, manual callback input, and provider setup fields must render inline under the relevant provider row, not as a detached section below all providers.+- OAuth device-code polling must honor provider `interval`, `expires_at`, and `slow_down` updates; do not poll immediately or keep a stale fixed interval after a provider asks the client to slow down.- OAuth settings model slots must keep provider choice editable per slot, list only connected OAuth account providers, and persist the selected provider IDs into `chat_model.provider` and `utility_model.provider`.- `helpers/providers/registry.py` is the source of truth for connectable OAuth providers.- OAuth provider config must not expose the dummy `oauth` API key in `conf/model_providers.yaml`; the dummy key is a runtime-only shim supplied by the `get_api_key` extension after the account provider reports connected.diff --git a/plugins/_oauth/api/start_device_login.py b/plugins/_oauth/api/start_device_login.pyindex 04c9e4ab9..c93fb199b 100644--- a/plugins/_oauth/api/start_device_login.py+++ b/plugins/_oauth/api/start_device_login.py@@ -6,4 +6,28 @@ from plugins._oauth.helpers.providers import CODEX_PROVIDER_ID, get_providerclass StartDeviceLogin(ApiHandler):async def process(self, input: dict, request: Request) -> dict:- return get_provider(CODEX_PROVIDER_ID).start_login(input, request).to_dict()+ raw_provider_id = _provider_id(input)+ try:+ return get_provider(raw_provider_id).start_login(input, request).to_dict()+ except Exception as exc:+ return {+ "ok": False,+ "provider_id": _provider_id_label(raw_provider_id),+ "error": str(exc),+ }+++def _provider_id(input: dict) -> object:+ if "provider_id" not in input or input.get("provider_id") is None:+ return CODEX_PROVIDER_ID+ value = input.get("provider_id")+ if isinstance(value, str) and not value.strip():+ return CODEX_PROVIDER_ID+ return value+++def _provider_id_label(value: object) -> str:+ if value is None:+ return CODEX_PROVIDER_ID+ text = str(value).strip()+ return text or CODEX_PROVIDER_IDdiff --git a/plugins/_oauth/webui/oauth-config-store.js b/plugins/_oauth/webui/oauth-config-store.jsindex 9b5279d54..6e2b2201d 100644--- a/plugins/_oauth/webui/oauth-config-store.js+++ b/plugins/_oauth/webui/oauth-config-store.js@@ -758,9 +758,23 @@ export const store = createStore("oauthConfig", {startPolling(providerId = CODEX_PROVIDER) {this.stopPolling(providerId);this.pollStartedAt = { ...this.pollStartedAt, [providerId]: Date.now() };+ const clearTimer = () => {+ if (this.pollTimers[providerId]) window.clearTimeout(this.pollTimers[providerId]);+ const timers = { ...this.pollTimers };+ delete timers[providerId];+ this.pollTimers = timers;+ if (providerId === CODEX_PROVIDER) this.pollTimer = null;+ };+ const schedule = (delayMs) => {+ clearTimer();+ this.pollTimers = { ...this.pollTimers, [providerId]: window.setTimeout(tick, delayMs) };+ if (providerId === CODEX_PROVIDER) this.pollTimer = this.pollTimers[providerId];+ };const tick = async () => {+ clearTimer();const device = this.devices[providerId];if (!device?.attempt_id) return;+ let nextDelay = Math.max(1500, Number(device.interval || 5) * 1000);try {const response = await callJsonApi(POLL_LOGIN_API, {provider_id: providerId,@@ -782,6 +796,16 @@ export const store = createStore("oauthConfig", {void toastFrontendSuccess(`${this.providerLabel(providerId)} connected.`, "OAuth Connections");return;}+ if (response.interval || response.expires_at) {+ const updatedDevice = {+ ...device,+ interval: response.interval || device.interval,+ expires_at: response.expires_at || device.expires_at,+ };+ this.devices = { ...this.devices, [providerId]: updatedDevice };+ if (providerId === CODEX_PROVIDER) this.device = updatedDevice;+ nextDelay = Math.max(1500, Number(updatedDevice.interval || 5) * 1000);+ }} catch (error) {if (this.connectingProvider === providerId) this.connectingProvider = "";this.connecting = Boolean(this.connectingProvider);@@ -789,17 +813,21 @@ export const store = createStore("oauthConfig", {void toastFrontendError(messageOf(error), "OAuth Connections");return;}- if (Date.now() - Number(this.pollStartedAt[providerId] || 0) > MAX_POLL_MS) {+ const expiresAt = Number(this.devices[providerId]?.expires_at || 0);+ const timedOut = expiresAt > 0+ ? Date.now() / 1000 > expiresAt+ : Date.now() - Number(this.pollStartedAt[providerId] || 0) > MAX_POLL_MS;+ if (timedOut) {if (this.connectingProvider === providerId) this.connectingProvider = "";this.connecting = Boolean(this.connectingProvider);this.clearProviderDevice(providerId);this.stopPolling(providerId);+ return;}+ schedule(nextDelay);};- const delay = Math.max(1500, Number(this.devices[providerId]?.interval || 5) * 1000);- this.pollTimers = { ...this.pollTimers, [providerId]: window.setInterval(tick, delay) };- if (providerId === CODEX_PROVIDER) this.pollTimer = this.pollTimers[providerId];- void tick();+ const initialDelay = Math.max(1500, Number(this.devices[providerId]?.interval || 5) * 1000);+ schedule(initialDelay);},pollProvider(providerId = CODEX_PROVIDER) {@@ -834,7 +862,7 @@ export const store = createStore("oauthConfig", {stopPolling(providerId = "") {if (providerId) {- if (this.pollTimers[providerId]) window.clearInterval(this.pollTimers[providerId]);+ if (this.pollTimers[providerId]) window.clearTimeout(this.pollTimers[providerId]);const timers = { ...this.pollTimers };delete timers[providerId];this.pollTimers = timers;@@ -846,7 +874,7 @@ export const store = createStore("oauthConfig", {}for (const timer of Object.values(this.pollTimers || {})) {- if (timer) window.clearInterval(timer);+ if (timer) window.clearTimeout(timer);}this.pollTimers = {};this.pollStartedAt = {};diff --git a/tests/test_oauth_providers.py b/tests/test_oauth_providers.pyindex baf1da369..155c2bcba 100644--- a/tests/test_oauth_providers.py+++ b/tests/test_oauth_providers.py@@ -540,7 +540,7 @@ def test_manual_callback_dispatches_to_xai_provider_without_active_attempt():assert "no active xai grok sign-in attempt" in response["error"].lower()-def test_start_device_login_wrapper_calls_codex_provider(monkeypatch):+def test_start_device_login_wrapper_defaults_to_codex_provider(monkeypatch):calls = []class FakeProvider:@@ -576,6 +576,56 @@ def test_start_device_login_wrapper_calls_codex_provider(monkeypatch):assert response["attempt_id"] == "attempt-1"+def test_start_device_login_with_provider_id_calls_github_provider(monkeypatch):+ calls = []++ class FakeProvider:+ def start_login(self, input, request):+ calls.append((input, request))+ return LoginStartResult(+ ok=True,+ provider_id=GITHUB_COPILOT_PROVIDER_ID,+ flow="device_code",+ attempt_id="github-attempt-1",+ verification_url="https://github.com/login/device",+ user_code="1234-5678",+ )++ monkeypatch.setattr(+ start_device_login_api,+ "get_provider",+ lambda provider_id: calls.append(("provider_id", provider_id)) or FakeProvider(),+ )++ request = FakeRequest()+ payload = {"provider_id": GITHUB_COPILOT_PROVIDER_ID, "enterprise_domain": ""}+ response = asyncio.run(+ start_device_login_api.StartDeviceLogin(None, None).process(payload, request)+ )++ assert calls[0] == ("provider_id", GITHUB_COPILOT_PROVIDER_ID)+ assert calls[1] == (payload, request)+ assert response["ok"] is True+ assert response["provider_id"] == GITHUB_COPILOT_PROVIDER_ID+ assert response["flow"] == "device_code"+ assert response["attempt_id"] == "github-attempt-1"+ assert response["verification_url"] == "https://github.com/login/device"+ assert response["user_code"] == "1234-5678"+++def test_start_device_login_unknown_provider_returns_structured_error():+ response = asyncio.run(+ start_device_login_api.StartDeviceLogin(None, None).process(+ {"provider_id": "missing"},+ FakeRequest(),+ )+ )++ assert response["ok"] is False+ assert response["provider_id"] == "missing"+ assert "Unknown OAuth provider" in response["error"]++def test_poll_device_login_wrapper_calls_codex_provider(monkeypatch):calls = []diff --git a/tests/test_oauth_static.py b/tests/test_oauth_static.pyindex fe9eb0b7d..155681e68 100644--- a/tests/test_oauth_static.py+++ b/tests/test_oauth_static.py@@ -126,6 +126,21 @@ def test_browser_callback_completion_is_observed_from_modal():assert "this.providerConnected(providerId)" in store_js+def test_device_polling_honors_provider_interval_updates():+ store_js = (PROJECT_ROOT / "plugins/_oauth/webui/oauth-config-store.js").read_text(encoding="utf-8")++ start_polling = store_js.split("startPolling(providerId = CODEX_PROVIDER)", 1)[1].split(+ "pollProvider(providerId = CODEX_PROVIDER)",+ 1,+ )[0]+ assert "window.setTimeout(tick, delayMs)" in start_polling+ assert "window.setInterval(tick" not in start_polling+ assert "void tick();" not in start_polling+ assert "interval: response.interval || device.interval" in start_polling+ assert "expires_at: response.expires_at || device.expires_at" in start_polling+ assert "Date.now() / 1000 > expiresAt" in start_polling++def test_usage_plan_catalog_stays_backend_only_on_oauth_settings_page():config_html = (PROJECT_ROOT / "plugins/_oauth/webui/config.html").read_text(encoding="utf-8")store_js = (PROJECT_ROOT / "plugins/_oauth/webui/oauth-config-store.js").read_text(encoding="utf-8")