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): explain discovery failures and enable subscriptions (#1404)
Call White14990fbd1988
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 33b1805c7..280a6ae6e 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -317,7 +317,18 @@ def _source_id() -> str:def _parse_datetime(value: str) -> datetime:- return datetime.fromisoformat(value.replace("Z", "+00:00"))+ """Parse a timestamp into something comparable with this service's clock.++ Every parsed value is compared against ``self.now()``, which is UTC-aware.+ A provider or an older persisted record may still carry a naive ISO string,+ and comparing the two raises ``TypeError`` rather than answering the+ question — so read a naive timestamp as the UTC it was written as.+ """++ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ if parsed.tzinfo is None:+ return parsed.replace(tzinfo=timezone.utc)+ return parseddef _mask_credential(value: str) -> str:@@ -620,6 +631,24 @@ class ModelHubService:))+ @staticmethod+ def _existing_native_source(+ config: ModelHubConfig,+ vendor: str,+ ) -> ModelHubSourceConfig | None:+ backend = _NATIVE_VENDOR_BACKENDS.get(vendor)+ if backend is None:+ return None+ return next(+ (+ source+ for source in config.sources+ if source.supply_channel == "native_cli"+ and source_eligible_for_backend(source, cast(BackendName, backend))+ ),+ None,+ )+async def _engine_call(self, awaitable):try:return await awaitable@@ -928,14 +957,15 @@ class ModelHubService:self,flow: OAuthFlowState,channel: OAuthChannel,- ) -> None:+ ) -> bool:if channel == "hub":await self._discard_unbound_hub_flow(flow)- return+ return Truetry:await self.native_oauth_adapter.cancel_oauth(flow.flow_id)except Exception:- pass+ return False+ return Trueasync def _discover(self, source: ModelHubSourceConfig) -> list[str]:if not source.credential_ref:@@ -1051,9 +1081,27 @@ class ModelHubService:observation.outcome is not ObservationOutcome.OBSERVEDor observation.protocol is None):+ detail_by_outcome = {+ ObservationOutcome.AMBIGUOUS: "modelHub.errors.ambiguous_source",+ ObservationOutcome.UNREACHABLE: "modelHub.errors.source_unreachable",+ ObservationOutcome.AUTHENTICATION_FAILED: "modelHub.errors.authentication_failed",+ ObservationOutcome.ADAPTER_ERROR: "modelHub.errors.observation_failed",+ ObservationOutcome.TIMEOUT: "modelHub.errors.source_timeout",+ }+ # An adapter error may carry authoritative reachability (for example,+ # a reachable endpoint returning an unsupported response), or no+ # reachability evidence at all after an unclassified adapter failure.+ # Only the former justifies copy that says we connected.+ detail = detail_by_outcome.get(observation.outcome)+ if (+ observation.outcome is ObservationOutcome.ADAPTER_ERROR+ and observation.reachable is None+ ):+ detail = "modelHub.errors.adapter_error"raise ModelHubError("discovery_failed",status=422,+ detail=detail,data={"observation": self._observation_payload(observation)},)return observation@@ -1442,6 +1490,29 @@ class ModelHubService:return existing.to_payload()if existing is not None:raise ModelHubError("migration_item_conflict", status=409)+ if channel == "native_cli":+ occupied = self._existing_native_source(previous, vendor)+ if occupied is not None:+ # A second provider flow can finish after the first one+ # committed. Re-check under the mutation lock and clean+ # the losing native flow before surfacing the singleton+ # conflict, so it cannot materialize a second Source.+ cleanup_confirmed = await self._discard_started_oauth_flow(+ flow,+ channel,+ )+ if not cleanup_confirmed:+ raise ModelHubError("engine_down", status=503)+ try:+ self.oauth_flows.forget(oauth_ref)+ except OSError:+ pass+ raise ModelHubError(+ "native_source_already_exists",+ status=409,+ detail="modelHub.errors.native_subscription_exists",+ data={"existing_source_id": occupied.id},+ )account_label: str | None = Nonestate = ModelHubSourceStateConfig(status="standby")discovered: list[str] | None@@ -3778,25 +3849,6 @@ class ModelHubService:raise ModelHubError("flow_not_found", status=400) from Noneoauth_channel = cast(OAuthChannel, channel)self._ensure_config_writable()- if oauth_channel == "native_cli":- backend = _NATIVE_VENDOR_BACKENDS.get(vendor)- if backend is not None:- existing = next(- (- source- for source in self.store.load().sources- if source.supply_channel == "native_cli"- and source_eligible_for_backend(source, cast(BackendName, backend))- ),- None,- )- if existing is not None:- raise ModelHubError(- "native_source_already_exists",- status=409,- data={"existing_source_id": existing.id},- )-nonce_key: tuple[str, str, OAuthChannel] | None = Noneif client_nonce is not None:try:@@ -3818,11 +3870,41 @@ class ModelHubService:raise ModelHubError("engine_down", status=503)return await asyncio.shield(task)+ # Everything the owner can wait on lives inside this coroutine, and that+ # is the invariant rather than an accident of layout: the claim above is+ # what a concurrent same-tuple retry looks for, and the ONLY release is+ # this coroutine's own ``finally``. So an owner await placed out here —+ # the native-slot read used to be one — strands the tuple until restart:+ # the retry finds a pending claim with no task and gets ``engine_down``,+ # and a cancelled owner never reaches the release at all.+ # ``test_oauth_start_keeps_every_owner_await_inside_the_installed_task``+ # holds the shape so the next pre-check cannot re-open the window.async def start_and_remember() -> dict:pending_source_id = _source_id()flow: OAuthFlowState | None = Noneflow_cleanup_done = False+ flow_cleanup_attempted = Falsetry:+ if oauth_channel == "native_cli":+ async with self._mutation_lock:+ # The sanctioned CLI keeps one credential per vendor, so+ # a second native Source would describe a credential the+ # first one already owns. The lock serializes this read+ # with migration's native Source writer and with the+ # re-check in ``_create_oauth_source``, so a flow that+ # started before the first Source was persisted still+ # cannot materialize a sibling.+ occupied = self._existing_native_source(+ self.store.load(),+ vendor,+ )+ if occupied is not None:+ raise ModelHubError(+ "native_source_already_exists",+ status=409,+ detail="modelHub.errors.native_subscription_exists",+ data={"existing_source_id": occupied.id},+ )flow = await self._oauth_call(self._oauth_adapter(oauth_channel).start_oauth(pending_source_id,@@ -3830,12 +3912,22 @@ class ModelHubService:))if flow.source_id != pending_source_id or flow.vendor != vendor:- await self._discard_started_oauth_flow(flow, oauth_channel)- flow_cleanup_done = True+ flow_cleanup_attempted = True+ flow_cleanup_done = await self._discard_started_oauth_flow(+ flow,+ oauth_channel,+ )+ if not flow_cleanup_done:+ raise ModelHubError("engine_down", status=503)raise ModelHubError("flow_not_found", status=502)if client_nonce is not None and flow.expires_at_iso is None:- await self._discard_started_oauth_flow(flow, oauth_channel)- flow_cleanup_done = True+ flow_cleanup_attempted = True+ flow_cleanup_done = await self._discard_started_oauth_flow(+ flow,+ oauth_channel,+ )+ if not flow_cleanup_done:+ raise ModelHubError("engine_down", status=503)raise ModelHubError("flow_not_found", status=502)self.oauth_flows.remember(flow.flow_id,@@ -3849,7 +3941,12 @@ class ModelHubService:)except BaseException as error:try:- if flow is not None and not flow_cleanup_done:+ if (+ flow is not None+ and not flow_cleanup_done+ and not flow_cleanup_attempted+ ):+ flow_cleanup_attempted = Trueawait self._discard_started_oauth_flow(flow,oauth_channel,diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex ad7a06f1d..709985774 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -1,7 +1,10 @@from __future__ import annotations+import astimport asyncio+import inspectimport json+import textwrapfrom datetime import datetime, timezonefrom pathlib import Path@@ -31,7 +34,10 @@ from core.handlers.model_hub.adapter import ()from core.handlers.model_hub.errors import ModelDiscoveryErrorfrom core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent-from core.handlers.model_hub.oauth import NativeOAuthSourceStatus, OAuthFlowRegistry+from core.handlers.model_hub.oauth import (+ NativeOAuthSourceStatus,+ OAuthFlowRegistry,+)from core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import (CONTRACT_VERSION,@@ -1054,6 +1060,58 @@ def test_native_oauth_rejects_duplicate_source_before_adapter(tmp_path):assert adapter.oauth_start_calls == []+def test_nonce_oauth_start_replays_committed_flow_before_native_slot_conflict(tmp_path):+ service, store, adapter = _service(tmp_path)+ request = {+ "vendor": "anthropic",+ "channel": "native_cli",+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",+ }+ first = asyncio.run(service.oauth_start(request))["flow"]+ existing = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],+ )+ store.config.sources.append(existing)+ _refresh_fixture_routes(store.config)++ replayed = asyncio.run(service.oauth_start(request))["flow"]++ assert replayed == first+ assert adapter.oauth_start_calls == [(first["source_id"], "anthropic")]+++def test_native_oauth_malformed_start_keeps_flow_id_when_cleanup_fails(tmp_path):+ """A malformed provider response remains reconcilable if cancel fails."""+ service, _store, adapter = _service(tmp_path)+ original_start = adapter.start_oauth++ async def malformed_start(source_id, vendor):+ flow = await original_start(source_id, vendor)+ return OAuthFlowState(+ **{**flow.__dict__, "source_id": "src_provider_mismatch"}+ )++ adapter.start_oauth = malformed_start+ adapter.fail_cancel = True+ with pytest.raises(ModelHubError) as failed:+ asyncio.run(+ service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})+ )++ assert failed.value.code == "engine_down"+ # The flow id the provider was started under stays the cleanup handle even+ # though its own response disagreed about the source it belongs to.+ assert adapter.cancelled == ["oaf_00000001"]++def test_oauth_start_normalizes_vendor_before_singleton_and_adapter(tmp_path):service, _store, adapter = _service(tmp_path)@@ -3364,6 +3422,116 @@ def test_nonce_oauth_start_owner_cancellation_releases_waiter_and_tuple(tmp_pathassert len(adapter.oauth_start_calls) == 1+def test_oauth_start_keeps_every_owner_await_inside_the_installed_task(tmp_path):+ """A claimed nonce stays awaitable and releasable from the claim onward.++ The claim is what a concurrent same-tuple retry looks for, and the only+ release is ``start_and_remember``'s own ``finally``. An owner await placed+ before the task is installed therefore strands the tuple until restart, so+ this asserts the property rather than the one pre-check that broke it: on the+ owner path from claim to install there is nothing to wait on at all.+ """++ tree = ast.parse(textwrap.dedent(inspect.getsource(ModelHubService.oauth_start)))+ body = tree.body[0].body+ claim = next(i for i, stmt in enumerate(body) if "claim_nonce" in ast.unparse(stmt))+ install = next(+ i for i, stmt in enumerate(body)+ if "_oauth_start_tasks[nonce_key] = task" in ast.unparse(stmt)+ )++ for stmt in body[claim + 1:install]:+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):+ # The task's own awaits are the safe ones: it is installed before it+ # is awaited, and it owns the release.+ continue+ if isinstance(stmt, ast.If) and ast.unparse(stmt.test) == "nonce_key is None":+ # No nonce, no claim — nothing for a retry to await or for a+ # cancellation to leak.+ continue+ waits = [+ node for node in ast.walk(stmt)+ if isinstance(node, (ast.Await, ast.AsyncWith, ast.AsyncFor))+ ]+ assert not waits, f"owner awaits before its task is installed: {ast.unparse(stmt)}"+++def test_nonce_oauth_start_coalesces_a_retry_while_the_native_slot_read_waits(tmp_path):+ """The member the structure guard above exists for, end to end."""++ async def run_concurrent_start():+ service, _, adapter = _service(tmp_path)+ request = {+ "vendor": "anthropic",+ "channel": "native_cli",+ "client_nonce": "ofn_01j5w8z7p4n6q2rt",+ }+ # Migration holds the same lock the native-slot read needs, which is the+ # wait this test is about.+ await service._mutation_lock.acquire()+ owner = asyncio.create_task(service.oauth_start(request))+ await asyncio.sleep(0)+ retry = asyncio.create_task(service.oauth_start(dict(request)))+ await asyncio.sleep(0)++ assert owner.done() is False+ assert retry.done() is False++ service._mutation_lock.release()+ first, second = await asyncio.gather(owner, retry)+ return first, second, adapter++ first, second, adapter = asyncio.run(run_concurrent_start())++ assert first == second+ assert len(adapter.oauth_start_calls) == 1+++def test_native_oauth_start_recovers_the_vendor_after_failure_and_cancel(tmp_path):+ """A login that never reached the CLI leaves nothing behind to unblock."""++ async def run_recovery():+ service, _, adapter = _service(tmp_path)+ original_start = adapter.start_oauth++ async def failing_start(source_id, vendor):+ raise RuntimeError("provider start failed")++ adapter.start_oauth = failing_start+ with pytest.raises(ModelHubError) as failure:+ await service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})+ assert failure.value.code == "engine_down"++ provider_started = asyncio.Event()+ release_provider = asyncio.Event()++ async def blocked_start(source_id, vendor):+ provider_started.set()+ await release_provider.wait()+ return await original_start(source_id, vendor)++ adapter.start_oauth = blocked_start+ pending = asyncio.create_task(+ service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})+ )+ await provider_started.wait()+ pending.cancel()+ with pytest.raises(asyncio.CancelledError):+ await pending+ release_provider.set()+ await asyncio.sleep(0)+ adapter.start_oauth = original_start+ recovered = await service.oauth_start(+ {"vendor": "anthropic", "channel": "native_cli"}+ )+ return recovered, adapter++ recovered, adapter = asyncio.run(run_recovery())++ assert recovered["flow"]["vendor"] == "anthropic"+ assert len(adapter.oauth_start_calls) == 1++def test_cancel_materializes_terminal_successful_hub_reauth(tmp_path):service, store, adapter = _service(tmp_path)source = ModelHubSourceConfig(@@ -3563,6 +3731,37 @@ def test_expired_oauth_flow_is_rejected_before_submit(tmp_path):assert service.oauth_flows.channel(flow["flow_id"]) is None[email protected]("suffix", ["+00:00", "Z", ""])[email protected]("iso,expired", [("2026-07-23T02:59:00", True), ("2026-07-23T03:01:00", False)])+def test_a_flow_deadline_decides_the_same_way_however_it_was_written(tmp_path, iso, suffix, expired):+ """Seed every shape a provider can write the deadline in.++ The service clock is UTC-aware, so a naive timestamp compared against it+ raises ``TypeError`` instead of answering — turning "is this flow still+ open?" into a 500 on a path whose whole job is to answer it.+ """++ service, _, adapter = _service(tmp_path)+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "expires_at_iso": f"{iso}{suffix}",+ }+ )++ submit = lambda: asyncio.run( # noqa: E731+ service.oauth_submit({"flow_id": flow["flow_id"], "value": "code"})+ )+ if expired:+ with pytest.raises(ModelHubError) as exc_info:+ submit()+ assert exc_info.value.code == "flow_expired"+ else:+ submit()+ assert adapter.secret_lengths == [4]++def test_model_hub_mutations_use_existing_origin_and_csrf_guards(monkeypatch, tmp_path):service, _, _ = _service(tmp_path)monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex fe41cae4c..2172d859d 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1571,6 +1571,27 @@ def test_authentication_failure_observation_never_creates_a_source(tmp_path):assert adapter.revoked == ["cred_00000001"]+def test_create_failure_preserves_human_safe_observation_detail(tmp_path):+ adapter = FakeAdapter()+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)++ with pytest.raises(ModelHubError) as exc:+ asyncio.run(service.create_source({"kind": "api_key", "vendor": "custom", "key": "sk-test-detail"}))++ assert exc.value.code == "discovery_failed"+ assert exc.value.detail == "modelHub.errors.authentication_failed"+ assert exc.value.data["observation"]["outcome"] == "authentication_failed"+ assert store.load().sources == []++@pytest.mark.parametrize(("adapter_result", "expected_outcome"),[@@ -1648,6 +1669,38 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):}+def test_unknown_adapter_error_does_not_claim_connection(tmp_path):+ adapter = FakeAdapter()+ adapter.observation_error = RuntimeError("injected adapter failure")+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)++ with pytest.raises(ModelHubError) as exc:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "custom",+ "display_name": "Unknown adapter failure",+ "key": "sk-test-unknown-adapter-error",+ }+ )+ )++ assert exc.value.code == "discovery_failed"+ assert exc.value.detail == "modelHub.errors.adapter_error"+ assert exc.value.data["observation"] == {+ "contract_version": 5,+ "outcome": "adapter_error",+ "reachable": None,+ "authenticated": "unknown",+ "protocol": None,+ "discovery": "not_attempted",+ "models": [],+ }+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]++def test_observation_terminal_legality_has_no_service_or_runtime_copy():from ast import AsyncFunctionDef, Attribute, Call, FunctionDef, Name, parse, walkfrom pathlib import Pathdiff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsxindex bf367fa30..a9525aa68 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { AddApiKeyDialog } from './AddApiKeyDialog';import { createSourceCollectionReadAuthority } from './collectionReadAuthority';-import { modelsApi } from './modelsApi';+import { ApiCallError, modelsApi } from './modelsApi';import { CONTRACT_VERSION, SOURCE_DISPLAY_NAME_MAX_LENGTH, SOURCE_PROTOCOLS, type Source, type SourceObservation } from './types';const observed = (patch: Partial<SourceObservation> = {}): SourceObservation => ({@@ -318,4 +318,84 @@ describe('AddApiKeyDialog', () => {expect(screen.getByRole('button', { name: /^Add$|^添加$/i })).toBeTruthy();expect(create).toHaveBeenCalledOnce();});++ it('renders the safe observation cause when create rejects after probing', async () => {+ const failure = new ApiCallError(+ 'discovery_failed',+ 'modelHub.errors.discovery_failed',+ true,+ [],+ [],+ [],+ 422,+ observed({+ outcome: 'authentication_failed',+ authenticated: 'rejected',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }),+ );+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(observed());+ vi.spyOn(modelsApi, 'createApiKeySource').mockRejectedValue(failure);+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));++ expect(await screen.findByText(i18n.t('settings.models.addKey.fail.auth'))).toBeTruthy();+ expect(screen.queryByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeNull();+ });++ it('re-enters the classified observation state when create rejects with inventory evidence', async () => {+ const failure = new ApiCallError(+ 'discovery_failed',+ 'modelHub.errors.discovery_failed',+ true,+ [],+ [],+ [],+ 422,+ observed({ discovery: 'failed', models: [] }),+ );+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(observed());+ vi.spyOn(modelsApi, 'createApiKeySource').mockRejectedValue(failure);+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));++ expect(await screen.findByText(/model list did not come back|没拿到它的型号清单/i)).toBeTruthy();+ expect(screen.getByRole('button', { name: /Add anyway|仍要添加/i })).toBeTruthy();+ expect(screen.queryByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeNull();+ });++ it('re-enters the classified observation state when create rejects with ambiguous evidence', async () => {+ const failure = new ApiCallError(+ 'discovery_failed',+ 'modelHub.errors.discovery_failed',+ true,+ [],+ [],+ [],+ 422,+ observed({+ outcome: 'ambiguous',+ reachable: true,+ authenticated: 'authenticated',+ protocol: null,+ discovery: 'not_attempted',+ models: [],+ }),+ );+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValue(observed());+ vi.spyOn(modelsApi, 'createApiKeySource').mockRejectedValue(failure);+ renderDialog();+ const user = await fillCredentials();++ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));++ expect(await screen.findByText(/cannot tell which interface|无法判断是哪种接口/i)).toBeTruthy();+ expect(screen.queryByText(i18n.t('settings.models.addKey.fail.unclassified'))).toBeNull();+ });});diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex d27a954c5..66e5a89ad 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -62,11 +62,29 @@ const failureCopy = (cause: AddApiKeyFailure): string => {switch (cause) {case 'auth': return 'settings.models.addKey.fail.auth';case 'network': return 'settings.models.addKey.fail.network';+ case 'interface': return 'settings.models.addKey.fail.undetermined';case 'engineDown': return 'settings.models.addKey.fail.engineDown';case 'unclassified': return 'settings.models.addKey.fail.unclassified';}};+const observationFailureCopy = (observation: SourceObservation | undefined): string | null => {+ if (!observation) return null;+ if (observation.outcome === 'authentication_failed') return 'settings.models.addKey.fail.auth';+ if (observation.outcome === 'unreachable' || observation.outcome === 'timeout') return 'settings.models.addKey.fail.network';+ if (observation.outcome === 'ambiguous') return 'settings.models.addKey.fail.undetermined';+ if (observation.outcome === 'observed' && observation.discovery === 'failed') return 'settings.models.addKey.fail.inventory';+ return 'settings.models.addKey.fail.unclassified';+};++const failureMessageKey = (failure: ReturnType<typeof apiFailure>): string | null => {+ if (!failure) return null;+ const observationKey = observationFailureCopy(failure.observation);+ if (observationKey) return observationKey;+ if (failure.detail?.startsWith('modelHub.errors.')) return failure.detail;+ return failure.code || null;+};+export const AddApiKeyDialog: React.FC<{open: boolean;onClose: () => void;@@ -123,9 +141,22 @@ export const AddApiKeyDialog: React.FC<{&& failure.responseStatus >= 400&& failure.responseStatus < 500&& failure.responseStatus !== 409;- continuation.settle(seq, () => setPhase(definitiveClientFailure- ? { kind: 'persist_failure', messageKey: failure.detail ?? failure.code ?? null, protocolOrder }- : { kind: 'save_unconfirmed', protocolOrder }));+ const verdict = failure?.observation ? classifyObservation(failure.observation) : null;+ continuation.settle(seq, () => {+ if (definitiveClientFailure && verdict && verdict.kind !== 'ready') {+ if (verdict.kind === 'undetermined') {+ setPhase({ kind: 'undetermined', origin: 'add', observation: verdict.observation, hint: null });+ } else if (verdict.kind === 'inventory') {+ setPhase({ kind: 'inventory', origin: 'add', observation: verdict.observation });+ } else {+ setPhase({ kind: 'failure', origin: 'add', cause: verdict.cause });+ }+ return;+ }+ setPhase(definitiveClientFailure+ ? { kind: 'persist_failure', messageKey: failureMessageKey(failure), protocolOrder }+ : { kind: 'save_unconfirmed', protocolOrder });+ });}}, [continuation, createdDelivery, draft]);diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.tsindex 8001f1f90..bf94843c4 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts@@ -1,5 +1,14 @@-import { describe, expect, it } from 'vitest';+// @vitest-environment jsdom+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { I18nextProvider } from 'react-i18next';+import * as React from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ToastProvider } from '@/context/ToastProvider';+import i18n from '@/i18n';+import { OAuthConnectDialog } from './OAuthConnectDialog';+import { ApiCallError, modelsApi } from './modelsApi';import {initialSubscriptionChannel,nativeSubscriptionSlotTaken,@@ -8,6 +17,11 @@ import {} from './subscriptionOptions';import type { Source } from './types';+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});+const subscription = (over: Partial<Source> = {}): Source => ({id: 'src_subscription',last_discovered_at: null,@@ -49,3 +63,44 @@ describe('add-subscription channel choice', () => {expect(nativeSubscriptionSlotTaken('anthropic', sources)).toBe(false);});});++describe('add-subscription start recovery', () => {+ it('reuses the exact nonce after a start response is lost', async () => {+ const start = vi.spyOn(modelsApi, 'startOAuth')+ .mockRejectedValueOnce(new ApiCallError('bad_response', undefined, false))+ .mockResolvedValueOnce({+ flow_id: 'oaf_recovered',+ client_nonce: 'server-echo-is-not-the-authority',+ vendor: 'anthropic',+ channel: 'native_cli',+ state: 'awaiting_action',+ presentation: { expects: 'paste_code' },+ expires_at: '2099-01-01T00:00:00Z',+ });++ render(React.createElement(+ ToastProvider,+ null,+ React.createElement(+ I18nextProvider,+ { i18n },+ React.createElement(OAuthConnectDialog, {+ open: true,+ vendor: 'anthropic',+ sources: [],+ onClose: vi.fn(),+ onConnected: vi.fn(),+ }),+ ),+ ));++ const user = userEvent.setup();+ await user.click(screen.getByRole('button', { name: /Sign in|去登录/i }));+ await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));++ await waitFor(() => expect(start).toHaveBeenCalledTimes(2));+ expect(start.mock.calls[0].slice(0, 2)).toEqual(['anthropic', 'native_cli']);+ expect(start.mock.calls[1]).toEqual(start.mock.calls[0]);+ expect(start.mock.calls[0][2]).toMatch(/^ofn_[a-z0-9]{16,64}$/);+ });+});diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex a7287c114..8b88b3e8a 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -37,8 +37,9 @@ import {type FlowView,} from './asyncLifetime';import { apiFailure, modelsApi, type Adoption, type OAuthResult } from './modelsApi';+import { preopenProviderTab, takeHandedProviderTab } from './providerTab';import { REPAIR_LINE_KEY, REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';-import { oauthFailureKey, serverText, type OAuthJourney } from './serverCopy';+import { NATIVE_SUBSCRIPTION_EXISTS_FAILURE, oauthFailureKey, oauthStartFailureKey, serverText, type OAuthJourney } from './serverCopy';import {initialSubscriptionChannel,nativeSubscriptionSlotTaken,@@ -89,9 +90,18 @@ export const OAuthConnectDialog: React.FC<{const [view, setView] = React.useState<FlowView>(initialFlowView);const [code, setCode] = React.useState('');const [submitting, setSubmitting] = React.useState(false);- const [channel, setChannel] = React.useState<SupplyChannel>('native_cli');+ // Seed the chooser from the opening snapshot. Radix may autofocus a control+ // before the passive open effect runs; deriving this here prevents an occupied+ // native row from ever being the initially focused/selected option.+ const [channel, setChannel] = React.useState<SupplyChannel>(() =>+ reauth ? (reauth.supply_channel ?? 'native_cli') : initialSubscriptionChannel(vendor, sources),+ );const [phase, setPhase] = React.useState<ConnectPhase>('choose');- const [nativeSlotTaken, setNativeSlotTaken] = React.useState(false);+ const [nativeSlotTaken, setNativeSlotTaken] = React.useState(() =>+ !reauth && nativeSubscriptionSlotTaken(vendor, sources),+ );+ const [startAttempt, setStartAttempt] = React.useState(0);+ const [startFailureCode, setStartFailureCode] = React.useState<string | null>(null);// Which Agents took the new subscription in, frozen at commit (api.md). Same// note as the API-key dialog: connecting a credential is not the same as// putting it into service, and an Agent with no accepted match is absent.@@ -127,6 +137,37 @@ export const OAuthConnectDialog: React.FC<{const onCloseRef = React.useRef(onClose);onCloseRef.current = onClose;const initializedOpenSubject = React.useRef<string | null>(null);+ const clientNonce = React.useRef<string | null>(null);+ const providerWindow = React.useRef<Window | null>(null);+ const heldFlowId = React.useRef<string | null>(null);+ const rereadHeldFlow = React.useRef<(() => Promise<boolean>) | null>(null);++ const preopenProviderWindow = React.useCallback(() => {+ if (providerWindow.current && !providerWindow.current.closed) return;+ providerWindow.current = preopenProviderTab();+ }, []);++ const closeProviderWindow = React.useCallback(() => {+ // Also the tab a gesture outside this dialog handed over: an unused handoff+ // is an unused tab, and this is already the owner that closes one.+ const target = providerWindow.current ?? takeHandedProviderTab();+ providerWindow.current = null;+ if (!target || target.closed) return;+ try {+ target.close();+ } catch {+ // Cross-origin or already-closing windows can reject access; clearing the+ // ref above is still the important ownership transition.+ }+ }, []);++ const createClientNonce = React.useCallback(() => {+ const uuid = globalThis.crypto?.randomUUID?.();+ if (uuid) return `ofn_${uuid.replaceAll('-', '').toLowerCase()}`;+ const bytes = new Uint8Array(16);+ globalThis.crypto?.getRandomValues?.(bytes);+ return `ofn_${Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('')}`;+ }, []);const accent = vendor === 'openai' ? 'gold' : 'mint';// One derivation for 「which journey is this」, read by the start call, the@@ -145,11 +186,17 @@ export const OAuthConnectDialog: React.FC<{React.useEffect(() => {if (!openSubject) {initializedOpenSubject.current = null;+ clientNonce.current = null;+ setStartAttempt(0);+ setStartFailureCode(null);setPhase('choose');return;}if (initializedOpenSubject.current === openSubject) return;initializedOpenSubject.current = openSubject;+ clientNonce.current = null;+ setStartAttempt(0);+ setStartFailureCode(null);if (isReauth) {setChannel(reauth?.supply_channel ?? 'native_cli');setPhase('flow');@@ -334,6 +381,7 @@ export const OAuthConnectDialog: React.FC<{// the guard above already makes that poll harmless, but there is no reason// to let it fire.if (isDone(step.action)) stop();+ if (isDone(step.action)) closeProviderWindow();return isDone(step.action);};settleRef.current = settle;@@ -343,7 +391,28 @@ export const OAuthConnectDialog: React.FC<{// could have written — unlike the two exits below.if (cancelled) return;const overdue = transition({ kind: 'tick', overdue: Date.now() > deadline });- if (isDone(overdue.action)) return;+ if (isDone(overdue.action)) {+ // Keep the just-expired flow addressable. Retry performs one authoritative+ // status read before it is allowed to mint a fresh provider flow.+ if (overdue.action === 'timeout' && openedFlowId) {+ const timedOutFlowId = openedFlowId;+ rereadHeldFlow.current = async () => {+ try {+ const result = await modelsApi.getOAuthStatus(timedOutFlowId);+ if (cancelled || flowAuthorityRef.current !== authority) return true;+ transition({ kind: 'reset' });+ if (settle(result)) return true;+ // The held flow is still pending. Let retryStart continue with a+ // fresh acquisition; this status read was the required last chance+ // to observe a near-deadline terminal result.+ return false;+ } catch {+ return false;+ }+ };+ }+ return;+ }try {const result = await modelsApi.getOAuthStatus(flowId);if (cancelled) {@@ -375,7 +444,7 @@ export const OAuthConnectDialog: React.FC<{// about the flow at all — that same read is what materializes a// just-succeeded one. Keep reading instead of stopping; the deadline check// at the top of each poll bounds either.- if (!pollFailureSettles(submittingRef.current, failure?.serverNamed ?? false)) {+ if (!pollFailureSettles(submittingRef.current, failure?.serverNamed ?? false, failure?.code ?? failure?.detail)) {pollTimer = window.setTimeout(() => void poll(flowId), POLL_MS);return;}@@ -401,7 +470,7 @@ export const OAuthConnectDialog: React.FC<{// existing source; a create opens a fresh one for the selected channel.const started = reauthId? await modelsApi.reauthSource(reauthId)- : await modelsApi.startOAuth(vendor, channel);+ : await modelsApi.startOAuth(vendor, channel, clientNonce.current ?? (clientNonce.current = createClientNonce()));if (cancelled) {// The dialog closed while this request was in flight, so the cleanup// below found no flow to cancel — the flow id exists nowhere but here.@@ -445,6 +514,7 @@ export const OAuthConnectDialog: React.FC<{// to find a null. Earlier than this the abandoned-start branch above is the// owner, because cleanup has already run and already answered.openedFlowId = started.flow_id;+ heldFlowId.current = started.flow_id;if (startNeedsStatusRead(started)) {await poll(started.flow_id);return;@@ -472,8 +542,10 @@ export const OAuthConnectDialog: React.FC<{// position moves.const step = transition({kind: 'error',- errorKey: 'settings.models.oauth.error.start',+ errorKey: isReauth ? 'settings.models.oauth.error.start' : oauthStartFailureKey(failure?.detail ?? failure?.code),});+ if (!isReauth) setStartFailureCode(failure?.detail ?? failure?.code ?? 'start_failed');+ closeProviderWindow();rowsBehindAreStale(failure, failureLanded(step.action));}})();@@ -508,13 +580,16 @@ export const OAuthConnectDialog: React.FC<{// first, and by then the attempt it belongs to is not merely settled but// GONE. Whatever gap report is on screen when it returns is somebody else's.const opened = openedFlowId;+ closeProviderWindow();+ if (heldFlowId.current === opened) heldFlowId.current = null;+ rereadHeldFlow.current = null;void releaseFlow(authority, owner, {cancel: opened ? () => modelsApi.cancelOAuth(opened) : null,reusable: isReauth,reread: () => rowsBehindAreStale(),});};- }, [open, phase, vendor, channel, reauthId, t, showToast, isReauth, rowsBehindAreStale, resolvedAfterAttempt, journey]);+ }, [open, phase, startAttempt, vendor, channel, reauthId, t, showToast, isReauth, rowsBehindAreStale, resolvedAfterAttempt, journey, createClientNonce]);// 1-second ticker so the paste-flow countdown updates.React.useEffect(() => {@@ -575,6 +650,28 @@ export const OAuthConnectDialog: React.FC<{}};+ const retryStart = async () => {+ if (startFailureCode === NATIVE_SUBSCRIPTION_EXISTS_FAILURE && !isReauth) {+ // The start route checked the current store under its mutation lock, so+ // this error is newer and more authoritative than the page snapshot.+ setNativeSlotTaken(true);+ setChannel('hub');+ setStartFailureCode(null);+ closeProviderWindow();+ setPhase('choose');+ return;+ }+ const timedOutFlow = view.errorKey === 'settings.models.oauth.error.timeout' ? heldFlowId.current : null;+ if (timedOutFlow && rereadHeldFlow.current) {+ if (await rereadHeldFlow.current()) return;+ }+ const freshAcquisition = startFailureCode === null;+ setStartFailureCode(null);+ if (freshAcquisition) clientNonce.current = null;+ setStartAttempt((attempt) => attempt + 1);+ setPhase('flow');+ };+const { flow, errorKey } = view;const presentation = flow?.presentation;const expects = presentation?.expects;@@ -603,6 +700,29 @@ export const OAuthConnectDialog: React.FC<{: 'settings.models.oauth.pasteCode.hint';const step2Label = serverText(t, presentation?.instructions_key, step2Fallback) ?? '';+ const flowActive = Boolean(+ flow+ && !view.settled+ && (flow.state === 'starting' || flow.state === 'awaiting_action' || flow.state === 'verifying'),+ );+ React.useEffect(() => {+ if (!flowActive || !presentation?.auth_url) return;+ // Claimed at the point of use, not when the dialog opens: the re-auth journey's+ // tab is allocated by the confirm gesture before this component exists, and a+ // claim taken at mount is stranded by anything that remounts (StrictMode+ // replays effects in development) with the tab still open and unreachable.+ // Claiming here also means a run with nothing to navigate keeps the handoff.+ const target = providerWindow.current ?? takeHandedProviderTab();+ if (!target || target.closed) return;+ try {+ target.location.href = presentation.auth_url;+ } catch {+ // A popup may become inaccessible after opening; the visible link remains+ // the fallback in that case.+ }+ providerWindow.current = null;+ }, [flowActive, presentation?.auth_url]);+const choosing = !isReauth && phase === 'choose';const vendorCopy = subscriptionVendorCopy(vendor);const vendorName = vendor === 'openai' ? 'ChatGPT' : 'Claude';@@ -625,7 +745,13 @@ export const OAuthConnectDialog: React.FC<{<DialogPrimitive.Root open={open} onOpenChange={(value) => !value && onClose()}><DialogPrimitive.Portal><DialogPrimitive.Overlay className="model-hub-add-sub-overlay fixed inset-0 z-50" />- <DialogPrimitive.Content className="model-hub-add-sub-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-y-auto border border-border-strong bg-surface p-0 shadow-xl outline-none">+ <DialogPrimitive.Content+ className="model-hub-add-sub-dialog fixed left-1/2 top-1/2 z-50 flex max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-y-auto border border-border-strong bg-surface p-0 shadow-xl outline-none"+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ window.requestAnimationFrame(() => optionRefs.current[channel]?.focus());+ }}+ ><header className="model-hub-add-sub-head flex flex-col border-b border-border"><div className="flex items-center justify-between gap-3"><DialogPrimitive.Title id="model-hub-add-sub-title" className="model-hub-add-sub-title font-bold">@@ -731,7 +857,15 @@ export const OAuthConnectDialog: React.FC<{<Button variant="ghost" size="sm" className="model-hub-dialog-action" onClick={onClose}>{t('settings.models.addSub.cancel')}</Button>- <Button variant="brand" size="sm" className="model-hub-dialog-action" onClick={() => setPhase('flow')}>+ <Button+ variant="brand"+ size="sm"+ className="model-hub-dialog-action"+ onClick={() => {+ preopenProviderWindow();+ setPhase('flow');+ }}+ >{t('settings.models.addSub.signIn')}<ArrowRight className="size-3.5" /></Button>@@ -767,11 +901,13 @@ export const OAuthConnectDialog: React.FC<{an unknown one degrades to 连接失败 rather than rendering itself. */}<span>{serverText(t, errorKey, 'settings.models.oauth.error.generic')}</span></div>+ {isReauth && stranded.length > 0 && <>{/* Past tense (`gapsDone`), because this is not a confirm: thecredential change these pairs are the cost of has alreadyhappened. Self-hides when the failure stranded nobody. */}<p className="text-[12px] font-semibold text-foreground">{t('settings.models.repair.gapsDone')}</p><GuardGapList gaps={stranded} />+ </>}</div>)}@@ -880,9 +1016,29 @@ export const OAuthConnectDialog: React.FC<{) : (<span />)}- <Button variant={active ? 'ghost' : 'outline'} size="sm" className="h-10 sm:h-9" onClick={onClose}>- {active ? t('common.cancel') : t('common.close')}- </Button>+ <div className="flex items-center gap-2">+ {/* A re-auth retry too. `retryStart` repeats the journey it is in, and+ on a failed re-auth the irreversible half is already spent — the+ siblings are already marked — so sending the user back to the row+ to confirm it a second time asks them to agree to a cost they have+ already paid, for the only gesture that can undo it. */}+ {failed && (+ <Button+ variant="brand"+ size="sm"+ className="h-10 sm:h-9"+ onClick={() => {+ preopenProviderWindow();+ void retryStart();+ }}+ >+ {t('settings.models.addSub.retry')}+ </Button>+ )}+ <Button variant={active ? 'ghost' : 'outline'} size="sm" className="h-10 sm:h-9" onClick={onClose}>+ {active ? t('common.cancel') : t('common.close')}+ </Button>+ </div></div></DialogContent></Dialog>diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex ef20b42ed..f04db7d97 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -1,5 +1,7 @@// @vitest-environment jsdom-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -38,6 +40,20 @@ const retainedSource: Source = {models: [],};+const nativeSubscription: Source = {+ ...retainedSource,+ id: 'src_native_subscription',+ kind: 'subscription',+ supply_channel: 'native_cli',+ display_name: 'Claude native login',+};++/** The row every re-auth journey starts from: a subscription that stopped. */+const blockedSubscription: Source = {+ ...nativeSubscription,+ state: { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' },+};+const takeoverAgent: AgentSupply = {backend: 'codex',cli_present: true,@@ -98,6 +114,16 @@ afterEach(() => {});describe('SettingsModelsPage surface branches', () => {+ it('coalesces the OAuth success landing with its trailing stale-row notification', () => {+ const page = readFileSync(join(process.cwd(), 'src/components/settings/models/SettingsModelsPage.tsx'), 'utf8');+ const start = page.indexOf('const subscriptionAdded');+ const callback = page.slice(start, page.indexOf('React.useEffect(() => {', start));++ expect(callback).toMatch(/if \(!source\) \{[\s\S]*?subscriptionSuccessReconcileRef\.current/);+ expect(callback).toMatch(/sourceEntityAuthority\.landLatest\(source\)[\s\S]*?subscriptionSuccessReconcileRef\.current = true;[\s\S]*?void refresh\(\)/);+ expect((callback.match(/void refresh\(\)/g) ?? []).length).toBe(2);+ });+it('renders Frame 09 without tabs when every backend is direct and no source exists', async () => {renderPage([]);@@ -183,6 +209,168 @@ describe('SettingsModelsPage surface branches', () => {expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到网关,你会多出三件事$/i)).toBeNull();});+ it('opens the subscription vendor picker and OAuth flow from the Sources card', async () => {+ renderPage([retainedSource]);++ await screen.findByText('Retained source');+ await userEvent.click(screen.getByRole('button', { name: /Add subscription|添加订阅/i }));+ expect(await screen.findByRole('dialog')).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /Claude subscription|Claude 订阅/i }));++ expect((await screen.findByRole('dialog')).textContent).toMatch(/Add Claude subscription|添加 anthropic 订阅/i);+ });++ it('supports roving keyboard navigation in the subscription vendor picker', async () => {+ renderPage([retainedSource]);++ const user = userEvent.setup();+ await screen.findByText('Retained source');+ const trigger = screen.getByRole('button', { name: /Add subscription|添加订阅/i });+ await user.click(trigger);+ const picker = await screen.findByRole('dialog');+ const claude = within(picker).getByRole('button', { name: /Claude subscription|Claude 订阅/i });+ const chatgpt = within(picker).getByRole('button', { name: /ChatGPT subscription|ChatGPT 订阅/i });++ await waitFor(() => expect(document.activeElement).toBe(claude));+ expect(claude.getAttribute('tabindex')).toBe('0');+ expect(chatgpt.getAttribute('tabindex')).toBe('-1');+ await user.keyboard('{ArrowDown}');+ expect(document.activeElement).toBe(chatgpt);+ await user.keyboard('{Home}');+ expect(document.activeElement).toBe(claude);+ await user.keyboard('{End}');+ expect(document.activeElement).toBe(chatgpt);+ await user.keyboard('{ArrowUp}');+ expect(document.activeElement).toBe(claude);+ });++ it('restores the Add subscription trigger when the vendor picker is dismissed', async () => {+ renderPage([retainedSource]);++ const user = userEvent.setup();+ await screen.findByText('Retained source');+ const trigger = screen.getByRole('button', { name: /Add subscription|添加订阅/i });+ await user.click(trigger);+ await screen.findByRole('dialog');+ await user.keyboard('{Escape}');++ await waitFor(() => expect(document.activeElement).toBe(trigger));+ });++ it('opens an occupied native vendor with the gateway option selected', async () => {+ renderPage([nativeSubscription]);++ const user = userEvent.setup();+ await screen.findByText('Claude native login');+ await user.click(screen.getByRole('button', { name: /Add subscription|添加订阅/i }));+ await user.click(await screen.findByRole('button', { name: /Claude subscription|Claude 订阅/i }));++ const native = await screen.findByRole('radio', { name: /Native|原生/i });+ const hub = screen.getByRole('radio', { name: /Gateway|网关/i });+ expect(native.getAttribute('aria-disabled')).toBe('true');+ expect(hub.getAttribute('aria-checked')).toBe('true');+ await waitFor(() => expect(document.activeElement).toBe(hub));+ });++ it('returns focus to Add subscription when the OAuth flow is cancelled', async () => {+ renderPage([retainedSource]);++ await screen.findByText('Retained source');+ const trigger = screen.getByRole('button', { name: /Add subscription|添加订阅/i });+ await userEvent.click(trigger);+ await userEvent.click(screen.getByRole('button', { name: /Claude subscription|Claude 订阅/i }));+ const cancelButtons = screen.getAllByRole('button', { name: /^Cancel$|^取消$/i });+ await userEvent.click(cancelButtons[cancelButtons.length - 1]);++ await waitFor(() => expect(document.activeElement).toBe(trigger));+ });++ // The wiring §4.5 was missing, end to end. `repair.ts` had decided the remedy+ // and `OAuthConnectDialog` had run the re-login journey since it shipped, but no+ // mount connected them, so a stopped subscription rendered its cause and+ // stopped. The proof is the request: from the row a user can reach, one tap and+ // one confirm reach `POST …/reauth` for THAT source.+ it('reaches the re-auth request from a stopped subscription row', async () => {+ const started = {+ flow_id: 'flow_reauth',+ intent: 'reauth' as const,+ vendor: 'anthropic',+ channel: 'native_cli' as const,+ state: 'starting' as const,+ presentation: { expects: 'none' as const },+ };+ const reauth = vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(started);+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue(started);+ 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 }));+ expect(reauth).not.toHaveBeenCalled();+ await userEvent.click(await screen.findByRole('button', { name: /^Start sign-in$|^开始登录$/i }));++ await waitFor(() => expect(reauth).toHaveBeenCalledWith(blockedSubscription.id));+ });++ // The confirm IS this journey's gesture — the dialog it opens POSTs as it mounts,+ // so nothing after it can be granted a tab. Asserted where the user feels it: the+ // provider page lands in the tab, instead of behind a blocked popup and a link+ // the user has to notice.+ it('lands the provider page in the tab the re-auth confirmation opened', async () => {+ const authUrl = 'https://provider.example/authorize?code=1';+ const started = {+ flow_id: 'flow_reauth',+ intent: 'reauth' as const,+ vendor: 'anthropic',+ channel: 'native_cli' as const,+ state: 'awaiting_action' as const,+ presentation: { expects: 'paste_callback_url' as const, auth_url: authUrl },+ };+ vi.spyOn(modelsApi, 'reauthSource').mockResolvedValue(started);+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue(started);+ const tab = { closed: false, opener: {} as unknown, location: { href: '' } };+ const open = vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window);+ 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 }));++ expect(open).toHaveBeenCalledWith('about:blank', '_blank');+ expect(tab.opener).toBeNull();+ await waitFor(() => expect(tab.location.href).toBe(authUrl));+ });++ // A failed re-auth has already spent the irreversible half — the sibling sources+ // are already marked. Sending the user back to the row to agree to that cost a+ // second time, for the only gesture that can undo it, is the one journey where a+ // second confirmation is worse than none.+ it('retries a failed re-auth in place, without asking to confirm again', async () => {+ const started = {+ flow_id: 'flow_reauth',+ intent: 'reauth' as const,+ vendor: 'anthropic',+ channel: 'native_cli' as const,+ state: 'starting' as const,+ presentation: { expects: 'none' as const },+ };+ const reauth = vi+ .spyOn(modelsApi, 'reauthSource')+ .mockRejectedValueOnce(new Error('start failed'))+ .mockResolvedValue(started);+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue(started);+ 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 retry = await screen.findByRole('button', { name: /^Retry$|^重试$/i });+ expect(screen.queryByRole('button', { name: /^Start sign-in$|^开始登录$/i })).toBeNull();+ await userEvent.click(retry);++ await waitFor(() => expect(reauth).toHaveBeenCalledTimes(2));+ });+it('lands the operational overview without waiting for event history', async () => {const pendingEvents = deferred<[]>();vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 82b437bff..49ddcd5ac 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,11 +1,13 @@import * as React from 'react';-import { ArrowLeft, Gauge, Info, LoaderCircle, Route } from 'lucide-react';+import { ArrowLeft, Gauge, Info, LoaderCircle, Route, Sparkles } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';import { AddApiKeyDialog } from './AddApiKeyDialog';+import { OAuthConnectDialog } from './OAuthConnectDialog';import { AdvancedRow } from './AdvancedRow';import { EnableGatewayDialog } from './EnableGatewayDialog';import { GatewayModule } from './GatewayModule';@@ -286,6 +288,28 @@ export const SettingsModelsPage: React.FC = () => {const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);const [installOpen, setInstallOpen] = React.useState(false);const [apiKeyOpen, setApiKeyOpen] = React.useState(false);+ const [subscriptionPickerOpen, setSubscriptionPickerOpen] = React.useState(false);+ const [subscriptionPickerIndex, setSubscriptionPickerIndex] = React.useState(0);+ const [subscriptionVendor, setSubscriptionVendor] = React.useState<string | null>(null);+ // The source a re-login is FOR, held as the snapshot `OAuthConnectDialog`+ // documents its `reauth` prop to be: a native re-auth writes 需处理 onto the row+ // before the login starts, so re-reading the live row mid-flow would rewrite+ // the dialog's own subject. Separate from `subscriptionVendor` because the two+ // journeys start from different surfaces — this one from the source detail,+ // which replaces the overview that holds 添加订阅 — and only the create path+ // owns the success-landing timer and reconcile flag below.+ const [reauthSource, setReauthSource] = React.useState<Source | null>(null);+ const subscriptionTriggerRef = React.useRef<HTMLButtonElement>(null);+ const subscriptionPickerRefs = React.useRef<Partial<Record<'anthropic' | 'openai', HTMLButtonElement | null>>>({});+ const subscriptionPickerHandoffRef = React.useRef(false);+ const subscriptionCloseTimer = React.useRef<number | null>(null);+ // A successful OAuth terminal reports the same moved rows twice: first with+ // the created source, then as the generic stale-row notification. The source+ // callback owns the one full reconciliation; consume the trailing notification+ // so it cannot launch a second refresh that overwrites a successful landing.+ const subscriptionSuccessReconcileRef = React.useRef(false);+ const sourceDetailHeadingRef = React.useRef<HTMLHeadingElement>(null);+ const focusSourceDetailPendingRef = React.useRef(false);const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);const [adoptAgent, setAdoptAgent] = React.useState<AgentSupply | null>(null);const [routeTarget, setRouteTarget] = React.useState<{ agent: AgentSupply; modelId: string; opener: HTMLElement | null } | null>(null);@@ -831,6 +855,77 @@ export const SettingsModelsPage: React.FC = () => {reconcile: refresh,});};+ const subscriptionAdded = React.useCallback((source?: Source) => {+ if (!source) {+ if (subscriptionSuccessReconcileRef.current) {+ subscriptionSuccessReconcileRef.current = false;+ return;+ }+ void refresh();+ return;+ }+ // Keep the success panel readable until its existing handoff timer closes it;+ // the effect below then moves focus into the committed source detail surface.+ focusSourceDetailPendingRef.current = true;+ sourceEntityAuthority.landLatest(source);+ selectSource(source.id);+ subscriptionSuccessReconcileRef.current = true;+ void refresh();+ if (subscriptionCloseTimer.current !== null) window.clearTimeout(subscriptionCloseTimer.current);+ subscriptionCloseTimer.current = window.setTimeout(() => {+ subscriptionCloseTimer.current = null;+ setSubscriptionVendor(null);+ }, 1400);+ }, [refresh, selectSource, sourceEntityAuthority]);+ React.useEffect(() => {+ if (!focusSourceDetailPendingRef.current || subscriptionVendor !== null || !selectedSourceId || !selectedSource) return;+ focusSourceDetailPendingRef.current = false;+ window.requestAnimationFrame(() => sourceDetailHeadingRef.current?.focus());+ }, [selectedSource, selectedSourceId, subscriptionVendor]);+ const closeSubscription = React.useCallback(() => {+ if (subscriptionCloseTimer.current !== null) {+ window.clearTimeout(subscriptionCloseTimer.current);+ subscriptionCloseTimer.current = null;+ }+ setSubscriptionVendor(null);+ window.setTimeout(() => subscriptionTriggerRef.current?.focus(), 0);+ }, []);+ /**+ * A re-login's whole obligation to this page: re-read everything.+ *+ * Not `subscriptionAdded`, even though the reauth journey also calls back with+ * no source. That callback's no-source branch can be CONSUMED by the create+ * path's success flag, and a reauth has no success landing to coalesce with —+ * it terminates on the row it started from. And the read has to be the wide+ * one: `_materialize_reauth` can leave other agents without a source, so+ * `/agents` and the chains behind it are stale too, not just this row.+ */+ const sourceReauthed = React.useCallback(() => { void refresh(); }, [refresh]);+ const closeReauth = React.useCallback(() => {+ setReauthSource(null);+ // Back to the detail heading rather than to the button that opened this: a+ // repair that worked unmounts that button (the row is no longer stopped), and+ // Radix would restore focus to a node that is gone — i.e. to <body>.+ window.setTimeout(() => sourceDetailHeadingRef.current?.focus(), 0);+ }, []);+ const closeSubscriptionPicker = React.useCallback(() => {+ subscriptionPickerHandoffRef.current = false;+ setSubscriptionPickerOpen(false);+ }, []);+ const focusSubscriptionPickerOption = React.useCallback((index: number) => {+ const bounded = Math.max(0, Math.min(index, 1));+ setSubscriptionPickerIndex(bounded);+ const vendor = (['anthropic', 'openai'] as const)[bounded];+ subscriptionPickerRefs.current[vendor]?.focus();+ }, []);+ const openSubscriptionPicker = React.useCallback(() => {+ subscriptionPickerHandoffRef.current = false;+ setSubscriptionPickerIndex(0);+ setSubscriptionPickerOpen(true);+ }, []);+ React.useEffect(() => () => {+ if (subscriptionCloseTimer.current !== null) window.clearTimeout(subscriptionCloseTimer.current);+ }, []);return (<ModelHubShell@@ -854,7 +949,7 @@ export const SettingsModelsPage: React.FC = () => {{landingLoading ? <div className="text-[13px] text-muted">{t('common.loading')}</div>: selectedSourceId? selectedSource- ? <SourceDetailPanel source={selectedSource} trackMutation={trackSourceMutation(selectedSource.id)} />+ ? <SourceDetailPanel source={selectedSource} headingRef={sourceDetailHeadingRef} trackMutation={trackSourceMutation(selectedSource.id)} onReauth={setReauthSource} />: <section className="rounded-xl border border-border bg-surface px-5 py-12 text-center text-[12px] text-muted">{t('settings.models.sourceDetail.gone')}</section>: directEmpty ? <DirectHome agents={installedAgents} onSwitch={setAdoptAgent} />: <div className="space-y-[22px]">@@ -862,7 +957,7 @@ export const SettingsModelsPage: React.FC = () => {{tab === 'sources' ? <div className="model-hub-overview"><div className="model-hub-overview-body"><div ref={overviewRef} className="model-hub-overview-grid relative flex flex-col gap-4">- <SourcesCard read={sourcesRead} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} />+ <SourcesCard read={sourcesRead} readFailureCopy={routeCommitStatus?.failed.has('sources') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} onRetry={() => routeCommitStatus?.failed.has('sources') ? retryRouteCommit() : void retrySources()} onOpenSource={(source) => selectSource(source.id)} onAddApiKey={() => setApiKeyOpen(true)} onAddSubscription={openSubscriptionPicker} subscriptionTriggerRef={subscriptionTriggerRef} /><div className="hidden lg:block" aria-hidden="true" /><GatewayModule supply={installedSupplyRead} readFailureCopy={routeCommitStatus?.failed.has('agents') ? t('settings.models.routeDialog.impact.refreshFail') : undefined} sources={sources} chains={chains} runtime={runtime} runtimeSnapshot={retainedRuntime} onRetry={() => routeCommitStatus?.failed.has('agents') ? retryRouteCommit() : void retrySupply()} pendingBackends={agentWrites} switchFailures={switchFailures} connectingBackend={adoptAgent?.backend ?? null} onConnectHub={setAdoptAgent} onSwitchDirect={switchToDirect} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} /><SupplyGraph containerRef={overviewRef} relations={supplyRelations} />@@ -874,6 +969,84 @@ export const SettingsModelsPage: React.FC = () => {</div> : <section className="rounded-xl border border-border bg-surface px-5 py-8"><div className="flex items-start gap-3"><Info className="mt-0.5 size-4 text-muted" /><div><h2 className="text-[14px] font-semibold text-foreground">{t('settings.models.usageTab.title')}</h2><p className="mt-1 text-[12px] text-muted">{t('settings.models.usageTab.detail')}</p></div></div></section>}</div>}<AddApiKeyDialog open={apiKeyOpen} sourceReads={sourceCollectionReads} onClose={() => setApiKeyOpen(false)} onAdded={(created) => void sourceAdded(created)} />+ <Dialog open={subscriptionPickerOpen} onOpenChange={(open) => open ? setSubscriptionPickerOpen(true) : closeSubscriptionPicker()}>+ <DialogContent+ className="max-w-[420px]"+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ window.requestAnimationFrame(() => subscriptionPickerRefs.current[(['anthropic', 'openai'] as const)[subscriptionPickerIndex]]?.focus());+ }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ if (subscriptionPickerHandoffRef.current) {+ subscriptionPickerHandoffRef.current = false;+ return;+ }+ window.setTimeout(() => subscriptionTriggerRef.current?.focus(), 0);+ }}+ >+ <DialogHeader>+ <DialogTitle>{t('settings.models.subscriptionPicker.title')}</DialogTitle>+ <DialogDescription>{t('settings.models.subscriptionPicker.detail')}</DialogDescription>+ </DialogHeader>+ <div className="grid gap-2 sm:grid-cols-2" onKeyDown={(event) => {+ if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {+ event.preventDefault();+ focusSubscriptionPickerOption(subscriptionPickerIndex + 1);+ } else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {+ event.preventDefault();+ focusSubscriptionPickerOption(subscriptionPickerIndex - 1);+ } else if (event.key === 'Home') {+ event.preventDefault();+ focusSubscriptionPickerOption(0);+ } else if (event.key === 'End') {+ event.preventDefault();+ focusSubscriptionPickerOption(1);+ }+ }}>+ {(['anthropic', 'openai'] as const).map((vendor, index) => (+ <Button+ key={vendor}+ ref={(node) => { subscriptionPickerRefs.current[vendor] = node; }}+ type="button"+ variant="outline"+ className="h-auto justify-start gap-3 px-3 py-3 text-left"+ tabIndex={subscriptionPickerIndex === index ? 0 : -1}+ onClick={() => {+ subscriptionPickerHandoffRef.current = true;+ setSubscriptionPickerOpen(false);+ setSubscriptionVendor(vendor);+ }}+ >+ <span className="model-hub-accent-tile--mint grid size-8 shrink-0 place-items-center rounded-lg"><Sparkles className="model-hub-accent-ink--mint size-4" /></span>+ <span className="flex flex-col items-start">+ <span className="font-semibold">{t(`settings.models.subscriptionPicker.${vendor}.title`)}</span>+ <span className="text-[11px] text-muted">{t(`settings.models.subscriptionPicker.${vendor}.detail`)}</span>+ </span>+ </Button>+ ))}+ </div>+ </DialogContent>+ </Dialog>+ {subscriptionVendor && (+ <OAuthConnectDialog+ open+ vendor={subscriptionVendor}+ sources={sources}+ onClose={closeSubscription}+ onConnected={subscriptionAdded}+ />+ )}+ {reauthSource && (+ <OAuthConnectDialog+ open+ vendor={reauthSource.vendor}+ reauth={reauthSource}+ sources={sources}+ onClose={closeReauth}+ onConnected={sourceReauthed}+ />+ )}{orderAgent && <SourceOrderDrawer open agent={orderAgent} sources={sources} sourceReads={sourceCollectionReads} onClose={() => setOrderBackend(null)} onSaved={agentSaved} orderWrite={{ pending: agentWrites.has(orderAgent.backend), track: (work) => agentWriteRegistry.track(orderAgent.backend, work) }} />}<RouteChainDialogselection={routeSelection}diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex efc6a55e4..0e6c6760d 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -13,8 +13,15 @@ import { createPendingWrites } from './asyncLifetime';import { modelsApi } from './modelsApi';import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';import { GuardGapList } from './GuardGapList';+import { repairAction } from './repair';import { SourceDetailPanel } from './SourceDetailPanel';-import type { Source } from './types';+import {+ COOLDOWN_DETAIL_KEYS,+ ERROR_DETAIL_KEYS,+ NEEDS_ACTION_DETAIL_KEYS,+ SOURCE_STATUSES,+} from './types';+import type { Source, SourceDetailKey, SourceKind, SupplyChannel } from './types';const source: Source = {id: 'src_detail',@@ -30,6 +37,22 @@ const source: Source = {models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: ['high'] }],};+const noReauth = () => {+ throw new Error('this source has no re-login entry to reach');+};++/**+ * A stopped subscription whose cause IS the credential — `repairAction` rule 1,+ * so the one tap is a re-login. Parameterized by channel because that is the one+ * thing the two blocked subscriptions do not share: what starting the login costs.+ */+const blockedSubscription = (supply_channel: SupplyChannel): Source => ({+ ...source,+ kind: 'subscription',+ supply_channel,+ state: { status: 'needs_action', retry_at: null, detail_key: 'models.source.needs_action.oauth_expired' },+});+const deferred = <T,>() => {let resolve!: (value: T) => void;const promise = new Promise<T>((done) => { resolve = done; });@@ -60,7 +83,7 @@ const serializedTrack = (): MutationScheduler => {const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(<ToastProvider><I18nextProvider i18n={i18n}>- <SourceDetailPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} />+ <SourceDetailPanel source={{ ...source, adopted_by: adoptedBy }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider></ToastProvider>,);@@ -79,7 +102,7 @@ const EchoPanel: React.FC<{ reconcile?: () => Promise<void> | void; scheduler?:}));});return current- ? <SourceDetailPanel source={current} trackMutation={trackMutation} />+ ? <SourceDetailPanel source={current} trackMutation={trackMutation} onReauth={noReauth} />: <p data-testid="source-gone">Source gone</p>;};@@ -99,6 +122,20 @@ afterEach(() => {});describe('SourceDetailPanel', () => {+ it('exposes a stable, programmatically focusable heading for committed navigation', () => {+ const headingRef = React.createRef<HTMLHeadingElement>();+ render(+ <I18nextProvider i18n={i18n}>+ <SourceDetailPanel source={source} headingRef={headingRef} trackMutation={immediateTrack} onReauth={noReauth} />+ </I18nextProvider>,+ );++ expect(headingRef.current).toBe(screen.getByRole('heading', { name: source.display_name }));+ expect(headingRef.current?.tabIndex).toBe(-1);+ headingRef.current?.focus();+ expect(document.activeElement).toBe(headingRef.current);+ });+it('keeps the detail surface to inventory, entry kind, tiers, and refetch', () => {renderPanel();expect(screen.queryByText(/latency|延迟|enrollment|protocol|协议/i)).toBeNull();@@ -113,7 +150,7 @@ describe('SourceDetailPanel', () => {});it('omits native refetch because that channel has no stored discovery credential', () => {- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={{ ...source, kind: 'subscription', supply_channel: 'native_cli' }} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);expect(screen.queryByRole('button', { name: /^Refetch$|^重新拉取$/i })).toBeNull();});@@ -149,7 +186,7 @@ describe('SourceDetailPanel', () => {vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([reconciled]);const applySource = vi.fn().mockResolvedValue(undefined);const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: applySource }));- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));@@ -360,7 +397,7 @@ describe('SourceDetailPanel', () => {const list = vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([{ ...source, models: [] }]);const onMutation = vi.fn().mockResolvedValue(undefined);const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ source: onMutation }));- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));@@ -406,7 +443,7 @@ describe('SourceDetailPanel', () => {vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([]);const onGone = vi.fn().mockResolvedValue(undefined);const trackMutation: TrackSourceMutation = (work) => work(source, settlement({ gone: onGone }));- render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={source} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i }));await userEvent.click(screen.getByRole('menuitem', { name: /^Remove$|^移除$/i }));@@ -416,4 +453,70 @@ describe('SourceDetailPanel', () => {expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();});+ // The property, not the rows that satisfy it today: the entry is offered exactly+ // when `repairAction` — the module that owns 「which remedy this source has」 —+ // names a re-login. Seeding is complete by construction, so a status, cause,+ // kind or channel added later is swept without editing this test: the two+ // vocabularies are the const arrays `contractLocaleKeys` pins to the schema, and+ // the two unions are enumerated through `satisfies`, which stops compiling when+ // a member appears.+ it('offers the re-login entry exactly where repairAction names one', () => {+ const kinds = Object.keys({ subscription: 0, api_key: 0 } satisfies Record<SourceKind, 0>) as SourceKind[];+ const channels = Object.keys({ native_cli: 0, hub: 0 } satisfies Record<SupplyChannel, 0>) as SupplyChannel[];+ const causes: (SourceDetailKey | null)[] = [+ null,+ ...COOLDOWN_DETAIL_KEYS,+ ...NEEDS_ACTION_DETAIL_KEYS,+ ...ERROR_DETAIL_KEYS,+ ];+ const shapes = SOURCE_STATUSES.flatMap((status) => causes.flatMap((detail_key) => kinds.flatMap(+ (kind) => channels.map((supply_channel): Source => ({+ ...source,+ kind,+ supply_channel,+ state: { status, retry_at: null, detail_key },+ })),+ )));++ for (const shape of shapes) {+ const view = render(+ <I18nextProvider i18n={i18n}>+ <SourceDetailPanel source={shape} trackMutation={immediateTrack} onReauth={vi.fn()} />+ </I18nextProvider>,+ );+ const offered = screen.queryAllByRole('button', { name: /^Sign in$|^重新登录$/i }).length > 0;+ expect(offered, JSON.stringify({ kind: shape.kind, channel: shape.supply_channel, ...shape.state }))+ .toBe(repairAction(shape) === 'reauth');+ view.unmount();+ }+ });++ it('confirms a native re-login with the cost it pays at start before handing the source up', async () => {+ const native = blockedSubscription('native_cli');+ const onReauth = vi.fn();+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={native} trackMutation={immediateTrack} onReauth={onReauth} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /^Sign in$|^重新登录$/i }));++ // The confirm has to come BEFORE the journey opens: the dialog POSTs the+ // re-auth as it mounts, and on native that call is the irreversible half.+ expect(await screen.findByText(/as soon as you start|旧的登录立即失效/i)).toBeTruthy();+ expect(onReauth).not.toHaveBeenCalled();++ await userEvent.click(screen.getByRole('button', { name: /^Start sign-in$|^开始登录$/i }));++ expect(onReauth).toHaveBeenCalledWith(native);+ });++ it('warns a hub re-login about the cost it can pay, not the one it cannot', async () => {+ render(<I18nextProvider i18n={i18n}><SourceDetailPanel source={blockedSubscription('hub')} trackMutation={immediateTrack} onReauth={vi.fn()} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /^Sign in$|^重新登录$/i }));++ expect(await screen.findByText(/go through|没成功/i)).toBeTruthy();+ // A hub re-login writes nothing at start, so the native sentence would warn+ // about a loss that does not happen.+ expect(screen.queryByText(/as soon as you start|旧的登录立即失效/i)).toBeNull();+ });+});diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex b8e095fda..bbe6d82fe 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -1,9 +1,10 @@import * as React from 'react';import * as DialogPrimitive from '@radix-ui/react-dialog';-import { Info, Loader2, MoreHorizontal, Plus, RefreshCw, X } from 'lucide-react';+import { Info, Loader2, LogIn, MoreHorizontal, Plus, RefreshCw, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Input } from '@/components/ui/input';import { ResponsiveMenu } from '@/components/ui/responsive-menu';import { cn } from '@/lib/utils';@@ -11,7 +12,9 @@ import { GuardGapList } from './GuardGapList';import { formatRelativeTime } from '@/lib/relativeTime';import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';import type { SourceMutationSettlement, TrackSourceMutation } from './mutationSettlement';+import { handOffProviderTab } from './providerTab';import { reconcileUnknownWrite } from './reconcileUnknownWrite';+import { REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';import { sourceStatePresentation } from './sourceStatePresentation';import { tierMutationPayload, type TierMutationIntent } from './tierMutation';import { useDeadlineClock } from './useDeadlineClock';@@ -199,11 +202,27 @@ const DraftTiers: React.FC<{export const SourceDetailPanel: React.FC<{source: Source;trackMutation: TrackSourceMutation;-}> = ({ source, trackMutation }) => {+ /**+ * Start the re-login journey for this source. REQUIRED, and required for the+ * reason §4.5 exists: `repair.ts` decided the one-tap remedy and+ * `OAuthConnectDialog` has run the re-auth journey since it shipped, but no+ * mount ever connected them, so a stopped subscription rendered its cause and+ * stopped — the dead end that sentence forbids. Optional here, the same mount+ * could forget again silently.+ *+ * The journey itself belongs to the caller rather than to this panel: a+ * re-login can strand OTHER agents' models (`interrupted_pairs`), so what it+ * invalidates is wider than the one row this panel owns.+ */+ onReauth: (source: Source) => void;+ /** Stable focus target for callers that navigate into this detail surface. */+ headingRef?: React.Ref<HTMLHeadingElement>;+}> = ({ source, trackMutation, onReauth, headingRef }) => {const { t, i18n } = useTranslation();const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);const { Icon, accent } = sourceVisual(source);const [busy, setBusy] = React.useState(false);+ const [confirmingReauth, setConfirmingReauth] = React.useState(false);const [manualDraft, setManualDraft] = React.useState<{ modelId: string; tiers: string[]; failed: boolean; retryRead: boolean } | null>(null);const [guard, setGuard] = React.useState<GuardedAction | null>(null);const [result, setResult] = React.useState<{ added: string[]; removed: string[] } | null>(null);@@ -386,13 +405,20 @@ export const SourceDetailPanel: React.FC<{native: source.supply_channel === 'native_cli',});const host = enteredHost(source);+ // `repairAction` is the authority on which remedy a stopped source has, so the+ // condition is 「this source's one tap IS a re-login」 rather than a status list+ // this file would have to keep in step with it. `retest` needs no entry of its+ // own — it is the same `POST …/refresh` the 重新拉取 button beside this one+ // already runs — and `replace_key` has no dialog in the UI yet (ledgered as+ // follow-up), so neither renders here.+ const repair = repairAction(source);return (<div className="model-hub-source-detail"><section className="model-hub-source-bar flex flex-col border border-border bg-surface sm:flex-row sm:items-center"><span className={cn('model-hub-source-tile flex shrink-0 items-center justify-center', ACCENT_TILE[accent])}><Icon className={cn('size-[18px]', ACCENT_ICON[accent])} /></span><div className="min-w-0 flex-1">- <h2 className="model-hub-source-title truncate font-bold text-foreground">{source.display_name}</h2>+ <h2 ref={headingRef} tabIndex={-1} className="model-hub-source-title truncate font-bold text-foreground">{source.display_name}</h2>{(state.key || source.last_discovered_at) && <p className={cn('mt-1 flex flex-wrap items-center gap-x-2 gap-y-1', state.textClass)}>{state.key && <span className="model-hub-source-state flex items-center gap-1.5"><span className={cn('size-[5px] rounded-full', state.dotClass)} />{t(state.key, state.values)}</span>}{source.last_discovered_at && <span className="model-hub-source-age text-muted">{t('settings.models.sourceDetail.status.listUpdated', { time: formatRelativeTime(source.last_discovered_at, t) })}</span>}@@ -400,6 +426,7 @@ export const SourceDetailPanel: React.FC<{<p className="model-hub-source-summary mt-1 truncate font-mono">{t(host ? 'settings.models.sourceDetail.summary' : 'settings.models.gateway.modelCount', { host, count: source.models.length })}</p></div><div className="flex shrink-0 gap-2">+ {repair === 'reauth' && <Button size="sm" className="model-hub-source-action" disabled={busy} onClick={() => setConfirmingReauth(true)}><LogIn />{t(REPAIR_LABEL_KEY.reauth)}</Button>}{source.supply_channel === 'hub' && <Button variant="outline" size="sm" className="model-hub-source-action" disabled={busy} onClick={() => void refetch()}>{busy ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}{source.kind === 'api_key' && <Button variant="secondary" size="sm" className="model-hub-source-action model-hub-ink-mint" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', tiers: [], failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}</div>@@ -456,6 +483,31 @@ export const SourceDetailPanel: React.FC<{)}</section><p className="model-hub-source-footnote leading-relaxed">{t('settings.models.sourceDetail.footnote')}</p>+ {/* Confirmed before the journey opens, not inside it: `OAuthConnectDialog`+ POSTs the re-auth as it mounts, and on a native source that call is the+ irreversible half — `mark_native_irreversible_start` empties every+ sibling source on the shared CLI. `reauthBodyKey` is what makes one+ confirm true on both channels; a single sentence over both warns a hub+ user about a loss that does not happen and stays silent about the one+ that does. */}+ <ConfirmDialog+ open={confirmingReauth}+ onOpenChange={setConfirmingReauth}+ title={t('settings.models.repair.reauthTitle', { name: source.display_name })}+ description={t(reauthBodyKey(source))}+ confirmLabel={t('settings.models.repair.reauthConfirm') as string}+ destructive={reauthCost(source) === 'immediate'}+ onConfirm={() => {+ // This click is the journey's only user gesture: the dialog it opens POSTs+ // as it mounts, and a browser grants the provider tab to the gesture that+ // asked for it, not to the response one round trip later. Allocate here and+ // hand it over, or the provider handoff is popup-blocked and the user has+ // to notice the fallback link.+ handOffProviderTab();+ setConfirmingReauth(false);+ onReauth(source);+ }}+ /><DialogPrimitive.Root open={guard !== null} onOpenChange={(open) => !open && !busy && setGuard(null)}><DialogPrimitive.Portal><DialogPrimitive.Overlay className="model-hub-guard-overlay fixed inset-0 z-50" />diff --git a/ui/src/components/settings/models/SourcesCard.test.tsx b/ui/src/components/settings/models/SourcesCard.test.tsxindex db577b7ec..b291d3847 100644--- a/ui/src/components/settings/models/SourcesCard.test.tsx+++ b/ui/src/components/settings/models/SourcesCard.test.tsx@@ -29,7 +29,7 @@ describe('SourcesCard footer', () => {const user = userEvent.setup();render(<I18nextProvider i18n={i18n}>- <SourcesCard read={readyRegion([])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} />+ <SourcesCard read={readyRegion([])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} onAddSubscription={vi.fn()} /></I18nextProvider>,);@@ -44,25 +44,28 @@ describe('SourcesCard footer', () => {it('draws the two Frame 01 commands without restoring the retired vendor menu', async () => {const onAddApiKey = vi.fn();+ const onAddSubscription = vi.fn();render(<I18nextProvider i18n={i18n}>- <SourcesCard read={readyRegion([])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={onAddApiKey} />+ <SourcesCard read={readyRegion([])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={onAddApiKey} onAddSubscription={onAddSubscription} /></I18nextProvider>,);const subscription = screen.getByRole('button', { name: /Add subscription|添加订阅/i });- expect((subscription as HTMLButtonElement).disabled).toBe(true);+ expect((subscription as HTMLButtonElement).disabled).toBe(false);expect(screen.queryByRole('button', { name: /^Add source$|^添加来源$/i })).toBeNull();await userEvent.click(screen.getByRole('button', { name: /Add API key|添加 API Key/i }));expect(onAddApiKey).toHaveBeenCalledOnce();+ await userEvent.click(subscription);+ expect(onAddSubscription).toHaveBeenCalledOnce();});it('keeps the last good source rows visible with an F2 retry after a later read fails', async () => {const onRetry = vi.fn();render(<I18nextProvider i18n={i18n}>- <SourcesCard read={failRegionRead(readyRegion([retained]))} onRetry={onRetry} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} />+ <SourcesCard read={failRegionRead(readyRegion([retained]))} onRetry={onRetry} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} onAddSubscription={vi.fn()} /></I18nextProvider>,);diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex 14ed24b62..26a5d060c 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -14,7 +14,9 @@ export const SourcesCard: React.FC<{readFailureCopy?: string;onOpenSource: (source: Source) => void;onAddApiKey: () => void;-}> = ({ read, onRetry, readFailureCopy, onOpenSource, onAddApiKey }) => {+ onAddSubscription: () => void;+ subscriptionTriggerRef?: React.Ref<HTMLButtonElement>;+}> = ({ read, onRetry, readFailureCopy, onOpenSource, onAddApiKey, onAddSubscription, subscriptionTriggerRef }) => {const { t } = useTranslation();const sources = foldRegionRead<Source[], Source[] | undefined>(read, {loading: () => undefined,@@ -52,14 +54,12 @@ export const SourcesCard: React.FC<{</>}</div><div className="flex h-14 shrink-0 items-center gap-2 border-t border-border px-3.5">- {/* G-21: the frame supplies no vendor for the per-vendor subscription- dialog. Keep the drawn command visible without inventing a picker or- a default vendor. */}<Button+ ref={subscriptionTriggerRef}variant="default"size="xs"- disabledclassName="model-hub-footer-action shadow-none disabled:opacity-100"+ onClick={onAddSubscription}><Plus className="size-3" />{t('settings.models.upstream.addSubscription')}diff --git a/ui/src/components/settings/models/addApiKeyState.ts b/ui/src/components/settings/models/addApiKeyState.tsindex 7b54f80ab..d7a83d3a8 100644--- a/ui/src/components/settings/models/addApiKeyState.ts+++ b/ui/src/components/settings/models/addApiKeyState.ts@@ -5,7 +5,7 @@ import {} from './types';export type AddApiKeyOrigin = 'add' | 'pull';-export type AddApiKeyFailure = 'auth' | 'network' | 'unclassified' | 'engineDown';+export type AddApiKeyFailure = 'auth' | 'network' | 'interface' | 'unclassified' | 'engineDown';export type ObservationVerdict =| { kind: 'ready'; observation: SourceObservation }@@ -42,7 +42,7 @@ export function classifyObservation(observation: SourceObservation): Observationcase 'timeout':return { kind: 'failure', cause: 'network' };case 'adapter_error':- return { kind: 'failure', cause: 'unclassified' };+ return { kind: 'failure', cause: observation.reachable ? 'interface' : 'unclassified' };}}diff --git a/ui/src/components/settings/models/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsindex 4cb7d573d..a505109e3 100644--- a/ui/src/components/settings/models/asyncLifetime.test.ts+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -767,6 +767,11 @@ describe('pollFailureSettles — who speaks for a journey whose submit is outstaexpect(pollFailureSettles(true, false)).toBe(false);});+ it('keeps a named engine outage inconclusive so the held flow is polled again', () => {+ expect(pollFailureSettles(false, true, 'engine_down')).toBe(false);+ expect(pollFailureSettles(false, true, 'modelHub.errors.engine_down')).toBe(false);+ });+it('shows what latching one costs: the success right behind it is ignored', () => {// Interleaving 5 as a sequence. `flowStep` is right to ignore the second// arrival — the fix is upstream, at which arrival is allowed to be a verdict.@@ -787,7 +792,7 @@ describe('pollFailureSettles — who speaks for a journey whose submit is outstaconst dialog = readFileSync(join(__dirname, 'OAuthConnectDialog.tsx'), 'utf8');expect(dialog).toMatch(- /pollFailureSettles\(submittingRef\.current, failure\?\.serverNamed \?\? false\)/,+ /pollFailureSettles\(submittingRef\.current, failure\?\.serverNamed \?\? false, failure\?\.code \?\? failure\?\.detail\)/,);expect(dialog).toMatch(/submittingRef\.current = submitting;/);// The second argument only exists if the failure is read BEFORE the question isdiff --git a/ui/src/components/settings/models/asyncLifetime.ts b/ui/src/components/settings/models/asyncLifetime.tsindex da9f080d7..5bfb3f915 100644--- a/ui/src/components/settings/models/asyncLifetime.ts+++ b/ui/src/components/settings/models/asyncLifetime.ts@@ -536,8 +536,12 @@ export const terminalArrivalMovedRows = (action: FlowAction): boolean =>* Dropping it is bounded either way — the caller keeps polling, and the deadline at* the top of each tick is the dialog's own verdict when nothing ever answers.*/-export const pollFailureSettles = (submitOutstanding: boolean, serverNamed: boolean): boolean =>- !submitOutstanding && serverNamed;+export const pollFailureSettles = (+ submitOutstanding: boolean,+ serverNamed: boolean,+ code?: string,+): boolean =>+ !submitOutstanding && serverNamed && code !== 'engine_down' && code !== 'modelHub.errors.engine_down';/*** Whether the failure that just arrived is the one now ON SCREEN.diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 8e0642ae1..badedd976 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -137,7 +137,7 @@ export type ModelsApi = {/** Start the contract-owned client installation transaction. */installRuntime(): Promise<RuntimeDependency>;startRuntime(): Promise<RuntimeDependency>;- startOAuth(vendor: string, channel: SupplyChannel): Promise<OAuthFlow>;+ startOAuth(vendor: string, channel: SupplyChannel, clientNonce?: string): Promise<OAuthFlow>;getOAuthStatus(flowId: string): Promise<OAuthResult>;submitOAuth(flowId: string, value: string): Promise<OAuthResult>;cancelOAuth(flowId: string): Promise<void>;@@ -190,6 +190,8 @@ export class ApiCallError extends Error {serverNamed: boolean;/** HTTP status observed by this client. Absent when no response arrived. */responseStatus?: number;+ /** Safe, structured add-time observation returned with a rejected create. */+ observation?: SourceObservation;constructor(code: string,detail?: string,@@ -198,6 +200,7 @@ export class ApiCallError extends Error {interrupted: SupplyGap[] = [],wouldRemoveHops: RouteHopRef[] = [],responseStatus?: number,+ observation?: SourceObservation,) {super(detail || code);this.name = 'ApiCallError';@@ -208,6 +211,7 @@ export class ApiCallError extends Error {this.interrupted = interrupted;this.wouldRemoveHops = wouldRemoveHops;this.responseStatus = responseStatus;+ this.observation = observation;}}@@ -249,6 +253,7 @@ export const apiFailure = (interrupted: SupplyGap[];wouldRemoveHops: RouteHopRef[];responseStatus?: number;+ observation?: SourceObservation;} | null =>err instanceof ApiCallError? {@@ -259,6 +264,7 @@ export const apiFailure = (interrupted: err.interrupted,wouldRemoveHops: err.wouldRemoveHops,responseStatus: err.responseStatus,+ observation: err.observation,}: null;@@ -286,6 +292,9 @@ async function call<T>(path: string, init?: RequestInit): Promise<T> {supplyGaps(envelope.interrupted_pairs),routeHopRefs(envelope.would_remove_hops),res.status,+ typeof envelope.observation === 'object' && envelope.observation !== null+ ? envelope.observation as SourceObservation+ : undefined,);}return payload as T;@@ -405,10 +414,10 @@ const liveApi: ModelsApi = {getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),installRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/install', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),- startOAuth: (vendor, channel) =>+ startOAuth: (vendor, channel, clientNonce) =>call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/start',- jsonInit('POST', { vendor, channel }),+ jsonInit('POST', { vendor, channel, ...(clientNonce ? { client_nonce: clientNonce } : {}) }),).then((r) => (r.flow ?? r) as OAuthFlow),getOAuthStatus: (flowId) => call<OAuthResultResponse>(`/api/models/oauth/status/${encodeURIComponent(flowId)}`).then(oauthResult),submitOAuth: (flowId, value) => call<OAuthResultResponse>('/api/models/oauth/submit', jsonInit('POST', { flow_id: flowId, value })).then(oauthResult),@@ -1081,7 +1090,15 @@ class MockStore {return delay(structuredClone(this.runtime));}- startOAuth(vendor: string, channel: SupplyChannel) {+ startOAuth(vendor: string, channel: SupplyChannel, clientNonce?: string) {+ if (clientNonce) {+ const existing = [...this.flows.values()].find((entry) =>+ entry.flow.client_nonce === clientNonce+ && entry.flow.vendor === vendor+ && entry.flow.channel === channel,+ );+ if (existing) return delay(structuredClone(existing.flow), 500);+ }const isDevice = vendor === 'openai';const flow: OAuthFlow = {flow_id: rid('oaf'),@@ -1091,6 +1108,7 @@ class MockStore {source_id: rid('src'),vendor,channel,+ client_nonce: clientNonce ?? null,state: 'awaiting_action',presentation: isDevice? {@@ -1328,7 +1346,7 @@ const mockApi: ModelsApi = {getRuntimeStatus: () => mockStore.getRuntimeStatus(),installRuntime: () => mockStore.installRuntime(),startRuntime: () => mockStore.startRuntime(),- startOAuth: (vendor, channel) => mockStore.startOAuth(vendor, channel),+ startOAuth: (vendor, channel, clientNonce) => mockStore.startOAuth(vendor, channel, clientNonce),getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),submitOAuth: (flowId, value) => mockStore.submitOAuth(flowId, value),cancelOAuth: (flowId) => mockStore.cancelOAuth(flowId),diff --git a/ui/src/components/settings/models/providerTab.test.ts b/ui/src/components/settings/models/providerTab.test.tsnew file mode 100644index 000000000..3eae3abce--- /dev/null+++ b/ui/src/components/settings/models/providerTab.test.ts@@ -0,0 +1,167 @@+// Node environment on purpose: the AST sweep below reads this directory through+// `import.meta.url`, which is only a file URL outside a browser-like environment.+// `window` is stubbed per test instead, which is all `providerTab` touches.+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++import * as ts from 'typescript';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { handOffProviderTab, preopenProviderTab, takeHandedProviderTab } from './providerTab';++type FakeTab = { closed: boolean; opener: unknown };++function fakeTab(closed = false): FakeTab {+ return { closed, opener: {} };+}++/** Install a `window.open` and report what it was asked for. */+function stubWindowOpen(behavior: () => Window | null): { calls: unknown[][] } {+ const calls: unknown[][] = [];+ vi.stubGlobal('window', {+ open: (...args: unknown[]) => {+ calls.push(args);+ return behavior();+ },+ });+ return { calls };+}++function sourceFiles(directory: URL): URL[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const child = new URL(`${entry.name}${entry.isDirectory() ? '/' : ''}`, directory);+ if (entry.isDirectory()) return sourceFiles(child);+ return /\.(ts|tsx)$/.test(entry.name) && !/\.test\.(ts|tsx)$/.test(entry.name) ? [child] : [];+ });+}++/** Names a call by its identifier, so `foo()` and `obj.foo()` read the same. */+function calledNames(node: ts.Node): Set<string> {+ const names = new Set<string>();+ const visit = (child: ts.Node) => {+ if (ts.isCallExpression(child)) {+ const target = child.expression;+ if (ts.isIdentifier(target)) names.add(target.text);+ else if (ts.isPropertyAccessExpression(target)) names.add(target.name.text);+ if (+ ts.isIdentifier(target) &&+ target.text === 'setPhase' &&+ child.arguments.length > 0 &&+ ts.isStringLiteral(child.arguments[0])+ ) {+ names.add(`setPhase:${child.arguments[0].text}`);+ }+ }+ ts.forEachChild(child, visit);+ };+ ts.forEachChild(node, visit);+ return names;+}++/**+ * Every inline JSX event handler in this feature, with what it does: whether it+ * puts an OAuth journey into its flow phase, and whether it allocates the+ * provider tab while the user's gesture is still on the stack.+ *+ * Found by walking, never listed: a handler added later is swept by construction.+ * The limit is honest — a handler that delegates to a named function defined+ * elsewhere is not followed, which is why both journeys are also asserted+ * end-to-end in `SettingsModelsPage.render.test.tsx`.+ */+function journeyStartHandlers(url: URL): { site: string; allocates: boolean }[] {+ const path = fileURLToPath(url);+ const source = ts.createSourceFile(+ path,+ readFileSync(url, 'utf8'),+ ts.ScriptTarget.Latest,+ true,+ path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );+ const starts = ['retryStart', 'onReauth', 'setPhase:flow'];+ const allocators = ['preopenProviderWindow', 'preopenProviderTab', 'handOffProviderTab'];+ const found: { site: string; allocates: boolean }[] = [];+ const visit = (node: ts.Node) => {+ if (+ ts.isJsxAttribute(node) &&+ node.initializer &&+ ts.isJsxExpression(node.initializer) &&+ node.initializer.expression &&+ ts.isFunctionLike(node.initializer.expression)+ ) {+ const handler = node.initializer.expression;+ const names = calledNames(handler);+ if (starts.some((name) => names.has(name))) {+ const line = source.getLineAndCharacterOfPosition(handler.getStart(source)).line + 1;+ found.push({+ site: `${path.slice(path.lastIndexOf('/') + 1)}:${line} ${node.name.getText(source)}`,+ allocates: allocators.some((name) => names.has(name)),+ });+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return found;+}++afterEach(() => {+ vi.unstubAllGlobals();+ takeHandedProviderTab();+});++describe('provider tab', () => {+ it('severs opener on the tab it allocates', () => {+ const tab = fakeTab();+ const { calls } = stubWindowOpen(() => tab as unknown as Window);++ expect(preopenProviderTab()).toBe(tab);+ expect(calls).toEqual([['about:blank', '_blank']]);+ expect(tab.opener).toBeNull();+ });++ it.each([+ ['a blocked popup', () => null],+ ['a throwing window.open', () => { throw new Error('blocked'); }],+ ])('reports no tab for %s', (_label, behavior) => {+ stubWindowOpen(behavior as () => Window | null);++ expect(preopenProviderTab()).toBeNull();+ });++ it('hands the gesture-allocated tab to the journey exactly once', () => {+ const tab = fakeTab();+ stubWindowOpen(() => tab as unknown as Window);++ handOffProviderTab();++ expect(takeHandedProviderTab()).toBe(tab);+ // A second claim must not hand the same tab to a later journey: it has been+ // navigated to the provider by then, and reusing it would replace the page+ // the user is working in.+ expect(takeHandedProviderTab()).toBeNull();+ });++ it('does not hand over a tab the user closed', () => {+ stubWindowOpen(() => fakeTab(true) as unknown as Window);++ handOffProviderTab();++ expect(takeHandedProviderTab()).toBeNull();+ });++ it('has no tab to hand over before a gesture asks for one', () => {+ expect(takeHandedProviderTab()).toBeNull();+ });++ // The invariant behind both re-auth findings on b594ef986: a journey's provider+ // tab must be allocated by the gesture that starts it. The create journey's+ // gesture is inside the dialog, the re-auth journey's is the confirm outside it,+ // and the browser grants the tab to neither one after the start response.+ it('allocates the provider tab in every gesture that starts a journey', () => {+ const handlers = sourceFiles(new URL('./', import.meta.url)).flatMap(journeyStartHandlers);++ // The pattern must exist somewhere, or this asserts nothing at all.+ expect(handlers.length).toBeGreaterThan(0);+ expect(handlers.filter(({ allocates }) => !allocates)).toEqual([]);+ });+});diff --git a/ui/src/components/settings/models/providerTab.ts b/ui/src/components/settings/models/providerTab.tsnew file mode 100644index 000000000..dd8bd7c50--- /dev/null+++ b/ui/src/components/settings/models/providerTab.ts@@ -0,0 +1,64 @@+/**+ * One owner for the tab the provider's authorization page is navigated into.+ *+ * A browser only grants `window.open` inside the gesture that asked for it, and+ * the auth URL arrives one round trip later — so the tab must be allocated by+ * the gesture that STARTS an OAuth journey, never by the response that needs it.+ * `OAuthConnectDialog` satisfies that for the journeys whose gesture lives+ * inside it (Sign in, Retry), but the re-auth journey's gesture is the confirm+ * OUTSIDE it: the dialog POSTs as it mounts, so by the time it could open a tab+ * the gesture is already over and the popup is blocked.+ *+ * Hence the handoff below. The tab is a single browser-wide resource with a+ * lifetime that spans the gesture → mount boundary, which is exactly what a+ * component ref cannot hold; threading a live `Window` through page state and a+ * prop would model that lifetime as data and copy it. One module owns the+ * allocation, and whichever journey opens next claims it.+ */++/** Allocated by a gesture, not yet claimed by the journey it was opened for. */+let handedTab: Window | null = null;++/**+ * The single `window.open` for provider handoffs: blank, and with `opener`+ * severed, because the provider page is navigated into it later and would+ * otherwise be able to drive this window (reverse tabnabbing).+ */+export function preopenProviderTab(): Window | null {+ try {+ const tab = window.open('about:blank', '_blank');+ if (tab) {+ try {+ tab.opener = null;+ } catch {+ // Some browser WindowProxy implementations expose a read-only opener.+ }+ }+ return tab;+ } catch {+ return null;+ }+}++/**+ * Allocate the tab for a journey that starts outside the dialog that will use+ * it. Called from the gesture; claimed by the dialog as it opens.+ */+export function handOffProviderTab(): void {+ handedTab = preopenProviderTab();+}++/**+ * Claim the handed tab, exactly once. Returns null when no gesture handed one+ * over, or when the user closed it in the meantime — both mean "this journey+ * has no tab", which the visible fallback link already covers.+ *+ * Every dialog open claims, including a journey that allocates its own tab, so+ * a handoff whose journey never opened cannot survive into a later one.+ */+export function takeHandedProviderTab(): Window | null {+ const tab = handedTab;+ handedTab = null;+ if (!tab || tab.closed) return null;+ return tab;+}diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex 777f2564e..bd9ed8f63 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -11,7 +11,7 @@ import { describe, expect, it } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';-import { oauthFailureKey, serverText } from './serverCopy';+import { NATIVE_SUBSCRIPTION_EXISTS_FAILURE, oauthFailureKey, oauthStartFailureKey, serverText } from './serverCopy';const t = (lng: 'en' | 'zh'): TFunction => {const i18n = createInstance();@@ -119,3 +119,20 @@ describe('oauthFailureKey', () => {expect(t('en')(oauthFailureKey('discovery_failed', 'reauth')) as string).not.toMatch(/creat/i);});});++describe('oauthStartFailureKey', () => {+ it('surfaces the native singleton race with the dedicated already-bound copy', () => {+ expect(oauthStartFailureKey(NATIVE_SUBSCRIPTION_EXISTS_FAILURE)).toBe(+ 'settings.models.addSub.error.alreadyBound',+ );+ });++ it('keeps unknown start failures retryable without inventing a cause', () => {+ expect(oauthStartFailureKey(undefined)).toBe('settings.models.addSub.error.startFailed');+ });++ it('uses the dedicated gateway outage copy for engine-down starts', () => {+ expect(oauthStartFailureKey('engine_down')).toBe('settings.models.addSub.error.engineDown');+ expect(oauthStartFailureKey('modelHub.errors.engine_down')).toBe('settings.models.addSub.error.engineDown');+ });+});diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsindex f93d3d78b..0f74e520e 100644--- a/ui/src/components/settings/models/serverCopy.ts+++ b/ui/src/components/settings/models/serverCopy.ts@@ -86,3 +86,13 @@ export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney)? 'settings.models.oauth.error.finalizeReauth': 'settings.models.oauth.error.finalize': 'settings.models.oauth.error.generic';++/** Start-route failures have not reached provider authorization yet. */+export const NATIVE_SUBSCRIPTION_EXISTS_FAILURE = 'modelHub.errors.native_subscription_exists';++export const oauthStartFailureKey = (code: string | undefined): string =>+ code === NATIVE_SUBSCRIPTION_EXISTS_FAILURE+ ? 'settings.models.addSub.error.alreadyBound'+ : code === 'engine_down' || code === 'modelHub.errors.engine_down'+ ? 'settings.models.addSub.error.engineDown'+ : 'settings.models.addSub.error.startFailed';diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 843fd3e29..6eee04c70 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -443,6 +443,8 @@ export type OAuthPresentation = {export type OAuthFlow = {flow_id: string;+ /** Exact client correlation echoed by nonce-backed OAuth starts. */+ client_nonce?: string | null;/*** What the flow is FOR, and therefore what its terminal success response* carries: `create` → `{flow, source, adopted_by}`, `reauth` →diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex c92d6b1d1..e94711068 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -864,6 +864,12 @@"unavailableDue": "Unavailable · the retry is due"}},+ "subscriptionPicker": {+ "title": "Choose a subscription to connect",+ "detail": "Choose the account subscription you want to add to Model Hub.",+ "anthropic": { "title": "Claude subscription", "detail": "Claude Pro / Max" },+ "openai": { "title": "ChatGPT subscription", "detail": "ChatGPT Plus / Pro" }+ },"sources": {"title": "Sources","info": "Accounts and credentials available to gateway routes",@@ -1071,7 +1077,9 @@"auth.detail": "Check whether the API key is valid","address": "Wrong address: 404 Not Found","network": "Could not connect to this address (unreachable or timed out)",- "unclassified": "It did not connect, and the cause could not be identified",+ "undetermined": "Connected, but we could not identify the model interface",+ "inventory": "The interface was confirmed, but its model list did not come back",+ "unclassified": "Connection failed. Check the address and API key, then retry","engineDown": "The gateway is not responding — try again","save": "The source is not confirmed saved"},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 572942c4b..975174f5f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -864,6 +864,12 @@"unavailableDue": "暂不可用 · 已到重试时间"}},+ "subscriptionPicker": {+ "title": "选择要连接的订阅",+ "detail": "选择要添加到 Model Hub 的账号订阅。",+ "anthropic": { "title": "Claude 订阅", "detail": "Claude Pro / Max" },+ "openai": { "title": "ChatGPT 订阅", "detail": "ChatGPT Plus / Pro" }+ },"sources": {"title": "来源","info": "可用于网关路由的账号与凭据",@@ -1071,7 +1077,9 @@"auth.detail": "检查 API Key 是否有效","address": "地址不对:404 Not Found","network": "无法连接到该地址(不可达或超时)",- "unclassified": "没连成,原因认不出来",+ "undetermined": "已连接,但无法确认这是哪种模型接口",+ "inventory": "接口已确认,但暂时没拿到型号清单",+ "unclassified": "连接失败,请检查地址和 API Key 后重试","engineDown": "网关没有响应,请重试","save": "没能确认这个来源已经保存"},diff --git a/ui/src/lib/pwaNavigation.test.ts b/ui/src/lib/pwaNavigation.test.tsindex 81b18aa06..e7699e0ee 100644--- a/ui/src/lib/pwaNavigation.test.ts+++ b/ui/src/lib/pwaNavigation.test.ts@@ -44,6 +44,63 @@ function directWindowOpenCount(url: URL): number {return count;}+function seversOpener(node: ts.Node): boolean {+ let found = false;+ const visit = (child: ts.Node) => {+ if (+ ts.isBinaryExpression(child) &&+ child.operatorToken.kind === ts.SyntaxKind.EqualsToken &&+ ts.isPropertyAccessExpression(child.left) &&+ child.left.name.text === 'opener' &&+ child.right.kind === ts.SyntaxKind.NullKeyword+ ) {+ found = true;+ }+ ts.forEachChild(child, visit);+ };+ ts.forEachChild(node, visit);+ return found;+}++/**+ * Preallocated blank tabs that keep an `opener` are reverse-tabnabbing holes:+ * whatever is navigated into them later can drive this window. Report each+ * such tab with whether the function that opened it severs the reference.+ */+function blankTabOpeners(url: URL): { line: number; severed: boolean }[] {+ const path = fileURLToPath(url);+ const source = ts.createSourceFile(+ path,+ readFileSync(url, 'utf8'),+ ts.ScriptTarget.Latest,+ true,+ path.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );+ const found: { line: number; severed: boolean }[] = [];+ const visit = (node: ts.Node) => {+ if (+ ts.isCallExpression(node) &&+ ts.isPropertyAccessExpression(node.expression) &&+ ts.isIdentifier(node.expression.expression) &&+ node.expression.expression.text === 'window' &&+ node.expression.name.text === 'open' &&+ node.arguments.length > 0 &&+ ts.isStringLiteral(node.arguments[0]) &&+ node.arguments[0].text === 'about:blank'+ ) {+ let scope: ts.Node = node;+ while (scope.parent && !ts.isFunctionLike(scope)) scope = scope.parent;+ found.push({+ line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,+ severed: seversOpener(scope),+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ return found;+}+afterEach(() => {vi.unstubAllGlobals();});@@ -182,14 +239,25 @@ describe('programmatic PWA navigation', () => {.sort((left, right) => left.path.localeCompare(right.path));expect(directCalls).toEqual([+ { path: 'components/settings/models/providerTab.ts', count: 1 },{ path: 'components/workbench/ShowPageLaunchControl.tsx', count: 1 },{ path: 'lib/pwaNavigation.ts', count: 1 },]);- const preallocatedTab = readFileSync(- new URL('../components/workbench/ShowPageLaunchControl.tsx', import.meta.url),- 'utf8',+ });++ it('severs the opener of every preallocated blank tab', () => {+ const sourceRoot = new URL('../', import.meta.url);+ const rootPath = fileURLToPath(sourceRoot);+ const tabs = sourceFiles(sourceRoot).flatMap((url) =>+ blankTabOpeners(url).map(({ line, severed }) => ({+ site: `${fileURLToPath(url).slice(rootPath.length)}:${line}`,+ severed,+ })),);- expect(preallocatedTab).toContain("window.open('about:blank', '_blank')");++ // The pattern must exist somewhere, or this asserts nothing at all.+ expect(tabs.length).toBeGreaterThan(0);+ expect(tabs.filter(({ severed }) => !severed)).toEqual([]);});});diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 8300a09f3..5e72e4215 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -793,6 +793,13 @@"flow_not_found": "Authorization flow not found.","flow_expired": "Authorization flow expired.","discovery_failed": "Could not validate or discover this source.",+ "ambiguous_source": "Connected, but we could not identify the model interface.",+ "source_unreachable": "Could not reach this address. Check the address and retry.",+ "authentication_failed": "Authentication failed. Check whether the API key is valid.",+ "observation_failed": "Connected, but the response did not prove a valid model interface.",+ "adapter_error": "We could not confirm whether the service is reachable. Retry the connection.",+ "native_subscription_exists": "This vendor already has a native subscription source.",+ "source_timeout": "The connection timed out. Check the network and retry.","invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source.","mode_switch_blocked": "This operation is blocked by the current supply mode or selection.","engine_down": "The local model gateway is unavailable.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex da5166211..7debe5be9 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -793,6 +793,13 @@"flow_not_found": "未找到授权流程。","flow_expired": "授权流程已过期。","discovery_failed": "无法验证或发现此来源。",+ "ambiguous_source": "已连接,但无法确认这是哪种模型接口。",+ "source_unreachable": "无法连接到这个地址,请检查地址后重试。",+ "authentication_failed": "鉴权失败,请检查 API Key 是否有效。",+ "observation_failed": "已连接,但无法确认服务返回的是有效模型接口。",+ "adapter_error": "无法确认服务是否可连接,请重试。",+ "native_subscription_exists": "该厂商已经有一个原生订阅来源。",+ "source_timeout": "连接超时,请检查网络后重试。","invalid_source_order": "来源顺序包含不可用、不适用或重复的来源。","mode_switch_blocked": "当前供给模式或选择阻止了此操作。","engine_down": "本地模型网关不可用。",