Agent Zero AI framework
fix(oauth): guide Codex reconnection and add sign-in code copying
Alessandro45b74ab7cf0b
diff --git a/plugins/_oauth/AGENTS.md b/plugins/_oauth/AGENTS.mdindex 6db82efd5..74eb7c841 100644--- a/plugins/_oauth/AGENTS.md+++ b/plugins/_oauth/AGENTS.md@@ -17,7 +17,7 @@- `helpers/routes.py` owns local OAuth callback and OpenAI-compatible proxy routes mounted by the route bootstrap extension.- `webui/config.html` and `webui/oauth-config-store.js` own the OAuth Connections settings UI.- `extensions/python/_functions/models/get_api_key/end/` owns the dummy API-key extension used by OAuth model providers.-- `tests/test_oauth_*.py` own provider contract, security, static UI, and compatibility regressions.+- `tests/test_oauth_*.py` and `tests/test_oauth_reconnect.mjs` own provider contract, security, UI, and compatibility regressions.## Local Contracts@@ -27,6 +27,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.+- Device challenge codes use a selectable standalone box and an accessible copy button, reusing the shared clipboard helper and OAuth notifications for feedback.- 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`.- When exactly one OAuth provider is connected, use it as an unsaved default only for empty slots or slots already using that provider. A different saved provider must keep the explicit `Choose connected provider` prompt until the user opts into the switch.@@ -69,10 +70,13 @@- Treat Gemini API OAuth as a Google Cloud OAuth-client flow. Do not conflate it with Antigravity, Gemini Code Assist, Gemini CLI, Google AI Pro, or Google AI Ultra subscription quota.- Treat Claude Code subscription auth and Antigravity product auth as non-connectable unless their vendors provide an explicit third-party provider contract.- Keep user-facing errors safe: report setup or tier restrictions without exposing tokens, callback secrets, or raw auth payloads.+- Codex refresh-token rejection raises a safe `reconnect_required` HTTP 401, marks the private auth file, and sends one actionable notification per failed connection. Marked credentials must not refresh again until successful sign-in replaces them or disconnect clears them; transient upstream failures must not mark credentials. Status retains account metadata and exposes `reconnect_required`.+- Codex Reconnect reuses device sign-in without deleting stored credentials or model choices. Pending device controls remain visible for connected accounts; only successful sign-in replaces tokens and clears the reconnect marker.## Verification- Run `pytest tests/test_oauth_*.py` after backend provider, route, token, or UI contract changes.+- Run `node tests/test_oauth_reconnect.mjs` after changing reconnect, pending-auth controls, or cancellation.- Run `pytest tests/test_plugin_scan_prompt.py` after plugin structure, extension, or docs changes.- Run onboarding or model-config tests when provider metadata, `api_key_mode`, or model-provider config changes.- Run `git diff --check` before committing.diff --git a/plugins/_oauth/README.md b/plugins/_oauth/README.mdindex 6ebc68eef..ce576dd61 100644--- a/plugins/_oauth/README.md+++ b/plugins/_oauth/README.md@@ -15,8 +15,10 @@ OAuth-backed model providers do not require users to enter API keys. Agent Zero### Codex/ChatGPT (`codex_oauth`)- Uses the existing Codex device-code flow.+- Shows the sign-in code in a selectable box with a copy button.- Writes Codex-compatible credentials to an Agent Zero-owned `auth.json` file.- Refreshes local tokens when needed.+- If a refresh token expires or is revoked, shows an **Open OAuth settings** toast. Choose **Reconnect** on the Codex row and complete sign-in, then retry your request. No manual disconnect is needed; cancelling sign-in preserves the saved credentials and model choices.- Exposes the local OpenAI-compatible wrapper at `/oauth/codex/v1`.- Lets users choose default reasoning effort, visible reasoning summaries, and answer verbosity while preserving explicit per-request settings.diff --git a/plugins/_oauth/helpers/codex.py b/plugins/_oauth/helpers/codex.pyindex 1175082b0..a03b1ced1 100644--- a/plugins/_oauth/helpers/codex.py+++ b/plugins/_oauth/helpers/codex.py@@ -23,6 +23,7 @@ import requestsfrom helpers import filesfrom plugins._oauth.helpers.config import codex_config+from plugins._oauth.helpers.providers.base import ProviderErrortry:import fcntl@@ -59,6 +60,7 @@ CLIENT_METADATA_KEYS = ("priority",)OAUTH_ERROR_KEYS = ("error_description", "error")+RECONNECT_MESSAGE = "Your Codex session has expired or was revoked. Reconnect your account to continue."DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60WINDOWS_LOCK_RETRY_SECONDS = 0.05USAGE_ENDPOINT_PATHS = (@@ -86,6 +88,7 @@ class EffectiveAuth:refresh_token: str = ""source_path: str = ""last_refresh: str = ""+ reconnect_required: bool = Falsedef generate_pkce() -> PkcePair:@@ -291,9 +294,20 @@ def load_auth(*, ensure_fresh: bool = True) -> EffectiveAuth:refresh_token = _string(tokens.get("refresh_token"))account_id = _string(tokens.get("account_id")) or derive_account_id(id_token)last_refresh = _string(data.get("last_refresh")) if isinstance(data, dict) else ""+ reconnect_required = bool(data.get("reconnect_required"))++ if ensure_fresh and reconnect_required:+ raise ProviderError(RECONNECT_MESSAGE, status=401, code="reconnect_required")if ensure_fresh and refresh_token and should_refresh(access_token, last_refresh):- refreshed = refresh_tokens(refresh_token)+ try:+ refreshed = refresh_tokens(refresh_token)+ except ProviderError as exc:+ if exc.code == "reconnect_required":+ data["reconnect_required"] = True+ _write_auth_file_unlocked(path, data)+ _notify_reconnect_required()+ raiseaccess_token = refreshed.get("access_token") or access_tokenid_token = refreshed.get("id_token") or id_tokenrefresh_token = refreshed.get("refresh_token") or refresh_token@@ -320,6 +334,7 @@ def load_auth(*, ensure_fresh: bool = True) -> EffectiveAuth:refresh_token=refresh_token,source_path=str(path),last_refresh=last_refresh,+ reconnect_required=reconnect_required,)@@ -351,6 +366,7 @@ def status() -> dict[str, Any]:result.update({"connected": True,+ "reconnect_required": auth.reconnect_required,"auth_file_path": auth.source_path,"account_id": auth.account_id,"email": id_claims.get("email")@@ -363,6 +379,9 @@ def status() -> dict[str, Any]:)try:result["usage"] = fetch_usage()+ except ProviderError as exc:+ result["reconnect_required"] = exc.code == "reconnect_required"+ result["usage"] = {"available": False, "error": str(exc)}except Exception as exc:result["usage"] = {"available": False, "error": str(exc)}return result@@ -394,6 +413,7 @@ def disconnect_auth() -> dict[str, Any]:cleaned = dict(data)cleaned.pop("tokens", None)cleaned.pop("last_refresh", None)+ cleaned.pop("reconnect_required", None)if _string(cleaned.get("auth_mode")).lower() == "chatgpt":cleaned.pop("auth_mode", None)@@ -537,7 +557,18 @@ def refresh_tokens(refresh_token: str) -> dict[str, str]:timeout=30,)if not response.ok:- raise RuntimeError(_token_error_message(response))+ try:+ payload = response.json()+ except ValueError:+ payload = {}+ error = payload.get("error") if isinstance(payload, dict) else None+ code = (error.get("code") or error.get("type")) if isinstance(error, dict) else error+ message = _token_error_message(response)+ if code in (+ "invalid_grant", "refresh_token_expired", "refresh_token_reused", "refresh_token_invalidated",+ ) or "invalid refresh token" in message.lower():+ raise ProviderError(RECONNECT_MESSAGE, status=401, code="reconnect_required")+ raise RuntimeError(message)payload = response.json()if not isinstance(payload, dict):@@ -550,6 +581,22 @@ def refresh_tokens(refresh_token: str) -> dict[str, str]:}+def _notify_reconnect_required() -> None:+ from helpers.notification import NotificationManager, NotificationPriority, NotificationType++ NotificationManager.send_notification(+ type=NotificationType.WARNING,+ priority=NotificationPriority.HIGH,+ title="Reconnect Codex",+ message=RECONNECT_MESSAGE + """+<div class="toast-action-row"><button type="button" class="button confirm"[email protected]="(await import('/components/plugins/plugin-settings-store.js')).store.openConfig('_oauth'); $store.notificationStore.dismissToast('toast-oauth-codex-reconnect')">Open OAuth settings</button></div>""",+ display_time=0,+ id="oauth-codex-reconnect",+ group="oauth-codex-reconnect",+ )++def resolve_agent_zero_user_agent() -> str:try:from helpers import gitdiff --git a/plugins/_oauth/helpers/routes.py b/plugins/_oauth/helpers/routes.pyindex 7c75cca1f..7313d82f9 100644--- a/plugins/_oauth/helpers/routes.py+++ b/plugins/_oauth/helpers/routes.py@@ -129,6 +129,8 @@ def codex_responses():body=json.dumps(upstream_body),stream=True,)+ except ProviderError as exc:+ return _json_error(str(exc), status=exc.status, code=exc.code)except Exception as exc:return _json_error(str(exc), status=502, code="upstream_error")@@ -170,6 +172,8 @@ def codex_chat_completions():body=json.dumps(codex.prepare_responses_body(response_body, force_stream=True)),stream=True,)+ except ProviderError as exc:+ return _json_error(str(exc), status=exc.status, code=exc.code)except Exception as exc:return _json_error(str(exc), status=502, code="upstream_error")diff --git a/plugins/_oauth/webui/config.html b/plugins/_oauth/webui/config.htmlindex f650a6dab..974e9cb24 100644--- a/plugins/_oauth/webui/config.html+++ b/plugins/_oauth/webui/config.html@@ -30,24 +30,24 @@<template x-for="card in $store.oauthConfig.providerCards()" :key="card.provider_id"><articleclass="oauth-provider-row"- :class="{ selected: $store.oauthConfig.selectedProviderId === card.provider_id, connected: card.connected }"+ :class="{ selected: $store.oauthConfig.selectedProviderId === card.provider_id, connected: card.connected && !card.reconnect_required }"@click="$store.oauthConfig.selectProvider(card.provider_id)">- <span class="oauth-mark" :class="{ connected: card.connected }">- <x-icon :name="card.connected ? 'check' : card.mark"></x-icon>+ <span class="oauth-mark" :class="{ connected: card.connected && !card.reconnect_required }">+ <x-icon :name="card.connected && !card.reconnect_required ? 'check' : card.mark"></x-icon></span><div class="oauth-provider-row-copy"><strong x-text="card.display_name"></strong><span x-text="$store.oauthConfig.providerReadinessLabel(card.provider_id)"></span></div>- <span class="oauth-account-state connected" x-show="card.connected">Connected</span>+ <span class="oauth-account-state connected" x-show="card.connected && !card.reconnect_required">Connected</span><div class="oauth-row-actions"><buttonclass="oauth-connect compact"type="button"@click.stop="$store.oauthConfig.handleProviderPrimary(card.provider_id)":disabled="$store.oauthConfig.providerPrimaryDisabled(card.provider_id)"- x-show="!card.connected"+ x-show="!card.connected || card.provider_id === 'codex_oauth'"><x-icon :name="$store.oauthConfig.connectingProvider === card.provider_id ? 'progress_activity' : ($store.oauthConfig.providerSetupReady(card.provider_id) ? 'login' : 'tune')"></x-icon><span x-text="$store.oauthConfig.providerPrimaryLabel(card.provider_id)"></span>@@ -56,7 +56,7 @@class="oauth-connect danger compact"type="button"@click.stop="$store.oauthConfig.disconnectProvider(card.provider_id)"- :disabled="$store.oauthConfig.disconnectingProvider === card.provider_id"+ :disabled="$store.oauthConfig.providerPrimaryDisabled(card.provider_id)"x-show="card.connected"><x-icon :name="$store.oauthConfig.disconnectingProvider === card.provider_id ? 'progress_activity' : 'link_off'"></x-icon>@@ -164,7 +164,12 @@<div class="oauth-device" x-show="$store.oauthConfig.providerDevice(card.provider_id)?.user_code"><span>Enter this code</span>- <strong x-text="$store.oauthConfig.providerDevice(card.provider_id)?.user_code"></strong>+ <div class="oauth-device-code">+ <code x-text="$store.oauthConfig.providerDevice(card.provider_id)?.user_code"></code>+ <button class="oauth-icon-button" type="button" title="Copy sign-in code" aria-label="Copy sign-in code" @click="$store.oauthConfig.copyDeviceCode(card.provider_id)">+ <x-icon name="content_copy"></x-icon>+ </button>+ </div><button class="text-button" type="button" @click="$store.oauthConfig.cancelConnect(card.provider_id)"><x-icon name="close"></x-icon><span>Cancel</span>@@ -716,9 +721,23 @@font-weight: 700;}- .oauth-device strong {+ .oauth-device-code {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding: 8px 12px;+ border: 1px solid var(--color-border);+ border-radius: 8px;+ background: var(--color-background);+ color: var(--color-text);+ }++ .oauth-device-code code {font-size: 1.12rem;- letter-spacing: 0;+ font-weight: 700;+ letter-spacing: 0.06em;+ user-select: all;}.oauth-usage-window {diff --git a/plugins/_oauth/webui/oauth-config-store.js b/plugins/_oauth/webui/oauth-config-store.jsindex 36ebb64db..bbe8a8d39 100644--- a/plugins/_oauth/webui/oauth-config-store.js+++ b/plugins/_oauth/webui/oauth-config-store.js@@ -1,7 +1,9 @@import { createStore } from "/js/AlpineStore.js";import { callJsonApi, fetchApi } from "/js/api.js";+import { copyToClipboard } from "/components/messages/action-buttons/simple-action-buttons.js";import { store as modelConfigStore } from "/plugins/_model_config/webui/model-config-store.js";import {+ store as notificationStore,toastFrontendError,toastFrontendInfo,toastFrontendSuccess,@@ -309,6 +311,17 @@ export const store = createStore("oauthConfig", {return this.devices[String(providerId || "")] || null;},+ async copyDeviceCode(providerId) {+ const code = this.providerDevice(providerId)?.user_code;+ if (!code) return;+ try {+ await copyToClipboard(code);+ void toastFrontendSuccess("Sign-in code copied.", "OAuth Connections");+ } catch {+ void toastFrontendError("Could not copy the code. Select it and copy manually.", "OAuth Connections");+ }+ },+providerShowSetupFields(providerId) {if (this.providerConnected(providerId)) return false;if (this.providerDevice(providerId)) return false;@@ -322,8 +335,9 @@ export const store = createStore("oauthConfig", {},providerDetailOpen(providerId) {- if (!this.isOauthProvider(providerId) || this.providerConnected(providerId)) return false;+ if (!this.isOauthProvider(providerId)) return false;if (this.providerDevice(providerId)) return true;+ if (this.providerConnected(providerId)) return false;const status = this.providerStatus(providerId);return this.selectedProviderId === providerId && Boolean(status.supports_enterprise_domain@@ -336,6 +350,7 @@ export const store = createStore("oauthConfig", {providerReadinessLabel(providerId) {const status = this.providerStatus(providerId);if (this.loadingStatus) return "Checking";+ if (status.reconnect_required) return "Sign in again to continue";if (status.connected) return this.providerStatusLabel(providerId);if (!this.providerSetupReady(providerId)) return "Needs OAuth client details";if (status.warning) return "Available with restrictions";@@ -357,6 +372,7 @@ export const store = createStore("oauthConfig", {providerPrimaryLabel(providerId) {if (this.connectingProvider === providerId) return "Waiting";+ if (providerId === CODEX_PROVIDER && this.providerConnected(providerId)) return "Reconnect";return this.providerSetupReady(providerId) ? "Connect" : "Configure";},@@ -715,6 +731,7 @@ export const store = createStore("oauthConfig", {async handleProviderConnected(providerId, { statusLoaded = false } = {}) {if (!statusLoaded) await this.loadStatus();+ if (providerId === CODEX_PROVIDER) notificationStore.dismissToast("toast-oauth-codex-reconnect");this.notifyModelSetupChanged(providerId);},@@ -756,7 +773,7 @@ export const store = createStore("oauthConfig", {},async connectProvider(providerId) {- if (!this.isOauthProvider(providerId) || this.connectingProvider) return;+ if (this.providerPrimaryDisabled(providerId)) return;this.connectingProvider = providerId;this.connecting = true;try {diff --git a/tests/test_oauth_codex.py b/tests/test_oauth_codex.pyindex 585770d4b..fee9e8bcf 100644--- a/tests/test_oauth_codex.py+++ b/tests/test_oauth_codex.py@@ -703,6 +703,93 @@ def test_token_error_message_prefers_description():assert codex._token_error_message(FakeResponse()) == "refresh token was already used"[email protected]("error", [+ {"error": {"code": "upstream_error", "message": "Invalid refresh token."}},+ {"error": "invalid_grant", "error_description": "private upstream detail"},+ {"error": {"code": "refresh_token_reused", "message": "private upstream detail"}},+ {"error": {"code": "refresh_token_expired", "message": "private upstream detail"}},+ {"error": {"code": "refresh_token_invalidated", "message": "private upstream detail"}},+])+def test_rejected_refresh_notifies_once_and_recovers_after_sign_in(tmp_path, monkeypatch, error):+ from helpers.notification import NotificationManager++ path = tmp_path / "auth.json"+ auth = {+ "tokens": {"access_token": "old-access", "refresh_token": "old-refresh", "account_id": "account"},+ "last_refresh": "2000-01-01T00:00:00Z",+ }+ path.write_text(json.dumps(auth))+ monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: path)+ monkeypatch.setattr(codex, "codex_config", lambda: {+ "token_url": "https://auth.example/token", "client_id": "client", "forced_workspace_id": "",+ })+ monkeypatch.setattr(codex, "resolve_agent_zero_user_agent", lambda: "test")+ refresh_calls, notifications = [], []+ monkeypatch.setattr(codex.requests, "post", lambda *a, **kw: refresh_calls.append(kw) or SimpleNamespace(+ ok=False, status_code=400, text=json.dumps(error), json=lambda: error,+ ))+ monkeypatch.setattr(NotificationManager, "send_notification", lambda **kw: notifications.append(kw))++ for _ in range(2):+ with pytest.raises(codex.ProviderError, match="Reconnect your account") as failure:+ codex.load_auth()+ assert failure.value.status == 401+ assert failure.value.code == "reconnect_required"+ assert len(refresh_calls) == len(notifications) == 1+ saved = json.loads(path.read_text())+ assert saved["tokens"] == auth["tokens"]+ assert saved["reconnect_required"] is True+ status = codex.status()+ assert status["connected"] is True+ assert status["reconnect_required"] is True+ assert len(refresh_calls) == len(notifications) == 1+ message = notifications[0]["message"]+ assert "Open OAuth settings" in message and "openConfig('_oauth')" in message+ assert "private upstream detail" not in message and "old-refresh" not in message++ monkeypatch.setattr(codex, "derive_account_id", lambda _: "account")+ monkeypatch.setattr(codex, "obtain_api_key", lambda _: "")+ monkeypatch.setattr(codex, "fetch_usage", lambda: {"available": False})+ codex.persist_exchanged_tokens({"id_token": "new-id", "access_token": "new-access", "refresh_token": "new-refresh"})+ assert codex.load_auth().access_token == "new-access"+ assert codex.status()["reconnect_required"] is False+ assert "reconnect_required" not in json.loads(path.read_text())+++def test_transient_refresh_failure_does_not_require_reconnect(tmp_path, monkeypatch):+ path = tmp_path / "auth.json"+ _write_refreshable_auth(path)+ original = path.read_text()+ monkeypatch.setattr(codex, "resolve_auth_write_path", lambda: path)+ monkeypatch.setattr(codex, "codex_config", lambda: {"token_url": "https://auth.example/token", "client_id": "client"})+ monkeypatch.setattr(codex, "resolve_agent_zero_user_agent", lambda: "test")+ monkeypatch.setattr(codex.requests, "post", lambda *a, **kw: SimpleNamespace(+ ok=False, status_code=503, text="unavailable", json=lambda: {"error": "temporarily_unavailable"},+ ))+ with pytest.raises(RuntimeError, match="temporarily_unavailable"):+ codex.load_auth()+ assert path.read_text() == original++[email protected]("route", [routes.codex_models, routes.codex_responses, routes.codex_chat_completions])[email protected]("stream", [False, True])+def test_codex_routes_preserve_reconnect_error(monkeypatch, route, stream):+ from flask import Flask++ def rejected(*args, **kwargs):+ raise codex.ProviderError(codex.RECONNECT_MESSAGE, status=401, code="reconnect_required")++ monkeypatch.setattr(routes, "_proxy_denied_response", lambda: None)+ monkeypatch.setattr(codex, "prepare_responses_body", lambda body, **kw: body)+ monkeypatch.setattr(codex, "fetch_models", rejected)+ monkeypatch.setattr(codex, "request_codex", rejected)+ with Flask(__name__).test_request_context("/", method="POST", json={"model": "test", "messages": [], "stream": stream}):+ response, status = route()+ assert status == 401+ assert response.json["error"]["code"] == "reconnect_required"+ assert response.json["error"]["message"] == codex.RECONNECT_MESSAGE++def test_refresh_tokens_sends_agent_zero_user_agent(monkeypatch):requests: list[dict] = []@@ -1045,6 +1132,7 @@ def test_disconnect_auth_only_mutates_agent_zero_private_auth_file(tmp_path, mon{"auth_mode": "chatgpt","OPENAI_API_KEY": "sk-keep",+ "reconnect_required": True,"tokens": {"access_token": "access","refresh_token": "refresh",diff --git a/tests/test_oauth_reconnect.mjs b/tests/test_oauth_reconnect.mjsnew file mode 100644index 000000000..e53823e1f--- /dev/null+++ b/tests/test_oauth_reconnect.mjs@@ -0,0 +1,63 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import vm from 'node:vm';++const requests = [];+const timers = new Map();+const dismissed = [];+const copied = [];+const feedback = [];+let clipboardDenied = false;+const source = readFileSync(new URL('../plugins/_oauth/webui/oauth-config-store.js', import.meta.url), 'utf8')+ .replace(/^import [\s\S]*? from .*;\n/gm, '').replace('export const store', 'const store');+const store = vm.runInNewContext(`${source}\nstore`, {+ createStore: (_name, value) => value,+ callJsonApi: async (url, payload) => {+ requests.push({ url, payload });+ assert.ok(url.endsWith('/start_login'));+ return { ok: true, flow: 'device_code', attempt_id: 'test', user_code: 'TEST', verification_url: 'https://example.com', interval: 5 };+ },+ window: {+ open() {},+ setTimeout: fn => { timers.set(1, fn); return 1; },+ clearTimeout: id => timers.delete(id),+ },+ toastFrontendInfo() {},+ toastFrontendSuccess: message => feedback.push(message),+ toastFrontendError: message => feedback.push(message),+ copyToClipboard: async code => {+ if (clipboardDenied) throw new Error('Permission denied');+ copied.push(code);+ },+ notificationStore: { dismissToast: id => dismissed.push(id) },+});+const provider = 'codex_oauth';+store.status = { provider_map: { [provider]: { provider_id: provider, connected: true, reconnect_required: true } } };+store.modelConfig = { chat_model: { provider, name: 'chosen-model' } };+assert.equal(store.providerPrimaryLabel(provider), 'Reconnect');+assert.equal(store.providerReadinessLabel(provider), 'Sign in again to continue');+assert.equal(store.providerDetailOpen(provider), false);+await store.connectProvider(provider);+assert.equal(store.providerPrimaryLabel(provider), 'Waiting');+assert.equal(store.providerDetailOpen(provider), true);+assert.equal(store.providerDevice(provider).user_code, 'TEST');+await store.copyDeviceCode(provider);+assert.deepEqual(copied, ['TEST']);+assert.equal(feedback.pop(), 'Sign-in code copied.');+clipboardDenied = true;+await store.copyDeviceCode(provider);+assert.equal(feedback.pop(), 'Could not copy the code. Select it and copy manually.');+assert.equal(timers.size, 1);+await store.connectProvider(provider);+assert.equal(requests.length, 1);+store.cancelConnect(provider);+assert.equal(timers.size, 0);+assert.equal(store.providerDevice(provider), null);+await store.copyDeviceCode(provider);+assert.equal(copied.length, 1);+assert.equal(feedback.length, 0);+assert.equal(store.providerConnected(provider), true);+assert.equal(store.modelConfig.chat_model.name, 'chosen-model');+assert.equal(store.providerPrimaryLabel(provider), 'Reconnect');+await store.handleProviderConnected(provider, { statusLoaded: true });+assert.deepEqual(dismissed, ['toast-oauth-codex-reconnect']);diff --git a/tests/test_oauth_static.py b/tests/test_oauth_static.pyindex 00360b57d..875c2c285 100644--- a/tests/test_oauth_static.py+++ b/tests/test_oauth_static.py@@ -46,7 +46,7 @@ def test_oauth_settings_exposes_provider_specific_controls_and_generic_copy():assert "Check models" not in config_htmlassert "card.connected ? 'Connected' : 'Available'" not in config_html- assert '<span class="oauth-account-state connected" x-show="card.connected">Connected</span>' in config_html+ assert '<span class="oauth-account-state connected" x-show="card.connected && !card.reconnect_required">Connected</span>' in config_htmlassert "Select account-backed models used by the Main model and Utility model slots." not in config_htmlassert "Primary model for chat, reasoning, and browser tasks." not in config_html + store_jsassert "Background model for summaries, memory, and prompt preparation." not in config_html + store_js