Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): keep mis-pasted OAuth callbacks recoverable and name why sign-in failed (#2377)
Call White51e133074462
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 29a68f361..de36f6b43 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -107,7 +107,19 @@ class OriginNotAllowedError(Exception):class OAuthSubmissionRejectedError(Exception):"""Raised by ``submit_oauth`` when the provider refuses the pasted valuebefore touching the flow. Nothing was written and the flow still awaits a- submission, so the user can paste again on the same flow."""+ submission, so the user can paste again on the same flow.++ ``reason`` names what to paste instead: ``no_answer`` is an address that+ carries no provider answer; ``other_attempt`` answers a different sign-in+ link than this flow's, whose code this flow can never exchange."""++ def __init__(+ self,+ flow_id: str,+ reason: Literal["no_answer", "other_attempt"] = "no_answer",+ ) -> None:+ super().__init__(flow_id)+ self.reason = reasonclass InvokeCancelledError(asyncio.CancelledError):@@ -391,6 +403,10 @@ class OAuthFlowState:channel: Literal["hub", "native_cli"] = "hub"retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONEretained_credential_ref: str | None = None+ # What the provider, engine, or native CLI said when the flow failed,+ # verbatim on one bounded line, for display beside ``error_key``. Null in+ # every other state and whenever there is nothing to add to the key.+ error_detail: str | None = Noneclass InvokeHandle(Protocol):diff --git a/core/handlers/model_hub/native_oauth.py b/core/handlers/model_hub/native_oauth.pyindex 163a6b278..0f60603e2 100644--- a/core/handlers/model_hub/native_oauth.py+++ b/core/handlers/model_hub/native_oauth.py@@ -10,7 +10,7 @@ from typing import Any, Callable, Mapping, Protocolfrom .adapter import OAuthFlowState, RetainedMaterialDispositionfrom .events import contains_credential_material-from .oauth import NativeOAuthSourceStatus, NativeOAuthUnavailableError+from .oauth import NativeOAuthSourceStatus, NativeOAuthUnavailableError, oauth_failure_detail_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}_INSTRUCTIONS_KEYS = {@@ -275,8 +275,11 @@ class AgentAuthNativeOAuthAdapter:account_label=resolved.account_label,)error_key = None+ error_detail = Noneif state == "failed":error_key = _TIMEOUT_ERROR_KEY if payload.get("error") == "timed_out" else _GENERIC_ERROR_KEY+ if error_key == _GENERIC_ERROR_KEY:+ error_detail = oauth_failure_detail(payload.get("error"))elif state == "cancelled":error_key = _GENERIC_ERROR_KEY@@ -299,6 +302,7 @@ class AgentAuthNativeOAuthAdapter:channel="native_cli",retained_material_disposition=RetainedMaterialDisposition.NONE,retained_credential_ref=None,+ error_detail=error_detail,)async def _read_source_status(self, backend: str) -> NativeOAuthSourceStatus:diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.pyindex be7e995ab..677bd3f92 100644--- a/core/handlers/model_hub/oauth.py+++ b/core/handlers/model_hub/oauth.py@@ -17,6 +17,28 @@ from .state_file import write_state_documentOAuthChannel = Literal["native_cli", "hub"]OAuthNonceStatus = Literal["released", "in_flight", "committed"]_CLIENT_NONCE_PATTERN = re.compile(r"^ofn_[a-z0-9]{16,64}$")+OAUTH_FAILURE_DETAIL_CHARS = 1000+++def oauth_failure_detail(value: object) -> str | None:+ """A failed sign-in's own reason, verbatim on one line and bounded.++ The reasons are the pinned engine's session errors (whose only quoted cause+ is the provider's OAuth error response — ``error``, ``error_description``,+ ``error_uri`` — or a transport error) and the native CLI's last output line.+ None of them carries grant material, so they are shown as written: the+ user's copy is only useful if it is what the provider said. Blank or+ non-text input has no detail.+ """++ if not isinstance(value, str):+ return None+ text = " ".join(value.split())+ if not text:+ return None+ if len(text) > OAUTH_FAILURE_DETAIL_CHARS:+ text = text[: OAUTH_FAILURE_DETAIL_CHARS - 1].rstrip() + "…"+ return textNATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY = "settings.models.source.oauthSignedOut"diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 487725b99..3357e489a 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -909,6 +909,8 @@ def _oauth_payload(}if client_nonce is not None:payload["client_nonce"] = client_nonce+ if flow.state == "failed" and flow.error_detail:+ payload["error_detail"] = flow.error_detailreturn payload@@ -1261,8 +1263,16 @@ class ModelHubService:status=409,detail="modelHub.errors.native_login_in_progress",) from None- except OAuthSubmissionRejectedError:- raise ModelHubError("submission_rejected", status=422) from None+ except OAuthSubmissionRejectedError as error:+ raise ModelHubError(+ "submission_rejected",+ status=422,+ detail=(+ "modelHub.errors.submission_rejected_other_attempt"+ if error.reason == "other_attempt"+ else None+ ),+ ) from Noneexcept ModelHubError:raiseexcept Exception as error:diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 29a68f361..de36f6b43 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -107,7 +107,19 @@ class OriginNotAllowedError(Exception):class OAuthSubmissionRejectedError(Exception):"""Raised by ``submit_oauth`` when the provider refuses the pasted valuebefore touching the flow. Nothing was written and the flow still awaits a- submission, so the user can paste again on the same flow."""+ submission, so the user can paste again on the same flow.++ ``reason`` names what to paste instead: ``no_answer`` is an address that+ carries no provider answer; ``other_attempt`` answers a different sign-in+ link than this flow's, whose code this flow can never exchange."""++ def __init__(+ self,+ flow_id: str,+ reason: Literal["no_answer", "other_attempt"] = "no_answer",+ ) -> None:+ super().__init__(flow_id)+ self.reason = reasonclass InvokeCancelledError(asyncio.CancelledError):@@ -391,6 +403,10 @@ class OAuthFlowState:channel: Literal["hub", "native_cli"] = "hub"retained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONEretained_credential_ref: str | None = None+ # What the provider, engine, or native CLI said when the flow failed,+ # verbatim on one bounded line, for display beside ``error_key``. Null in+ # every other state and whenever there is nothing to add to the key.+ error_detail: str | None = Noneclass InvokeHandle(Protocol):diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 9fe4bbe66..dc8b5745f 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -65,8 +65,8 @@ remain readable; ephemeral envelopes use only the terminal version.| GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report, plus each Source's API-price `value` (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline, and a Source still being read is listed in `pending`. Never starts the engine. || POST `/api/models/quota/refresh` | → `{quota: QuotaSummary}` | Forced re-read. Rate-limited per Source to one vendor call every 30 seconds and suppressed while a Source cools down after a vendor 429; a suppressed Source returns its cached snapshot. || POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |-| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. |-| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A value the provider refuses before writing anything (not a callback address, no `code`) is the non-terminal `422 submission_rejected`: the flow stays `awaiting_action` and accepts another submission until its `expires_at`. |+| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. A `failed` flow names its cause with the closed `error_key` and, when the provider, engine, or native CLI said more, carries that reason verbatim on one bounded line in `error_detail` for the dialog's copyable details. |+| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A callback address is recognized with or without its `http(s)://` scheme, which browsers drop when copying a page that failed to load; any other value is a bare code. An address the flow refuses before anything reaches the provider is the non-terminal `422 submission_rejected`: one with no `code` or `error`, or one whose `state` answers a different sign-in link than this flow's (`detail: modelHub.errors.submission_rejected_other_attempt`). The flow stays `awaiting_action` and accepts another submission until its `expires_at`. || POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. || POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It validates selected items before withdrawal, upgrades an existing native Source in place when present, commits Source/Routes/backend mode atomically, and removes only replaced native material. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. |diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.jsonindex 41e97d404..b062d048c 100644--- a/docs/plans/model-hub-contracts/oauth-flow.schema.json+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json@@ -33,7 +33,8 @@"instructions_key": { "type": ["string", "null"], "description": "i18n key for the step-2 helper line" }}},- "error_key": { "type": ["string", "null"], "description": "i18n key; raw upstream errors never surface" },+ "error_key": { "type": ["string", "null"], "description": "Closed i18n key for the user-facing sentence. The provider's own words never replace it; when there are any, they travel separately in `error_detail`." },+ "error_detail": { "type": "string", "minLength": 1, "maxLength": 1000, "description": "Present only on a failed flow whose provider, engine, or native CLI gave a reason beyond `error_key`: that reason verbatim, with whitespace collapsed to one line and bounded to 1000 characters. Its sources are the pinned engine's session errors (whose only quoted cause is the provider's OAuth error response or a transport error) and the native CLI's last output line; none carries grant material. Shown behind an expandable details control the user can copy. Never persisted." },"expires_at": { "type": ["string", "null"], "format": "date-time", "description": "Flow expiry. A flow without client_nonce may use null for ordinary or presentation-only lifetime handling; a nonce-bearing flow always carries a non-null date-time that bounds reconciliation and retained cancellation." }},"allOf": [diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex e73ccd819..05ccbb973 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -472,4 +472,18 @@ scenarios:- ui/src/components/onboarding/WizardCompletion.test.tsx- ui/src/components/onboarding/AssistantSetup.test.tsx- ui/e2e/onboarding-fidelity/provider-gate.spec.ts+ - id: AUTH-SETUP-127+ name: A mis-pasted Hub OAuth callback stays recoverable and a scheme-less callback address signs in+ status: covered+ kind: historical_regression+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_oauth_mispaste_stays_recoverable_and_schemeless_address_signs_in+ supporting_tests:+ - tests/test_model_hub_runtime.py::test_oauth_paste_reaches_the_engine_as_the_value_it_is+ - tests/test_model_hub_runtime.py::test_oauth_paste_that_cannot_exchange_keeps_the_flow_awaiting+ - tests/test_model_hub_runtime.py::test_oauth_engine_failure_names_what_the_user_can_do+ - tests/test_model_hub_runtime.py::test_oauth_failure_detail_is_the_engine_reason_on_one_bounded_line+ - ui/src/components/settings/models/serverCopy.test.ts+ - ui/src/components/settings/models/SettingsModelsPage.render.test.tsxnext_priority: []diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 5d149c7c5..1238bbe71 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -3971,6 +3971,128 @@ def test_hub_oauth_model_free_observation_closed_loop(ScenarioExpect.step_history(runner, ["start_login", "complete_consent", "materialize_source"])+def test_hub_oauth_mispaste_stays_recoverable_and_schemeless_address_signs_in(monkeypatch, tmp_path):+ """Scenario: AUTH-SETUP-127++ A user on another device pastes the callback address back. The first paste+ answers an earlier sign-in link; the second is the right address with its+ scheme dropped by the browser. Neither may end the flow: the first is refused+ before it reaches the provider, and the second signs in and materializes the+ subscription Source.+ """+ from core.handlers.model_hub.service import ModelHubError+ from tests.test_model_hub_api import _service+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+ from vibe.model_hub_runtime.state import EngineStateStore++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ state_store = EngineStateStore(tmp_path / "engine-state")+ auth_name = "codex-account-test-plus.json"+ engine = SimpleNamespace(files=[], callbacks=[], fields=[], signed_in=False)++ # The engine's side of the browser flow: it exchanges a callback only when+ # the address carries the code its own authorization issued, then saves+ # the grant as an auth file, the way CLIProxyAPI does.+ def management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return {"files": list(engine.files)}+ if path == "/codex-auth-url":+ return {+ "state": "browser-state",+ "url": "https://auth.openai.com/oauth/authorize?state=browser-state",+ }+ if path == "/get-auth-status":+ assert query == {"state": "browser-state"}+ return {"status": "ok" if engine.signed_in else "wait"}+ if path == "/oauth-callback":+ engine.callbacks.append(dict(payload))+ query_code = urllib.parse.parse_qs(urllib.parse.urlsplit(payload.get("redirect_url", "")).query).get("code")+ code = query_code[0] if query_code else payload.get("code")+ if code == "ac_issued":+ state_store._secure_write_json(+ state_store.auth_dir / auth_name,+ {"type": "codex", "access_token": "test-access", "refresh_token": "test-refresh"},+ )+ engine.files.append({+ "id": auth_name,+ "auth_index": "auth-index-test",+ "name": auth_name,+ "provider": "codex",+ "account": "[email protected]",+ "id_token": {"chatgpt_account_id": "account-test"},+ })+ engine.signed_in = True+ return {"status": "ok"}+ if (method, path) == ("PATCH", "/auth-files/fields"):+ engine.fields.append(dict(payload))+ return {"status": "ok"}+ raise AssertionError((method, path))++ client = Mock()+ client.management_request.side_effect = management_request+ supervisor = Mock()+ supervisor.client.return_value = client+ transport = CLIProxyEngineAdapter(supervisor=supervisor, state_store=state_store)+ service, store, adapter = _service(tmp_path)+ for method in ("start_oauth", "oauth_status", "submit_oauth", "cancel_oauth"):+ monkeypatch.setattr(adapter, method, getattr(transport, method))+ harness = SimpleNamespace()+ runner = ScenarioRunner(harness)++ async def start_login(h):+ started = await service.oauth_start({"vendor": "openai", "channel": "hub"})+ h.flow_id = started["flow"]["flow_id"]+ h.source_id = started["flow"]["source_id"]+ assert started["flow"]["presentation"]["expects"] == "paste_callback_url"++ async def paste_earlier_link_address(h):+ with pytest.raises(ModelHubError) as rejected:+ await service.oauth_submit({+ "flow_id": h.flow_id,+ "value": "http://localhost:1455/auth/callback?code=ac_old&state=earlier-state",+ })+ assert (rejected.value.code, rejected.value.status) == ("submission_rejected", 422)+ assert rejected.value.detail == "modelHub.errors.submission_rejected_other_attempt"+ assert engine.callbacks == []+ assert (await service.oauth_status(h.flow_id))["flow"]["state"] == "awaiting_action"++ async def paste_schemeless_address(h):+ await service.oauth_submit({+ "flow_id": h.flow_id,+ "value": "localhost:1455/auth/callback?code=ac_issued&scope=openid&state=browser-state",+ })+ assert engine.callbacks == [{+ "provider": "codex",+ "state": "browser-state",+ "redirect_url": "http://localhost:1455/auth/callback?code=ac_issued&scope=openid&state=browser-state",+ }]++ async def materialize_source(h):+ terminal = await service.oauth_status(h.flow_id)+ assert terminal["flow"]["state"] == "success"+ source = terminal["source"]+ assert source["id"] == h.source_id+ assert (source["vendor"], source["kind"], source["supply_channel"]) == ("openai", "subscription", "hub")+ credential_ref = state_store.oauth_credential_ref(auth_name)+ assert source["credential_ref"] == credential_ref+ assert engine.fields == [{+ "name": auth_name,+ "prefix": state_store.credential_metadata(credential_ref)["prefix"],+ }]+ assert [listed["id"] for listed in service.list_sources()] == [h.source_id]++ asyncio.run(runner.run(+ ScenarioStep("start_login", start_login),+ ScenarioStep("paste_earlier_link_address", paste_earlier_link_address),+ ScenarioStep("paste_schemeless_address", paste_schemeless_address),+ ScenarioStep("materialize_source", materialize_source),+ ))+ ScenarioExpect.step_history(+ runner,+ ["start_login", "paste_earlier_link_address", "paste_schemeless_address", "materialize_source"],+ )++@pytest.mark.parametrize("status", [401, 403])@pytest.mark.parametrize("policy_body", ["<html>Request blocked</html>", '{"message":"Regional policy"}'])@pytest.mark.parametrize("competing_protocol", [False, True])diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex e60f19811..6ee9ba808 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -74,6 +74,7 @@ from tests.ui_server_test_helpers import (save_config,)from vibe import backend_model_catalog, remote_access, ui_server+from vibe.i18n import t as i18n_tfrom vibe.model_hub_client import ModelHubRemoteService, _decodefrom vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalogfrom vibe.model_hub_runtime.state import EngineStateError, _validate_source_target@@ -9541,12 +9542,45 @@ def test_expired_oauth_flow_is_rejected_before_submit(tmp_path):assert service.oauth_flows.channel(flow["flow_id"]) is None-def test_rejected_oauth_submission_is_non_terminal_and_keeps_the_flow(tmp_path):[email protected]("error_detail", [None, "token exchange failed with status 401: token_expired"])+def test_failed_oauth_flow_carries_its_reason_only_when_there_is_one(tmp_path, error_detail):+ service, _, adapter = _service(tmp_path)+ flow_id = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))["flow"]["flow_id"]+ adapter.flows[flow_id] = OAuthFlowState(+ **{+ **adapter.flows[flow_id].__dict__,+ "state": "failed",+ "error_key": "models.oauth.code_rejected",+ "error_detail": error_detail,+ }+ )++ result = asyncio.run(service.oauth_status(flow_id))++ assert result["flow"]["error_key"] == "models.oauth.code_rejected"+ assert result["flow"].get("error_detail") == error_detail+ assert ("error_detail" in result["flow"]) is (error_detail is not None)+ validator = Draft7Validator(+ {"$ref": ("model-hub/api-response.schema.json#/definitions/OAuthResultResponse")},+ registry=_api_response_registry(),+ format_checker=FormatChecker(),+ )+ assert not list(validator.iter_errors({"ok": True, "contract_version": CONTRACT_VERSION, **result}))+++ ("reason", "detail"),+ [+ ("no_answer", "modelHub.errors.submission_rejected"),+ ("other_attempt", "modelHub.errors.submission_rejected_other_attempt"),+ ],+)+def test_rejected_oauth_submission_is_non_terminal_and_keeps_the_flow(tmp_path, reason, detail):service, _, adapter = _service(tmp_path)flow = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))["flow"]async def reject(_flow_id, _value):- raise OAuthSubmissionRejectedError(_flow_id)+ raise OAuthSubmissionRejectedError(_flow_id, reason)adapter.submit_oauth = rejectwith pytest.raises(ModelHubError) as exc_info:@@ -9554,6 +9588,10 @@ def test_rejected_oauth_submission_is_non_terminal_and_keeps_the_flow(tmp_path):assert exc_info.value.code == "submission_rejected"assert exc_info.value.status == 422+ # The detail tells the dialog what to paste instead, in both languages.+ assert exc_info.value.detail == detail+ for language in ("en", "zh"):+ assert i18n_t(detail, language) != detailassert service.oauth_flows.channel(flow["flow_id"]) == "hub"status = asyncio.run(service.oauth_status(flow["flow_id"]))assert status["flow"]["state"] == "awaiting_action"diff --git a/tests/test_model_hub_oauth.py b/tests/test_model_hub_oauth.pyindex 0f1d6ab09..9894c97cf 100644--- a/tests/test_model_hub_oauth.py+++ b/tests/test_model_hub_oauth.py@@ -6,7 +6,7 @@ from datetime import datetime, timezoneimport pytest-from core.handlers.model_hub.native_oauth import _signed_in+from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter, _signed_infrom core.handlers.model_hub.oauth import OAuthFlowRegistryfrom core.handlers.model_hub.revocations import (CredentialRevocationJournal,@@ -188,6 +188,41 @@ def test_flow_registry_returns_latest_pending_reauth_for_source(tmp_path):assert replaced[0] == "oaf_replaced1"+ ("error", "error_key", "error_detail"),+ [+ # The CLI's own last words are what the user needs beside the generic key.+ (+ "Error logging in: token exchange failed (401)",+ "settings.models.oauth.error.generic",+ "Error logging in: token exchange failed (401)",+ ),+ # A timeout already has its own sentence; there is nothing to add.+ ("timed_out", "settings.models.oauth.error.timeout", None),+ (None, "settings.models.oauth.error.generic", None),+ ],+)+def test_failed_native_login_carries_its_reason_beside_the_key(error, error_key, error_detail):+ class AgentAuth:+ def get_web_flow_status(self, flow_id):+ return {+ "ok": True,+ "flow_id": flow_id,+ "state": "failed",+ "error": error,+ "source_id": "src_native01",+ "vendor": "anthropic",+ "expires_at_iso": "2026-07-23T03:15:00+00:00",+ }++ adapter = AgentAuthNativeOAuthAdapter(AgentAuth(), auth_status_reader=lambda _backend: {})+ state = asyncio.run(adapter.oauth_status("flow_native01"))++ assert state.state == "failed"+ assert state.error_key == error_key+ assert state.error_detail == error_detail++def test_native_status_trusts_codex_keyring_success_but_not_active_api_keys():assert _signed_in("codex",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex c2b16a00f..49805f5be 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -8808,6 +8808,231 @@ def test_oauth_rejected_paste_keeps_flow_awaiting_a_corrected_value(tmp_path: Paasyncio.run(run())+_UI_BUNDLES = {+ language: json.loads((Path(__file__).resolve().parents[1] / "ui/src/i18n" / f"{language}.json").read_text())+ for language in ("en", "zh")+}+++def _ui_text(language: str, key: str) -> object:+ node: object = _UI_BUNDLES[language]+ for part in key.split("."):+ node = node.get(part) if isinstance(node, dict) else None+ return node+++class _BrowserCallbackEngine:+ """The engine's side of a browser OAuth flow, as far as a paste reaches it.++ It records what Avibe hands to ``POST /oauth-callback``; whether that value+ can ever exchange is the provider's business, decided by the code alone.+ """++ def __init__(self) -> None:+ self.submitted: list[dict] = []++ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/auth-files":+ return {"files": []}+ if path in {"/codex-auth-url", "/anthropic-auth-url", "/antigravity-auth-url"}:+ return {"state": "browser-state", "url": "https://example.test/oauth"}+ if path == "/oauth-callback":+ self.submitted.append(dict(payload))+ return {"status": "ok"}+ raise AssertionError((method, path, query, payload, timeout))+++def _browser_callback_adapter(tmp_path: Path, engine: _BrowserCallbackEngine) -> CLIProxyEngineAdapter:+ store = EngineStateStore(tmp_path / "state")+ return CLIProxyEngineAdapter(+ supervisor=SimpleNamespace(state_store=store, client=lambda: engine), # type: ignore[arg-type]+ state_store=store,+ )++[email protected]("vendor", ["openai", "anthropic", "gemini"])+ ("pasted", "sent"),+ [+ # Browsers that fail to load the loopback page copy its address without+ # the scheme. It is still the address, never a code.+ (+ "localhost:1455/auth/callback?code=ac_issued&state=browser-state",+ {"redirect_url": "http://localhost:1455/auth/callback?code=ac_issued&state=browser-state"},+ ),+ (+ "127.0.0.1:54545/callback?code=ac_issued&state=browser-state",+ {"redirect_url": "http://127.0.0.1:54545/callback?code=ac_issued&state=browser-state"},+ ),+ (+ "http://localhost:51121/oauth-callback?code=ac_issued&state=browser-state",+ {"redirect_url": "http://localhost:51121/oauth-callback?code=ac_issued&state=browser-state"},+ ),+ # Bare provider codes stay codes, including shapes with a slash or a+ # fragment-like suffix.+ ("ac_issued", {"code": "ac_issued"}),+ ("4/0AbCd-issued", {"code": "4/0AbCd-issued"}),+ ("issued.part#browser-state", {"code": "issued.part#browser-state"}),+ ("eyJhbGci.eyJzdWIi.c2lnbmF0dXJl", {"code": "eyJhbGci.eyJzdWIi.c2lnbmF0dXJl"}),+ ],+)+def test_oauth_paste_reaches_the_engine_as_the_value_it_is(+ tmp_path: Path, vendor: str, pasted: str, sent: dict,+) -> None:+ async def run() -> None:+ engine = _BrowserCallbackEngine()+ adapter = _browser_callback_adapter(tmp_path, engine)+ flow = await adapter.start_oauth("src_fixture123", vendor)+ result = await adapter.submit_oauth(flow.flow_id, pasted)+ assert result.state == "verifying"+ assert len(engine.submitted) == 1+ submitted = engine.submitted[0]+ assert submitted["state"] == "browser-state"+ assert {key: submitted[key] for key in submitted if key in {"code", "redirect_url"}} == sent++ asyncio.run(run())+++ ("pasted", "reason"),+ [+ ("localhost:1455/auth/callback?state=browser-state", "no_answer"),+ # Only the authority survived the copy: still an address, still no answer.+ ("localhost:1455", "no_answer"),+ ("127.0.0.1:54545", "no_answer"),+ ("chatgpt.com/", "no_answer"),+ ("https://chatgpt.com/", "no_answer"),+ # A code minted for an earlier sign-in link fails the provider's+ # verifier check, and that failure would end this flow.+ ("http://localhost:1455/auth/callback?code=ac_old&state=earlier-state", "other_attempt"),+ ("localhost:1455/auth/callback?code=ac_old&state=earlier-state", "other_attempt"),+ ],+)+def test_oauth_paste_that_cannot_exchange_keeps_the_flow_awaiting(+ tmp_path: Path, pasted: str, reason: str,+) -> None:+ async def run() -> None:+ engine = _BrowserCallbackEngine()+ adapter = _browser_callback_adapter(tmp_path, engine)+ flow = await adapter.start_oauth("src_fixture123", "openai")+ with pytest.raises(OAuthSubmissionRejectedError) as rejected:+ await adapter.submit_oauth(flow.flow_id, pasted)+ assert rejected.value.reason == reason+ held = adapter._oauth_flows[flow.flow_id]+ assert held.state == "awaiting_action"+ assert held.grant_write_possible is False+ assert engine.submitted == []++ asyncio.run(run())+++ ("engine_error", "error_key"),+ [+ # The pinned engine's own session errors, verbatim.+ (+ "Failed to exchange authorization code for tokens: token exchange failed with status 401: "+ '{"error": {"message": "Could not validate your token. Please try signing in again.", '+ '"type": "invalid_request_error", "param": null, "code": "token_expired"}}',+ "models.oauth.code_rejected",+ ),+ (+ "Failed to exchange authorization code for tokens: token exchange request failed: "+ "Post \"https://auth.openai.com/oauth/token\": dial tcp: i/o timeout",+ "models.oauth.exchange_failed",+ ),+ # Refusals that say nothing about the code: a proxy and a throttle.+ (+ "Failed to exchange authorization code for tokens: token exchange failed with status 407: "+ "Proxy Authentication Required",+ "models.oauth.exchange_failed",+ ),+ (+ "Failed to exchange authorization code for tokens: token exchange failed with status 429: "+ '{"error": {"message": "Too many requests", "code": "rate_limit_exceeded"}}',+ "models.oauth.exchange_failed",+ ),+ (+ "Failed to exchange authorization code for tokens: token exchange failed with status 403: "+ '{"error": "invalid_grant", "error_description": "code already redeemed"}',+ "models.oauth.code_rejected",+ ),+ ("Failed to exchange token", "models.oauth.exchange_failed"),+ ("Timeout waiting for OAuth callback", "models.oauth.expired"),+ ("OAuth flow timed out", "models.oauth.expired"),+ ("State code error", "models.oauth.callback_mismatch"),+ ("Authentication failed: state mismatch", "models.oauth.callback_mismatch"),+ ("Bad Request", "models.oauth.provider_denied"),+ ("Authentication failed", "models.oauth.provider_denied"),+ ("Failed to save authentication tokens", "models.oauth.upstream_failed"),+ # A timeout outside the callback wait says nothing about the callback.+ ("Failed to save authentication tokens: timed out writing auth file", "models.oauth.upstream_failed"),+ ("Authentication failed: device code expired", "models.oauth.upstream_failed"),+ ],+)+def test_oauth_engine_failure_names_what_the_user_can_do(+ tmp_path: Path, caplog: pytest.LogCaptureFixture, engine_error: str, error_key: str,+) -> None:+ class Engine(_BrowserCallbackEngine):+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/get-auth-status":+ return {"status": "error", "error": engine_error}+ return super().management_request(method, path, query=query, payload=payload, timeout=timeout)++ async def run() -> None:+ adapter = _browser_callback_adapter(tmp_path, Engine())+ flow = await adapter.start_oauth("src_fixture123", "openai")+ with caplog.at_level(logging.WARNING, logger="vibe.model_hub_runtime.adapter"):+ failed = await adapter.oauth_status(flow.flow_id)+ assert failed.state == "failed"+ assert failed.error_key == error_key+ # The engine's own words travel beside the key, for the dialog's+ # details and for the log.+ # The engine's own words travel beside the key, as written.+ assert failed.error_detail == " ".join(engine_error.split())+ assert any(+ error_key in record.getMessage() and engine_error[:24] in record.getMessage()+ for record in caplog.records+ )++ asyncio.run(run())+ for language in ("en", "zh"):+ assert isinstance(_ui_text(language, error_key), str), (language, error_key)+++def test_oauth_failure_detail_is_the_engine_reason_on_one_bounded_line(tmp_path: Path) -> None:+ reasons = iter([+ # What the user copies is what the provider said, unaltered.+ "Failed to exchange authorization code for tokens: token exchange failed with status 401: {\n"+ ' "error": {\n "message": "Could not validate your token. Please try signing in again.",\n'+ ' "type": "invalid_request_error",\n "param": null,\n "code": "token_expired"\n }\n}',+ # A proxy error page must not flood the dialog or the log.+ "Failed to exchange authorization code for tokens: token exchange failed with status 502: " + "<p>bad gateway</p>" * 200,+ ])++ class Engine(_BrowserCallbackEngine):+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/get-auth-status":+ return {"status": "error", "error": next(reasons)}+ return super().management_request(method, path, query=query, payload=payload, timeout=timeout)++ async def run() -> None:+ adapter = _browser_callback_adapter(tmp_path, Engine())+ first = await adapter.oauth_status((await adapter.start_oauth("src_fixture123", "openai")).flow_id)+ assert first.error_detail == (+ "Failed to exchange authorization code for tokens: token exchange failed with status 401: "+ '{ "error": { "message": "Could not validate your token. Please try signing in again.", '+ '"type": "invalid_request_error", "param": null, "code": "token_expired" } }'+ )+ second = await adapter.oauth_status((await adapter.start_oauth("src_fixture456", "openai")).flow_id)+ assert second.error_detail is not None+ assert len(second.error_detail) == 1000+ assert second.error_detail.startswith("Failed to exchange authorization code for tokens: ")+ assert second.error_detail.endswith("…")++ asyncio.run(run())++def test_oauth_engine_400_fails_the_flow_rather_than_claiming_it_retryable(tmp_path: Path) -> None:class Client:def management_request(self, method, path, *, query=None, payload=None, timeout=None):diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex dead05275..4faf313bb 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -15,10 +15,11 @@// the bug `settle` below was written to fix.import * as React from 'react';import * as DialogPrimitive from '@radix-ui/react-dialog';-import { ArrowRight, CheckCircle2, Info, Sparkles, TriangleAlert, X } from 'lucide-react';+import { ArrowRight, CheckCircle2, ChevronDown, ChevronRight, Info, Sparkles, TriangleAlert, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { CopyButton } from '@/components/ui/copy-button';import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';@@ -46,6 +47,7 @@ import {callbackValueCarriesResult,oauthFailureKey,oauthStartFailureKey,+ pasteRejectedKey,serverText,type OAuthJourney,} from './serverCopy';@@ -76,6 +78,37 @@ const Step: React.FC<{ n: number; label: string; children: React.ReactNode }> =</div>);+/**+ * The provider's own words behind a failed sign-in, collapsed by default under+ * the sentence that explains it, and copyable so the user can pass them on.+ * The server sends them verbatim on one bounded line.+ */+const OAuthFailureDetail: React.FC<{ detail: string }> = ({ detail }) => {+ const { t } = useTranslation();+ const [open, setOpen] = React.useState(false);+ return (+ <div className="flex min-w-0 flex-col gap-1.5">+ <button+ type="button"+ className="inline-flex items-center gap-0.5 self-start rounded text-[12px] text-destructive-ink/80 hover:text-destructive-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ >+ {open ? <ChevronDown className="size-3" aria-hidden /> : <ChevronRight className="size-3" aria-hidden />}+ {t(open ? 'settings.models.oauth.error.details.hide' : 'settings.models.oauth.error.details.show')}+ </button>+ {open && (+ <div className="flex min-w-0 flex-col items-start gap-1.5">+ <pre className="max-h-40 w-full overflow-auto whitespace-pre-wrap break-words rounded-md border border-destructive/20 bg-background/60 px-2.5 py-2 font-mono text-[11.5px] leading-relaxed text-foreground">+ {detail}+ </pre>+ <CopyButton value={detail} />+ </div>+ )}+ </div>+ );+};+export const OAuthConnectDialog: React.FC<{open: boolean;/** 'anthropic' (Claude) | 'openai' (ChatGPT) | any future subscription vendor. */@@ -638,7 +671,7 @@ export const OAuthConnectDialog: React.FC<{// ignored. `failureLanded` is the part that knows.const failure = apiFailure(err);if (failure?.code === SUBMISSION_REJECTED_FAILURE) {- setPasteError(PASTE_REJECTED_KEY);+ setPasteError(pasteRejectedKey(failure.detail));return;}const failureClass = classifyOAuthFailure(failure);@@ -880,9 +913,14 @@ export const OAuthConnectDialog: React.FC<{<div className="flex flex-col gap-2"><div className="flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/[0.08] px-4 py-3 text-[13px] text-destructive-ink"><TriangleAlert className="mt-0.5 size-4 shrink-0" />- {/* errorKey may be the flow's own runtime-declared `error_key`, so- an unknown one degrades to 连接失败 rather than rendering itself. */}- <span>{serverText(t, errorKey, 'settings.models.oauth.error.generic')}</span>+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ {/* errorKey may be the flow's own runtime-declared `error_key`, so+ an unknown one degrades to 连接失败 rather than rendering itself. */}+ <span>{serverText(t, errorKey, 'settings.models.oauth.error.generic')}</span>+ {/* Only the failed flow itself carries the provider's words; a+ failed request or the dialog's own timeout has none to show. */}+ {flow?.state === 'failed' && flow.error_detail && <OAuthFailureDetail detail={flow.error_detail} />}+ </div></div>{isReauth && stranded.length > 0 && <>{/* Past tense (`gapsDone`), because this is not a confirm: thediff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 76c1d8ad2..333b69bbf 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -1197,6 +1197,46 @@ describe('SettingsModelsPage surface branches', () => {await waitFor(() => expect(reauth).toHaveBeenCalledTimes(2));});+ // The sentence says what to do; the provider's own words are what the user+ // passes on when that is not enough. They stay folded until asked for, and+ // the copy control takes exactly what the server sent.+ it('folds the provider reason of a failed sign-in behind a copyable details control', async () => {+ const detail = 'Failed to exchange authorization code for tokens: token exchange failed with status 401: token_expired';+ const failed = {+ flow_id: 'flow_reauth',+ intent: 'reauth' as const,+ vendor: 'openai',+ channel: 'hub' as const,+ state: 'failed' as const,+ presentation: { expects: 'paste_callback_url' as const },+ error_key: 'models.oauth.code_rejected',+ error_detail: detail,+ };+ vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(failed);+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({ flow: failed, created: null, repaired: null });+ const writeText = vi.fn().mockResolvedValue(undefined);+ const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });+ try {+ renderPage([blockedSubscription]);++ await userEvent.click(await screen.findByRole('button', { name: /Claude native login/i }));+ await userEvent.click(await screen.findByRole('button', { name: /^Sign in$|^重新登录$/i }));+ await userEvent.click(await screen.findByRole('button', { name: /^Start sign-in$|^开始登录$/i }));++ const toggle = await screen.findByRole('button', { name: /^Show details$|^查看详情$/i });+ expect(screen.getByText(/rejected this authorization code|拒绝了这个授权码/)).toBeTruthy();+ expect(screen.queryByText(detail)).toBeNull();+ await userEvent.click(toggle);+ expect(screen.getByText(detail)).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /^Copy$|^复制$/i }));+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(detail));+ } finally {+ if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard);+ else Reflect.deleteProperty(navigator, 'clipboard');+ }+ });+it('lands the operational overview without reading hidden event history', async () => {vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex e4729f3df..bd8a12367 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -19,6 +19,7 @@ import {NATIVE_SUBSCRIPTION_EXISTS_FAILURE,oauthFailureKey,PASTE_REJECTED_KEY,+ pasteRejectedKey,oauthStartFailureKey,serverText,TIER_EDIT_MANAGED_FAILURE,@@ -299,6 +300,16 @@ describe('pasted OAuth callback value', () => {expect(callbackValueCarriesResult('http://localhost:1455/auth/callback?code=abc&state=s')).toBe(true);expect(callbackValueCarriesResult('http://localhost:1455/auth/callback?error=access_denied')).toBe(true);expect(callbackValueCarriesResult(' abc#state ')).toBe(true);+ expect(callbackValueCarriesResult('4/0AbCd-code')).toBe(true);+ });++ // Browsers that fail to load the loopback page copy its address without the+ // scheme; it is still an address and is judged as one.+ it('judges a scheme-less address by its answer, not as a bare code', () => {+ expect(callbackValueCarriesResult('localhost:1455/auth/callback?code=abc&state=s')).toBe(true);+ expect(callbackValueCarriesResult('127.0.0.1:54545/callback?code=abc&state=s')).toBe(true);+ expect(callbackValueCarriesResult('localhost:1455/auth/callback?state=s')).toBe(false);+ expect(callbackValueCarriesResult('chatgpt.com/')).toBe(false);});it('refuses a page address that carries no answer', () => {@@ -308,9 +319,16 @@ describe('pasted OAuth callback value', () => {expect(callbackValueCarriesResult('http://[broken')).toBe(false);});- it('explains the refusal in both bundles', () => {+ it('says what to paste instead, by why the server refused it, in both bundles', () => {+ const otherAttempt = pasteRejectedKey('modelHub.errors.submission_rejected_other_attempt');+ expect(otherAttempt).not.toBe(PASTE_REJECTED_KEY);+ for (const detail of [undefined, 'modelHub.errors.submission_rejected']) {+ expect(pasteRejectedKey(detail)).toBe(PASTE_REJECTED_KEY);+ }for (const lng of ['en', 'zh'] as const) {- expect(t(lng)(PASTE_REJECTED_KEY)).not.toBe(PASTE_REJECTED_KEY);+ for (const key of [PASTE_REJECTED_KEY, otherAttempt]) {+ expect(t(lng)(key)).not.toBe(key);+ }}});});diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsindex 306f89152..776567c81 100644--- a/ui/src/components/settings/models/serverCopy.ts+++ b/ui/src/components/settings/models/serverCopy.ts@@ -97,6 +97,19 @@ export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney)*/export const SUBMISSION_REJECTED_FAILURE = 'submission_rejected';export const PASTE_REJECTED_KEY: TranslationKey = 'settings.models.oauth.callback.rejected';+const PASTE_OTHER_ATTEMPT_KEY: TranslationKey = 'settings.models.oauth.callback.otherAttempt';+const SUBMISSION_OTHER_ATTEMPT_DETAIL = 'modelHub.errors.submission_rejected_other_attempt';++/** What to paste instead, by why the server refused the value. */+export const pasteRejectedKey = (detail: string | undefined): TranslationKey =>+ detail === SUBMISSION_OTHER_ATTEMPT_DETAIL ? PASTE_OTHER_ATTEMPT_KEY : PASTE_REJECTED_KEY;++// A browser that cannot load the loopback callback page often copies its address+// without the scheme (`localhost:1455/auth/callback?code=…`). Same rule as the+// server's `_oauth_callback_address`: a host followed by a port, path or query is+// an address; a provider code carries none of them.+const SCHEMELESS_CALLBACK_ADDRESS =+ /^(?:localhost|\[[0-9a-f:.]+\]|\d{1,3}(?:\.\d{1,3}){3}|(?:[a-z0-9-]+\.)+[a-z]{2,})(?::\d{1,5})?[/?]/i;/*** Whether a pasted callback address carries the provider's answer. The engine@@ -106,9 +119,14 @@ export const PASTE_REJECTED_KEY: TranslationKey = 'settings.models.oauth.callbac*/export const callbackValueCarriesResult = (value: string): boolean => {const trimmed = value.trim();- if (!/^https?:\/\//i.test(trimmed)) return trimmed.length > 0;+ const address = /^https?:\/\//i.test(trimmed)+ ? trimmed+ : trimmed.includes('?') || SCHEMELESS_CALLBACK_ADDRESS.test(trimmed)+ ? `http://${trimmed.replace(/^\/+/, '')}`+ : null;+ if (address === null) return trimmed.length > 0;try {- const params = new URL(trimmed).searchParams;+ const params = new URL(address).searchParams;return Boolean(params.get('code')?.trim() || params.get('error')?.trim() || params.get('error_description')?.trim());} catch {return false;diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex ef0dafd43..1e94daa74 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -721,8 +721,11 @@ export type OAuthFlow = {channel: SupplyChannel;state: OAuthFlowState;presentation: OAuthPresentation;- /** i18n key; raw upstream errors never surface. */+ /** Closed i18n key for the user-facing sentence. */error_key?: string | null;+ /** A failed flow's own reason (provider, engine, or CLI), verbatim on one+ * bounded line; shown behind the copyable details control. */+ error_detail?: string;expires_at?: string | null;};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1999490cb..f296c9986 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1968,7 +1968,8 @@},"callback": {"hint": "After signing in, paste the callback URL your browser landed on",- "rejected": "That isn't the callback address. Paste the full address from the browser bar after you approve (it contains code=), then submit again."+ "rejected": "That isn't the callback address. Paste the full address from the browser bar after you approve (it contains code=), then submit again.",+ "otherAttempt": "This address comes from an earlier sign-in link and can't be used here. Sign in with the current link in step 1 above, then paste the full address it leads to."},"deviceCode": {"hint": "Enter the device code on that page; this continues automatically"@@ -1984,7 +1985,11 @@"timeout": "Authorization timed out, please reconnect","generic": "Connection failed, please retry","finalize": "Authorized, but couldn't create the source — please retry",- "finalizeReauth": "Signed in, but this source still isn't working — please retry"+ "finalizeReauth": "Signed in, but this source still isn't working — please retry",+ "details": {+ "show": "Show details",+ "hide": "Hide details"+ }}},"toast": {@@ -2413,9 +2418,13 @@"engine_unavailable": "The Hub isn't responding, please retry","submission_failed": "Couldn't submit what you pasted, please retry","ambiguous_engine_binding": "Couldn't tell which account signed in — do one at a time, then retry",- "binding_failed": "That account is already used by another source",+ "binding_failed": "Signed in, but couldn't attach this account to the source (another source may already use it). Please retry.","account_already_added": "This account is already added. Sign in with a different account to add another subscription.",- "expired": "Authorization timed out, please reconnect"+ "expired": "Authorization timed out, please reconnect",+ "code_rejected": "The provider rejected this authorization code: the pasted address may be incomplete, come from an earlier sign-in link, or already be used or expired. Retry to get a new sign-in link, then paste the address it leads to.",+ "exchange_failed": "Got the authorization code, but couldn't exchange it with the provider — a network or proxy problem, or the code is no longer valid. Retry to get a new sign-in link.",+ "callback_mismatch": "The callback doesn't match this sign-in; it may come from an earlier link. Retry, then sign in only with the new link.",+ "provider_denied": "The provider declined this authorization — it was cancelled, or this account can't use it. Retry to sign in again."},"probe": {"native_cli_unavailable": "Can't use the CLI's sign-in",diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.tsindex e15cb47d0..d3d90917b 100644--- a/ui/src/i18n/keyCoverage.test.ts+++ b/ui/src/i18n/keyCoverage.test.ts@@ -883,6 +883,7 @@ const NON_KEY_LITERALS = ['modelHub.errors.models_dev_unavailable','modelHub.errors.native_login_in_progress','modelHub.errors.native_subscription_exists',+ 'modelHub.errors.submission_rejected_other_attempt',// Storage keys. Namespaced on purpose, which is also why they read like keys.'avibe.agents.tab.v1',diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1ad82ac3a..50fb4ff31 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1968,7 +1968,8 @@},"callback": {"hint": "登录后,把浏览器最终停留的回调地址粘贴回来",- "rejected": "这不是授权完成后的回调地址。请粘贴登录同意后浏览器地址栏里的完整网址(包含 code=),改好后重新提交。"+ "rejected": "这不是授权完成后的回调地址。请粘贴登录同意后浏览器地址栏里的完整网址(包含 code=),改好后重新提交。",+ "otherAttempt": "这个地址来自之前的登录链接,在这里用不了。请用上面第 1 步里当前的链接重新登录,再粘贴登录后的完整网址。"},"deviceCode": {"hint": "在那个页面输入设备码,这里会自动继续"@@ -1984,7 +1985,11 @@"timeout": "授权超时,请重新连接","generic": "连接失败,请重试","finalize": "已完成授权,但创建模型供应商失败,请重试",- "finalizeReauth": "已重新登录,但这个供应商还是不可用,请重试"+ "finalizeReauth": "已重新登录,但这个供应商还是不可用,请重试",+ "details": {+ "show": "查看详情",+ "hide": "收起详情"+ }}},"toast": {@@ -2413,9 +2418,13 @@"engine_unavailable": "模型网关没有响应,请重试","submission_failed": "粘贴的内容没能提交,请重试","ambiguous_engine_binding": "分不清登录的是哪个账号,请一次只登一个再重试",- "binding_failed": "该账号已被另一个供应商使用",+ "binding_failed": "登录成功了,但没能把这个账号接到当前供应商上(它可能已被其他供应商使用),请重试","account_already_added": "这个账号已经添加过了,不能重复添加。要添加另一个订阅,请登录其他账号。",- "expired": "授权超时,请重新连接"+ "expired": "授权超时,请重新连接",+ "code_rejected": "供应商拒绝了这个授权码:粘贴的网址可能不完整、来自之前的登录链接,或者已经用过、过期了。点「重试」获取新的登录链接,登录后再粘贴。",+ "exchange_failed": "已收到授权码,但没能向供应商换到登录凭据,可能是网络或代理问题,也可能授权码已失效。点「重试」获取新的登录链接。",+ "callback_mismatch": "回调和这次登录对不上,可能来自之前打开的登录链接。点「重试」后,只用新出现的链接登录。",+ "provider_denied": "供应商拒绝了这次授权,比如授权被取消,或这个账号无权使用。点「重试」重新登录。"},"probe": {"native_cli_unavailable": "无法使用 Agent 的登录",diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 2eb1c8a99..a285ba1e5 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -919,6 +919,7 @@"flow_not_found": "Authorization flow not found.","flow_expired": "Authorization flow expired.","submission_rejected": "That is not the authorization callback address. Paste the full address shown after authorizing.",+ "submission_rejected_other_attempt": "That address answers an earlier sign-in link. Sign in with the link in this dialog, then paste the address it leads to.","discovery_failed": "Could not validate or discover this source.","ambiguous_source": "Connected, but we could not identify the model interface.","inventory_unavailable": "The interface was confirmed, but its model list is unavailable.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex c85b837f5..54324f8f6 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -919,6 +919,7 @@"flow_not_found": "未找到授权流程。","flow_expired": "授权流程已过期。","submission_rejected": "这不是授权完成后的回调地址,请粘贴授权后地址栏里的完整网址。",+ "submission_rejected_other_attempt": "这个地址来自之前的登录链接。请用当前弹窗里的链接登录,再粘贴登录后的地址。","discovery_failed": "无法验证或识别此供应商。","ambiguous_source": "已连接,但无法确认这是哪种模型接口。","inventory_unavailable": "接口已确认,但暂时无法获取模型清单。",diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 78ebd3c8b..5a91e283e 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -13,7 +13,7 @@ import uuidfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timedelta, timezonefrom enum import Enum-from typing import Any, Callable, Mapping, Sequence+from typing import Any, Callable, Literal, Mapping, Sequenceimport aiohttp@@ -38,6 +38,7 @@ from core.handlers.model_hub.adapter import (make_source_observation,)from core.handlers.model_hub.errors import ModelDiscoveryError+from core.handlers.model_hub.oauth import oauth_failure_detailfrom core.handlers.model_hub.identifiers import model_id_without_credential_addressfrom core.handlers.model_hub.quota import (CLAUDE_PLAN_FETCH_TIMEOUT_SECONDS,@@ -1323,6 +1324,7 @@ class _OAuthFlow:credential_ref: str | None = Noneretained_material_disposition: RetainedMaterialDisposition = RetainedMaterialDisposition.NONEretained_credential_ref: str | None = None+ error_detail: str | None = Nonegrant_write_possible: bool = Falseretained_material_decided: bool = Falseoperation_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)@@ -1343,6 +1345,7 @@ class _OAuthFlow:channel="hub",retained_material_disposition=self.retained_material_disposition,retained_credential_ref=self.retained_credential_ref,+ error_detail=self.error_detail,)@@ -2693,11 +2696,12 @@ class CLIProxyEngineAdapter:if status == "ok":await self._complete_oauth(flow, client)elif status == "error":- self._fail_flow(flow, "models.oauth.upstream_failed")+ reason = str(payload.get("error") or "")+ self._fail_flow(flow, _oauth_engine_failure_key(reason), detail=reason)elif flow.state != "verifying":flow.state = "awaiting_action"- except (EngineClientError, EngineUnavailableError):- self._fail_flow(flow, "models.oauth.engine_unavailable")+ except (EngineClientError, EngineUnavailableError) as error:+ self._fail_flow(flow, "models.oauth.engine_unavailable", detail=str(error))return flow.snapshot()async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:@@ -2711,23 +2715,33 @@ class CLIProxyEngineAdapter:submitted = value.strip()if not submitted:raise EngineStateError("OAuth submission is empty")- is_redirect = submitted.startswith(("http://", "https://"))- if is_redirect and not any(- answer.strip()- for key, answer in urllib.parse.parse_qsl(urllib.parse.urlsplit(submitted).query)- if key in {"code", "error", "error_description"}- ):- # The one rejection that provably writes nothing and leaves the- # session waiting: an address carrying no answer at all, which- # the engine would refuse before reading its session. Decided- # here, where the value is known, not from an engine status- # that several different refusals share.- logger.info(- "OAuth submission carries no code: flow=%s provider=%s",- flow.flow_id,- flow.callback_provider,- )- raise OAuthSubmissionRejectedError(flow_id)+ address = _oauth_callback_address(submitted)+ if address is not None:+ answers = {+ key: answer.strip()+ for key, answer in urllib.parse.parse_qsl(urllib.parse.urlsplit(address).query)+ }+ # The rejections that provably write nothing and leave the+ # session waiting, decided here where the value is known rather+ # than from an engine status several refusals share. An address+ # without an answer is refused by the engine before it reads its+ # session. An answer to another sign-in link would reach the+ # provider, which refuses its code for this flow's verifier —+ # and that refusal ends the session the user could have pasted+ # the right address into.+ rejection: Literal["no_answer", "other_attempt"] | None = None+ if not any(answers.get(key) for key in ("code", "error", "error_description")):+ rejection = "no_answer"+ elif answers.get("state") and answers["state"] != flow.engine_state:+ rejection = "other_attempt"+ if rejection is not None:+ logger.info(+ "OAuth submission rejected before the engine: flow=%s provider=%s reason=%s",+ flow.flow_id,+ flow.callback_provider,+ rejection,+ )+ raise OAuthSubmissionRejectedError(flow_id, rejection)# Any failure after submission begins cannot prove whether the# engine wrote grant material.flow.grant_write_possible = True@@ -2735,8 +2749,8 @@ class CLIProxyEngineAdapter:"provider": flow.callback_provider,"state": flow.engine_state,}- if is_redirect:- payload["redirect_url"] = submitted+ if address is not None:+ payload["redirect_url"] = addresselse:payload["code"] = submittedtry:@@ -2747,11 +2761,8 @@ class CLIProxyEngineAdapter:"/oauth-callback",payload=payload,)- except EngineClientError:- self._fail_flow(flow, "models.oauth.submission_failed")- return flow.snapshot()- except EngineUnavailableError:- self._fail_flow(flow, "models.oauth.submission_failed")+ except (EngineClientError, EngineUnavailableError) as error:+ self._fail_flow(flow, "models.oauth.submission_failed", detail=str(error))return flow.snapshot()flow.state = "verifying"return flow.snapshot()@@ -3077,10 +3088,19 @@ class CLIProxyEngineAdapter:raise EngineStateError("OAuth flow is unknown")return flow- def _fail_flow(self, flow: _OAuthFlow, error_key: str) -> None:+ def _fail_flow(self, flow: _OAuthFlow, error_key: str, *, detail: str | None = None) -> None:self._mark_retention_unknown_if_needed(flow)flow.state = "failed"flow.error_key = error_key+ flow.error_detail = oauth_failure_detail(detail)+ if flow.error_detail is not None:+ logger.warning(+ "OAuth flow failed: flow=%s provider=%s error_key=%s detail=%s",+ flow.flow_id,+ flow.callback_provider,+ error_key,+ flow.error_detail,+ )self._release_provider(flow)@staticmethod@@ -3135,6 +3155,63 @@ class CLIProxyEngineAdapter:self._active_oauth_providers.discard(flow.auth_provider)+# A browser that cannot load the loopback callback page often copies its address+# without the scheme (``localhost:1455/auth/callback?code=…``). That value is an+# address, not a code: sent as a code, the provider refuses it and the refusal+# ends the session. A host followed by a port, path or query marks an address; a+# provider code carries none of them (Google's ``4/0A…`` has no host before its+# slash, and Anthropic's ``code#state`` has no path or query).+_SCHEMELESS_CALLBACK_ADDRESS = re.compile(+ r"^(?:"+ # A loopback or IP host is an address on its own, with or without a port.+ r"(?:localhost|\[[0-9a-f:.]+\]|\d{1,3}(?:\.\d{1,3}){3})(?::\d{1,5})?(?:[/?]|$)"+ # A named host needs a port, path or query: ``a.b.c`` alone may be a code.+ r"|(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d{1,5}(?:[/?]|$)|[/?])"+ r")",+ re.IGNORECASE,+)+++def _oauth_callback_address(submitted: str) -> str | None:+ """Return a pasted OAuth value as a callback address, or None for a bare code."""++ if submitted.lower().startswith(("http://", "https://")):+ return submitted+ if "?" in submitted or _SCHEMELESS_CALLBACK_ADDRESS.match(submitted):+ return "http://" + submitted.lstrip("/")+ return None+++# The pinned engine's OAuth session errors, verbatim and lower-cased, mapped to+# what the user can do about each. A closed table: anything the engine says that+# is not here, including a future rewording, keeps the generic key rather than+# borrowing a cause it did not state.+_OAUTH_ENGINE_SESSION_ERRORS = {+ "timeout waiting for oauth callback": "models.oauth.expired",+ "oauth flow timed out": "models.oauth.expired",+ "state code error": "models.oauth.callback_mismatch",+ "authentication failed: state mismatch": "models.oauth.callback_mismatch",+ "bad request": "models.oauth.provider_denied",+ "authentication failed": "models.oauth.provider_denied",+ "failed to exchange token": "models.oauth.exchange_failed",+}+# The one session error that carries its cause after the phrase.+_OAUTH_ENGINE_EXCHANGE_FAILURE = "failed to exchange authorization code for tokens"+++def _oauth_engine_failure_key(reason: str) -> str:+ """Map the engine's session error to what the user can do about it."""++ text = " ".join(reason.split()).lower()+ if text == _OAUTH_ENGINE_EXCHANGE_FAILURE or text.startswith(_OAUTH_ENGINE_EXCHANGE_FAILURE + ":"):+ # Only the provider's answers about the grant itself blame the pasted+ # code; a proxy (407), a throttle (429) or any other refusal does not.+ if re.search(r"\bstatus 40[01]\b", text) or "invalid_grant" in text:+ return "models.oauth.code_rejected"+ return "models.oauth.exchange_failed"+ return _OAUTH_ENGINE_SESSION_ERRORS.get(text, "models.oauth.upstream_failed")++def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:payload = client.management_request("GET", "/auth-files")files = payload.get("files")