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): carry what migrates, place subscriptions by catalog, fix ChatGPT login (#2156)
Call Whiteda923e288c90
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 80cc6a970..c45660468 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -99,6 +99,12 @@ class OriginNotAllowedError(Exception):``RawCallOutcome`` and never triggers fallback."""+class OAuthSubmissionRejectedError(Exception):+ """Raised by ``submit_oauth`` when the provider refuses the pasted value+ before touching the flow. Nothing was written and the flow still awaits a+ submission, so the user can paste again on the same flow."""++class InvokeCancelledError(asyncio.CancelledError):"""Owner cancellation carrying wire facts observed before transport cleanup."""@@ -672,7 +678,11 @@ class EngineAdapter(Protocol):async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:- """``value`` per ``expects``: pasted code or callback URL."""+ """``value`` per ``expects``: pasted code or callback URL.++ A value the provider refuses without writing anything raises+ ``OAuthSubmissionRejectedError`` and leaves the flow awaiting action.+ """...async def cancel_oauth(self, flow_id: str) -> None: ...diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 53124b933..214147190 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -6,6 +6,7 @@ import asyncioimport base64import hashlibimport json+import mathimport refrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezone@@ -239,6 +240,12 @@ class NativeMigrationItem:file_snapshots: tuple[NativeFileEdit, ...] = field(default=(), repr=False)auth_scheme: str | None = field(default=None, repr=False)receipt_identity: str | None = field(default=None, repr=False)+ # The native config file itself cannot be parsed, so the CLI fails before+ # any Hub override applies; this row blocks Hub mode, not just import.+ config_blocker: bool = field(default=False, repr=False)+ # The settings ``env`` field a Claude credential came from; cleanup+ # consent is bound to it, not to equal bytes held in another field.+ native_field: str | None = field(default=None, repr=False)def to_payload(self) -> dict[str, object]:# Presentation metadata is additive: `vendor` and `display_name` let a@@ -259,6 +266,9 @@ class NativeMigrationItem:"masked_credential": self.masked_credential,"source_paths": list(self.source_paths),"required_backends": list(self.required_backends),+ # The backend's native config cannot be parsed, so Hub mode would+ # fail every launch: the whole group is blocked, not just this row.+ "config_blocker": self.config_blocker,}@@ -490,6 +500,12 @@ def _native_store_items(native_store_revision=snapshot.revision,native_store_placeholder=placeholder,source_paths=source_paths,+ # Codex reads its own auth.json before any Hub routing applies,+ # so one it cannot read or parse fails every launch.+ config_blocker=(+ backend == "codex" and payload.get("store") == "file"+ and payload.get("status") in {"invalid", "permission_needed"}+ ),))if secret:base_url = _oauth_text(state, "base_url")@@ -524,6 +540,7 @@ def _blocked_item(source_paths: tuple[str, ...] = (),shell_variables: tuple[str, ...] = (),shell_auth_variables: tuple[str, ...] = (),+ config_blocker: bool = False,) -> NativeMigrationItem:item_id, source_id = _ids(backend, "api_key", identity, "reauth")return NativeMigrationItem(@@ -534,7 +551,7 @@ def _blocked_item(protocol="anthropic" if backend == "claude" else "openai_responses",display_name={"claude": "Claude Code", "codex": "Codex", "opencode": "OpenCode"}[backend],source_paths=source_paths, shell_variables=shell_variables,- shell_auth_variables=shell_auth_variables,+ shell_auth_variables=shell_auth_variables, config_blocker=config_blocker,)@@ -559,6 +576,7 @@ def _claude_items(if path in persisted.problems:items.append(_blocked_item("claude", str(path), persisted.problems[path], source_paths=(str(path),),+ config_blocker=True,))continueconfig = persisted.documents[path]@@ -566,7 +584,9 @@ def _claude_items(continueenv = config.get("env", {})if not isinstance(env, dict):- items.append(_blocked_item("claude", str(path), source_paths=(str(path),)))+ items.append(_blocked_item(+ "claude", str(path), source_paths=(str(path),), config_blocker=True,+ ))continuebase_url = _oauth_text(env, "ANTHROPIC_BASE_URL")api_key = _oauth_text(env, "ANTHROPIC_API_KEY")@@ -582,7 +602,7 @@ def _claude_items(notes_key=_CUSTOM_ENDPOINT_NOTE if base_url else None,vendor="anthropic", protocol="anthropic", display_name="Anthropic",base_url=base_url, secret=api_key, masked_credential=detail,- source_paths=(str(path),),+ source_paths=(str(path),), native_field="ANTHROPIC_API_KEY",))if config.get("apiKeyHelper"):items.append(_blocked_item(@@ -608,6 +628,7 @@ def _claude_items(notes_key=_CUSTOM_ENDPOINT_NOTE, vendor="anthropic", protocol="anthropic",display_name="Anthropic", base_url=base_url, secret=token,masked_credential=masked, source_paths=(str(path),), auth_scheme=scheme,+ native_field="ANTHROPIC_AUTH_TOKEN",))if env.get("CLAUDE_CODE_OAUTH_TOKEN"):items.append(_blocked_item(@@ -639,17 +660,29 @@ def _codex_items(if path in persisted.problems:items.append(_blocked_item("codex", str(path), persisted.problems[path], source_paths=(str(path),),+ config_blocker=True,))continueconfig = persisted.documents[path]if config is None:continueproviders = config.get("model_providers", {})+ # Only the provider map migration reads and rewrites is checked here.+ # The rest of the file belongs to the installed CLI, whose accepted+ # shapes differ by version, and fails in direct mode alike.if not isinstance(providers, dict):- items.append(_blocked_item("codex", str(path), source_paths=(str(path),)))+ items.append(_blocked_item(+ "codex", str(path), source_paths=(str(path),), config_blocker=True,+ ))continuefor provider_id, provider in providers.items():- if not isinstance(provider, dict):+ if not _codex_provider_well_typed(provider):+ # Codex deserializes the whole provider map before any Hub+ # override applies, so one malformed entry fails every launch.+ items.append(_blocked_item(+ "codex", f"{path}:{provider_id}", source_paths=(str(path),),+ config_blocker=True,+ ))continuekey = _oauth_text(provider, "experimental_bearer_token")env_key = _oauth_text(provider, "env_key")@@ -748,6 +781,192 @@ def _opencode_protocol(return None+# Every field of Codex's `ModelProviderInfo` (codex-rs/core/config.schema.json),+# by declared type. Codex ignores unknown keys but rejects a known one of the+# wrong type, so the whole table is checked rather than fields one at a time.+_CODEX_PROVIDER_FIELDS: dict[str, str] = {+ **dict.fromkeys((+ "name", "base_url", "env_key", "env_key_instructions",+ "experimental_bearer_token", "model_catalog_url",+ ), "text"),+ **dict.fromkeys(("http_headers", "env_http_headers", "query_params"), "text_map"),+ **{field: field for field in ("auth", "aws", "gateway_oauth")},+ **dict.fromkeys((+ "request_max_retries", "stream_max_retries", "stream_idle_timeout_ms",+ "websocket_connect_timeout_ms",+ ), "count"),+ **dict.fromkeys((+ "requires_openai_auth", "supports_websockets", "supports_standalone_web_search",+ ), "flag"),+ "wire_api": "wire_api",+}+++# The nested tables Codex deserializes (required keys present, known ones of+# their declared type), from the same schema. Unknown keys are ignored: only+# `--strict-config`, which launches never pass, rejects them. A value is a kind name, a+# nested spec, or a tuple of alternative specs (a tagged enum).+_CodexSpec = dict[str, object]+_COMMAND_SPEC: _CodexSpec = {"command": "text", "args": "texts", "timeout_ms": "positive_count"}+_CODEX_NESTED_SPECS: dict[str, tuple[_CodexSpec, frozenset[str]]] = {+ "auth": ({+ "command": "text", "args": "texts", "cwd": "text",+ "refresh_interval_ms": "count", "timeout_ms": "positive_count",+ }, frozenset({"command"})),+ "aws": ({+ "profile": "text", "region": "text",+ "auth_refresh": (_COMMAND_SPEC, frozenset({"command"})),+ "credential_export": (_COMMAND_SPEC, frozenset({"command"})),+ }, frozenset()),+ "gateway_oauth": ({+ "authorization_url": "text", "client_id": "text", "token_url": "text",+ "resource": "text", "scopes": "texts", "redirect_port": "port",+ "delivery": (+ ({"kind": ("header",), "name": "text", "scheme": "text"}, frozenset({"kind", "name"})),+ ({"kind": ("cookie",), "name": "text"}, frozenset({"kind", "name"})),+ ),+ }, frozenset({"authorization_url", "client_id", "delivery", "token_url"})),+}+++def _text_map(value: object) -> bool:+ return isinstance(value, dict) and all(+ isinstance(key, str) and isinstance(item, str) for key, item in value.items()+ )+++def _codex_field_well_typed(kind: str, value: object) -> bool:+ if kind == "text":+ return isinstance(value, str)+ if kind == "text_map":+ return _text_map(value)+ if kind == "count":+ # TOML integers are signed 64-bit; Codex rejects anything wider.+ return isinstance(value, int) and not isinstance(value, bool) and 0 <= value < 2**63+ if kind == "flag":+ return isinstance(value, bool)+ if kind in _CODEX_NESTED_SPECS:+ return _codex_table_well_typed(_CODEX_NESTED_SPECS[kind], value)+ # An unknown variant fails deserialization. `chat` stays accepted: older+ # CLIs still run it, and migration carries it as openai_chat.+ return value in ("chat", "responses")+++def _codex_table_well_typed(spec: object, value: object) -> bool:+ if isinstance(spec, str):+ if spec == "texts":+ return isinstance(value, list) and all(isinstance(item, str) for item in value)+ if spec in ("positive_count", "port"):+ limit = 2**16 if spec == "port" else 2**63+ minimum = 1 if spec == "positive_count" else 0+ return isinstance(value, int) and not isinstance(value, bool) and minimum <= value < limit+ return _codex_field_well_typed(spec, value)+ if isinstance(spec, tuple) and spec and isinstance(spec[0], tuple):+ # A tagged enum: exactly one variant has to accept the table.+ return any(_codex_table_well_typed(variant, value) for variant in spec)+ if isinstance(spec, tuple) and len(spec) == 2 and isinstance(spec[0], dict):+ fields, required = spec+ return (+ isinstance(value, dict)+ and required <= value.keys()+ and all(_codex_table_well_typed(fields[key], item) for key, item in value.items() if key in fields)+ )+ # A literal-choice tuple, such as a variant tag.+ return value in spec+++def _codex_provider_well_typed(provider: object) -> bool:+ """Whether Codex can deserialize this ``model_providers`` entry.++ A field of the wrong type fails the whole config before any Hub override+ applies, so only an absent field or one of its declared type is safe.+ """+ return isinstance(provider, dict) and all(+ _codex_field_well_typed(kind, provider[field])+ for field, kind in _CODEX_PROVIDER_FIELDS.items() if field in provider+ )+++_OPENCODE_COST = ({+ "input": "finite", "output": "finite", "cache_read": "finite", "cache_write": "finite",+}, frozenset({"input", "output"}))+_OPENCODE_MODALITIES = ("modality", "text", "audio", "image", "video", "pdf")+_OPENCODE_MODEL = ({+ "id": "text", "name": "text", "family": "text", "release_date": "text",+ "attachment": "flag", "reasoning": "flag", "temperature": "flag", "tool_call": "flag",+ "experimental": "flag",+ "interleaved": ("any", "flag", "text", ({"field": "text"}, frozenset({"field"}))),+ "cost": ({**_OPENCODE_COST[0], "context_over_200k": _OPENCODE_COST}, _OPENCODE_COST[1]),+ "limit": ({"context": "finite", "input": "finite", "output": "finite"}, frozenset({"context", "output"})),+ "modalities": ({"input": _OPENCODE_MODALITIES, "output": _OPENCODE_MODALITIES}, frozenset()),+ "status": ("choice", "alpha", "beta", "deprecated", "active"),+ "provider": ({"npm": "text", "api": "text"}, frozenset()),+ "options": "record",+ "headers": "text_map",+ "variants": ("values", ({"disabled": "flag"}, frozenset())),+}, frozenset())+_OPENCODE_TIMEOUT = ("any", "positive_count", ("choice", False))+_OPENCODE_PROVIDER = ({+ "api": "text", "name": "text", "id": "text", "npm": "text",+ "env": "texts", "whitelist": "texts", "blacklist": "texts",+ "options": ({+ "apiKey": "text", "baseURL": "text", "enterpriseUrl": "text", "setCacheKey": "flag",+ "timeout": _OPENCODE_TIMEOUT, "headerTimeout": _OPENCODE_TIMEOUT,+ "chunkTimeout": _OPENCODE_TIMEOUT,+ }, frozenset()),+ "models": ("values", _OPENCODE_MODEL),+}, frozenset())+++def _opencode_value_well_typed(spec: object, value: object) -> bool:+ """Check ``value`` against OpenCode's ``ProviderConfig`` schema.++ Effect structs drop unknown keys, so only declared fields are checked.+ """+ if spec == "text":+ return isinstance(value, str)+ if spec == "flag":+ return isinstance(value, bool)+ if spec == "texts":+ return isinstance(value, list) and all(isinstance(item, str) for item in value)+ if spec == "text_map":+ return _text_map(value)+ if spec == "record":+ return isinstance(value, dict)+ if spec == "finite":+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)+ if spec == "positive_count":+ # JSON has one number type; `1.0` is the integer 1 to OpenCode.+ return (+ isinstance(value, (int, float)) and not isinstance(value, bool)+ and math.isfinite(value) and value == int(value) and value > 0+ )+ kind = spec[0] if isinstance(spec, tuple) else None+ if kind == "any":+ return any(_opencode_value_well_typed(variant, value) for variant in spec[1:])+ if kind == "choice":+ return any(value is choice or (type(value) is type(choice) and value == choice) for choice in spec[1:])+ if kind == "modality":+ return isinstance(value, list) and all(item in spec[1:] for item in value)+ if kind == "values":+ return isinstance(value, dict) and all(_opencode_value_well_typed(spec[1], item) for item in value.values())+ fields, required = cast(tuple[dict[str, object], frozenset[str]], spec)+ return (+ isinstance(value, dict)+ and required <= value.keys()+ and all(_opencode_value_well_typed(fields[key], item) for key, item in value.items() if key in fields)+ )+++def _opencode_provider_well_typed(provider: object) -> bool:+ """Whether OpenCode's config schema accepts this ``provider`` entry.++ OpenCode validates the whole file on start, so a malformed typed field+ fails every launch, Hub-owned or not.+ """+ return _opencode_value_well_typed(_OPENCODE_PROVIDER, provider)++def _opencode_manual_models(provider_config: dict[str, Any],) -> tuple[NativeManualModel, ...]:@@ -792,16 +1011,20 @@ def _opencode_items(try:auth_entries = read_native_config(opencode_auth_path(home)) or {}except (TakeoverStateError, OSError):- return [_blocked_item(+ # Hub mode cannot prove what an unreadable auth map would shadow, so+ # it blocks; config layers still surface their own rows beside it.+ auth_entries = {}+ items.append(_blocked_item("opencode", "auth-file", "unreadable",- source_paths=(str(opencode_auth_path(home)),),- )]+ source_paths=(str(opencode_auth_path(home)),), config_blocker=True,+ ))provider_catalog = _load_opencode_provider_catalog(persisted)seen_providers: set[str] = set()for path in opencode_config_paths(home, project_roots):if path in persisted.problems:items.append(_blocked_item("opencode", str(path), persisted.problems[path], source_paths=(str(path),),+ config_blocker=True,))continueconfig = persisted.documents[path]@@ -809,7 +1032,9 @@ def _opencode_items(continueprovider_configs = config.get("provider", {})if not isinstance(provider_configs, dict):- items.append(_blocked_item("opencode", str(path), source_paths=(str(path),)))+ items.append(_blocked_item(+ "opencode", str(path), source_paths=(str(path),), config_blocker=True,+ ))continueseen_providers.update(provider_configs)relevant_auth = {key: value for key, value in auth_entries.items() if key in provider_configs}@@ -837,10 +1062,12 @@ def _opencode_candidates(names: tuple[str, ...] = ()auth_names: tuple[str, ...] = ()- def blocked(identity: str, reason: str = "config") -> NativeMigrationItem:+ def blocked(+ identity: str, reason: str = "config", *, config_blocker: bool = False,+ ) -> NativeMigrationItem:return _blocked_item("opencode", identity, reason, source_paths=paths, shell_variables=names,- shell_auth_variables=auth_names,+ shell_auth_variables=auth_names, config_blocker=config_blocker,)if (@@ -853,8 +1080,10 @@ def _opencode_candidates(items.append(blocked(f"{locator}:invalid-provider"))continueprovider_config = provider_configs.get(provider_id, {})- if not isinstance(provider_config, dict):- items.append(blocked(f"{locator}:{provider_id}"))+ if not _opencode_provider_well_typed(provider_config):+ # OpenCode validates the whole provider map before any Hub+ # override applies, so one malformed entry fails every launch.+ items.append(blocked(f"{locator}:{provider_id}", config_blocker=True))continueoptions = provider_config.get("options")if not isinstance(options, dict):@@ -1224,6 +1453,23 @@ def _require_native_api_key_transport(raise MigrationConflictError from None+def _bearer_transport(item: NativeMigrationItem) -> NativeMigrationItem | None:+ """Carry a custom-endpoint Anthropic key over as the Bearer the engine sends.++ The pinned engine sends ``x-api-key`` only to the official origin. Custom+ endpoints get Bearer, so migration proves and provisions exactly that header;+ an endpoint that refuses it fails proof and the native files stay untouched.+ """+ if item.kind == "oauth_native" or item.protocol != "anthropic" or item.auth_scheme is not None:+ return None+ candidate = replace(item, auth_scheme="bearer")+ try:+ _require_native_api_key_transport(candidate)+ except MigrationConflictError:+ return None+ return candidate++def scan_native_configs(config: ModelHubConfig,*,@@ -1301,7 +1547,7 @@ def scan_native_configs(try:_require_native_api_key_transport(item)except MigrationConflictError:- item = replace(+ item = _bearer_transport(item) or replace(item, proposed_action="reauth", selected=False,notes_key="settings.models.migration.blocked.transport",)@@ -1505,6 +1751,8 @@ async def _prepare_takeover("vendor": item.vendor,"base_url": validate_base_url(item.base_url),"key": item.secret,+ # Bearer exists only on the Anthropic interface.+ **({"protocol": "anthropic"} if item.auth_scheme == "bearer" else {}),}, on_reserved=lambda ref: host.revocations.add("observation", ref), **auth_options)protocol = cast(Any, observation.protocol)_require_native_api_key_transport(item, observed_protocol=protocol)@@ -1875,7 +2123,11 @@ async def apply_native_migration(project_roots=host.migration_project_roots(),clean_native_stores=record.get("clean_native_stores"),)- if not any(item.backend in record["backends"] for item in residual):+ if not any(+ item.backend in record["backends"]+ and (item.proposed_action == "import" or item.config_blocker)+ for item in residual+ ):return resultcompleted_record = recordelse:@@ -1896,9 +2148,16 @@ async def apply_native_migration(backends = tuple(sorted({item.backend for item in selected}))if any(set(item.required_backends) - set(backends) for item in selected):raise MigrationConflictError- # A CLI takeover cannot leave an unselected credential maintaining its- # original authentication. Selection is therefore grouped by backend.- if any(item.backend in backends and item.id not in item_ids for item in available):+ # A takeover moves every credential the Hub can carry, so selection is+ # grouped by backend. Rows it cannot carry stay native: a Hub launch+ # pins its own connection above them, so they are shadowed, not used.+ if any(+ item.backend in backends and item.proposed_action == "import" and item.id not in item_ids+ for item in available+ ):+ raise MigrationConflictError+ # Hub mode over a native config the CLI cannot parse fails every launch.+ if any(item.backend in backends and item.config_blocker for item in available):raise MigrationConflictErrorretained_inventory_ids = (set(record.get("inventory_ids", [item["id"] for item in record["items"]]))@@ -1996,7 +2255,13 @@ async def apply_native_migration(selected.extend(item for item in resolved if item not in selected)if (original.receipt_identity or original.id) in retained_inventory_ids:retained_item_ids.update(item.id for item in resolved)- if any(item.backend in backends and item not in selected for item in rescanned):+ if any(+ item.backend in backends and (+ (item.proposed_action == "import" and item not in selected)+ or item.config_blocker+ )+ for item in rescanned+ ):raise MigrationConflictErrorrecord = await _prepare_takeover(host, previous, selected, mask_credential=mask_credential,diff --git a/core/handlers/model_hub/migration_files.py b/core/handlers/model_hub/migration_files.pyindex 33a975a4b..175511e22 100644--- a/core/handlers/model_hub/migration_files.py+++ b/core/handlers/model_hub/migration_files.py@@ -257,34 +257,61 @@ def plan_native_cleanup(# Consent to inspect an opaque, verified-empty container does not transfer# any credential. It cannot authorize cleanup of another native store.backends = {item.backend for item in items if not item.native_store_placeholder}- selected_secrets = {item.secret for item in items if item.secret}+ # Consent is per backend: equal bytes selected for another backend never+ # authorize removing a credential this backend's scan kept native.+ selected_by_backend: dict[str, set[str]] = {}+ for item in items:+ if item.secret:+ selected_by_backend.setdefault(item.backend, set()).add(item.secret)- def selected_api_key(value: object) -> bool:+ def selected_api_key(value: object, backend: str) -> bool:# Producers normalize static keys for proof/custody. Exact raw bytes# remain in the checked snapshots and journal before-images; this# comparison does not replace their consent or concurrency checks.- return isinstance(value, str) and value.strip() in selected_secrets+ return isinstance(value, str) and value.strip() in selected_by_backend.get(backend, set())if "claude" in backends:+ claude_keys = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")+ # Consent is per field too: equal bytes carried from one Claude field+ # never authorize removing another field the scan kept native.+ selected_by_field: dict[str, set[str]] = {}+ for item in items:+ if item.backend == "claude" and item.secret:+ for field in (item.native_field, *item.shell_auth_variables):+ if field:+ selected_by_field.setdefault(field, set()).add(item.secret)++ def claude_retained(key: str, value: object) -> bool:+ selected = isinstance(value, str) and value.strip() in selected_by_field.get(key, set())+ return bool(value) and not selected++ # Claude merges its settings layers, so a credential kept native in any+ # one of them still sends to the Base URL another layer names.+ claude_auth_retained = False+ for path in claude_settings_paths(home, project_roots):+ staged = edits.get(path.absolute())+ raw = staged.before if staged else _read_regular(path.absolute())+ if raw is None:+ continue+ layer = _object(raw)+ env = layer.get("env")+ if layer.get("apiKeyHelper") or (+ isinstance(env, dict) and any(claude_retained(key, env.get(key)) for key in claude_keys)+ ):+ claude_auth_retained = True+def clear_settings(payload: dict) -> None:env = payload.get("env")if env is not None and not isinstance(env, dict):raise TakeoverStateError("native configuration cannot be parsed")+ # A credential the Hub cannot carry stays native, with the Base+ # URL it may depend on. Hub launches pin their own connection.if isinstance(env, dict):- for key in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN"):- value = env.get(key)- if key != "ANTHROPIC_BASE_URL" and value:- selected = (- selected_api_key(value)- if key in {"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"}- else isinstance(value, str) and value in selected_secrets- )- if not selected:- raise TakeoverStateError("another native credential requires migration")- env.pop(key, None)- if payload.get("apiKeyHelper"):- raise TakeoverStateError("native credential helper requires configuration")- payload.pop("apiKeyHelper", None)+ for key in claude_keys:+ if not claude_retained(key, env.get(key)):+ env.pop(key, None)+ if not claude_auth_retained:+ env.pop("ANTHROPIC_BASE_URL", None)for path in claude_settings_paths(home, project_roots):edit_json(path, clear_settings, guard_unchanged=True)@@ -299,40 +326,89 @@ def plan_native_cleanup(config_path, auth_path = get_codex_config_paths(home)def clear_auth(payload: dict) -> None:- if payload.get("OPENAI_API_KEY") and not selected_api_key(payload["OPENAI_API_KEY"]):- raise TakeoverStateError("another native credential requires migration")- if payload.get("tokens") and not any(+ # Credentials outside the selection stay native (see Claude above).+ if not payload.get("OPENAI_API_KEY") or selected_api_key(payload["OPENAI_API_KEY"], "codex"):+ payload.pop("OPENAI_API_KEY", None)+ if not payload.get("tokens") or any(item.backend == "codex" and item.kind == "oauth_native"and not item.native_store_placeholderfor item in items):- raise TakeoverStateError("another native credential requires migration")- for key in ("OPENAI_API_KEY", "tokens", "auth_mode", "last_refresh"):- payload.pop(key, None)+ for key in ("tokens", "auth_mode", "last_refresh"):+ payload.pop(key, None)edit_json(auth_path, clear_auth, guard_unchanged=True)+ managed_ids = {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS}+ # An env_key is carried only when a selected row resolved it to a+ # selected key; an unresolved or unselected one stays native.+ carried_env_keys = {+ name for item in items if item.backend == "codex"+ for name, value in item.shell_values+ if value.strip() in selected_by_backend.get("codex", set())+ }++ def codex_auth_retained(provider_id: str, provider: dict) -> bool:+ if provider_id in managed_ids:+ return False+ env_key = provider.get("env_key")+ return bool(+ any(provider.get(field) for field in ("http_headers", "env_http_headers"))+ or (provider.get("experimental_bearer_token")+ and not selected_api_key(provider["experimental_bearer_token"], "codex"))+ or (env_key and env_key not in carried_env_keys)+ )++ layers: list[tuple[Path, bytes | None, dict | None]] = []for config_path in codex_config_paths(home, project_roots):content = _read_regular(config_path)if config_path in edits and content != edits[config_path].before:raise TakeoverStateError("native configuration changed")edits.setdefault(config_path, NativeFileEdit(config_path, content, content))if content is None:+ layers.append((config_path, None, None))continuetry:- config = tomllib.loads(content.decode())+ layers.append((config_path, content, tomllib.loads(content.decode())))except (ValueError, UnicodeError):raise TakeoverStateError("native configuration cannot be parsed") from None+ # Codex merges its layers, so authentication migration did not carry,+ # in any layer, keeps the whole provider native in every layer,+ # selectors included, or direct mode would stop using what was kept.+ retained_ids = {+ provider_id+ for _, _, config in layers if config is not None+ for provider_id, provider in (+ config["model_providers"].items() if isinstance(config.get("model_providers"), dict) else ()+ )+ if isinstance(provider, dict) and codex_auth_retained(provider_id, provider)+ }+ for config_path, content, config in layers:+ if config is None:+ continuebefore = json.dumps(config, sort_keys=True, default=str)- removable = {MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS}+ removable = set(managed_ids)removable.update(item.native_provider_id for item in items if item.backend == "codex" and item.native_provider_id)providers = config.get("model_providers")if isinstance(providers, dict):- for provider_id in removable:+ # A retained provider keeps its selectors and whatever+ # authentication was not carried, but a credential that WAS+ # carried still leaves the layer that supplied it: the Hub now+ # holds it, and a replay must not find it importable again.+ for provider_id in sorted(removable & retained_ids):+ provider = providers.get(provider_id)+ if not isinstance(provider, dict):+ continue+ token = provider.get("experimental_bearer_token")+ if token and selected_api_key(token, "codex"):+ provider.pop("experimental_bearer_token")+ if provider.get("env_key") in carried_env_keys:+ provider.pop("env_key")+ removable -= retained_ids+ if isinstance(providers, dict):+ for provider_id in sorted(removable):provider = providers.get(provider_id)if not isinstance(provider, dict):continue- if provider.get("experimental_bearer_token") and not selected_api_key(provider["experimental_bearer_token"]):- raise TakeoverStateError("another native credential requires migration")# Retain user labels, capabilities, and timeout preferences.for key in ("base_url", "env_key", "experimental_bearer_token", "requires_openai_auth"):provider.pop(key, None)@@ -363,6 +439,59 @@ def plan_native_cleanup(vendors = {item.vendor for item in items if item.backend == "opencode"}shell_values = dict(pair for item in items for pair in item.shell_values)+ absent = object()++ def auth_entry_retained(entry: object) -> bool:+ # An entry the Hub could not carry (OAuth, a key outside the+ # selection, or a value of no shape it reads) stays native, like+ # every other unselected credential. Only an absent entry and the+ # selected API key itself are free to go.+ return entry is not absent and not (+ isinstance(entry, dict)+ and "type" in entry and entry["type"] == "api"+ and selected_api_key(entry.get("key"), "opencode")+ )++ native_auth = read_native_config(opencode_auth_path(home)) or {}+ retained_auth = {vendor for vendor in vendors if auth_entry_retained(native_auth.get(vendor, absent))}++ # References a selected row read: bound to its saved assignment, or+ # proved empty before it selected the auth.json fallback. Any other+ # reference (unresolved, or never scanned into a selection) stays.+ carried_references = {+ name for item in items if item.backend == "opencode" for name in item.shell_variables+ }++ def api_key_retained(value: object) -> bool:+ if not value or selected_api_key(value, "opencode"):+ return False+ return not (+ isinstance(value, str)+ and value.startswith("{env:") and value.endswith("}")+ and value[5:-1] in carried_references+ and (+ not shell_values.get(value[5:-1])+ or shell_values[value[5:-1]].strip() in selected_by_backend.get("opencode", set())+ )+ )++ # OpenCode merges its layers, so a credential kept native in any one of+ # them, header auth or an unselected key, still sends to the endpoint+ # another layer names.+ for path in opencode_config_paths(home, project_roots):+ staged = edits.get(path.absolute())+ raw = staged.before if staged else _read_regular(path.absolute())+ if raw is None:+ continue+ providers = _object(raw, jsonc=True).get("provider")+ if not isinstance(providers, dict):+ continue+ for vendor in vendors:+ provider = providers.get(vendor)+ options = provider.get("options") if isinstance(provider, dict) else None+ if isinstance(options, dict) and (options.get("headers") or api_key_retained(options.get("apiKey"))):+ retained_auth.add(vendor)+def clear_providers(payload: dict) -> None:providers = payload.get("provider")if providers is None:@@ -375,22 +504,13 @@ def plan_native_cleanup(continueoptions = provider.get("options")if isinstance(options, dict):- value = options.get("apiKey")- if value and not selected_api_key(value):- # The inventory bound the saved assignment, or proved- # its absence before selecting the auth.json fallback.- reference = (- isinstance(value, str)- and value.startswith("{env:") and value.endswith("}")- and (- not shell_values.get(value[5:-1])- or shell_values[value[5:-1]].strip() in selected_secrets- )- )- if not reference:- raise TakeoverStateError("another native credential requires migration")+ if api_key_retained(options.get("apiKey")):+ continueoptions.pop("apiKey", None)- options.pop("baseURL", None)+ if vendor not in retained_auth:+ # A retained same-vendor credential, in auth.json or in+ # any layer's config, keeps its endpoint.+ options.pop("baseURL", None)if not options:provider.pop("options", None)@@ -399,6 +519,8 @@ def plan_native_cleanup(def clear_provider_auth(payload: dict) -> None:for vendor in vendors:+ if vendor not in payload or auth_entry_retained(payload[vendor]):+ continuepayload.pop(vendor, None)edit_json(opencode_auth_path(home), clear_provider_auth, guard_unchanged=True)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 0b24c6fcc..051079f0b 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -57,6 +57,7 @@ from .adapter import (InvokeCancelledError,InvokeHandle,OAuthFlowState,+ OAuthSubmissionRejectedError,OriginNotAllowedError,RawCallOutcome,RawOutcomeKind,@@ -1066,6 +1067,8 @@ class ModelHubService:status=409,detail="modelHub.errors.native_login_in_progress",) from None+ except OAuthSubmissionRejectedError:+ raise ModelHubError("submission_rejected", status=422) from Noneexcept ModelHubError:raiseexcept Exception:@@ -2191,12 +2194,55 @@ class ModelHubService:config: ModelHubConfig,source: ModelHubSourceConfig,) -> None:- """Add a new Source to eligible backend defaults without editing overrides."""+ """Add a new Source to eligible backend defaults without editing overrides.++ A subscription serves a fixed catalog, so it joins only the backends whose+ menu that catalog serves (OpenCode reaches every vendor), ahead of the API+ keys there. API keys stay open to every eligible backend, appended.+ """for backend in MODEL_HUB_BACKENDS:agent = config.agents[backend]- if self._eligible_for_agent(source, backend) and source.id not in agent.sources.order:+ if not self._eligible_for_agent(source, backend) or source.id in agent.sources.order:+ continue+ if source.kind != "subscription":agent.sources.order.append(source.id)+ continue+ if not self._subscription_serves_backend(agent, source, backend):+ continue+ by_id = {item.id: item for item in config.sources}+ position = next(+ (+ index+ for index, source_id in enumerate(agent.sources.order)+ if (existing := by_id.get(source_id)) is not None and existing.kind != "subscription"+ ),+ len(agent.sources.order),+ )+ agent.sources.order.insert(position, source.id)++ @staticmethod+ def _subscription_serves_backend(+ agent: ModelHubAgentSupplyConfig,+ source: ModelHubSourceConfig,+ backend: BackendName,+ ) -> bool:+ if backend == "opencode" or _NATIVE_VENDOR_BACKENDS.get(source.vendor) == backend:+ # The vendor's own Agent serves its subscription even when the+ # catalog is ahead of the backend's menu.+ return True+ if not agent.models or not any(not model.retired for model in source.models):+ return False+ # Another backend serves it only where the catalogs overlap.+ return any(+ _matching_v1_model_id(+ backend=backend,+ requested_model=model.id,+ source=source,+ include_manual=True,+ ) is not None+ for model in agent.models+ )def _matching_menu_model_hops(self,@@ -4621,7 +4667,15 @@ class ModelHubService:self.migration_journal.completed() or {}).get("clean_native_stores"),)- if any(item.backend == backend for item in available):+ # Retained auth stays native beside the Hub, but a+ # config the CLI cannot parse fails every launch.+ if any(+ item.backend == backend and (+ item.proposed_action == "import"+ or item.config_blocker+ )+ for item in available+ ):raise ModelHubError("mode_switch_blocked", status=409)config = self._clone_config(previous)self._agent(config, backend).mode = "hub"@@ -5007,17 +5061,26 @@ class ModelHubService:)if admission_error == "backend_model_id_invalid":raise ModelHubError(admission_error)+ # Two different refusals, and they are separate codes because they+ # name different next steps. Forging `builtin` is a claim about a+ # model this backend publishes, and the way out is to drop the row.+ # Rewriting a saved row's origin is a claim about a row that already+ # exists, and the way out is to EDIT that row instead of removing it+ # and adding it again — advice the built-in wording cannot carry, and+ # which the merged code left unsayable on a backend like OpenCode+ # whose built-in snapshot is empty by construction.for model_id, desired in desired_by_id.items():trusted = current_by_id.get(model_id) or baseline_by_id.get(model_id)- if (- (- trusted is None- and desired.origin == "builtin"- and model_id not in builtin_ids+ if trusted is None:+ if desired.origin == "builtin" and model_id not in builtin_ids:+ raise ModelHubError("backend_model_locked", status=409)+ elif desired.origin != trusted.origin:+ # `origin` records how a row was FIRST created, so a saved+ # row keeps its own answer however often it is re-filled.+ raise ModelHubError(+ "backend_model_origin_immutable",+ status=409,)- or (trusted is not None and desired.origin != trusted.origin)- ):- raise ModelHubError("backend_model_locked", status=409)for model_id in desired_by_id.keys() - current_by_id.keys():admission_error = self._backend_model_admission_error(agent_backend,diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 80cc6a970..c45660468 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -99,6 +99,12 @@ class OriginNotAllowedError(Exception):``RawCallOutcome`` and never triggers fallback."""+class OAuthSubmissionRejectedError(Exception):+ """Raised by ``submit_oauth`` when the provider refuses the pasted value+ before touching the flow. Nothing was written and the flow still awaits a+ submission, so the user can paste again on the same flow."""++class InvokeCancelledError(asyncio.CancelledError):"""Owner cancellation carrying wire facts observed before transport cleanup."""@@ -672,7 +678,11 @@ class EngineAdapter(Protocol):async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:- """``value`` per ``expects``: pasted code or callback URL."""+ """``value`` per ``expects``: pasted code or callback URL.++ A value the provider refuses without writing anything raises+ ``OAuthSubmissionRejectedError`` and leaves the flow awaiting action.+ """...async def cancel_oauth(self, flow_id: str) -> None: ...diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 42ef2fc9e..6fa7b7739 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -64,7 +64,7 @@ remain readable; ephemeral envelopes use only the terminal version.| GET `/api/models/usage?days=<n>` | → `{usage: UsageSummary}` | Bounded metered token report over a trailing local-day window. `days` is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. || POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. || GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. |-| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. |+| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A value the provider refuses before writing anything (not a callback address, no `code`) is the non-terminal `422 submission_rejected`: the flow stays `awaiting_action` and accepts another submission until its `expires_at`. || POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels provider work. A committed flow with `client_nonce` remains the same bounded terminal `OAuthFlow` with `state: "cancelled"` until its existing `expires_at`; a flow without a nonce is forgotten. || POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It validates selected items before withdrawal, upgrades an existing native Source in place when present, commits Source/Routes/backend mode atomically, and removes only replaced native material. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. |@@ -1416,7 +1416,7 @@ strand the state permanently.Minimum v5 set:-`source_not_found`, `flow_not_found`, `flow_expired`, `discovery_failed`,+`source_not_found`, `flow_not_found`, `flow_expired`, `submission_rejected`, `discovery_failed`,`invalid_source_order`, `source_create_in_progress`, `source_nonce_conflict`, `source_last_supplier`,`source_in_route_chain`,`source_model_in_route_chain`, `backend_model_in_route`,diff --git a/docs/plans/model-hub-contracts/migration-scan.schema.json b/docs/plans/model-hub-contracts/migration-scan.schema.jsonindex fcec6b4e8..500afa8e9 100644--- a/docs/plans/model-hub-contracts/migration-scan.schema.json+++ b/docs/plans/model-hub-contracts/migration-scan.schema.json@@ -38,6 +38,10 @@"items": { "enum": ["claude", "codex", "opencode"] },"uniqueItems": true,"description": "Backend-group consent closure for a shared persisted assignment. Empty/absent means this row's backend alone. The server independently requires the entire closure."+ },+ "config_blocker": {+ "type": "boolean",+ "description": "The backend's native config cannot be parsed, so Hub mode would fail every launch. Blocks the row's whole consent group; apply refuses it."}}}diff --git a/tests/e2e/test_model_hub_migration_persisted.py b/tests/e2e/test_model_hub_migration_persisted.pyindex 59d3d45bc..f688aaf7d 100644--- a/tests/e2e/test_model_hub_migration_persisted.py+++ b/tests/e2e/test_model_hub_migration_persisted.py@@ -178,10 +178,10 @@ def test_f4_unproven_shell_key_is_not_removed(@pytest.mark.parametrize("shape", ["settings", "shell"])-def test_f4_custom_api_key_transport_is_refused_without_cleanup(+def test_f4_custom_api_key_refusing_bearer_is_kept_without_cleanup(model_hub_app_factory, mock_llm_upstream, shape,):- """F4: discovery cannot prove a header the pinned engine will not send."""+ """F4: proof uses the Bearer header the pinned engine sends to a relay."""_configure_protocol(mock_llm_upstream, "anthropic")mock_llm_upstream.configure(required_api_key=KEY, required_auth_scheme="protocol")paths = []@@ -206,13 +206,12 @@ def test_f4_custom_api_key_transport_is_refused_without_cleanup(response = app.client.post("/api/models/migration/scan", {})assert response.status == 200, response.json()[row] = response.json()["scan"]["items"]- assert row["selected"] is False- assert row["notes_key"] == "settings.models.migration.blocked.transport"+ assert row["selected"] is True and row["proposed_action"] == "import"refused = app.client.post("/api/models/migration/apply", {"item_ids": [row["id"]]})- assert refused.status == 409, refused.json()+ assert refused.status >= 400, refused.json()assert paths[0].read_bytes() == beforeassert app.client.get("/api/models/sources").json()["sources"] == []- assert mock_llm_upstream.requests() == []+ assert all("x-api-key" not in request["headers"] for request in mock_llm_upstream.requests())@pytest.mark.parametrize("profile,writer", [diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex cc1363cc6..fb9effca1 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -714,12 +714,18 @@ def test_mh_mig_001_api_apply_takes_over_credentials_and_cleans_native_auth(reloaded = _assert_canonical_round_trip(store.config)by_id = {source.id: source for source in store.config.sources}imported_ids = set(by_id)+ # A subscription joins only the Agents its fixed catalog serves (OpenCode+ # reaches every vendor), ahead of the keys; keys join every eligible Agent.+ serves = {"claude": {"anthropic"}, "codex": {"openai"}, "opencode": {"anthropic", "openai"}}for backend in ("claude", "codex", "opencode"):- assert store.config.agents[backend].sources.order == [- source.id- for source in store.config.sources+ eligible = [+ source for source in store.config.sourcesif ModelHubConfig.source_eligible_for_backend(source, backend)]+ assert store.config.agents[backend].sources.order == [+ source.id for source in eligible+ if source.kind == "subscription" and source.vendor in serves[backend]+ ] + [source.id for source in eligible if source.kind != "subscription"]codex_payload = next(agent for agent in service.list_agents() if agent["backend"] == "codex")diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex c415cfb9d..5afef065e 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -37,6 +37,7 @@ from core.handlers.model_hub.adapter import (ObservationDiscovery,ObservationOutcome,OAuthFlowState,+ OAuthSubmissionRejectedError,RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,@@ -3825,7 +3826,7 @@ def test_backend_catalog_keeps_every_existing_origin_immutable(with pytest.raises(ModelHubError) as raised:asyncio.run(service.set_agent_models("codex", baseline, desired))- assert raised.value.code == "backend_model_locked"+ assert raised.value.code == "backend_model_origin_immutable"assert next(model for model in agent.models if model.id == model_id).origin == origin@@ -3846,10 +3847,65 @@ def test_backend_catalog_rejects_an_origin_forged_into_the_baseline(tmp_path):with pytest.raises(ModelHubError) as raised:asyncio.run(service.set_agent_models("codex", forged_baseline, forged_desired))- assert raised.value.code == "backend_model_locked"+ assert raised.value.code == "backend_model_origin_immutable"assert next(model for model in agent.models if model.id == model_id).origin == "manual"+def test_backend_catalog_names_a_re_added_row_by_its_own_refusal(tmp_path):+ """A row removed and added back keeps the origin the server recorded.++ OpenCode publishes no built-in models at all, so the built-in refusal can+ never be the honest answer there. The save is refused for re-deciding an+ existing row's creation path, and has to say that and nothing else.+ """+ service, store, _adapter = _service(tmp_path)+ model_id = "grok-4.6"+ agent = store.config.agents["opencode"]+ agent.models.append(ModelHubBackendModelConfig(+ id=model_id, origin="provider", native_protocol="openai_responses",+ ))+ agent.routes[model_id] = ModelHubRouteConfig()+ if agent.menu is not None:+ agent.menu.checked.append(model_id)+ baseline = next(+ projected["catalog_models"] for projected in service.list_agents() if projected["backend"] == "opencode"+ )+ kept = [copy.deepcopy(model) for model in baseline if model["id"] != model_id]+ re_added = copy.deepcopy(next(model for model in baseline if model["id"] == model_id))+ re_added["origin"] = "models_dev"++ with pytest.raises(ModelHubError) as raised:+ asyncio.run(service.set_agent_models("opencode", baseline, [*kept, re_added]))++ assert raised.value.code == "backend_model_origin_immutable"+ assert next(model for model in agent.models if model.id == model_id).origin == "provider"+++def test_backend_catalog_accepts_a_re_added_row_under_its_recorded_origin(tmp_path):+ """The same removal and re-add saves once the origin is the recorded one."""+ service, store, _adapter = _service(tmp_path)+ model_id = "grok-4.6"+ agent = store.config.agents["opencode"]+ agent.models.append(ModelHubBackendModelConfig(+ id=model_id, origin="provider", native_protocol="openai_responses",+ ))+ agent.routes[model_id] = ModelHubRouteConfig()+ if agent.menu is not None:+ agent.menu.checked.append(model_id)+ baseline = next(+ projected["catalog_models"] for projected in service.list_agents() if projected["backend"] == "opencode"+ )+ kept = [copy.deepcopy(model) for model in baseline if model["id"] != model_id]+ re_added = copy.deepcopy(next(model for model in baseline if model["id"] == model_id))+ re_added["display_name"] = "Grok 4.6"++ response = asyncio.run(service.set_agent_models("opencode", baseline, [*kept, re_added]))++ saved = next(model for model in response["agent"]["catalog_models"] if model["id"] == model_id)+ assert saved["origin"] == "provider"+ assert saved["display_name"] == "Grok 4.6"++@pytest.mark.parametrize("model_id", ["opus", "sonnet[1m]"])def test_backend_catalog_restores_a_removed_claude_builtin_alias(tmp_path,@@ -8431,6 +8487,24 @@ def test_expired_oauth_flow_is_rejected_before_submit(tmp_path):assert service.oauth_flows.channel(flow["flow_id"]) is None+def test_rejected_oauth_submission_is_non_terminal_and_keeps_the_flow(tmp_path):+ service, _, adapter = _service(tmp_path)+ flow = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))["flow"]++ async def reject(_flow_id, _value):+ raise OAuthSubmissionRejectedError(_flow_id)++ adapter.submit_oauth = reject+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_submit({"flow_id": flow["flow_id"], "value": "https://chatgpt.com/"}))++ assert exc_info.value.code == "submission_rejected"+ assert exc_info.value.status == 422+ assert service.oauth_flows.channel(flow["flow_id"]) == "hub"+ status = asyncio.run(service.oauth_status(flow["flow_id"]))+ assert status["flow"]["state"] == "awaiting_action"++@pytest.mark.parametrize("suffix", ["+00:00", "Z", ""])@pytest.mark.parametrize("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):diff --git a/tests/test_model_hub_migration_bearer.py b/tests/test_model_hub_migration_bearer.pyindex 91abc2ce5..c22e6b147 100644--- a/tests/test_model_hub_migration_bearer.py+++ b/tests/test_model_hub_migration_bearer.py@@ -108,7 +108,7 @@ async def _relay(*, public_models=False, protocol_success=False, scheme="bearer"@pytest.mark.parametrize("changes", [{"auth_scheme": "auto"}, {"auth_scheme": "x-api-key"}, {"auth_scheme": ""},- {"auth_scheme": []}, {"vendor": "custom"}, {"vendor": "openai"},+ {"auth_scheme": []}, {"vendor": ""}, {"vendor": "openai"},{"protocol": "openai_chat"}, {"protocol": "openai_responses"},{"base_url": None}, {"base_url": "https://api.anthropic.com"},{"base_url": "https://API.ANTHROPIC.COM:443/v1"},diff --git a/tests/test_model_hub_migration_source_identity.py b/tests/test_model_hub_migration_source_identity.pyindex 842f74b12..82cbb9d48 100644--- a/tests/test_model_hub_migration_source_identity.py+++ b/tests/test_model_hub_migration_source_identity.py@@ -240,13 +240,14 @@ def test_deduplication_keeps_blocked_config_layers_visible(monkeypatch, tmp_pathrows = service.migration_scan()["items"]assert len(rows) == 2assert {row["proposed_action"] for row in rows} == {"import", "reauth"}- before = auth.read_bytes()- with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(- [row["id"] for row in rows if row["proposed_action"] == "import"],- ))- assert not adapter.provisioned- assert auth.read_bytes() == before+ # The importable layer migrates; the {file:} layer stays native.+ blocked = paths[1].read_bytes()+ result = asyncio.run(service.migration_apply(+ [row["id"] for row in rows if row["proposed_action"] == "import"],+ ))+ assert result["applied"] == 1 and adapter.provisioned+ assert paths[1].read_bytes() == blocked+ assert [row["proposed_action"] for row in service.migration_scan()["items"]] == ["reauth"]def _model_only_opencode(monkeypatch, tmp_path):diff --git a/tests/test_model_hub_migration_static_cleanup.py b/tests/test_model_hub_migration_static_cleanup.pyindex df4460fc8..5084a1c5c 100644--- a/tests/test_model_hub_migration_static_cleanup.py+++ b/tests/test_model_hub_migration_static_cleanup.py@@ -159,13 +159,14 @@ def test_static_canonical_value_reuses_existing_ref(home, tmp_path, shape):@pytest.mark.parametrize("shape", CONFIG_SHAPES)-def test_other_canonical_credential_does_not_authorize_cleanup(home, tmp_path, shape):+def test_other_canonical_credential_is_left_in_place(home, tmp_path, shape):path, roots = _seed(home, shape)before = path.read_bytes()service, _, adapter = _service(tmp_path, migration_home=home)[item] = _items(service, roots)- with pytest.raises(TakeoverStateError, match="another native credential"):- plan_native_cleanup([replace(item, secret="fixture-other")], home=home, project_roots=roots)+ edits = plan_native_cleanup([replace(item, secret="fixture-other")], home=home, project_roots=roots)+ # An unselected credential stays native; the Hub launch shadows it.+ assert next(edit for edit in edits if edit.path == path).after == beforeassert path.read_bytes() == before and not adapter.provisioned@@ -207,8 +208,8 @@ def test_padding_only_change_never_bypasses_exact_consent(home, tmp_path, shape,@pytest.mark.parametrize("value", [" \t ", "fixture-other", ["fixture"], {"key": KEY}, 123])@pytest.mark.parametrize("field", ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"])-def test_unselected_settings_value_still_refuses_cleanup(home, tmp_path, value, field):- _seed(home, "claude-user-api", KEY)+def test_unselected_settings_value_stays_while_selected_key_is_cleaned(home, tmp_path, value, field):+ path, _ = _seed(home, "claude-user-api", KEY)# A real second native layer, not a new supported filename.project = home / "project"other = project / ".claude/settings.local.json"@@ -216,9 +217,9 @@ def test_unselected_settings_value_still_refuses_cleanup(home, tmp_path, value,before = other.read_bytes()service, _, adapter = _service(tmp_path, migration_home=home)selected = next(item for item in _items(service, (project,)) if item.secret == KEY)- with pytest.raises(TakeoverStateError, match="another native credential"):- plan_native_cleanup([selected], home=home, project_roots=(project,))- assert other.read_bytes() == before+ edits = {edit.path: edit for edit in plan_native_cleanup([selected], home=home, project_roots=(project,))}+ assert KEY.encode() not in edits[path].after+ assert edits[other.absolute()].after == beforeassert not adapter.provisioned@@ -244,3 +245,372 @@ def test_padded_settings_bearer_uses_proven_header_after_custody(home, tmp_path)assert json.loads(path.read_bytes()) == {"env": {"KEEP_FIXTURE": "preserved"}}asyncio.run(scenario())+++def test_codex_retained_bearer_provider_keeps_its_selectors(home, tmp_path):+ path = home / ".codex/config.toml"+ _write(path, 'model_provider = "relay"\n'+ '[profiles.work]\nmodel_provider = "relay"\n'+ '[model_providers.relay]\nbase_url = "https://relay.example/v1"\n'+ 'experimental_bearer_token = "fixture-unselected-bearer"\n')+ service, _, _ = _service(tmp_path, migration_home=home)+ [item] = _items(service, ())+ # Another credential (e.g. OAuth) is imported while `relay` is active.+ other = replace(item, kind="oauth_native", secret=None, native_provider_id="relay")+ edits = plan_native_cleanup([other], home=home)+ for edit in edits:+ edit.apply()+ content = path.read_text()+ assert content.count('model_provider = "relay"') == 2+ assert "fixture-unselected-bearer" in content and "relay.example" in content+++def test_opencode_shell_key_leaves_a_same_vendor_oauth_entry_native(home, tmp_path):+ auth = home / ".local/share/opencode/auth.json"+ oauth = {"type": "oauth", "access": "fixture-access", "refresh": "fixture-refresh", "expires": 1}+ _write(auth, json.dumps({"openrouter": oauth}))+ _write(home / ".profile", f"export OPENROUTER_API_KEY='{KEY}'\n")+ service, _, adapter = _service(tmp_path, migration_home=home)+ rows = [row for row in service.migration_scan()["items"] if row["proposed_action"] == "import"]+ assert len(rows) == 1+ assert asyncio.run(service.migration_apply([rows[0]["id"]]))["applied"] == 1+ assert adapter.provisioned+ assert json.loads(auth.read_text())["openrouter"] == oauth++[email protected]("entry", ["legacy-or-malformed-value", 7, ["fixture"], None])+def test_opencode_shell_key_leaves_a_non_object_auth_entry_native(home, tmp_path, entry):+ auth = home / ".local/share/opencode/auth.json"+ _write(auth, json.dumps({"openrouter": entry}))+ _write(home / ".profile", f"export OPENROUTER_API_KEY='{KEY}'\n")+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [item for item in _items(service, ()) if item.proposed_action == "import"]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, _include_shell=False):+ edit.apply()+ # Not carried, so not removed: direct mode finds what it left.+ assert json.loads(auth.read_text()) == {"openrouter": entry}++[email protected]("field", ["http_headers", "env_http_headers"])+def test_codex_retained_header_provider_keeps_its_configuration(home, tmp_path, field):+ path = home / ".codex/config.toml"+ header = '{ Authorization = "Bearer fixture-header" }' if field == "http_headers" else '{ Authorization = "RELAY_TOKEN" }'+ _write(path, 'model_provider = "relay"\n'+ '[model_providers.relay]\nbase_url = "https://relay.example/v1"\n'+ f'{field} = {header}\n')+ service, _, _ = _service(tmp_path, migration_home=home)+ [item] = _items(service, ())+ assert item.proposed_action != "import"+ other = replace(item, kind="oauth_native", proposed_action="import", native_provider_id="relay")+ for edit in plan_native_cleanup([other], home=home):+ edit.apply()+ content = path.read_text()+ assert 'model_provider = "relay"' in content+ assert "relay.example" in content and "Authorization" in content+++def test_opencode_shell_key_keeps_the_endpoint_a_retained_oauth_entry_uses(home, tmp_path):+ config = home / ".config/opencode/opencode.json"+ auth = home / ".local/share/opencode/auth.json"+ # The OAuth entry's endpoint; the shell key is the only importable row.+ _write(config, json.dumps({"provider": {"openrouter": {"options": {+ "baseURL": "https://relay.example/api/v1"}}}}))+ oauth = {"type": "oauth", "access": "fixture-access", "refresh": "fixture-refresh", "expires": 1}+ _write(auth, json.dumps({"openrouter": oauth}))+ _write(home / ".profile", f"export OPENROUTER_API_KEY='{KEY}'\\n")+ service, _, _ = _service(tmp_path, migration_home=home)+ items = _items(service, ())+ importable = [item for item in items if item.proposed_action == "import"]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, _include_shell=False):+ edit.apply()+ assert json.loads(auth.read_text())["openrouter"] == oauth+ options = json.loads(config.read_text())["provider"]["openrouter"]["options"]+ assert options.get("baseURL") == "https://relay.example/api/v1"+++def test_opencode_shell_key_keeps_the_endpoint_a_retained_header_layer_uses(home, tmp_path):+ config = home / ".config/opencode/opencode.json"+ # Header auth is left native; the shell key is the importable row.+ layer = {"baseURL": "https://relay.example/api/v1", "headers": {"Authorization": "Bearer fixture"}}+ _write(config, json.dumps({"provider": {"openrouter": {"options": layer}}}))+ _write(home / ".profile", f"export OPENROUTER_API_KEY='{KEY}'\\n")+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [item for item in _items(service, ()) if item.proposed_action == "import"]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, _include_shell=False):+ edit.apply()+ assert json.loads(config.read_text())["provider"]["openrouter"]["options"] == layer++[email protected]("entry", [+ '"bad"',+ '{ http_headers = "bad" }',+ '{ env_http_headers = ["X_KEY"] }',+ '{ base_url = 1 }',+ '{ stream_max_retries = "3" }',+ '{ wire_api = "bogus" }',+ '{ supports_websockets = "bad" }',+ '{ websocket_connect_timeout_ms = -1 }',+ '{ auth = "bad" }',+ '{ aws = { profile = 1 }, http_headers = { X = "y" } }',+ '{ aws = { credential_export = { args = ["x"] } } }',+ '{ auth = { command = "fixture", timeout_ms = 0 } }',+ '{ gateway_oauth = { authorization_url = "a", client_id = "b", token_url = "c", delivery = { kind = "query", name = "x" } } }',+])+def test_codex_malformed_provider_entry_blocks_hub_mode(home, tmp_path, entry):+ _write(home / ".codex/config.toml", f"model_providers = {{ relay = {entry} }}\n")+ service, _, _ = _service(tmp_path, migration_home=home)+ assert any(item.backend == "codex" and item.config_blocker for item in _items(service, ()))++[email protected]("entry", [+ '"bad"', '{"options": "bad"}', '{"options": {"baseURL": 1}}', '{"models": {"m": "bad"}}',+ '{"npm": 1}', '{"env": "KEY"}', '{"options": {"timeout": 0}}', '{"options": {"setCacheKey": "yes"}}',+ '{"models": {"m": {"limit": {"context": 1}}}}', '{"models": {"m": {"status": "gone"}}}',+ '{"models": {"m": {"modalities": {"input": ["smell"]}}}}', '{"models": {"m": {"headers": {"X": 1}}}}',+])+def test_opencode_malformed_provider_entry_blocks_hub_mode(home, tmp_path, entry):+ _write(home / ".config/opencode/opencode.json", f'{{"provider": {{"relay": {entry}}}}}')+ service, _, _ = _service(tmp_path, migration_home=home)+ assert any(item.backend == "opencode" and item.config_blocker for item in _items(service, ()))+++def test_well_typed_header_providers_do_not_block_hub_mode(home, tmp_path):+ _write(home / ".codex/config.toml", 'model_providers = { relay = { http_headers = { X = "y" }, '+ 'supports_websockets = true, wire_api = "responses", future_field = 1, '+ 'auth = { command = "fixture", args = ["x"], refresh_interval_ms = 0, extension = "y" }, '+ 'aws = { profile = "p", credential_export = { command = "fixture" } }, '+ 'gateway_oauth = { authorization_url = "a", client_id = "b", token_url = "c", '+ 'delivery = { kind = "header", name = "X" } } } }\n')+ _write(home / ".config/opencode/opencode.json", '{"provider": {"relay": {"npm": "@ai-sdk/openai-compatible", '+ '"future": 1, "options": {"headers": {"X": "y"}, "timeout": false, "chunkTimeout": 1000}, '+ '"models": {"m": {"limit": {"context": 1, "output": 2}, "interleaved": {"field": "reasoning"}, '+ '"cost": {"input": 0.5, "output": 1}, "variants": {"high": {"disabled": false, "x": 1}}}}}}}')+ service, _, _ = _service(tmp_path, migration_home=home)+ assert not any(item.config_blocker for item in _items(service, ()))++[email protected]("field", [+ "model = 1", "model_post_turn_compact_threshold_percent = 12.5", '[features]\nunified_exec = "bad"',+])+def test_codex_fields_outside_the_provider_map_stay_with_the_cli(home, tmp_path, field):+ # Accepted shapes differ by CLI version and fail direct launches alike;+ # migration neither reads nor rewrites them.+ _write(home / ".codex/config.toml", f'{field}\n[model_providers.relay]\nhttp_headers = {{ X = "y" }}\n'+ if not field.startswith("[") else f'[model_providers.relay]\nhttp_headers = {{ X = "y" }}\n{field}\n')+ service, _, _ = _service(tmp_path, migration_home=home)+ assert not any(item.config_blocker for item in _items(service, ()))+++def test_codex_count_beyond_signed_64_bits_blocks_hub_mode(home, tmp_path):+ _write(home / ".codex/config.toml", "model_providers = { relay = { stream_max_retries = 9223372036854775808 } }\n")+ service, _, _ = _service(tmp_path, migration_home=home)+ assert any(item.backend == "codex" and item.config_blocker for item in _items(service, ()))+++def test_apply_rejects_a_backend_whose_native_config_blocks_hub_mode(home, tmp_path):+ _seed(home, "codex-auth")+ _write(home / ".codex/config.toml", 'model_providers = { relay = "bad" }\n')+ service, store, adapter = _service(tmp_path, migration_home=home)+ importable = [row for row in service.migration_scan()["items"] if row["proposed_action"] == "import"]+ assert len(importable) == 1+ with pytest.raises(ModelHubError) as caught:+ asyncio.run(service.migration_apply([importable[0]["id"]]))+ assert caught.value.status == 409+ assert not store.config.sources and not adapter.provisioned+ assert KEY.encode() in (home / ".codex/auth.json").read_bytes()+++def test_completed_replay_rejects_a_config_blocker_written_after_cleanup(home, tmp_path):+ _seed(home, "codex-auth")+ service, _, _ = _service(tmp_path, migration_home=home)+ [item_id] = [row["id"] for row in service.migration_scan()["items"] if row["proposed_action"] == "import"]+ assert asyncio.run(service.migration_apply([item_id]))["applied"] == 1+ _write(home / ".codex/config.toml", 'model_providers = { relay = "bad" }\n')+ with pytest.raises(ModelHubError) as caught:+ asyncio.run(service.migration_apply([item_id]))+ assert caught.value.status == 409++[email protected]("unreadable", [False, True])+def test_invalid_codex_auth_file_blocks_hub_mode(home, tmp_path, unreadable):+ _write(home / ".codex/auth.json", json.dumps({"OPENAI_API_KEY": KEY}) if unreadable else "{1: 2}")+ if unreadable:+ (home / ".codex/auth.json").chmod(0)+ service, _, _ = _service(tmp_path, migration_home=home)+ assert any(item.backend == "codex" and item.config_blocker for item in _items(service, ()))++[email protected]("config", [+ {"provider": {"openrouter": {"options": {"apiKey": KEY}}}},+ {"provider": {"openrouter": "bad"}},+])+def test_unreadable_opencode_auth_file_blocks_hub_mode_and_scans_config_layers(home, tmp_path, config):+ _write(home / ".local/share/opencode/auth.json", "{1: 2}")+ user = home / ".config/opencode/opencode.json"+ _write(user, json.dumps(config))+ service, _, _ = _service(tmp_path, migration_home=home)+ items = [item for item in _items(service, ()) if item.backend == "opencode"]+ assert any(item.config_blocker and item.notes_key.endswith(".unreadable") for item in items)+ assert any(str(user) in item.source_paths for item in items)+++def test_apply_rejects_a_config_blocker_found_by_the_guarded_rescan(home, tmp_path, monkeypatch):+ from contextlib import asynccontextmanager++ import core.handlers.model_hub.migration as migration++ _seed(home, "codex-auth")+ service, store, adapter = _service(tmp_path, migration_home=home)+ [item_id] = [row["id"] for row in service.migration_scan()["items"] if row["proposed_action"] == "import"]+ draining = False+ scan = migration.scan_native_configs++ def rescan(*args, **kwargs):+ # A real file edit also rebinds the selected row's revision, so inject+ # the blocker beside an unchanged selection to reach the final check.+ items = scan(*args, **kwargs)+ if draining:+ items.append(migration._blocked_item("codex", "drained", config_blocker=True))+ return items++ @asynccontextmanager+ async def guard(backends):+ nonlocal draining+ draining = True++ async def verify_idle():+ return None++ yield verify_idle++ monkeypatch.setattr(migration, "scan_native_configs", rescan)+ service.migration_guard = guard+ with pytest.raises(ModelHubError) as caught:+ asyncio.run(service.migration_apply([item_id]))+ assert caught.value.status == 409+ assert not store.config.sources and not adapter.provisioned+ assert KEY.encode() in (home / ".codex/auth.json").read_bytes()+++def test_opencode_header_auth_in_one_layer_keeps_another_layers_endpoint(home, tmp_path):+ user = home / ".config/opencode/opencode.json"+ project = home / "project/opencode.json"+ _write(user, json.dumps({"provider": {"openrouter": {"options": {+ "baseURL": "https://relay.example/api/v1", "apiKey": KEY}}}}))+ _write(project, json.dumps({"provider": {"openrouter": {"options": {+ "headers": {"Authorization": "Bearer fixture"}}}}}))+ roots = (home / "project",)+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [item for item in _items(service, roots) if item.proposed_action == "import"]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, project_roots=roots, _include_shell=False):+ edit.apply()+ options = json.loads(user.read_text())["provider"]["openrouter"]["options"]+ assert options == {"baseURL": "https://relay.example/api/v1"}+++def test_equal_secret_selected_for_another_backend_leaves_claude_oauth_token(home, tmp_path):+ settings = home / ".claude/settings.json"+ _write(settings, json.dumps({"env": {"CLAUDE_CODE_OAUTH_TOKEN": KEY}}))+ _seed(home, "codex-auth", raw=KEY)+ service, _, _ = _service(tmp_path, migration_home=home)+ codex = [item for item in _items(service, ()) if item.backend == "codex" and item.proposed_action == "import"]+ assert codex+ claude = replace(codex[0], backend="claude", secret=None, kind="oauth_native", proposed_action="import")+ for edit in plan_native_cleanup([*codex, claude], home=home):+ edit.apply()+ assert json.loads(settings.read_text())["env"]["CLAUDE_CODE_OAUTH_TOKEN"] == KEY+++def test_equal_claude_api_key_leaves_a_blocked_oauth_token_in_another_field(home, tmp_path):+ settings = home / ".claude/settings.json"+ _write(settings, json.dumps({"env": {"ANTHROPIC_API_KEY": KEY, "CLAUDE_CODE_OAUTH_TOKEN": KEY}}))+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [item for item in _items(service, ()) if item.proposed_action == "import"]+ assert [item.backend for item in importable] == ["claude"]+ for edit in plan_native_cleanup(importable, home=home, _include_shell=False):+ edit.apply()+ assert json.loads(settings.read_text())["env"] == {"CLAUDE_CODE_OAUTH_TOKEN": KEY}+++def test_claude_retained_credential_in_one_layer_keeps_another_layers_base_url(home, tmp_path):+ user = home / ".claude/settings.json"+ project = home / "project/.claude/settings.json"+ _write(user, json.dumps({"env": {"ANTHROPIC_API_KEY": KEY, "ANTHROPIC_BASE_URL": "https://relay.example"}}))+ _write(project, json.dumps({"apiKeyHelper": "fixture-helper"}))+ roots = (home / "project",)+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [item for item in _items(service, roots) if item.proposed_action == "import"]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, project_roots=roots, _include_shell=False):+ edit.apply()+ assert json.loads(user.read_text())["env"] == {"ANTHROPIC_BASE_URL": "https://relay.example"}+++def test_scan_payload_exposes_configuration_blockers(home, tmp_path):+ _write(home / ".codex/config.toml", 'model_providers = { relay = "bad" }\n')+ service, _, _ = _service(tmp_path, migration_home=home)+ rows = service.migration_scan()["items"]+ assert any(row["backend"] == "codex" and row["config_blocker"] for row in rows)+++def test_opencode_unselected_key_in_one_layer_keeps_another_layers_endpoint(home, tmp_path):+ user = home / ".config/opencode/opencode.json"+ project = home / "project/opencode.json"+ _write(user, json.dumps({"provider": {"openrouter": {"options": {"apiKey": "fixture-kept-native"}}}}))+ _write(project, json.dumps({"provider": {"openrouter": {"options": {+ "baseURL": "https://relay.example/api/v1", "apiKey": KEY}}}}))+ roots = (home / "project",)+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [+ item for item in _items(service, roots)+ if item.proposed_action == "import" and item.secret == KEY+ ]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, project_roots=roots, _include_shell=False):+ edit.apply()+ assert json.loads(user.read_text())["provider"]["openrouter"]["options"] == {"apiKey": "fixture-kept-native"}+ assert json.loads(project.read_text())["provider"]["openrouter"]["options"] == {+ "baseURL": "https://relay.example/api/v1"}+++def test_codex_unresolved_env_key_in_one_layer_keeps_the_provider_native(home, tmp_path):+ user = home / ".codex/config.toml"+ project = home / "project/.codex/config.toml"+ _write(user, 'model_provider = "relay"\n[model_providers.relay]\nenv_key = "FIXTURE_UNSET_KEY"\n')+ _write(project, '[model_providers.relay]\nbase_url = "https://relay.example/v1"\n'+ f"experimental_bearer_token = {json.dumps(KEY)}\n")+ roots = (home / "project",)+ service, _, _ = _service(tmp_path, migration_home=home)+ items = _items(service, roots)+ importable = [item for item in items if item.proposed_action == "import"]+ assert importable and any(item.proposed_action != "import" for item in items if item.backend == "codex")+ for edit in plan_native_cleanup(importable, home=home, project_roots=roots, _include_shell=False):+ edit.apply()+ assert 'env_key = "FIXTURE_UNSET_KEY"' in user.read_text()+ assert 'model_provider = "relay"' in user.read_text()+ assert "relay.example" in project.read_text()+ # The carried bearer still leaves the layer that supplied it, so a replay+ # cannot rediscover it as importable.+ assert KEY not in project.read_text()+ assert "experimental_bearer_token" not in project.read_text()+++def test_unresolved_opencode_reference_in_another_layer_stays_with_its_endpoint(home, tmp_path):+ user = home / ".config/opencode/opencode.json"+ project = home / "project/opencode.json"+ _write(user, json.dumps({"provider": {"openrouter": {"options": {"apiKey": "{env:FIXTURE_MISSING_KEY}"}}}}))+ _write(project, json.dumps({"provider": {"openrouter": {"options": {+ "baseURL": "https://relay.example/api/v1", "apiKey": KEY}}}}))+ roots = (home / "project",)+ service, _, _ = _service(tmp_path, migration_home=home)+ importable = [item for item in _items(service, roots) if item.proposed_action == "import"]+ assert importable+ for edit in plan_native_cleanup(importable, home=home, project_roots=roots, _include_shell=False):+ edit.apply()+ assert json.loads(user.read_text())["provider"]["openrouter"]["options"] == {"apiKey": "{env:FIXTURE_MISSING_KEY}"}+ assert json.loads(project.read_text())["provider"]["openrouter"]["options"] == {+ "baseURL": "https://relay.example/api/v1"}diff --git a/tests/test_model_hub_migration_transport.py b/tests/test_model_hub_migration_transport.pyindex 607396166..e5fd86064 100644--- a/tests/test_model_hub_migration_transport.py+++ b/tests/test_model_hub_migration_transport.py@@ -111,13 +111,21 @@ def _scan(service, roots=(), legacy=None):@pytest.mark.parametrize("entry", ENTRIES)[email protected]("base_url,secret", [- (CUSTOM, KEY), (OFFICIAL, "fixture-sk-ant-oat-static"),-])-def test_all_anthropic_native_producers_refuse_unpreservable_transport(- tmp_path, native, entry, base_url, secret,-):- paths, roots, legacy = _seed(native, entry, base_url=base_url, secret=secret)+def test_custom_anthropic_key_is_offered_as_the_bearer_the_engine_sends(tmp_path, native, entry):+ _, roots, legacy = _seed(native, entry, base_url=CUSTOM)+ service, store, _ = _service(tmp_path, migration_home=native)+ if legacy:+ store.native_auth_snapshot = lambda backends: legacy+ rows = _scan(service, roots, legacy)+ assert rows+ assert all(row.proposed_action == "import" and row.selected for row in rows)+ assert all(row.auth_scheme == "bearer" for row in rows)++[email protected]("entry", ENTRIES)+def test_all_anthropic_native_producers_refuse_unpreservable_transport(tmp_path, native, entry):+ secret = "fixture-sk-ant-oat-static"+ paths, roots, legacy = _seed(native, entry, base_url=OFFICIAL, secret=secret)before = {path: path.read_bytes() for path in paths}service, store, adapter = _service(tmp_path, migration_home=native)if legacy:@@ -189,7 +197,8 @@ def test_migration_oauth_heuristic_is_never_reinterpreted_as_static(secret):("anthropic", "https://api.anthropic.com:0443", "bearer", True),("anthropic", OFFICIAL, "bearer", False),("anthropic", CUSTOM, "unknown", False),- ("custom", CUSTOM, "bearer", False),+ ("custom", CUSTOM, "bearer", True),+ ("openai", CUSTOM, "bearer", False),("minimax", None, None, False),("custom", None, None, False),("custom", OFFICIAL, None, True),@@ -330,7 +339,7 @@ def _real_http_adapter(service, tmp_path):@pytest.mark.parametrize("entry", ["claude-settings", "shell", "opencode-custom"])@pytest.mark.parametrize("reuse", [False, True])-def test_strict_custom_x_api_key_never_becomes_successful_migration(+def test_custom_endpoint_refusing_bearer_fails_proof_and_keeps_native_files(tmp_path, native, entry, reuse,):async def scenario():@@ -352,19 +361,14 @@ def test_strict_custom_x_api_key_never_becomes_successful_migration(async with client.post(origin + "/v1/messages", headers=headers, json={"model": "claude-fixture"}) as response:assert response.status == statusrequests.clear()- # Demonstrate the old observation path can prove this key using- # x-api-key. That proof must not license destructive migration.- proof = await service._require_proven_source_payload({- "vendor": "anthropic", "key": KEY, "base_url": origin,- })- assert proof.authenticated and proof.protocol == "anthropic"- assert any(headers.get("x-api-key") == KEY for _, headers in requests)- requests.clear()+ # Offered as the Bearer the engine would send; a native x-api-key+ # proof never licenses the migration.rows = service.migration_scan()["items"]+ assert rows and all(row["proposed_action"] == "import" for row in rows)with pytest.raises(ModelHubError):await service.migration_apply([row["id"] for row in rows])- assert all(row["notes_key"] == BLOCKED for row in rows)- assert requests == []+ assert requests+ assert all("x-api-key" not in headers for _, headers in requests)assert {path: path.read_bytes() for path in paths} == beforeassert store.config.to_payload() == config_beforeassert set((runtime.state_store.root / "credentials").glob("*.json")) == credentials_before@@ -397,11 +401,14 @@ def test_real_observation_cannot_promote_custom_key_to_anthropic_transport(tmp_pasyncio.run(scenario())[email protected]("entry", ["claude-settings", "shell"])-def test_custom_bearer_keeps_actual_proof_discovery_and_cleanup(tmp_path, native, entry):[email protected]("entry,bearer", [+ ("claude-settings", True), ("shell", True),+ ("claude-settings", False), ("shell", False),+])+def test_custom_bearer_keeps_actual_proof_discovery_and_cleanup(tmp_path, native, entry, bearer):async def scenario():async with _upstream("bearer") as (origin, requests):- paths, _, _ = _seed(native, entry, base_url=origin, bearer=True)+ paths, _, _ = _seed(native, entry, base_url=origin, bearer=bearer)service, store, _ = _service(tmp_path, migration_home=native)runtime = _real_http_adapter(service, tmp_path)rows = service.migration_scan()["items"]diff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.pyindex 12342d8c5..80ed07923 100644--- a/tests/test_model_hub_native_takeover.py+++ b/tests/test_model_hub_native_takeover.py@@ -612,3 +612,32 @@ def test_rejected_grant_terminal_decision_recovers_after_crash(monkeypatch, tmp_assert not service.migration_blocked_backendsassert store.config.sources[0].state.status == "needs_action"assert adapter.revoked == []++[email protected](("backend", "relative", "payload"), [+ ("claude", ".claude/settings.json", "{not json"),+ ("codex", ".codex/config.toml", "model_providers = ["),+ ("opencode", ".config/opencode/opencode.json", '{"provider": []}'),+])+def test_mode_only_adoption_refuses_a_native_config_the_cli_cannot_parse(+ monkeypatch, tmp_path, backend, relative, payload,+):+ home = tmp_path / "native"+ _isolate_native_home(monkeypatch, home)+ service, store, _adapter = _service(tmp_path, migration_home=home)+ store.config.agents[backend].mode = "direct"+ _write(home / relative, payload)+ # Nothing is importable, yet the CLI would fail before any Hub override.+ assert not any(item["proposed_action"] == "import" for item in service.migration_scan()["items"])++ @asynccontextmanager+ async def guard(backends):+ async def verify():+ return None+ yield verify++ service.migration_guard = guard+ with pytest.raises(ModelHubError) as failure:+ asyncio.run(service.set_agent_mode(backend, "hub"))+ assert failure.value.code == "mode_switch_blocked"+ assert store.config.agents[backend].mode == "direct"diff --git a/tests/test_model_hub_persisted_inventory.py b/tests/test_model_hub_persisted_inventory.pyindex 246619295..e40d68e3a 100644--- a/tests/test_model_hub_persisted_inventory.py+++ b/tests/test_model_hub_persisted_inventory.py@@ -277,7 +277,8 @@ def test_claude_key_and_bearer_are_both_retained(home):}}))rows = scan(home)assert {(row.secret, row.auth_scheme) for row in rows} == {- ("fixture-api-key", None), ("fixture-bearer", "bearer"),+ # A custom-origin API key travels as the Bearer the engine sends.+ ("fixture-api-key", "bearer"), ("fixture-bearer", "bearer"),}assert len({row.id for row in rows}) == 2diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex f9201399c..f6a644e2e 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -2365,3 +2365,41 @@ def test_direct_mode_refuses_chain_and_probe(tmp_path):with pytest.raises(ModelHubError) as probe_error:asyncio.run(service.probe_agent("claude", "claude-opus-4-6"))assert probe_error.value.code == "direct_mode"+++def test_new_subscription_joins_only_the_agents_its_catalog_serves(tmp_path):+ key = _source("src_placekey01", ("claude-opus-4-6",))+ config = _config([key])+ service, _, _ = _service(tmp_path, config)+ chatgpt = _source("src_placegpt01", ("gpt-5.5",), kind="subscription", vendor="openai")+ claude = _source("src_placeclaude", ("claude-opus-4-6",), kind="subscription")+ gemini = _source("src_placegemini", ("gemini-3-pro",), kind="subscription", vendor="gemini")+ bundle = _source("src_placebundle", ("claude-opus-4-6", "gpt-5.5"), kind="subscription", vendor="opencode")+ for source in (chatgpt, claude, gemini, bundle):+ config.sources.append(source)+ service._apply_source_placement(config, source)+ order = {backend: config.agents[backend].sources.order for backend in ("claude", "codex", "opencode")}+ # Subscriptions go ahead of keys, only where their fixed catalog serves the+ # menu; OpenCode reaches every vendor. Keys stay everywhere.+ assert order["claude"] == [claude.id, bundle.id, key.id]+ assert order["codex"] == [chatgpt.id, bundle.id, key.id]+ assert order["opencode"] == [chatgpt.id, claude.id, gemini.id, bundle.id, key.id]+++def test_new_subscription_without_a_catalog_joins_its_vendor_agent(tmp_path):+ config = _config([])+ service, _, _ = _service(tmp_path, config)+ chatgpt = _source("src_placeempty", (), kind="subscription", vendor="openai")+ config.sources.append(chatgpt)+ service._apply_source_placement(config, chatgpt)+ assert [backend for backend in ("claude", "codex", "opencode") if chatgpt.id in config.agents[backend].sources.order] == ["codex", "opencode"]+++def test_new_subscription_ahead_of_its_agents_menu_still_joins_its_vendor_agent(tmp_path):+ config = _config([])+ service, _, _ = _service(tmp_path, config)+ chatgpt = _source("src_placeahead", ("gpt-9-preview",), kind="subscription", vendor="openai")+ config.sources.append(chatgpt)+ service._apply_source_placement(config, chatgpt)+ assert config.agents["codex"].models+ assert [backend for backend in ("claude", "codex", "opencode") if chatgpt.id in config.agents[backend].sources.order] == ["codex", "opencode"]diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex c8dbaab7d..abef0285e 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -28,6 +28,7 @@ from core.process_isolation import PROCESS_IDENTITY_ENV, fingerprint_process_marfrom core.handlers.model_hub.adapter import (DiscoveredModel,EngineHealth,+ OAuthSubmissionRejectedError,OriginNotAllowedError,RawOutcomeKind,RetainedMaterialDisposition,@@ -8085,8 +8086,12 @@ def test_oauth_flow_handles_new_refreshed_and_conflicting_auth_records()if oauth_record_case == "conflict":+ # Signing in again to an account another Source already holds is a+ # duplicate add, reported as such, and that Source's file is kept.assert completed.state == "failed"- assert completed.error_key == "models.oauth.binding_failed"+ assert completed.error_key == "models.oauth.account_already_added"+ assert (store.auth_dir / "claude-account.json").exists()+ assert not client.deletesassert completed.channel == "hub"assert completed.retained_material_disposition is RetainedMaterialDisposition.FOREIGN_SOURCE_REFassert completed.retained_credential_ref is None@@ -8291,6 +8296,97 @@ def test_oauth_terminal_uncertainty_never_claims_cleanup(tmp_path: Path) -> Noneasyncio.run(run())+def test_oauth_rejected_paste_keeps_flow_awaiting_a_corrected_value(tmp_path: Path) -> None:+ submitted: list[dict] = []++ class Client:+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/auth-files":+ return {"files": []}+ if path == "/codex-auth-url":+ return {"state": "browser-state", "url": "https://example.test/oauth"}+ if path == "/oauth-callback":+ submitted.append(dict(payload))+ if "code=" not in payload.get("redirect_url", ""):+ raise EngineClientError(+ "code or error is required",+ status_code=400,+ error_candidates=("code or error is required",),+ )+ return {"status": "ok"}+ raise AssertionError((method, path, query, payload, timeout))++ class Supervisor:+ def __init__(self, store: EngineStateStore, client: Client) -> None:+ self.state_store = store+ self._client = client++ def client(self):+ return self._client++ async def run() -> None:+ store = EngineStateStore(tmp_path / "state")+ adapter = CLIProxyEngineAdapter(+ supervisor=Supervisor(store, Client()), # type: ignore[arg-type]+ state_store=store,+ )+ flow = await adapter.start_oauth("src_fixture123", "openai")+ with pytest.raises(OAuthSubmissionRejectedError):+ await adapter.submit_oauth(flow.flow_id, "https://chatgpt.com/")+ held = adapter._oauth_flows[flow.flow_id]+ assert held.state == "awaiting_action"+ assert held.error_key is None+ assert held.grant_write_possible is False++ corrected = await adapter.submit_oauth(+ flow.flow_id,+ "http://localhost:1455/auth/callback?code=abc&state=browser-state",+ )+ assert corrected.state == "verifying"+ # The code-less address never reached the engine.+ assert len(submitted) == 1++ asyncio.run(run())+++def test_oauth_engine_400_fails_the_flow_rather_than_claiming_it_retryable(tmp_path: Path) -> None:+ class Client:+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/auth-files":+ return {"files": []}+ if path == "/codex-auth-url":+ return {"state": "browser-state", "url": "https://example.test/oauth"}+ if path == "/oauth-callback":+ raise EngineClientError("invalid state", status_code=400)+ raise AssertionError((method, path, query, payload, timeout))++ class Supervisor:+ def __init__(self, store: EngineStateStore, client: Client) -> None:+ self.state_store = store+ self._client = client++ def client(self):+ return self._client++ async def run() -> None:+ store = EngineStateStore(tmp_path / "state")+ adapter = CLIProxyEngineAdapter(+ supervisor=Supervisor(store, Client()), # type: ignore[arg-type]+ state_store=store,+ )+ flow = await adapter.start_oauth("src_fixture123", "openai")+ # A code the engine still refuses says nothing about what it wrote, so+ # the flow fails closed instead of inviting another paste.+ failed = await adapter.submit_oauth(+ flow.flow_id,+ "http://localhost:1455/auth/callback?code=abc&state=browser-state",+ )+ assert failed.state == "failed"+ assert adapter._oauth_flows[flow.flow_id].grant_write_possible is True++ asyncio.run(run())++def test_supervisor_fails_closed_with_direct_mode_escape(tmp_path: Path) -> None:class FailedInstaller:def resolve_engine_path(self):@@ -8321,3 +8417,113 @@ def test_supervisor_fails_closed_with_direct_mode_escape(tmp_path: Path) -> Noneassert exc_info.value.error_key == "models.engine.install_failed"assert exc_info.value.reason == "model_hub_engine_archive_checksum_mismatch"assert exc_info.value.direct_mode_available is True++[email protected]("second_account", ["other", "same", "mixed"])+def test_oauth_flow_adds_a_second_account_and_refuses_the_same_one(+ tmp_path: Path,+ second_account: str,+) -> None:+ """A second subscription of one vendor is its own Source; a repeat is refused.++ The first account's file keeps changing in the background (token refresh,+ status), so it must not be mistaken for the login a later flow produced.+ """+ first = {+ "id": "codex-a.json",+ "name": "codex-a.json",+ "provider": "codex",+ "modtime": "2026-09-23T01:00:00Z",+ "id_token": {"chatgpt_account_id": "acct-a"},+ }++ class Client:+ def __init__(self) -> None:+ self.auth_calls = 0+ self.patches: list[dict[str, object]] = []+ self.deletes: list[str] = []++ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/auth-files":+ if method == "DELETE":+ self.deletes.append(str((query or {}).get("name")))+ return {"status": "ok"}+ self.auth_calls += 1+ unbound = {**first, "id": "codex-c.json", "name": "codex-c.json",+ "id_token": {"chatgpt_account_id": "acct-c"}}+ if self.auth_calls == 1:+ return {"files": [first, unbound] if second_account == "mixed" else [first]}+ refreshed = {**first, "modtime": "2026-09-23T01:40:00Z"}+ if second_account == "mixed":+ # Nothing new: the login rewrote one of two existing+ # records, and either could be it.+ return {"files": [refreshed, {**unbound, "modtime": "2026-09-23T01:41:00Z"}]}+ new = {+ "id": "codex-b.json",+ "name": "codex-b.json",+ "provider": "codex",+ "modtime": "2026-09-23T01:41:00Z",+ "id_token": {"chatgpt_account_id": "acct-b" if second_account == "other" else "acct-a"},+ }+ return {"files": [refreshed, new]}+ if path == "/codex-auth-url":+ return {"state": "engine-state", "url": "https://example.test/oauth"}+ if path == "/get-auth-status":+ return {"status": "ok"}+ if path == "/auth-files/fields":+ self.patches.append(dict(payload or {}))+ return {"status": "ok"}+ raise AssertionError((method, path, query, payload, timeout))++ class Supervisor:+ def __init__(self, store: EngineStateStore, client: Client) -> None:+ self.state_store = store+ self._client = client++ def client(self):+ return self._client++ def client_if_running(self):+ return None++ def with_engine_excluded(self, operation):+ return operation(self._client)++ def invalidate_configs(self) -> None:+ self.state_store.clear_runtime_configs()++ async def run() -> None:+ store = EngineStateStore(tmp_path / "state")+ store.prepare_instance("install-1")+ for name in ("codex-a.json", "codex-b.json", "codex-c.json"):+ (store.auth_dir / name).write_text("{}", encoding="utf-8")+ (store.auth_dir / name).chmod(0o600)+ first_ref = store.bind_oauth_credential("src_first12345", "openai", "codex-a.json")+ client = Client()+ adapter = CLIProxyEngineAdapter(+ supervisor=Supervisor(store, client), # type: ignore[arg-type]+ state_store=store,+ )+ flow = await adapter.start_oauth("src_second1234", "openai")+ completed = await adapter.oauth_status(flow.flow_id)++ assert store.credential_metadata(first_ref)["source_id"] == "src_first12345"+ assert (store.auth_dir / "codex-a.json").exists()+ if second_account == "mixed":+ assert completed.state == "failed"+ assert completed.error_key == "models.oauth.ambiguous_engine_binding"+ assert not client.patches and not client.deletes+ elif second_account == "other":+ assert completed.state == "success"+ assert completed.credential_ref and completed.credential_ref != first_ref+ assert store.credential_metadata(completed.credential_ref)["auth_name"] == "codex-b.json"+ assert [patch["name"] for patch in client.patches] == ["codex-b.json"]+ else:+ assert completed.state == "failed"+ assert completed.error_key == "models.oauth.account_already_added"+ assert completed.retained_material_disposition is RetainedMaterialDisposition.NONE+ assert client.deletes == ["codex-b.json"]+ assert not (store.auth_dir / "codex-b.json").exists()+ assert not client.patches++ asyncio.run(run())diff --git a/tests/test_model_hub_takeover_inventory.py b/tests/test_model_hub_takeover_inventory.pyindex f5f0eb12f..df06546f0 100644--- a/tests/test_model_hub_takeover_inventory.py+++ b/tests/test_model_hub_takeover_inventory.py@@ -179,9 +179,15 @@ def test_empty_codex_container_never_authorizes_deleting_dormant_file_grant(store.config.agents["codex"].mode = "direct"ids = [row["id"] for row in service.migration_scan()["items"]]if with_api_key:- with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply(ids))- assert store.config.agents["codex"].mode == "direct"+ # The key migrates; the dormant file grant is never deleted.+ asyncio.run(service.migration_apply(ids))+ assert json.loads(dormant.read_bytes()) == {"tokens": payload["tokens"]}+ assert store.config.agents["codex"].mode == "hub"+ assert len(adapter.provisioned) == len(store.config.sources) == 1+ assert not adapter.oauth_provisioned+ assert not keychain.delete_calls and not keychain.write_calls+ assert service.migration_journal.load() is None+ returnelse:assert asyncio.run(service.migration_apply(ids))["applied"] == 1assert store.config.agents["codex"].mode == "hub"@@ -270,10 +276,12 @@ def test_unsupported_provider_blocks_only_its_cli_before_any_cleanup(monkeypatchservice, _, adapter = _service(tmp_path, migration_home=home)rows = service.migration_scan()["items"]assert {row["proposed_action"] for row in rows} == {"import", "reauth"}- with pytest.raises(ModelHubError):- asyncio.run(service.migration_apply([row["id"] for row in rows if row["proposed_action"] == "import"]))- assert path.read_bytes() == before- assert adapter.provisioned == []+ asyncio.run(service.migration_apply([row["id"] for row in rows if row["proposed_action"] == "import"]))+ # The OAuth provider the Hub cannot carry stays exactly as it was.+ assert json.loads(path.read_bytes()) == {+ "github-copilot": json.loads(before)["github-copilot"],+ }+ assert len(adapter.provisioned) == 1def test_project_key_changed_after_consent_refuses_without_import(monkeypatch, tmp_path):diff --git a/ui/e2e/model-catalog/gateway-status.spec.ts b/ui/e2e/model-catalog/gateway-status.spec.tsindex 7cfc45bb9..2ced0141b 100644--- a/ui/e2e/model-catalog/gateway-status.spec.ts+++ b/ui/e2e/model-catalog/gateway-status.spec.ts@@ -19,7 +19,7 @@ for (const lang of ['en', 'zh'] as const) {await expect(toggle).toHaveAttribute('aria-expanded', 'true');await expect(issues.locator('ul')).toBeVisible();await expect(issues).toContainText(long ? 'long-model-id-' : 'grok/grok-4.6');- await expect(issues).toContainText(lang === 'zh' ? '此模型未配置路由' : 'No route configured for this model');+ await expect(issues).toContainText(lang === 'zh' ? '模型名不存在' : 'is not a known model name');expect(await head.boundingBox()).toEqual(headBefore);const overflow = await card.evaluate((element) => {const box = element.getBoundingClientRect();diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxindex 6b859f629..27914807d 100644--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx@@ -167,7 +167,11 @@ const OPENCODE_LEGACY: MigrationItem = {};/** The one sentence the migration feature has for a row it cannot take. */-const BLOCKED_SENTENCE = 'This credential cannot be imported.';+// Setup takes API keys only, so an importable sign-in beside a key sends that+// backend to Settings; a row the Hub cannot carry is never shown at all.+const CLAUDE_IMPORTABLE_SUBSCRIPTION: MigrationItem = { ...CLAUDE_SUBSCRIPTION, proposed_action: 'import' };++const BLOCKED_SENTENCE = 'This credential can be migrated, but not from here.';// ── The fake server ───────────────────────────────────────────────────────@@ -679,7 +683,7 @@ describe('ProvidersScreen — the stage', () => {// capsule counting a key its own review would refuse is the quiet one.describe('ProvidersScreen — what it found but may not take', () => {it('keeps a blocked credential on the stage, with its reason and no way to consent', async () => {- serve({ scan: [CLAUDE_KEY, CLAUDE_SUBSCRIPTION] });+ serve({ scan: [CLAUDE_KEY, CLAUDE_IMPORTABLE_SUBSCRIPTION] });renderScreen();await settled();const user = userEvent.setup();@@ -703,7 +707,7 @@ describe('ProvidersScreen — what it found but may not take', () => {});it('counts the takeable group beside it, and only that one', async () => {- serve({ scan: [CLAUDE_KEY, CLAUDE_SUBSCRIPTION, CODEX_KEY] });+ serve({ scan: [CLAUDE_KEY, CLAUDE_IMPORTABLE_SUBSCRIPTION, CODEX_KEY] });renderScreen();await settled();const user = userEvent.setup();@@ -731,7 +735,7 @@ describe('ProvidersScreen — what it found but may not take', () => {});it('MH-MIG-004: submits the batch it counted, and keeps the blocked card after the rescan', async () => {- serve({ scan: [CLAUDE_KEY, CLAUDE_SUBSCRIPTION, CODEX_KEY] });+ serve({ scan: [CLAUDE_KEY, CLAUDE_IMPORTABLE_SUBSCRIPTION, CODEX_KEY] });const { handle } = renderScreen();await settled();const user = userEvent.setup();diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.tsindex a8edf88d2..0b67c8e67 100644--- a/ui/src/components/onboarding/providers/providerStage.test.ts+++ b/ui/src/components/onboarding/providers/providerStage.test.ts@@ -104,11 +104,9 @@ describe('providerSlots', () => {expect(slots.map((slot) => slot.vendor)).toEqual(['openai', 'anthropic']);});- it('keeps a detected candidate on the stage when its consent group is blocked, and says why', () => {- // A backend whose linked rows include something this entry cannot import is- // reviewed in Settings. What it is not is invisible: the key is on the machine,- // and replacing it with an empty 「add Anthropic」 invitation is how a person- // adds a second copy of the key they already have.+ it('does not let a row the Hub cannot carry hold back the key beside it', () => {+ // A row the server does not propose importing stays native and is shadowed by+ // the Hub launch. It is not shown, and it never blocks its group.const slots = providerSlots({sources: [],scan: scanOf(@@ -118,11 +116,8 @@ describe('providerSlots', () => {});expect(slots.map((slot) => [slot.vendor, slot.kind])).toEqual([['anthropic', 'detected'], ['openai', 'empty']]);- // Found, with a reason, and no permission: nothing in the card's `backends` is a- // backend anything here may take over. The reason is the migration feature's own- // note for that row — a server note nobody recognises still reads as a sentence.- expect(slots[0].reasons).toEqual(['settings.models.migration.blocked.fallback']);- expect(slots[0].backends).toEqual([]);+ expect(slots[0].reasons).toEqual([]);+ expect(slots[0].backends).toEqual(['claude']);});it('keeps the card and names setup’s own scope when the group holds an importable subscription', () => {@@ -151,7 +146,7 @@ describe('providerSlots', () => {row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),row({ id: 'mig_b', backend: 'claude', vendor: 'anthropic', kind: 'oauth_native' }),row({ id: 'mig_c', backend: 'opencode', kind: 'opencode_provider', vendor: 'zhipuai' }),- row({ id: 'mig_d', backend: 'opencode', kind: 'oauth_native', proposed_action: 'keep_native', vendor: undefined }),+ row({ id: 'mig_d', backend: 'opencode', kind: 'oauth_native', vendor: undefined }),);const slots = providerSlots({ sources: [], scan });@@ -180,7 +175,7 @@ describe('providerSlots', () => {scan: scanOf(row({ id: 'mig_a', backend: 'codex', vendor: 'openai' }),row({ id: 'mig_b', backend: 'opencode', kind: 'opencode_provider', vendor: 'openai' }),- row({ id: 'mig_c', backend: 'opencode', kind: 'oauth_native', proposed_action: 'keep_native' }),+ row({ id: 'mig_c', backend: 'opencode', kind: 'oauth_native' }),),});@@ -380,33 +375,19 @@ describe('pendingImportRows', () => {expect(rows.map((item) => item.id)).toEqual(['mig_1', 'mig_2']);});- it('submits nothing for a group holding any row it cannot import', () => {- // Consent is per group, never per row: one row the server does not propose- // importing blocks the whole custody boundary, so the batch is empty rather- // than partial. Settings is where a mixed group gets resolved.+ it('submits the carried rows and leaves the rest native', () => {+ // A row the server does not propose importing stays where it is; it neither+ // joins the batch nor keeps the rows beside it from moving.const rows = pendingImportRows({scan: scanOf(row({ id: 'mig_1', backend: 'codex' }),row({ id: 'mig_2', backend: 'codex', proposed_action: 'keep_native' }),+ row({ id: 'mig_3', backend: 'codex', kind: 'oauth_native', proposed_action: 'reauth' }),),selectedBackends: ['codex'],});- expect(rows).toEqual([]);- });-- it('refuses a backend this entry point cannot consent to, however it got selected', () => {- // A blocked group is Settings' to resolve. Naming it in the selection must not- // make the CTA promise a batch the dialog would decline to build.- const rows = pendingImportRows({- scan: scanOf(- row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),- row({ id: 'mig_b', backend: 'claude', kind: 'oauth_native', proposed_action: 'reauth' }),- ),- selectedBackends: ['claude'],- });-- expect(rows).toEqual([]);+ expect(rows.map((item) => item.id)).toEqual(['mig_1']);});it('never submits a subscription store alongside the key it is linked to', () => {@@ -440,7 +421,7 @@ describe('offeredImportKeys', () => {selectedBackends: [],});- expect(offered.map((item) => item.id)).toEqual(['mig_1']);+ expect(offered.map((item) => item.id)).toEqual(['mig_a', 'mig_1']);});it('does not count a key it could only take by taking a subscription too', () => {@@ -482,11 +463,11 @@ describe('defaultSelection', () => {))).toEqual(['codex']);});- it('never opens on a blocked group', () => {+ it('opens on a key whose neighbour the Hub cannot carry', () => {expect(defaultSelection(scanOf(row({ id: 'mig_a', backend: 'claude', vendor: 'anthropic' }),row({ id: 'mig_b', backend: 'claude', kind: 'oauth_native', proposed_action: 'reauth' }),- ))).toEqual([]);+ ))).toEqual(['claude']);});it('never opens on a group setup itself cannot take whole', () => {diff --git a/ui/src/components/settings/BackendOAuthPanel.tsx b/ui/src/components/settings/BackendOAuthPanel.tsxindex 2a01ef25a..a6bf2b8f2 100644--- a/ui/src/components/settings/BackendOAuthPanel.tsx+++ b/ui/src/components/settings/BackendOAuthPanel.tsx@@ -90,7 +90,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({const { showToast } = useToast();const { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError,- startFlow, cancelFlow, submitCallback, resetToIdle, copyUrl, copyDeviceCode, isActive, hubOwnedAuth } =+ startFlow, cancelFlow, submitCallback, resetToIdle, isActive, hubOwnedAuth } =useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailure, onCancel, onActiveChange });const [removing, setRemoving] = useState(false);const [removeHubOwnedAuth, setRemoveHubOwnedAuth] = useState(false);@@ -251,11 +251,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({<Label className="text-[11px] font-medium uppercase tracking-wide text-muted">{t('settings.backends.oauthAuthUrlLabel')}</Label>- <OAuthLinkRow- url={url}- onCopy={(e) => void copyUrl(e)}- copyLabel={t('common.copy') as string}- />+ <OAuthLinkRow url={url} /></div>)}@@ -264,11 +260,7 @@ export const BackendOAuthPanel: React.FC<BackendOAuthPanelProps> = ({<Label className="text-[11px] font-medium uppercase tracking-wide text-muted">{t('settings.backends.codexDeviceCodeLabel')}</Label>- <OAuthDeviceCodeRow- code={deviceCode ?? ''}- onCopy={(e) => void copyDeviceCode(e)}- copyLabel={t('common.copy') as string}- />+ <OAuthDeviceCodeRow code={deviceCode ?? ''} /><p className="text-[12px] leading-relaxed text-muted">{t('settings.backends.codexDeviceInstructions')}</p>diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex ece391732..14aa9fa62 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -345,11 +345,30 @@ describe('AgentCard', () => {expect(details.hidden).toBe(false);expect(within(details).getByText('opencode')).toBeTruthy();expect(within(details).getByText('grok/grok-4.6')).toBeTruthy();- expect(within(details).getByText(instance.t('settings.models.gateway.agentIssues.routeMissing'))).toBeTruthy();+ expect(within(details).getByText(instance.t('settings.models.gateway.agentIssues.routeMissing', { model: 'grok/grok-4.6' }))).toBeTruthy();await userEvent.click(toggle);expect(details.hidden).toBe(true);});+ it('names the unresolved model in the reason and opens the Agent that has to change', async () => {+ const instance = localeInstance('zh');+ const onOpenAgent = vi.fn();+ const agent = {+ ...openCodeAgent,+ menu: { view: 'featured' as const, checked: ['listed-model'] },+ model_supply: [{ model_id: 'listed-model', route_origin: 'automatic' as const, chain_length: 1, has_runnable_hop: true }],+ named_agents: [{ name: 'opencode', effective_model_id: 'grok/grok-4.6', supply_status: 'interrupted' as const, route_reason: 'route_unconfigured' as const }],+ };+ render(<I18nextProvider i18n={instance}><AgentCard agents={[agent]} sources={[]} chains={{}} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} onOpenAgent={onOpenAgent} /></I18nextProvider>);+ await userEvent.click(screen.getByRole('button', { name: instance.t('settings.models.gateway.agentIssues.summary', { count: 1 }) }));++ const reason = screen.getByText(/grok\/grok-4\.6 模型名不存在/);+ expect(reason.textContent).toContain('添加 grok/grok-4.6 模型的路由');+ await userEvent.click(reason);++ expect(onOpenAgent).toHaveBeenCalledWith('opencode');+ });+it.each([['en', 'Backup → claude-opus-4-6 (Taken over)', 'Open claude-opus-4-6 route chain · Backup → claude-opus-4-6 (Taken over)'],['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 41f73633e..471aa8fd4 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -116,7 +116,12 @@ const ModelRow: React.FC<{);};-const AgentSupplyIssues: React.FC<{ agent: AgentSupply }> = ({ agent }) => {+const AgentSupplyIssues: React.FC<{+ agent: AgentSupply;+ // Optional so a caller with no route to the Agents page renders the same list,+ // just not as links.+ onOpenAgent?: (name: string) => void;+}> = ({ agent, onOpenAgent }) => {const { t } = useTranslation();const [open, setOpen] = React.useState(false);const detailsId = React.useId();@@ -144,11 +149,29 @@ const AgentSupplyIssues: React.FC<{ agent: AgentSupply }> = ({ agent }) => {: named.route_reason === 'route_unconfigured' ? 'routeMissing': named.supply_status;if (reason === null || reason === 'ok') return null;- return (- <li key={named.name} className="min-w-0 text-[11px] leading-4" data-agent-supply-issue>+ // The reason reads the model back to the user, so a name that resolves+ // to nothing is named rather than described as "this model".+ const detail = (+ <><p className="min-w-0 font-semibold text-foreground [overflow-wrap:anywhere]">{named.name}</p>{named.effective_model_id !== null && <p className="min-w-0 font-mono text-muted [overflow-wrap:anywhere]">{named.effective_model_id}</p>}- <p className="model-hub-ink-gold mt-1 [overflow-wrap:anywhere]">{t(`settings.models.gateway.agentIssues.${reason}`)}</p>+ <p className="model-hub-ink-gold mt-1 [overflow-wrap:anywhere]">+ {t(`settings.models.gateway.agentIssues.${reason}`, { model: named.effective_model_id ?? '' })}+ </p>+ </>+ );+ return (+ <li key={named.name} className="min-w-0 text-[11px] leading-4" data-agent-supply-issue>+ {onOpenAgent ? (+ <button+ type="button"+ className="-mx-1.5 flex w-full min-w-0 items-start gap-2 rounded-md px-1.5 py-1 text-left transition-colors hover:bg-muted/10"+ onClick={() => onOpenAgent(named.name)}+ >+ <span className="min-w-0 flex-1">{detail}</span>+ <ChevronRight className="model-hub-overview-chevron mt-0.5 size-[15px] shrink-0" aria-hidden="true" />+ </button>+ ) : detail}</li>);})}@@ -173,7 +196,8 @@ const AgentModelCard: React.FC<{onOpenOrder: (agent: AgentSupply) => void;onOpenRoute: (agent: AgentSupply, modelId: string, opener: HTMLElement) => void;onProbeSettled: (agent: AgentSupply) => void;-}> = ({ agent, runtime, sources, chains, pending, connecting, switchFailed, activeOriginHelp, onOriginHelpChange, onConnectHub, onSwitchDirect, onOpenModels, onOpenOrder, onOpenRoute, onProbeSettled }) => {+ onOpenAgent?: (name: string) => void;+}> = ({ agent, runtime, sources, chains, pending, connecting, switchFailed, activeOriginHelp, onOriginHelpChange, onConnectHub, onSwitchDirect, onOpenModels, onOpenOrder, onOpenRoute, onProbeSettled, onOpenAgent }) => {const { t } = useTranslation();const { Icon, accent } = backendVisual(agent.backend);const [expanded, setExpanded] = React.useState(false);@@ -303,7 +327,7 @@ const AgentModelCard: React.FC<{</div></div>{agent.mode === 'hub' && (models.length === 0 ? <div className="flex flex-col items-center gap-3 px-4 py-10 text-center sm:px-5"><p className="text-[12.5px] text-muted">{t('settings.models.gateway.group.emptyModels')}</p><ManageModelsButton disabled={pending} onClick={() => onOpenModels(agent)} /></div> : <div className="space-y-2 p-2">{noUsableSource && <p className="px-3 py-1 text-[11px] font-semibold text-muted">{t('settings.models.gateway.supply.none')}</p>}{models.map((modelId) => <ModelRow key={modelId} agent={agent} modelId={modelId} sources={sources} read={chainProjectionLive ? chains[modelChainKey(agent.backend, modelId)] : undefined} originHelpOpen={activeOriginHelp === modelChainKey(agent.backend, modelId)} onOriginHelpChange={onOriginHelpChange} onOpenRoute={onOpenRoute} />)}{(canCollapse || needsChainRepair) && <div className="flex h-6 w-full items-center">{canCollapse && <button type="button" onClick={toggleCollapsed} className="model-hub-model-collapse flex h-6 flex-1 items-center gap-1.5 hover:text-foreground">{expanded ? <ChevronUp /> : <ChevronDown />}{expanded ? t('settings.models.gateway.collapse') : t('settings.models.gateway.moreModels', { count: collapsed.hidden.length })}</button>}{needsChainRepair && <button type="button" onClick={retryChains} className="model-hub-model-collapse model-hub-model-collapse--repair flex h-6 items-center gap-1.5 hover:text-foreground"><RefreshCw />{t('settings.models.gateway.retry')}</button>}</div>}</div>)}- {agent.mode === 'hub' && <AgentSupplyIssues agent={agent} />}+ {agent.mode === 'hub' && <AgentSupplyIssues agent={agent} onOpenAgent={onOpenAgent} />}</section>);};@@ -321,6 +345,7 @@ export const AgentCard: React.FC<{onOpenOrder: (agent: AgentSupply) => void;onOpenRoute: (agent: AgentSupply, modelId: string, opener: HTMLElement) => void;onProbeSettled: (agent: AgentSupply) => void;+ onOpenAgent?: (name: string) => void;connectingBackend: string | null;}> = ({ agents, pendingBackends, switchFailures, connectingBackend, ...props }) => {const [activeOriginHelp, setActiveOriginHelp] = React.useState<string | null>(null);diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsxindex 97c812053..38a7f1b5f 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx@@ -8,7 +8,7 @@ import i18n from '@/i18n';import { BackendModelCatalogDialog } from './BackendModelCatalogDialog';import { blankBackendModel, candidateBackendModel } from './backendCatalog';import { ApiCallError, modelsApi } from './modelsApi';-import type { AgentSupply, BackendModel, ModelCandidate, RouteHop } from './types';+import type { AgentSupply, BackendModel, ModelCandidate, ModelsDevMatch, RouteHop } from './types';const model = (id: string, overrides: Partial<BackendModel> = {}): BackendModel => ({...blankBackendModel(),@@ -137,6 +137,119 @@ describe('BackendModelCatalogDialog', () => {expect(screen.getByText('2 models')).toBeTruthy();});+ it('opens the named row\'s editor alone and saves its answer, never on a locked row', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([locked, model('alpha')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent([locked, model('alpha', { display_name: 'Alpha' })]));+ const { onClose, onSaved } = renderDialog({ focus: { modelId: 'alpha', action: 'edit' } });+ expect(await screen.findByRole('button', { name: 'Save model' })).toBeTruthy();+ // The editor is the whole dialog: the list is not shown behind it.+ expect(screen.queryByRole('heading', { name: 'Claude Code models' })).toBeNull();+ await user.type(screen.getByLabelText('Display name'), 'Alpha');+ await user.click(screen.getByRole('button', { name: 'Save model' }));+ await waitFor(() => expect(onClose).toHaveBeenCalledWith(undefined));+ expect(write).toHaveBeenCalledTimes(1);+ expect(onSaved).toHaveBeenCalled();+ cleanup();++ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([locked, model('alpha')]));+ renderDialog({ focus: { modelId: 'claude-default', action: 'edit' } });+ await screen.findByText('claude-default');+ expect(screen.queryByRole('button', { name: 'Save model' })).toBeNull();+ });++ it('closes a focused editor without writing or showing the list', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels');+ const { onClose } = renderDialog({ focus: { modelId: 'alpha', action: 'edit' } });+ await user.click(await screen.findByRole('button', { name: 'Cancel' }));+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(onClose.mock.calls[0][0]?.removed).toBeFalsy();+ expect(write).not.toHaveBeenCalled();+ });++ it.each([+ ['routed', { beta: { hops: [{ source_id: 'src_a', model_id: 'beta-air' }] } }],+ ['unrouted', {}],+ ])('removes a %s focused row straight from one confirmation', async (_, routes) => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')], { routes }));+ const write = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent([model('alpha')]));+ const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove' } });+ const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });+ if (Object.keys(routes).length > 0) expect(within(confirm).getByRole('alert').textContent).toContain('beta-air');+ expect(screen.queryByText('2 models')).toBeNull();+ expect(write).not.toHaveBeenCalled();+ await user.click(within(confirm).getByRole('button', { name: 'Remove' }));+ await waitFor(() => expect(onClose).toHaveBeenCalledWith({ removed: true }));+ expect(write).toHaveBeenCalledTimes(1);+ expect(write.mock.calls[0][1].models.map((entry: BackendModel) => entry.id)).toEqual(['alpha']);+ });++ it('does not ask a focused removal twice about the route its one confirmation covered', async () => {+ const user = userEvent.setup();+ const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_a', model_id: 'beta-air', position: 1 }];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,+ ))+ .mockResolvedValue(agent([model('alpha')]));+ const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove', route: [{ source_id: 'src_a', model_id: 'beta-air' }] } });+ const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });+ await user.click(within(confirm).getByRole('button', { name: 'Remove' }));+ await waitFor(() => expect(onClose).toHaveBeenCalledWith({ removed: true }));+ expect(write).toHaveBeenCalledTimes(2);+ expect(write.mock.calls[1][1]).toMatchObject({ force: true, would_remove_hops: hops, would_interrupt: [] });+ });++ it('asks a focused removal again when the refused route is not the one it showed', async () => {+ const user = userEvent.setup();+ const hops = [{ backend: 'claude' as const, menu_model: 'beta', source_id: 'src_b', model_id: 'beta-max', position: 1 }];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels')+ .mockRejectedValueOnce(new ApiCallError(+ 'backend_model_in_route', 'modelHub.errors.backend_model_in_route', true, [], [], hops, 409,+ ))+ .mockResolvedValue(agent([model('alpha')]));+ renderDialog({ focus: { modelId: 'beta', action: 'remove', route: [{ source_id: 'src_a', model_id: 'beta-air' }] } });+ const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });+ await user.click(within(confirm).getByRole('button', { name: 'Remove' }));+ await waitFor(() => expect(write).toHaveBeenCalledTimes(1));+ const again = await screen.findByRole('dialog', { name: 'Remove beta?' });+ await waitFor(() => expect(within(again).getByRole('button', { name: 'Remove' })).toHaveProperty('disabled', false));+ expect(write).toHaveBeenCalledTimes(1);+ await user.click(within(again).getByRole('button', { name: 'Remove' }));+ await waitFor(() => expect(write).toHaveBeenCalledTimes(2));+ expect(write.mock.calls[1][1]).toMatchObject({ force: true, would_remove_hops: hops });+ });++ it('keeps a focused editor on screen and inert while its save is pending', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha')]));+ let settle: (value: ReturnType<typeof agent>) => void = () => {};+ vi.spyOn(modelsApi, 'putAgentModels').mockReturnValue(new Promise((resolve) => { settle = resolve; }));+ const { onClose } = renderDialog({ focus: { modelId: 'alpha', action: 'edit' } });+ await user.click(await screen.findByRole('button', { name: 'Save model' }));+ expect(screen.getByRole('button', { name: 'Save model' })).toHaveProperty('disabled', true);+ expect(onClose).not.toHaveBeenCalled();+ await act(async () => { settle(agent([model('alpha')])); });+ await waitFor(() => expect(onClose).toHaveBeenCalledWith(undefined));+ });++ it('cancels a focused removal without writing', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([model('alpha'), model('beta')]));+ const write = vi.spyOn(modelsApi, 'putAgentModels');+ const { onClose } = renderDialog({ focus: { modelId: 'beta', action: 'remove' } });+ const confirm = await screen.findByRole('dialog', { name: 'Remove beta?' });+ await user.click(within(confirm).getByRole('button', { name: 'Cancel' }));+ expect(onClose).toHaveBeenCalledTimes(1);+ expect(onClose.mock.calls[0][0]?.removed).toBeFalsy();+ expect(write).not.toHaveBeenCalled();+ });+it('renders Claude models without inventing a native default choice', async () => {await i18n.changeLanguage('zh');vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent([@@ -300,6 +413,61 @@ describe('BackendModelCatalogDialog', () => {}));});+ it('keeps the recorded origin of a row re-added under an ID the editor only lands on at the end', async () => {+ const user = userEvent.setup();+ // The row the server already stores, and the creation path it recorded.+ const GROK = model('grok-4.6', {+ origin: 'provider',+ display_name: 'Grok 4.6',+ native_protocol: 'openai_responses',+ });+ const catalog = [model('glm-4.7', { native_protocol: 'openai_responses' }), GROK];+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, { backend: 'opencode' }));+ vi.spyOn(modelsApi, 'getAgentModelCandidates').mockResolvedValue(offered());+ // models.dev publishes this model under exactly the id the list already+ // holds, which is the whole point: the typed query does not name the saved+ // row, and the chosen suggestion does.+ vi.spyOn(modelsApi, 'searchModelsDev').mockResolvedValue([{+ provider_id: 'xai',+ provider_name: 'xAI',+ model_id: 'grok-4.6',+ models_dev_id: 'xai/grok-4.6',+ display_name: 'Grok 4.6',+ context_window: 256000,+ max_output_tokens: 64000,+ input_modalities: ['text'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: true,+ reasoning_efforts: ['low', 'high'],+ native_protocol: 'openai_responses',+ } satisfies ModelsDevMatch]);+ const write = vi.spyOn(modelsApi, 'putAgentModels').mockResolvedValue(agent(catalog));+ renderDialog({ backend: 'opencode' });++ await user.click(await screen.findByRole('button', { name: 'Remove Grok 4.6' }));+ await user.click(screen.getByRole('button', { name: 'Add models' }));+ await waitFor(() => expect((screen.getByLabelText('Search models or providers') as HTMLInputElement).disabled).toBe(false));+ // A query that is not the saved id, so nothing resolves it to the saved row+ // on the way in — the editor opens in add mode and stamps `models_dev`.+ await user.type(await screen.findByLabelText('Search models or providers'), 'grok 4.6');+ await user.click(await screen.findByRole('button', { name: 'Add "grok 4.6" as a custom model…' }));+ await user.click(await screen.findByRole('option', { name: /Grok 4\.6/ }));+ await user.click(screen.getByRole('button', { name: 'Add model' }));+ await user.click(await screen.findByRole('button', { name: 'Save' }));++ // `origin` is how the row was FIRST created and the server holds it+ // immutable, so the only list this can be saved as is one that still says+ // `provider`. Sending `models_dev` is refused outright, and the user is+ // left with a row they cannot re-add by hand at all.+ await waitFor(() => expect(write).toHaveBeenCalled());+ const [, body] = write.mock.calls[0];+ expect(body.models.find((entry) => entry.id === 'grok-4.6')?.origin).toBe('provider');+ // And the fill itself still landed: inheriting the origin is not reverting+ // the row to the one that was removed.+ expect(body.models.find((entry) => entry.id === 'grok-4.6')?.context_window).toBe(256000);+ });+it('edits an existing row without renaming it', async () => {const user = userEvent.setup();const catalog = [model('alpha', { context_window: 1000 })];diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsxindex 51ee5d823..81a733173 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx@@ -16,9 +16,11 @@ import { GripVertical, Lock, LoaderCircle, Pencil, Plus, Search, Trash2 } from 'import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';+import { ConfirmDialog } from '@/components/ui/confirm-dialog';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';+import { useLatestRef } from '@/lib/useLatestRef';import type { PendingWrite } from './asyncLifetime';import {applyBackendCatalogIntent,@@ -51,12 +53,39 @@ import type {BackendModel,BackendModelsPut,ModelCandidate,+ RouteHop,RouteHopRef,SupplyGap,} from './types';type ReadState = 'loading' | 'ready' | 'error';+/**+ * A model the opener already had on screen, and what it wants done to it.+ *+ * The Route dialog names one of its own rows and hands it over rather than+ * growing an edit or removal path of its own: everything that makes those+ * writes safe — the removal guard, the refusal replay, the single save — lives+ * here, and a second implementation of it would be a second protocol.+ */+export type CatalogFocus = {+ modelId: string;+ action: 'edit' | 'remove';+ /** The route the opener showed for this row, in order — what a focused+ * removal's one confirmation stands for. */+ route?: readonly RouteHop[];+};++/** Whether a refused plan removes exactly the route the opener showed. */+const sameShownRoute = (hops: readonly RouteHopRef[], modelId: string, route: readonly RouteHop[]): boolean =>+ hops.length === route.length+ && [...hops].sort((left, right) => left.position - right.position).every((hop, index) => (+ hop.menu_model === modelId+ && hop.position === index + 1+ && hop.source_id === route[index].source_id+ && hop.model_id === route[index].model_id+ ));+/** Same shape the Source order drawer announces with: the key alone would tell a* screen-reader user something moved without telling them where to. */type AnnouncementKey = 'grabbed' | 'moved' | 'dropped' | 'grabCancelled';@@ -196,11 +225,19 @@ export const BackendModelCatalogDialog: React.FC<{* Route with it has to say whose hop goes away — so the page's own Sources* answer it, and an id they do not cover simply goes unnamed. */sourceNames: Readonly<Record<string, string>>;- onClose: () => void;+ /** `removed` says the focused model left the saved list, so an opener that+ * was showing it has nothing to return to. */+ onClose: (result?: { removed: boolean }) => void;onSaved: (echoed: AgentSupply) => void | Promise<void>;onObserved: (observed: AgentSupply) => void | Promise<void>;catalogWrite: PendingWrite;-}> = ({ open, backend, canReadSources, sourceNames, onClose, onSaved, onObserved, catalogWrite }) => {+ /** Open straight onto one row's edit or removal, for an opener that already+ * named the model. Applied once the catalog it names has been read, and+ * shown without the list: the editor or the removal confirmation is the+ * whole dialog, and answering it saves. The list appears only when that+ * answer needs it — a row it cannot open, or a save it has to explain. */+ focus?: CatalogFocus | null;+}> = ({ open, backend, canReadSources, sourceNames, onClose, onSaved, onObserved, catalogWrite, focus = null }) => {const { t } = useTranslation();const [baseline, setBaseline] = React.useState<BackendCatalogBaseline | null>(null);const baselineRef = React.useRef<BackendCatalogBaseline | null>(null);@@ -213,6 +250,12 @@ export const BackendModelCatalogDialog: React.FC<{const [picking, setPicking] = React.useState<{ seed: ReadonlySet<string> } | null>(null);const [removing, setRemoving] = React.useState<RemovalQuestion | null>(null);const [grabbedId, setGrabbedId] = React.useState<string | null>(null);+ /** A focused opening that fell back to the full list. */+ const [expanded, setExpanded] = React.useState(false);+ /** The focused removal the user confirmed, kept on screen while it saves. */+ const [answered, setAnswered] = React.useState<RemovalQuestion | null>(null);+ /** The focused edit the user committed, kept on screen while it saves. */+ const [savingEdit, setSavingEdit] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);const [announcement, setAnnouncement] = React.useState<Announcement>(null);const readAttempt = React.useRef(0);const grips = React.useRef(new Map<string, HTMLButtonElement>());@@ -317,6 +360,8 @@ export const BackendModelCatalogDialog: React.FC<{guardedRef.current = [];setPicking(null);setRemoving(null);+ setExpanded(false);+ setAnswered(null);loadBaseline(false);return () => { readAttempt.current += 1; };}, [loadBaseline, open]);@@ -505,6 +550,42 @@ export const BackendModelCatalogDialog: React.FC<{dropModel(model.id, plan);};+ /**+ * The opener's named row, opened on once the catalog has been read.+ *+ * It runs the same two handlers the row's own buttons run, so a handoff and a+ * click are the same act — and it runs at most once per `focus`, because the+ * question it opens (an editor, a removal confirmation) is the user's from+ * that moment on and a re-read must not re-ask it.+ */+ const openFocus = useLatestRef((model: BackendModel) => {+ // With no list behind it, the confirmation is the only place the removal+ // can be answered, so it asks even when no route goes with the row.+ if (focus?.action === 'remove') setRemoving({ modelId: model.id, plan: removalPreview(model.id), account: 'draft' });+ else setEditing({ model });+ });+ const focusOpened = React.useRef<CatalogFocus | null>(null);+ React.useEffect(() => {+ if (!open || !focus) { focusOpened.current = null; return; }+ if (!editable || focusOpened.current === focus) return;+ focusOpened.current = focus;+ // A locked row offers neither action in the list, so it offers neither here.+ const model = draftRef.current.find((entry) => entry.id === focus.modelId);+ if (model && !model.locked) openFocus.current(model);+ else setExpanded(true);+ }, [editable, focus, open, openFocus]);+ const direct = focus !== null && !expanded;+ // A list this build cannot write, a read that failed and a save that failed+ // all need the list to explain themselves.+ const needsList = legacy || readState === 'error' || saveFailedKey !== null;+ React.useEffect(() => {+ if (direct && needsList) setExpanded(true);+ }, [direct, needsList]);+ /** A save closes the dialog; a focused opener learns whether its row survived. */+ const closeSaved = () => {+ onClose(focus !== null && !draftRef.current.some((entry) => entry.id === focus.modelId) ? { removed: true } : undefined);+ };+const commitEdit = (model: BackendModel) => {const existing = draft.findIndex((entry) => entry.id === model.id);// A row written by hand promises nothing about its suppliers, so an id@@ -512,9 +593,19 @@ export const BackendModelCatalogDialog: React.FC<{// existing row keeps whatever it already carried: the editor holds its id// fixed, so the projection is still about the same addition.if (existing < 0) chosenRef.current.delete(model.id);+ // `origin` is how a row was FIRST created, and the server holds it immutable+ // for an id it already stores — so it is read back off the saved list here+ // rather than taken from the editor. Add mode stamps `models_dev` on a+ // typeahead pick and only learns the final id at that moment, so a row the+ // user removed and then re-added by hand arrives claiming a creation path+ // the server will refuse. The saved answer is the one that survives; asking+ // the saved list and not the draft is what keeps a genuinely new row's own+ // creation path intact.+ const saved = (baselineRef.current?.models ?? []).find((entry) => entry.id === model.id);+ const kept = saved ? { ...model, origin: saved.origin } : model;mutate(existing >= 0- ? draft.map((entry, index) => (index === existing ? { ...model, locked: entry.locked, routeable: entry.routeable } : entry))- : [...draft, model]);+ ? draft.map((entry, index) => (index === existing ? { ...kept, locked: entry.locked, routeable: entry.routeable } : entry))+ : [...draft, kept]);setEditing(null);};@@ -639,7 +730,7 @@ export const BackendModelCatalogDialog: React.FC<{const intent = backendCatalogIntent(baselineModels, requested);setSaveFailedKey(null);const body = putBody(baselineModels, requested);- void catalogWrite.track(async () => {+ return catalogWrite.track(async () => {let echoed: AgentSupply;try {echoed = await modelsApi.putAgentModels(backend, body);@@ -750,7 +841,16 @@ export const BackendModelCatalogDialog: React.FC<{// server plan that names an interruption is by construction not// covered by what the user has already accepted, and the question is// re-asked with the server's own words.- const agreed = samePlanContents(refusal.wouldRemoveHops, shown.flatMap((plan) => plan.hops))+ //+ // A focused removal is the exception for its hops, but only for the+ // route its opener showed. Its one confirmation already said that+ // route goes with the row, and the picture cannot see an automatic+ // route at all — so re-asking over the same hops would be the same+ // question twice. A route that changed since it was shown is not what+ // the user confirmed, and is asked with the server's own words.+ const shownRoute = direct && focus?.route+ && sameShownRoute(refusal.wouldRemoveHops, focus.modelId, focus.route);+ const agreed = (shownRoute || samePlanContents(refusal.wouldRemoveHops, shown.flatMap((plan) => plan.hops)))&& samePlanContents(refusal.wouldInterrupt, shown.flatMap((plan) => plan.gaps ?? []));refusalRef.current = {hops: refusal.wouldRemoveHops,@@ -827,7 +927,7 @@ export const BackendModelCatalogDialog: React.FC<{if (current && landed && !decided) {applyBaseline(observed, current);await Promise.resolve(onSaved(observed.agent)).catch(() => {});- onClose();+ closeSaved();return;}applyBaseline(observed, current ? applyBackendCatalogIntent(current, intent) : []);@@ -845,7 +945,7 @@ export const BackendModelCatalogDialog: React.FC<{return;}await Promise.resolve(onSaved(echoed)).catch(() => {});- onClose();+ closeSaved();});};@@ -935,7 +1035,7 @@ export const BackendModelCatalogDialog: React.FC<{return (<><Dialog- open={open}+ open={open && !direct}onOpenChange={(next) => { if (!next && !busy) onClose(); }}><DialogContent@@ -1081,7 +1181,7 @@ export const BackendModelCatalogDialog: React.FC<{type="button"variant="outline"className="model-hub-catalog-control rounded-md px-5 text-[12.5px] font-semibold"- onClick={onClose}+ onClick={() => onClose()}disabled={busy}>{t('settings.models.gateway.catalog.cancel')}@@ -1153,6 +1253,54 @@ export const BackendModelCatalogDialog: React.FC<{)}</DialogContent></Dialog>+ {open && direct && (editing ?? savingEdit) && (+ <BackendModelEditorDialog+ open+ backend={backend}+ model={(editing ?? savingEdit)!.model}+ seedId={(editing ?? savingEdit)!.seedId}+ takenIds={takenIds}+ effortSuggestions={effortSuggestions}+ busy={busy || savingEdit !== null}+ onCancel={() => onClose()}+ onCommit={(model) => {+ // With no list behind it, the editor is the only thing on screen,+ // so it stays — inert — until the write it started settles.+ setSavingEdit(editing);+ commitEdit(model);+ const pending = save();+ if (pending) void pending.finally(() => setSavingEdit(null));+ else setSavingEdit(null);+ }}+ />+ )}+ {open && direct && (removing ?? answered) && (() => {+ const asked = (removing ?? answered)!;+ const row = draft.find((entry) => entry.id === asked.modelId);+ return (+ <ConfirmDialog+ open+ destructive+ onOpenChange={(next) => { if (!next && !busy) onClose(); }}+ title={t('settings.models.gateway.catalog.removeTitle', { model: row ? displayLabel(row) : asked.modelId })}+ confirmLabel={t('settings.models.gateway.catalog.removeConfirm') as string}+ cancelLabel={t('settings.models.gateway.catalog.cancel') as string}+ confirmDisabled={busy}+ onConfirm={() => {+ setAnswered(asked);+ acceptRemoval(asked);+ askNextGuarded();+ return save()?.finally(() => setAnswered(null));+ }}+ >+ {(asked.plan.hops.length > 0 || (asked.plan.gaps?.length ?? 0) > 0) && (+ <div className="model-hub-catalog-consequence" role="alert">+ <GuardImpact hops={asked.plan.hops} gaps={asked.plan.gaps} sourceNames={sourceNames} />+ </div>+ )}+ </ConfirmDialog>+ );+ })()}</>);};diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsxindex 46a3033f9..c77273ad4 100644--- a/ui/src/components/settings/models/BackendModelEditorDialog.tsx+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx@@ -129,9 +129,11 @@ export const BackendModelEditorDialog: React.FC<{/** Effort values this backend's other rows already use. Suggestions, never a* vocabulary — every effort is sent verbatim and any string is equally valid. */effortSuggestions: readonly string[];+ /** A committed answer is being written; the editor holds still until it settles. */+ busy?: boolean;onCancel: () => void;onCommit: (model: BackendModel) => void;-}> = ({ open, backend, model, seedId, takenIds, effortSuggestions, onCancel, onCommit }) => {+}> = ({ open, backend, model, seedId, takenIds, effortSuggestions, busy = false, onCancel, onCommit }) => {const { t } = useTranslation();const creating = model === null;const [draft, setDraft] = React.useState<BackendModel>(() => model ?? blankBackendModel());@@ -401,8 +403,10 @@ export const BackendModelEditorDialog: React.FC<{const idHint = submitted && idError ? t(`settings.models.gateway.modelEditor.id.${idError}`) as string : null;return (- <Dialog open={open} onOpenChange={(next) => { if (!next) onCancel(); }}>+ <Dialog open={open} onOpenChange={(next) => { if (!next && !busy) onCancel(); }}><DialogContent+ onEscapeKeyDown={(event) => { if (busy) event.preventDefault(); }}+ onPointerDownOutside={(event) => { if (busy) event.preventDefault(); }}mobileSheetHeight="tall"closeLabel={t('common.close') as string}className="model-hub-model-editor flex h-[min(660px,calc(100dvh-32px))] w-[min(720px,calc(100vw-32px))] max-w-[720px] flex-col gap-0 overflow-hidden rounded-[14px] border-border-strong bg-surface p-0 shadow-[var(--model-hub-dialog-shadow)] max-md:w-full max-md:max-w-none max-md:rounded-t-2xl max-md:p-0 max-md:pt-2"@@ -707,10 +711,10 @@ export const BackendModelEditorDialog: React.FC<{</div><DialogFooter className="model-hub-model-editor-foot shrink-0 items-center border-t border-border sm:justify-end">- <Button type="button" variant="outline" className="model-hub-model-control rounded-md px-5 text-[12.5px] font-semibold" onClick={onCancel}>+ <Button type="button" variant="outline" className="model-hub-model-control rounded-md px-5 text-[12.5px] font-semibold" disabled={busy} onClick={onCancel}>{t('settings.models.gateway.modelEditor.cancel')}</Button>- <Button type="button" variant="brand" className="model-hub-model-control rounded-md px-5 text-[12.5px] font-semibold" onClick={commit}>+ <Button type="button" variant="brand" className="model-hub-model-control rounded-md px-5 text-[12.5px] font-semibold" disabled={busy} onClick={commit}>{t(creating ? 'settings.models.gateway.modelEditor.add' : 'settings.models.gateway.modelEditor.apply')}</Button></DialogFooter>diff --git a/ui/src/components/settings/models/GuardImpact.test.tsx b/ui/src/components/settings/models/GuardImpact.test.tsxindex 2ef81bf42..c0b1eee4a 100644--- a/ui/src/components/settings/models/GuardImpact.test.tsx+++ b/ui/src/components/settings/models/GuardImpact.test.tsx@@ -77,17 +77,20 @@ describe('GuardImpact', () => {// Every claim this body can make about interruption, read off the keys// rather than copied, so a reworded claim is caught by the same assertion.const claims = ([- 'settings.models.guard.hint.safe','settings.models.guard.hint.interrupt',- 'settings.models.guard.result.hint.safe','settings.models.guard.result.hint.interrupt','settings.models.guard.gap.label','settings.models.guard.result.gapLabel',] as const).map((key) => i18n.t(key));- // `[]` is the guard saying so, and it is entitled to: it can see the supply.+ // `[]` is the guard saying so: nothing loses supply, so nothing is warned.const stated = renderImpact({ hops: [hop()], gaps: [] });- expect(stated.container.textContent).toContain(i18n.t('settings.models.guard.hint.safe'));+ expect(stated.container.querySelector('.model-hub-guard-hint')).toBeNull();++ // A named gap is the one consequence worth a warning.+ const gapped = renderImpact({ hops: [hop()], gaps: [{ backend: 'claude', model_id: 'alpha', agents: [] }] });+ expect(gapped.container.textContent).toContain(i18n.t('settings.models.guard.hint.interrupt'));+ gapped.unmount();// `null` is a caller that cannot see the supply and does not pretend to.const unstated = renderImpact({ hops: [hop()], gaps: null });diff --git a/ui/src/components/settings/models/GuardImpact.tsx b/ui/src/components/settings/models/GuardImpact.tsxindex e3377227b..fe069bf6d 100644--- a/ui/src/components/settings/models/GuardImpact.tsx+++ b/ui/src/components/settings/models/GuardImpact.tsx@@ -2,7 +2,6 @@ import * as React from 'react';import { Info } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { cn } from '@/lib/utils';import { GuardGapList } from './GuardGapList';import type { RouteHopRef, SupplyGap } from './types';@@ -79,10 +78,9 @@ export const GuardImpact: React.FC<GuardPicture & {</>)}{/* Both of these are statements ABOUT the gaps — the list names them, and- the hint below says whether there are any — so an unstated gap list- renders neither. Silence is the only honest reading: 「safe」 would be- this client vouching for supply it cannot see, and 「interrupt」 would- invent a consequence. The hops above are unaffected; they are what the+ the hint below warns when there are any — so an unstated gap list+ renders neither: 「interrupt」 would invent a consequence. No gaps+ reads as nothing to warn about, so it says nothing either. The hops above are unaffected; they are what thecaller does know. */}{gaps !== null && (<>@@ -90,10 +88,12 @@ export const GuardImpact: React.FC<GuardPicture & {gaps={gaps}labelKey={committed ? 'settings.models.guard.result.gapLabel' : undefined}/>- <p className={cn('model-hub-guard-hint', gaps.length > 0 && 'text-destructive-ink')}>- <Info aria-hidden />- {t(`settings.models.guard.${committed ? 'result.' : ''}hint.${gaps.length > 0 ? 'interrupt' : 'safe'}`)}- </p>+ {gaps.length > 0 && (+ <p className="model-hub-guard-hint text-destructive-ink">+ <Info aria-hidden />+ {t(`settings.models.guard.${committed ? 'result.' : ''}hint.interrupt`)}+ </p>+ )}</>)}</>diff --git a/ui/src/components/settings/models/MigrationDialog.test.tsx b/ui/src/components/settings/models/MigrationDialog.test.tsxindex 0df903e9c..aecc1f665 100644--- a/ui/src/components/settings/models/MigrationDialog.test.tsx+++ b/ui/src/components/settings/models/MigrationDialog.test.tsx@@ -1,8 +1,8 @@// @vitest-environment jsdom//// The settings migration and setup's key-import entry share the same takeover-// dialog. A backend is one custody boundary: unsupported rows stay visible and-// block that CLI, while a complete backend can still migrate independently.+// dialog. Rows the Hub cannot carry are hidden and stay native; every carried+// row of a backend still migrates together.import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { useState } from 'react';@@ -123,19 +123,19 @@ afterEach(() => {});describe('MigrationDialog — the settings default', () => {- it('shows blocked native rows and keeps a complete backend actionable', async () => {+ it('hides rows the Hub cannot carry and keeps every backend actionable', async () => {serve();renderDialog();const dialog = await screen.findByRole('dialog');await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy();- expect((within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ }) as HTMLButtonElement).disabled).toBe(true);- expect(within(dialog).getByText('This credential cannot be imported. Use the existing Add flow in Model Hub to add this source manually.')).toBeTruthy();+ expect(within(dialog).queryByRole('checkbox', { name: /sk-ant-…4b7e/ })).toBeNull();+ expect(within(dialog).queryByRole('status')).toBeNull();expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(false);});- it('applies only complete backend groups with one migration action', async () => {+ it('applies every carried row with one migration action, leaving the rest native', async () => {serve();renderDialog();const user = userEvent.setup();@@ -145,8 +145,7 @@ describe('MigrationDialog — the settings default', () => {await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));await waitFor(() => expect(applied).toHaveLength(1));- expect(applied[0]).toEqual(['mig_codex_key', 'mig_opencode_legacy']);- expect(applied[0]).not.toContain('mig_claude_oauth');+ expect(applied[0]).toEqual(['mig_claude_oauth', 'mig_codex_key', 'mig_opencode_legacy']);});it('selects and submits every import candidate for a backend as one group', async () => {@@ -167,21 +166,21 @@ describe('MigrationDialog — the settings default', () => {expect(applied[0]).not.toContain('mig_claude_oauth_2');});- it('shows but never submits a reauth row, even when it is pre-selected', async () => {+ it('never shows or submits a reauth row, even when it is pre-selected', async () => {serve();renderDialog();const user = userEvent.setup();const dialog = await screen.findByRole('dialog');await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());- expect((within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ }) as HTMLButtonElement).disabled).toBe(true);+ expect(within(dialog).queryByText(/sk-ant-…4b7e/)).toBeNull();await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));await waitFor(() => expect(applied).toHaveLength(1));expect(applied[0]).not.toContain('mig_claude_reauth');});- it('uses eligible as a backend scope without hiding blocked rows in that backend', async () => {+ it('uses eligible as a backend scope and still hides rows it cannot carry', async () => {const claudeKey: MigrationItem = {...CODEX_KEY,id: 'mig_claude_key',@@ -197,7 +196,7 @@ describe('MigrationDialog — the settings default', () => {const dialog = await screen.findByRole('dialog');await waitFor(() => expect(within(dialog).getAllByText('Anthropic').length).toBeGreaterThan(0));expect(within(dialog).getByText(/Claude 账号登录/)).toBeTruthy();- expect((within(dialog).getByRole('checkbox', { name: /sk-ant-…4b7e/ }) as HTMLButtonElement).disabled).toBe(true);+ expect(within(dialog).queryByText(/sk-ant-…4b7e/)).toBeNull();expect(within(dialog).getByRole('button', { name: 'Start migration' })).toBeTruthy();});@@ -351,26 +350,21 @@ describe('MigrationDialog — the settings default', () => {expect(onClose).not.toHaveBeenCalled();});- it.each([- ['settings.models.migration.blocked.config', "Check this CLI's saved configuration, then scan again."],- ['settings.models.migration.blocked.environment', 'This environment-based authentication cannot be imported. Save the key in a supported configuration file, then scan again.'],- ['settings.models.migration.blocked.credential', 'This credential could not be read or is not supported. Check credential access and the saved authentication format, then scan again.'],- ['settings.models.migration.blocked.unknown', 'This credential cannot be imported. Use the existing Add flow in Model Hub to add this source manually.'],- ] as const)('maps blocked note %s to actionable copy', async (notes_key, message) => {- const blocked = { ...REAUTH, notes_key };- serve([CODEX_KEY, blocked]);+ it('says nothing about a row it cannot carry', async () => {+ serve([CODEX_KEY, { ...REAUTH, notes_key: 'settings.models.migration.blocked.config' }]);renderDialog();const dialog = await screen.findByRole('dialog');await waitFor(() => expect(within(dialog).getByText('OpenAI')).toBeTruthy());- expect((within(dialog).getByRole('status') as HTMLElement).textContent).toContain(message);+ expect(within(dialog).queryByRole('status')).toBeNull();+ expect(within(dialog).getAllByRole('checkbox')).toHaveLength(1);});});describe('MigrationDialog — persisted authentication', () => {it.each([- ['en', 'Import authentication saved in configuration files, shell startup files, or supported credential stores, without reading runtime environment values. After migration, Model Hub will manage the selected authentication.'],- ['zh', '导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证,不读取运行中的环境变量。迁移后,所选认证由模型网关管理。'],+ ['en', 'Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, Model Hub will manage the selected authentication.'],+ ['zh', '导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,所选认证由模型网关管理。'],] as const)('explains the saved source boundary and consequence in %s', async (language, sentence) => {await i18n.changeLanguage(language);serve([CODEX_KEY]);@@ -380,136 +374,24 @@ describe('MigrationDialog — persisted authentication', () => {expect(within(dialog).getByText(sentence)).toBeTruthy();});- const blockedReasons = [- {- reason: 'dynamic_shell',- path: '/home/用户/.zshrc',- en: /expressions or commands.*literal values.*never executes shell code/,- zh: /表达式或命令.*固定值.*不会执行 Shell 代码/,- },- {- reason: 'ambiguous_shell',- path: '/home/用户/.profile',- en: /Conflicting saved assignments.*listed files.*unambiguous literal value/,- zh: /列出的文件.*互相冲突.*固定值.*统一相关配置/,- },- {- reason: 'unreadable',- path: '/home/用户/.bashrc',- en: /source file could not be read.*Avibe has read access/,- zh: /无法读取此配置文件.*Avibe 是否有读取权限/,- },- {- reason: 'reference',- path: '/home/用户/.claude/settings.json',- en: /referenced variable.*no unambiguous saved literal value.*save.*key.*listed configuration or shell startup file/,- zh: /引用的变量.*固定值.*列出的配置文件或 Shell 启动文件.*保存对应的密钥/,- },- {- reason: 'helper',- path: '/home/用户/.claude/settings.local.json',- en: /supplied by a command.*supported static configuration.*add the source manually/,- zh: /由命令提供.*静态配置.*手动添加供应商/,+ it.each(['dynamic_shell', 'ambiguous_shell', 'unreadable', 'reference', 'helper', 'token', 'headers', 'transport'])(+ 'hides a %s row and still migrates the backend beside it',+ async (reason) => {+ serve([+ { ...REAUTH, notes_key: `settings.models.migration.blocked.${reason}`, source_paths: ['/home/用户/.zshrc'] },+ { ...CODEX_KEY, source_paths: ['/home/用户/.codex/auth.json'] },+ ]);+ renderDialog();+ const user = userEvent.setup();++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText('OpenAI');+ expect(within(dialog).queryByRole('status')).toBeNull();+ expect(within(dialog).queryByText('/home/用户/.zshrc')).toBeNull();+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await waitFor(() => expect(applied).toEqual([[CODEX_KEY.id]]));},- {- reason: 'token',- path: '/home/用户/.zshenv',- en: /login token or authentication format cannot be imported.*Add a source.*sign in again/,- zh: /登录令牌或认证格式暂不支持导入.*添加供应商.*重新登录/,- },- {- reason: 'headers',- path: '/home/用户/.zprofile',- en: /Custom credential headers cannot be imported.*supported authentication method/,- zh: /自定义认证请求头.*受支持的认证方式/,- },- {- reason: 'transport',- path: '/home/用户/.bashrc',- en: /can't use this authentication method yet.*file is unchanged.*standard API key/,- zh: /暂不支持这里的认证方式.*原文件未改动.*标准 API Key 重新添加/,- },- ] as const;-- it.each(['en', 'zh'] as const)('shows every blocked file and its specific %s remedy while preserving backend selection', async (language) => {- await i18n.changeLanguage(language);- serve([- ...blockedReasons.map(({ reason, path }) => ({- ...REAUTH,- id: `blocked_${reason}`,- notes_key: `settings.models.migration.blocked.${reason}`,- source_paths: [path],- })),- SUBSCRIPTION,- { ...CODEX_KEY, source_paths: ['/home/用户/.codex/auth.json'] },- ]);- renderDialog();- const user = userEvent.setup();-- const dialog = await screen.findByRole('dialog');- const status = await within(dialog).findByRole('status');- const warnings = within(status).getAllByRole('listitem');- expect(warnings).toHaveLength(blockedReasons.length);- for (const { path, ...reason } of blockedReasons) {- const warning = warnings.find((element) => (- within(element).queryByText(path) && within(element).queryByText(reason[language])- ));- expect(warning).toBeTruthy();- expect(within(warning!).getByText(reason[language])).toBeTruthy();- }- expect(status.textContent).not.toMatch(/Allow credential access|请允许访问凭据|Remove this CLI|清除.*环境变量/);- for (const row of within(dialog).getAllByRole('checkbox', { name: /sk-ant-…4b7e|Claude 账号登录/ })) {- expect((row as HTMLButtonElement).disabled).toBe(true);- expect(row.getAttribute('aria-checked')).toBe('false');- }- const supportedRow = within(dialog).getByRole('checkbox', { name: /OpenAI.*\/home\/用户\/\.codex\/auth\.json/ });- expect((supportedRow as HTMLButtonElement).disabled).toBe(false);- expect(supportedRow.getAttribute('aria-checked')).toBe('true');- await user.click(within(dialog).getByRole('button', { name: language === 'en' ? 'Start migration' : '开始迁移' }));- await waitFor(() => expect(applied).toEqual([[CODEX_KEY.id]]));- });-- it('deduplicates only matching source/reason pairs, keeping different files and reasons', async () => {- const dynamic: MigrationItem = {- ...REAUTH,- notes_key: 'settings.models.migration.blocked.dynamic_shell',- source_paths: ['/home/用户/.zshrc', '/home/用户/.profile', '/home/用户/.zshrc'],- };- serve([- dynamic,- { ...dynamic, id: 'duplicate', source_paths: ['/home/用户/.zshrc'] },- { ...dynamic, id: 'different_reason', notes_key: 'settings.models.migration.blocked.reference', source_paths: ['/home/用户/.zshrc'] },- ]);- renderDialog();-- const dialog = await screen.findByRole('dialog');- const status = await within(dialog).findByRole('status');- const warnings = within(status).getAllByRole('listitem');- expect(warnings).toHaveLength(3);- expect(within(status).getAllByText('/home/用户/.zshrc')).toHaveLength(2);- expect(within(status).getAllByText('/home/用户/.profile')).toHaveLength(1);- expect(within(status).getAllByText(/expressions or commands/)).toHaveLength(2);- expect(within(status).getAllByText(/referenced variable/)).toHaveLength(1);- expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(true);- });-- it('keeps distinct blocked legacy rows visible without inventing file locators', async () => {- serve([- { ...REAUTH, notes_key: 'settings.models.migration.blocked.credential' },- { ...REAUTH, id: 'legacy_second', masked_detail: 'sk-ant-…5678', notes_key: 'settings.models.migration.blocked.environment' },- ]);- renderDialog();-- const dialog = await screen.findByRole('dialog');- const status = await within(dialog).findByRole('status');- const warnings = within(status).getAllByRole('listitem');- expect(warnings).toHaveLength(2);- expect(within(warnings[0]).getByText('Claude Code configuration')).toBeTruthy();- expect(within(warnings[0]).getByText(/could not be read or is not supported/)).toBeTruthy();- expect(within(warnings[1]).getByText('Claude Code configuration')).toBeTruthy();- expect(within(warnings[1]).getByText(/Save the key in a supported configuration file/)).toBeTruthy();- expect(status.textContent).not.toMatch(/\.json|\.zshrc|\.profile/);- });+ );it.each([['en', 'No configuration found to migrate.', 'Start migration'],@@ -654,7 +536,7 @@ describe('MigrationDialog — shared persisted files', () => {await waitFor(() => expect(applied).toEqual([linked.map((item) => item.id)]));});- it('shows a linked backend blocker in each affected group, even outside the entry-point scope', async () => {+ it('does not let a linked row it cannot carry hold back the group', async () => {serve([...linked,{@@ -668,23 +550,81 @@ describe('MigrationDialog — shared persisted files', () => {SUBSCRIPTION,]);renderDialog({ eligible: (item) => item.id === CODEX_KEY.id });+ const user = userEvent.setup();const dialog = await screen.findByRole('dialog');await within(dialog).findByText('OpenAI');- const warnings = within(dialog).getAllByRole('status');- expect(warnings).toHaveLength(2);- for (const warning of warnings) {- expect(within(warning).getByText('/home/用户/.config/opencode/opencode.json')).toBeTruthy();- expect(within(warning).getByText(/Credentials supplied by a command cannot be imported/)).toBeTruthy();- }+ expect(within(dialog).queryByRole('status')).toBeNull();const checkboxes = within(dialog).getAllByRole('checkbox');- expect(checkboxes).toHaveLength(4);- for (const checkbox of checkboxes) {- expect((checkbox as HTMLButtonElement).disabled).toBe(true);- expect(checkbox.getAttribute('aria-checked')).toBe('false');- }+ expect(checkboxes).toHaveLength(3);+ for (const checkbox of checkboxes) expect((checkbox as HTMLButtonElement).disabled).toBe(false);+ await user.click(within(dialog).getByRole('button', { name: 'Start migration' }));+ await waitFor(() => expect(applied).toEqual([linked.map((item) => item.id)]));+ });++ it('blocks a linked group whose other backend has nothing the Hub can carry', async () => {+ // The server requires every linked backend in the batch; one with no+ // carried row can never be selected, so offering the rest always fails.+ serve([+ { ...CODEX_KEY, source_paths: ['/home/用户/.profile'], required_backends: ['codex', 'opencode'] },+ {+ ...LEGACY,+ id: 'blocked_headers',+ proposed_action: 'keep_native',+ notes_key: 'settings.models.migration.blocked.headers',+ source_paths: ['/home/用户/.profile'],+ required_backends: ['codex', 'opencode'],+ },+ ]);+ renderDialog();++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findByText('OpenAI');+ const [checkbox] = within(dialog).getAllByRole('checkbox');+ expect((checkbox as HTMLButtonElement).disabled).toBe(true);+ expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(true);+ });++ it('blocks a backend whose native config the CLI cannot parse', async () => {+ // Hub mode over an unparseable native config fails every launch, so the+ // server refuses the batch; the dialog must not offer it.+ serve([+ CODEX_KEY,+ {+ ...CODEX_KEY,+ id: 'blocked_config',+ proposed_action: 'reauth',+ selected: false,+ notes_key: 'settings.models.migration.blocked.config',+ config_blocker: true,+ },+ ]);+ renderDialog();++ const dialog = await screen.findByRole('dialog');+ await within(dialog).findAllByText('OpenAI');+ const [checkbox] = within(dialog).getAllByRole('checkbox');+ expect((checkbox as HTMLButtonElement).disabled).toBe(true);+ expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(true);+ });++ it('names a standalone config blocker the user has to repair', async () => {+ serve([{+ ...CODEX_KEY,+ id: 'blocked_config',+ masked_detail: '',+ proposed_action: 'reauth',+ selected: false,+ notes_key: 'settings.models.migration.blocked.config',+ source_paths: ['/home/用户/.codex/config.toml'],+ config_blocker: true,+ }]);+ renderDialog();++ const dialog = await screen.findByRole('dialog');+ expect((await within(dialog).findAllByText('/home/用户/.codex/config.toml')).length).toBeGreaterThan(0);+ expect(within(dialog).getByRole('status')).toBeTruthy();expect((within(dialog).getByRole('button', { name: 'Start migration' }) as HTMLButtonElement).disabled).toBe(true);- expect(modelsApi.applyMigration).not.toHaveBeenCalled();});it('keeps a transitive three-backend closure visible and selected from one entry point', async () => {@@ -766,14 +706,10 @@ describe('MigrationDialog — the Settings surface the setup scope must not distexpect(visibleText(dialog)).toEqual(['Migrate to the Model Hub',- 'Import authentication saved in configuration files, shell startup files, or supported credential stores, without reading runtime environment values. After migration, Model Hub will manage the selected authentication.',+ 'Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, Model Hub will manage the selected authentication.','Claude Code',- 'Claude Code configuration',- 'This credential cannot be imported. Use the existing Add flow in Model Hub to add this source manually.','Anthropic','Claude 账号登录(OAuth) · Claude Code configuration',- 'Anthropic',- 'sk-ant-…4b7e · Claude Code configuration','Codex','OpenAI','sk-…9f21 · Codex configuration',@@ -782,8 +718,7 @@ describe('MigrationDialog — the Settings surface the setup scope must not dist'Close',]);expect(controls(dialog)).toEqual([- { role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: true },- { role: 'checkbox', name: 'Anthropic · sk-ant-…4b7e · Claude Code configuration', disabled: true },+ { role: 'checkbox', name: 'Anthropic · Claude 账号登录(OAuth) · Claude Code configuration', disabled: false },{ role: 'checkbox', name: 'OpenAI · sk-…9f21 · Codex configuration', disabled: false },{ role: null, name: 'Later', disabled: false },{ role: null, name: 'Start migration', disabled: false },diff --git a/ui/src/components/settings/models/OAuthConnectDialog.test.ts b/ui/src/components/settings/models/OAuthConnectDialog.test.tsindex 8c88316c7..839904687 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.test.ts+++ b/ui/src/components/settings/models/OAuthConnectDialog.test.ts@@ -89,7 +89,7 @@ describe('add-subscription channel choice', () => {expect(recommendedSubscriptionChannel('anthropic')).toBe('native_cli');expect(subscriptionOptionOrder('anthropic')).toEqual(['native_cli', 'hub']);expect(recommendedSubscriptionChannel('openai')).toBe('hub');- expect(subscriptionOptionOrder('openai')).toEqual(['hub', 'native_cli']);+ expect(subscriptionOptionOrder('openai')).toEqual(['hub']);});it('uses the recommended option while the native slot is free', () => {diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex e630a5cfe..5b9ba5d29 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -22,6 +22,7 @@ import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';import { cn } from '@/lib/utils';import { useToast } from '@/context/ToastContext';+import type { TranslationKey } from '@/i18n/types';import { OAuthDeviceCodeRow, OAuthLinkRow, OAuthSubmitRow } from '../oauth/OAuthFlowParts';import { AdoptionNote } from './AdoptionNote';import {@@ -45,7 +46,16 @@ import {takeProviderTabForNavigation,} from './providerTab';import { REPAIR_LINE_KEY, REPAIR_TOAST, repairOutcome, repairSettles, type RepairOutcome } from './repair';-import { NATIVE_SUBSCRIPTION_EXISTS_FAILURE, oauthFailureKey, oauthStartFailureKey, serverText, type OAuthJourney } from './serverCopy';+import {+ NATIVE_SUBSCRIPTION_EXISTS_FAILURE,+ PASTE_REJECTED_KEY,+ SUBMISSION_REJECTED_FAILURE,+ callbackValueCarriesResult,+ oauthFailureKey,+ oauthStartFailureKey,+ serverText,+ type OAuthJourney,+} from './serverCopy';import {initialSubscriptionChannel,nativeSubscriptionSlotTaken,@@ -62,7 +72,6 @@ const DEADLINE_MS = 16 * 60 * 1000;type ConnectPhase = 'choose' | 'flow';-const CHANNELS: SupplyChannel[] = ['native_cli', 'hub'];const Step: React.FC<{ n: number; label: string; children: React.ReactNode }> = ({ n, label, children }) => (<div className="flex flex-col gap-2.5 rounded-lg border border-border bg-surface-2/40 px-4 py-3">@@ -96,6 +105,10 @@ export const OAuthConnectDialog: React.FC<{const [view, setView] = React.useState<FlowView>(initialFlowView);const [code, setCode] = React.useState('');const [submitting, setSubmitting] = React.useState(false);+ // A paste the provider refused before touching the flow. The flow is still+ // waiting, so this stays beside the input instead of settling the dialog:+ // the user fixes the value and submits again on the same authorization.+ const [pasteError, setPasteError] = React.useState<TranslationKey | null>(null);// 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.@@ -278,22 +291,6 @@ export const OAuthConnectDialog: React.FC<{*/const resolvedAfterAttempt = React.useCallback(() => rowsBehindAreStale(), [rowsBehindAreStale]);- const copy = (text: string | null | undefined) => (e: React.MouseEvent) => {- e.preventDefault();- e.stopPropagation();- if (!text) return;- // navigator.clipboard is undefined in non-secure contexts / older browsers;- // touching .writeText there throws synchronously, not as a rejected promise.- if (!navigator.clipboard?.writeText) {- showToast(t('common.copyFailed') as string, 'error');- return;- }- navigator.clipboard- .writeText(text)- .then(() => showToast(t('common.copied') as string, 'success'))- .catch(() => showToast(t('common.copyFailed') as string, 'error'));- };-// Drive the flow only after the user confirms one channel.React.useEffect(() => {if (!open || phase !== 'flow') return;@@ -486,6 +483,7 @@ export const OAuthConnectDialog: React.FC<{// isn't shown while the new startOAuth request is in flight.transition({ kind: 'reset' });setCode('');+ setPasteError(null);setSubmitting(false);setAdoption(null);setRepair(null);@@ -630,6 +628,11 @@ export const OAuthConnectDialog: React.FC<{const authority = flowAuthorityRef.current;const cur = authority?.current().flow;if (!cur || !code.trim()) return;+ if (cur.presentation?.expects === 'paste_callback_url' && !callbackValueCarriesResult(code)) {+ setPasteError(PASTE_REJECTED_KEY);+ return;+ }+ setPasteError(null);const isCurrent = () =>flowAuthorityRef.current === authority && authority.current().flow?.flow_id === cur.flow_id;setSubmitting(true);@@ -668,6 +671,10 @@ export const OAuthConnectDialog: React.FC<{// the flow id, so a submit rejecting afterwards is still current and still// ignored. `failureLanded` is the part that knows.const failure = apiFailure(err);+ if (failure?.code === SUBMISSION_REJECTED_FAILURE) {+ setPasteError(PASTE_REJECTED_KEY);+ return;+ }const failureClass = classifyOAuthFailure(failure);const step = authority.transition({kind: 'error',@@ -763,7 +770,7 @@ export const OAuthConnectDialog: React.FC<{const recommended = recommendedSubscriptionChannel(vendor);const optionOrder = subscriptionOptionOrder(vendor);const optionRefs = React.useRef<Partial<Record<SupplyChannel, HTMLButtonElement | null>>>({});- const selectableChannels = CHANNELS.filter((candidate) => candidate !== 'native_cli' || !nativeSlotTaken);+ const selectableChannels = optionOrder.filter((candidate) => candidate !== 'native_cli' || !nativeSlotTaken);const moveSelection = (direction: number) => {const currentIndex = selectableChannels.indexOf(channel);@@ -816,9 +823,7 @@ export const OAuthConnectDialog: React.FC<{? 'settings.models.addSub.opt.added': candidate === recommended? 'settings.models.addSub.badge.recommended'- : vendorCopy === 'claude'- ? 'settings.models.addSub.badge.secondary'- : 'settings.models.addSub.badge.supportedNotRecommended';+ : 'settings.models.addSub.badge.secondary';const optionKey = isNative ? 'native' : 'hub';return (<button@@ -865,12 +870,14 @@ export const OAuthConnectDialog: React.FC<{<span className="model-hub-add-sub-option-label font-semibold text-foreground">{t(`settings.models.addSub.opt.${optionKey}.label`)}</span>- <span className="model-hub-accent-pill--mint model-hub-add-sub-badge rounded-full border font-semibold">- {t(badgeKey)}- </span>+ {(optionOrder.length > 1 || disabled) && (+ <span className="model-hub-accent-pill--mint model-hub-add-sub-badge rounded-full border font-semibold">+ {t(badgeKey)}+ </span>+ )}</span><span className="model-hub-add-sub-description block text-muted">- {t(`settings.models.addSub.opt.${optionKey}.desc.${vendorCopy}`)}+ {t(isNative ? 'settings.models.addSub.opt.native.desc.claude' : `settings.models.addSub.opt.hub.desc.${vendorCopy}`)}</span>{vendorCopy === 'claude' && candidate === 'hub' && (<span className="model-hub-add-sub-risk flex items-start gap-2 border border-gold/30 bg-gold/10">@@ -883,10 +890,12 @@ export const OAuthConnectDialog: React.FC<{);})}</div>- <p className="model-hub-add-sub-hint flex items-start gap-2 text-muted">- <Info className="mt-0.5 size-3 shrink-0" />- <span>{t(`settings.models.addSub.hint.${vendorCopy}`)}</span>- </p>+ {vendorCopy === 'claude' && (+ <p className="model-hub-add-sub-hint flex items-start gap-2 text-muted">+ <Info className="mt-0.5 size-3 shrink-0" />+ <span>{t('settings.models.addSub.hint.claude')}</span>+ </p>+ )}</div><div className="model-hub-add-sub-foot model-hub-fill-05 flex items-center justify-end gap-2 border-t border-border">@@ -1003,11 +1012,7 @@ export const OAuthConnectDialog: React.FC<{}>{presentation?.auth_url ? (- <OAuthLinkRow- url={presentation.auth_url}- onCopy={copy(presentation.auth_url)}- copyLabel={t('common.copy') as string}- />+ <OAuthLinkRow url={presentation.auth_url} />) : (<p className="text-[12px] text-muted">{t('settings.models.oauth.starting')}</p>)}@@ -1015,15 +1020,15 @@ export const OAuthConnectDialog: React.FC<{<Step n={2} label={step2Label}>{isDevice ? (- <OAuthDeviceCodeRow- code={presentation?.device_code ?? ''}- onCopy={copy(presentation?.device_code)}- copyLabel={t('common.copy') as string}- />+ <OAuthDeviceCodeRow code={presentation?.device_code ?? ''} />) : (<OAuthSubmitRowvalue={code}- onChange={setCode}+ onChange={(next) => {+ setCode(next);+ setPasteError(null);+ }}+ error={pasteError ? (t(pasteError) as string) : undefined}onSubmit={() => void submit()}submitting={submitting || state === 'verifying'}placeholder={diff --git a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsxindex 8afdc537d..84da77e62 100644--- a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx@@ -210,7 +210,8 @@ describe('direct route editing', () => {expect(modelsApi.getAgentChain).toHaveBeenCalledTimes(2);} else {expect(footer().queryByRole('button', { name: 'Cancel changes' })).toBeNull();- await user.click(footer().getByRole('button', { name: 'Close' }));+ expect(footer().queryByRole('button', { name: 'Close' })).toBeNull();+ await user.click(screen.getByRole('button', { name: 'Close' }));expect(close).toHaveBeenCalledTimes(1);expect(modelsApi.getAgentChain).toHaveBeenCalledTimes(1);}diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsxindex 40e5ac7a5..43f6597e2 100644--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx@@ -243,14 +243,59 @@ describe("RouteChainDialog", () => {}});const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);- const labels = state === 'inherited' ? ['Pin current route', 'Close', 'Save']- : [state === 'preview' ? 'Undo restore' : 'Restore automatic', state === 'preview' ? 'Cancel changes' : 'Close', 'Save'];+ const labels = state === 'inherited' ? ['Pin current route', 'Save']+ : state === 'preview' ? ['Undo restore', 'Cancel changes', 'Save'] : ['Restore automatic', 'Save'];expect(footer.getAllByRole('button').map((button) => button.textContent)).toEqual(labels);for (const label of labels) expect(footer.getByRole('button', { name: label }).hasAttribute('hidden')).toBe(false);expect(screen.getByRole('dialog').classList.contains('overflow-hidden')).toBe(true);},);+ it('hands the model to the catalog from the head, only while the route is unedited', async () => {+ const user = userEvent.setup();+ const catalogRow = { id: 'opus-5', display_name: null, origin: 'manual' as const, models_dev_id: null, context_window: null, max_output_tokens: null, input_modalities: [], output_modalities: [], supports_tools: null, supports_reasoning: null, reasoning_efforts: [], locked: false, routeable: true };+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);+ const manage = vi.fn();+ render(<I18nextProvider i18n={i18n}><RouteChainDialog+ selection={{ agent: { ...agent, catalog_models: [catalogRow] }, modelId: 'opus-5', read: readyRegion(chain) }}+ sources={sources} onClose={vi.fn()} onManageModel={manage} readAgents={vi.fn()} readSources={vi.fn()}+ /></I18nextProvider>);+ const head = within(document.querySelector<HTMLElement>('.model-hub-route-head')!);+ await user.click(await head.findByRole('button', { name: 'Edit model' }));+ await user.click(head.getByRole('button', { name: 'Remove model' }));+ const shown = [{ source_id: 'src_a', model_id: 'claude-opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }];+ expect(manage.mock.calls).toEqual([['edit', shown], ['remove', shown]]);+ // An unsaved draft would be dropped by leaving, so the handoff steps aside.+ await user.click(screen.getAllByRole('button', { name: 'Remove hop' })[0]);+ expect(head.queryByRole('button', { name: 'Edit model' })).toBeNull();+ expect(head.queryByRole('button', { name: 'Remove model' })).toBeNull();+ });++ it('offers no catalog handoff for a locked row', async () => {+ const lockedRow = { id: 'opus-5', display_name: null, origin: 'builtin' as const, models_dev_id: null, context_window: null, max_output_tokens: null, input_modalities: [], output_modalities: [], supports_tools: null, supports_reasoning: null, reasoning_efforts: [], locked: true, routeable: true };+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);+ render(<I18nextProvider i18n={i18n}><RouteChainDialog+ selection={{ agent: { ...agent, catalog_models: [lockedRow] }, modelId: 'opus-5', read: readyRegion(chain) }}+ sources={sources} onClose={vi.fn()} onManageModel={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()}+ /></I18nextProvider>);+ await screen.findAllByRole('button', { name: 'Remove hop' });+ expect(screen.queryByRole('button', { name: 'Edit model' })).toBeNull();+ });++ it('labels the origin line as the current route and explains the origin on hover', async () => {+ const user = userEvent.setup();+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(chain);+ render(<I18nextProvider i18n={i18n}><RouteChainDialog+ selection={{ agent, modelId: 'opus-5', read: readyRegion(chain) }}+ sources={sources} onClose={vi.fn()} readAgents={vi.fn()} readSources={vi.fn()}+ /></I18nextProvider>);+ await screen.findAllByRole('button', { name: 'Remove hop' });+ const line = document.querySelector<HTMLElement>('.model-hub-route-origin-line')!;+ expect(within(line).getByText('Current')).toBeTruthy();+ await user.hover(within(line).getByRole('button', { name: 'Manual' }));+ expect((await screen.findByText(/This model has a saved, fixed route/)).closest('.model-hub-origin-help')).toBeTruthy();+ });+it('closes an unchanged inherited editor without creating manual intent', async () => {const user = userEvent.setup();const inherited: AgentChain = { ...chain, manual_override: null, route_origin: 'automatic' };@@ -265,8 +310,10 @@ describe("RouteChainDialog", () => {await screen.findAllByRole('button', { name: 'Edit hop' });const footer = within(document.querySelector<HTMLElement>('.model-hub-route-foot')!);- const dismiss = footer.getByRole('button', { name: 'Close' });- expect(dismiss.textContent).toBe('Close');+ // The header close is the only dismiss control while there is nothing to discard.+ const dismiss = screen.getByRole('button', { name: 'Close' });+ expect(dismiss.classList.contains('model-hub-route-close')).toBe(true);+ expect(footer.queryByRole('button', { name: 'Close' })).toBeNull();expect(footer.queryByRole('button', { name: 'Cancel' })).toBeNull();expect(screen.queryByRole('button', { name: 'Cancel changes' })).toBeNull();expect(screen.getByRole('button', { name: 'Add a hop' })).toBeTruthy();diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsxindex e00dded41..1ba7452fe 100644--- a/ui/src/components/settings/models/RouteChainDialog.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.tsx@@ -11,6 +11,7 @@ import {Plus,RefreshCw,RotateCcw,+ Trash2,Undo2,X,} from "lucide-react";@@ -113,6 +114,10 @@ export const RouteChainDialog: React.FC<{attempt: SuspendedRouteAttempt | null,observedAgent: AgentSupply | null,) => void;+ /** Hand this model over to the catalog dialog, which is the one writer of the+ * model list — the Route dialog only names the model and the intent, so the+ * edit and removal protocols (guard, refusal, save) stay in one place. */+ onManageModel?: (action: "edit" | "remove", route: RouteHop[]) => void;}> = ({selection,sources,@@ -125,6 +130,7 @@ export const RouteChainDialog: React.FC<{readAgents,readSources,onDirectMode,+ onManageModel,}) => {const { t } = useTranslation();const [phase, setPhase] = React.useState<Phase>("loading");@@ -171,6 +177,8 @@ export const RouteChainDialog: React.FC<{const addButtonRef = React.useRef<HTMLButtonElement | null>(null);const reseedButtonRef = React.useRef<HTMLButtonElement | null>(null);const cancelButtonRef = React.useRef<HTMLButtonElement | null>(null);+ const closeButtonRef = React.useRef<HTMLButtonElement | null>(null);+ const [originHelp, setOriginHelp] = React.useState(false);const saveButtonRef = React.useRef<HTMLButtonElement | null>(null);const savingStatusRef = React.useRef<HTMLSpanElement | null>(null);const retryButtonRef = React.useRef<HTMLButtonElement | null>(null);@@ -183,6 +191,10 @@ export const RouteChainDialog: React.FC<{const agent = selection?.agent ?? null;const modelId = selection?.modelId ?? "";const selectionBackend = selection?.agent.backend;+ // Only an editable catalog row can be handed over: a locked row (Claude Code's+ // `Default`) offers no actions in the catalog either, and a server that+ // predates backend catalogs sends no list to answer from.+ const catalogRow = agent?.catalog_models?.find((model) => model.id === modelId) ?? null;const draft = interaction.draft;const rovingIndex = interaction.focusIndex;const grabbed = interaction.grab?.index ?? null;@@ -229,12 +241,23 @@ export const RouteChainDialog: React.FC<{const unresolvedPreview = restoring && preview === null;const dirty = manualDraft ? savedOverride === null || !sameRouteDraft(savedOverride.hops, draft) : savedOverride !== null;const canDiscardDraft = (phase === "ready" || phase === "rejected") && (dirty || restoring);+ // A handoff leaves this dialog, so it is offered only on a settled, unedited+ // route: mid-write phases own an exchange the user must finish, and an unsaved+ // draft would be discarded without asking.+ const manageableModel = Boolean(+ onManageModel && catalogRow && !catalogRow.locked && phase === "ready" && !dirty && !restoring,+ );const draftOrigin = manualDraft ? (draft.length ? 'manual' : null) : (preview ?? chain)?.route_origin ?? null;const announce = (key: TranslationKey, params?: Record<string, unknown>) =>setAnnouncement({ key, params });const focusAfterRender = (ref: React.RefObject<HTMLElement | null>) => {requestAnimationFrame(() => ref.current?.focus());};+ // The footer carries a dismiss control only while there is a draft to+ // discard; otherwise the header close is the dialog's single way out, so+ // every "return focus to the way out" path resolves through here.+ const focusDismiss = () =>+ (cancelButtonRef.current ?? closeButtonRef.current)?.focus();const readChain = React.useCallback(async () => {if (!selectionBackend) return;@@ -382,7 +405,7 @@ export const RouteChainDialog: React.FC<{} else if (reseedButtonRef.current && !reseedButtonRef.current.disabled) {reseedButtonRef.current.focus();} else {- cancelButtonRef.current?.focus();+ focusDismiss();}});if (nextDraft.length > 0) {@@ -653,7 +676,7 @@ export const RouteChainDialog: React.FC<{const retryUnknown = async () => {if (!selectionBackend || !submitted || phase !== "unknown") return;const token = ++generation.current;- cancelButtonRef.current?.focus();+ focusDismiss();setPhase("reconciling");setReconcileFailed(false);@@ -951,7 +974,7 @@ export const RouteChainDialog: React.FC<{ref={retryButtonRef}type="button"onClick={() => {- cancelButtonRef.current?.focus();+ focusDismiss();void readChain();}}>@@ -1092,7 +1115,10 @@ export const RouteChainDialog: React.FC<{) : (<div className="model-hub-route-body flex flex-col">{!unresolvedPreview && !(manualDraft && draft.length === 0) && <div className="model-hub-route-origin-line">- <RouteOriginBadge origin={draftOrigin} backend={agent!.backend} interactive={false} />+ {/* The line reads as the route in force unless an unsaved pin is+ about to replace it, which `manualPending` already says itself. */}+ {!(manualDraft && dirty) && <span className="model-hub-route-origin-now">{t('settings.models.routing.originNow')}</span>}+ <RouteOriginBadge origin={draftOrigin} backend={agent!.backend} open={originHelp} onOpenChange={setOriginHelp} /><span>{t(manualDraft ? (dirty ? 'settings.models.routing.manualPending' : 'settings.models.routing.frozen') : 'settings.models.routing.follows', { backend })}</span></div>}{unresolvedPreview && <div className="model-hub-route-preview" role="status">@@ -1187,7 +1213,7 @@ export const RouteChainDialog: React.FC<{className="model-hub-route-dialog fixed left-1/2 top-1/2 z-50 flex -translate-x-1/2 -translate-y-1/2 flex-col gap-0 overflow-hidden border border-border-strong bg-surface p-0"onOpenAutoFocus={(event) => {event.preventDefault();- cancelButtonRef.current?.focus();+ focusDismiss();}}onEscapeKeyDown={(event) => {if (phase === "ready" && interactionRef.current.grab) {@@ -1206,21 +1232,48 @@ export const RouteChainDialog: React.FC<{{ menuModel: modelId },)}</DialogPrimitive.Title>- <DialogPrimitive.Close- disabled={phase === "saving"}- aria-label={- t(- phase === "guard"- ? "settings.models.guard.cancel"- : phase === "impact" || phase === "refreshing"- ? "settings.models.routeDialog.impact.done"- : "settings.models.routing.close",- ) as string- }- className="model-hub-route-close grid shrink-0 place-items-center"- >- <X aria-hidden="true" />- </DialogPrimitive.Close>+ <span className="model-hub-route-head-actions flex shrink-0 items-center gap-1.5">+ {manageableModel && (+ <>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="model-hub-route-head-action"+ onClick={() => onManageModel?.("edit", draft)}+ >+ <Pencil aria-hidden="true" />+ {t("settings.models.routeDialog.editModel")}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ className="model-hub-route-head-action"+ onClick={() => onManageModel?.("remove", draft)}+ >+ <Trash2 aria-hidden="true" />+ {t("settings.models.routeDialog.removeModel")}+ </Button>+ </>+ )}+ <DialogPrimitive.Close+ ref={closeButtonRef}+ disabled={phase === "saving"}+ aria-label={+ t(+ phase === "guard"+ ? "settings.models.guard.cancel"+ : phase === "impact" || phase === "refreshing"+ ? "settings.models.routeDialog.impact.done"+ : "settings.models.routing.close",+ ) as string+ }+ className="model-hub-route-close grid shrink-0 place-items-center"+ >+ <X aria-hidden="true" />+ </DialogPrimitive.Close>+ </span></span><DialogPrimitive.Description className="model-hub-route-subtitle font-mono text-muted">{phase === "guard"@@ -1280,15 +1333,15 @@ export const RouteChainDialog: React.FC<{disabled={phase !== 'ready' || !valid.valid}onClick={() => setManualDraft(true)}><Pin aria-hidden />{t('settings.models.routing.pinRoute')}</Button>}- <Button+ {canDiscardDraft && <Buttonref={cancelButtonRef}type="button"variant="outline"className="model-hub-dialog-action"- onClick={canDiscardDraft ? cancelChanges : close}+ onClick={cancelChanges}>- {t(canDiscardDraft ? 'settings.models.routing.cancelChanges' : 'settings.models.routing.close')}- </Button>+ {t('settings.models.routing.cancelChanges')}+ </Button>}<Buttonref={saveButtonRef}type="button"diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 0ceaadf56..5c8a8d884 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -4,6 +4,7 @@ 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 { MemoryRouter } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';@@ -13,10 +14,20 @@ import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';import { MANAGE_COMMIT_ACTIONS } from './manage';import type { ModelsSurfaceKind } from './modelHubSurfaceState';import { ApiCallError, modelsApi } from './modelsApi';-import { SettingsModelsPage } from './SettingsModelsPage';+import { SettingsModelsPage as SettingsModelsRoute } from './SettingsModelsPage';import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type MigrationItem, type RuntimeDependency, type RuntimeManifest, type Source, type UsageSummary } from './types';+// The page navigates to Agents when the user clicks an Agent that needs+// attention, so it needs a router in scope. Every render site wants the same+// throwaway one — these tests assert on the page, not on where it routes — so+// the harness supplies it once instead of asking 23 call sites to remember.+const SettingsModelsPage = () => (+ <MemoryRouter>+ <SettingsModelsRoute />+ </MemoryRouter>+);+const directAgent = (backend: AgentBackend): AgentSupply => ({backend,cli_present: true,@@ -271,19 +282,15 @@ describe('SettingsModelsPage surface branches', () => {expect(apply).not.toHaveBeenCalled();});- it('keeps Direct mode and blocks migration when only unsupported native auth exists', async () => {+ it('switches straight to the gateway when only native auth it cannot carry exists', async () => {vi.spyOn(modelsApi, 'scanMigration').mockResolvedValue({ items: [blockedMigrationCandidate] });const setMode = vi.spyOn(modelsApi, 'setAgentMode').mockResolvedValue({ ...directAgent('claude'), mode: 'hub' });renderPage([], [directAgent('claude')]);await userEvent.click(await screen.findByRole('button', { name: /Switch to gateway|切换到模型网关/i }));- const dialog = await screen.findByRole('dialog');- expect(within(dialog).getByText(/Use the existing Add flow|现有的添加流程/)).toBeTruthy();- expect(- (within(dialog).getByRole('button', { name: /Start migration|开始迁移/i }) as HTMLButtonElement).disabled,- ).toBe(true);- expect(setMode).not.toHaveBeenCalled();+ await waitFor(() => expect(setMode).toHaveBeenCalledWith('claude', 'hub'));+ expect(screen.queryByRole('dialog')).toBeNull();});it('opens the same migration dialog from an existing Hub user entry', async () => {@@ -304,6 +311,47 @@ describe('SettingsModelsPage surface branches', () => {expect(apply).not.toHaveBeenCalled();});+ it.each([+ ['nothing at all', []],+ ['only native auth the Hub cannot carry', 'blocked'],+ ] as const)('offers no migrate entry when the scan finds %s', async (_, items) => {+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([]);+ const scan = vi.spyOn(modelsApi, 'scanMigration')+ .mockResolvedValue({ items: items === 'blocked' ? [blockedMigrationCandidate] : [] });+ renderPage([retainedSource], [{+ ...directAgent('claude'),+ mode: 'hub',+ sources: { order: [], eligibility: [] },+ }]);++ await waitFor(() => expect(scan).toHaveBeenCalled());+ // Settled, so the absence below is the answer rather than a scan in flight.+ await act(async () => { await scan.mock.results[0].value; });+ expect(screen.queryByRole('button', { name: /Migrate configuration|迁移配置/i })).toBeNull();+ });++ it('rescans on refresh so a native login made since the page opened can be migrated', async () => {+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([]);+ const hubClaude = { ...directAgent('claude'), mode: 'hub' as const, sources: { order: [], eligibility: [] } };+ vi.spyOn(modelsApi, 'refreshAgentPresence').mockResolvedValue([hubClaude]);+ const scan = vi.spyOn(modelsApi, 'scanMigration')+ .mockResolvedValueOnce({ items: [] })+ .mockResolvedValue({ items: [migrationCandidate] });+ renderPage([retainedSource], [{+ ...directAgent('claude'),+ mode: 'hub',+ sources: { order: [], eligibility: [] },+ }]);++ await waitFor(() => expect(scan).toHaveBeenCalledTimes(1));+ await act(async () => { await scan.mock.results[0].value; });+ expect(screen.queryByRole('button', { name: /Migrate configuration|迁移配置/i })).toBeNull();+ const refresh = screen.getByRole('button', { name: 'Detect Agent backends again' });+ await waitFor(() => expect(refresh).toHaveProperty('disabled', false));+ await userEvent.click(refresh);+ expect(await screen.findByRole('button', { name: /Migrate configuration|迁移配置/i })).toBeTruthy();+ });+it('installs and starts the runtime inline without an install confirmation dialog', async () => {const notInstalled = {...runtime,@@ -497,7 +545,7 @@ describe('SettingsModelsPage surface branches', () => {expect(await screen.findByText(/^Currently: direct$|^当前:直连$/i)).toBeTruthy();expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到模型网关$/i })).toHaveLength(3);- expect(screen.getByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,你会多出三件事$/i)).toBeTruthy();+ expect(screen.getByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,有三大益处$/i)).toBeTruthy();// Frame 09 is what the `sources` tab shows here — not what the Hub shows// instead of its tabs. It is still Frame 09's body: none of the gateway// overview leaks in beside it.@@ -754,7 +802,7 @@ describe('SettingsModelsPage surface branches', () => {expect(await screen.findByText('Retained source')).toBeTruthy();expect(screen.getAllByRole('tab')).toHaveLength(3);- expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,你会多出三件事$/i)).toBeNull();+ expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,有三大益处$/i)).toBeNull();});it('keeps manual-model draft Escape local to the provider dialog', async () => {@@ -1919,6 +1967,34 @@ describe('SettingsModelsPage surface branches', () => {}});+ it('MH-ROUTING-007 returns focus to the model row after a route-to-catalog handoff', async () => {+ const catalogModel: BackendModel = {+ id: 'gpt-5.6-sol', display_name: null, origin: 'manual', models_dev_id: null, context_window: null,+ max_output_tokens: null, input_modalities: ['text'], output_modalities: ['text'], supports_tools: true,+ supports_reasoning: false, reasoning_efforts: [], locked: false, routeable: true,+ };+ const agent = { ...takeoverAgent, catalog_models: [catalogModel] };+ vi.spyOn(modelsApi, 'getAgentChains').mockResolvedValue([takeoverChain]);+ vi.spyOn(modelsApi, 'getAgentChain').mockResolvedValue(takeoverChain);+ vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent);+ renderPage([+ { ...retainedSource, id: 'src_head', display_name: 'Paused source' },+ { ...retainedSource, id: 'src_relay', display_name: 'Replacement source' },+ ], [agent]);+ const opener = await screen.findByRole('button', { name: /Open gpt-5\.6-sol route chain|打开 gpt-5\.6-sol 的路由链/i });+ await userEvent.click(opener);+ await userEvent.click(await screen.findByRole('button', { name: /^Edit model$|^编辑模型$/i }));+ await waitFor(() => expect(document.querySelector('.model-hub-route-head')).toBeNull());+ // Edit opens the model editor over the catalog; leave both by keyboard.+ for (let open = 0; open < 3 && screen.queryAllByRole('dialog').length; open += 1) {+ await userEvent.keyboard('{Escape}');+ await flushRouteFocus();+ }+ await waitFor(() => expect(screen.queryAllByRole('dialog')).toHaveLength(0));+ await flushRouteFocus();+ expect(document.activeElement).toBe(opener);+ });+it('MH-ROUTING-007 keeps the previous retry fallback when another route opens', async () => {const { opener } = await saveRouteForFocusTest();const agentsRead = deferred<AgentSupply[]>();@@ -1936,7 +2012,7 @@ describe('SettingsModelsPage surface branches', () => {await screen.findAllByRole('button', { name: /^Remove hop$|^移除这个路由项$/i });await userEvent.click(screen.getAllByRole('button', { name: /^Close$|^关闭$/i })- .find((button) => button.classList.contains('model-hub-dialog-action'))!,+ .find((button) => button.classList.contains('model-hub-route-close'))!,);await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());await flushRouteFocus();@@ -1999,7 +2075,7 @@ describe('SettingsModelsPage surface branches', () => {expect(document.activeElement?.closest('[role="dialog"]')).toBeTruthy();await userEvent.click(within(screen.getByRole('dialog')).getAllByRole('button', { name: /^Close$/i })- .find((button) => button.classList.contains('model-hub-dialog-action'))!,+ .find((button) => button.classList.contains('model-hub-route-close'))!,);await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());await flushRouteFocus();diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 2d0b8bae3..de9aaab3e 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,6 +1,7 @@import * as React from 'react';import { ArrowDownToLine, Gauge, LoaderCircle, Power, RefreshCw, Route, ScrollText } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -11,7 +12,7 @@ import { useToast } from '@/context/ToastContext';import { cn } from '@/lib/utils';import { ToggleSwitch } from '../SettingsPrimitives';import { AddApiKeyDialog } from './AddApiKeyDialog';-import { BackendModelCatalogDialog } from './BackendModelCatalogDialog';+import { BackendModelCatalogDialog, type CatalogFocus } from './BackendModelCatalogDialog';import { OAuthConnectDialog } from './OAuthConnectDialog';import { GatewayModule } from './GatewayModule';import { MigrationDialog } from './MigrationDialog';@@ -65,6 +66,7 @@ import { freshRuntimeProjection, pollRuntimeStatus, resumeInstallAndStartRuntimeimport { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';import { handOffProviderTab } from './providerTab';import { resumeGatewayAdoption } from './gatewayAdoption';+import { groupMigrationCandidates } from './migrationGrouping';import { SUBSCRIPTION_MENU_ROWS, hasNativeSubscriptionCustody } from './subscriptionOptions';import { VendorGlyph } from './vendorGlyph';import { backendVisual } from './vendorMeta';@@ -344,6 +346,13 @@ const TakeoverPill: React.FC<{ count: number }> = ({ count }) => {export const SettingsModelsPage: React.FC = () => {const { t } = useTranslation();const { showToast } = useToast();+ const navigate = useNavigate();+ // An Agent named in the warning list is a destination, not a label: the page+ // that can fix it is Agents, and it has to open on the one that needs the fix.+ const openAgentDefinition = React.useCallback(+ (name: string) => navigate(`/agents?tab=definitions&agent=${encodeURIComponent(name)}`),+ [navigate],+ );/** The catalog's 「Add models」 action reads the candidates endpoint, which* names Sources — so it is offered on the same capability that lets a role* administer this instance's Agents, and read here rather than in the dialog@@ -363,6 +372,13 @@ export const SettingsModelsPage: React.FC = () => {const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);const [migrationOpen, setMigrationOpen] = React.useState(false);const [migrationBackend, setMigrationBackend] = React.useState<AgentBackend | null>(null);+ /** Whether the header's migrate entry has anything to open onto: the same+ * groups the dialog would list, so the button and the dialog cannot+ * disagree. `null` until a scan answers; a failed scan keeps the entry,+ * because the dialog is where that failure is explained. */+ const [migrationAvailable, setMigrationAvailable] = React.useState<boolean | null>(null);+ /** Bumped by the explicit refresh, so a native login made since is noticed. */+ const [migrationScanEpoch, setMigrationScanEpoch] = React.useState(0);const [apiKeyOpen, setApiKeyOpen] = React.useState(false);const [subscriptionPickerOpen, setSubscriptionPickerOpen] = React.useState(false);const [subscriptionPickerIndex, setSubscriptionPickerIndex] = React.useState(0);@@ -390,6 +406,10 @@ export const SettingsModelsPage: React.FC = () => {const sourceDetailReturnFocusRef = React.useRef<(() => HTMLElement | null) | null>(null);const [orderBackend, setOrderBackend] = React.useState<AgentBackend | null>(null);const [menuBackend, setMenuBackend] = React.useState<AgentBackend | null>(null);+ const [catalogFocus, setCatalogFocus] = React.useState<CatalogFocus | null>(null);+ // The route the catalog was opened from. Its action unmounted with the route+ // dialog, so closing the catalog returns focus to that model row instead.+ const catalogOriginRef = React.useRef<RouteTarget | null>(null);const [adoptAgent, setAdoptAgent] = React.useState<AgentSupply | null>(null);const [routeTarget, setRouteTarget] = React.useState<RouteTarget | null>(null);const pendingRouteOpenersRef = React.useRef(new Map<RouteReport, HTMLElement | null>());@@ -477,6 +497,20 @@ export const SettingsModelsPage: React.FC = () => {const runtimeConfigurationVisible = (runtimeRunning || (runtimeEnabled && runtimeHealth !== 'installing')) && !stoppingRuntime;+ React.useEffect(() => {+ // Re-asked whenever the dialog closes, since applying it is what empties+ // the scan.+ if (!runtimeConfigurationVisible || migrationOpen) return;+ let cancelled = false;+ modelsApi.scanMigration()+ .then((scan) => {+ if (!cancelled) setMigrationAvailable(groupMigrationCandidates(scan.items, () => true).length > 0);+ })+ .catch(() => {+ if (!cancelled) setMigrationAvailable(true);+ });+ return () => { cancelled = true; };+ }, [migrationOpen, migrationScanEpoch, runtimeConfigurationVisible]);React.useEffect(() => {const runtimeCanRecover = runtimeRead.kind === 'unread'|| (runtimeRead.kind === 'degraded' && runtimeRead.cause === 'read_failed')@@ -1349,7 +1383,7 @@ export const SettingsModelsPage: React.FC = () => {stopping={stoppingRuntime}directCount={directEmpty ? installedAgents.length : undefined}/>- {runtimeConfigurationVisible && (+ {runtimeConfigurationVisible && migrationAvailable === true && (<Buttontype="button"variant="outline"@@ -1370,7 +1404,7 @@ export const SettingsModelsPage: React.FC = () => {disabled={presenceRefreshing}aria-label={t('settings.models.direct.action.refreshAgents')}title={t('settings.models.direct.action.refreshAgents')}- onClick={() => void retrySupply()}+ onClick={() => { setMigrationScanEpoch((epoch) => epoch + 1); void retrySupply(); }}><RefreshCw aria-hidden className={cn('size-3.5', presenceRefreshing && 'animate-spin')} /></Button>}<span title={runtimeSwitchLabel}><ToggleSwitch@@ -1498,7 +1532,7 @@ export const SettingsModelsPage: React.FC = () => {</PopoverContent></Popover><div className="hidden xl:block" aria-hidden="true" />- <GatewayModule supply={installedSupplyRead} retryRef={supplyRetryRef} retryDisabled={routeCommitStatus?.pending === true} 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={switchToGateway} onSwitchDirect={switchToDirect} onOpenModels={(agent) => setMenuBackend(agent.backend)} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} />+ <GatewayModule supply={installedSupplyRead} retryRef={supplyRetryRef} retryDisabled={routeCommitStatus?.pending === true} 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={switchToGateway} onSwitchDirect={switchToDirect} onOpenModels={(agent) => { catalogOriginRef.current = null; setCatalogFocus(null); setMenuBackend(agent.backend); }} onOpenOrder={(agent) => setOrderBackend(agent.backend)} onOpenRoute={(agent, modelId, opener) => setRouteTarget({ agent, modelId, opener })} onProbeSettled={(agent) => void refreshAgentChains(agent)} onOpenAgent={openAgentDefinition} /><SupplyGraph containerRef={overviewRef} relations={supplyRelations} /></div><SupplyLegend relations={supplyRelations} />@@ -1574,7 +1608,17 @@ export const SettingsModelsPage: React.FC = () => {/>)}{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) }} />}- {menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} canReadSources={capabilities.can_manage_agents} sourceNames={sourceNames} onClose={() => setMenuBackend(null)} onSaved={catalogSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}+ {menuAgent && <BackendModelCatalogDialog open backend={menuAgent.backend} canReadSources={capabilities.can_manage_agents} sourceNames={sourceNames} focus={catalogFocus} onClose={(result) => {+ setMenuBackend(null);+ setCatalogFocus(null);+ const origin = catalogOriginRef.current;+ catalogOriginRef.current = null;+ if (!origin) return;+ // The route dialog handed its model over and comes back once the+ // catalog answers, unless the answer removed the model it was showing.+ if (result?.removed) focusRouteDestination(origin);+ else setRouteTarget(origin);+ }} onSaved={catalogSaved} onObserved={applyAgentEcho} catalogWrite={{ pending: agentWrites.has(menuAgent.backend), track: (work) => agentWriteRegistry.track(menuAgent.backend, work) }} />}<RouteChainDialogselection={routeSelection}covered={orderBackend !== null}@@ -1585,6 +1629,16 @@ export const SettingsModelsPage: React.FC = () => {setRouteTarget(null);if (target) focusRouteDestination(target);}}+ onManageModel={(action, route) => {+ // The catalog dialog is the one writer of the model list; the route+ // dialog steps aside while it edits or removes the model it was+ // showing, then reopens on that model.+ if (!routeTarget) return;+ catalogOriginRef.current = routeTarget;+ setRouteTarget(null);+ setCatalogFocus({ modelId: routeTarget.modelId, action, route });+ setMenuBackend(routeTarget.agent.backend);+ }}onCommitted={(result) => routeCommitted(result, routeTarget?.opener ?? null)}commitReconciliation={routeCommitReconciliation}onObserved={routeObserved}diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex 199655b7b..087a44aa1 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -34,9 +34,10 @@ export const SourcesCard: React.FC<{{ id: 'hub' as const, sources: (sources ?? []).filter((source) => source.supply_channel === 'hub') },].filter((group) => group.sources.length > 0);// The settings route pane owns vertical scrolling. This card grows with its- // sources so users never have to coordinate a second scroll area here.+ // sources so users never have to coordinate a second scroll area here; beside+ // the routes it sticks near the top so its wires stay readable.return (- <section className="relative z-20 flex w-full min-w-0 flex-col self-start overflow-hidden rounded-[14px] border border-border bg-surface">+ <section className="model-hub-upstream-card relative z-20 flex w-full min-w-0 flex-col self-start overflow-hidden rounded-[14px] border border-border bg-surface"><div className="flex h-14 shrink-0 items-center justify-between border-b border-border px-3.5"><span className="flex items-center gap-[7px]"><h2 className="text-[16px] font-bold leading-[23px] text-foreground">{t('settings.models.upstream.heading')}</h2>diff --git a/ui/src/components/settings/models/SupplyGraph.test.tsx b/ui/src/components/settings/models/SupplyGraph.test.tsxindex a64c97ae0..81c9bf625 100644--- a/ui/src/components/settings/models/SupplyGraph.test.tsx+++ b/ui/src/components/settings/models/SupplyGraph.test.tsx@@ -106,6 +106,31 @@ describe('SupplyGraph', () => {await waitFor(() => expect(path.getAttribute('d')).toContain('M 30 35'));});+ it('ignores scrolling elsewhere and measures once per frame', async () => {+ const bounds = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function measure(this: HTMLElement) {+ if (this.dataset.testid === 'graph-root') return rect(0, 0, 120, 100);+ if (this.dataset.sourceId === 'src_a') return rect(10, 10, 20, 10);+ if (this.dataset.agentBackend === 'claude') return rect(90, 40, 20, 20);+ return rect(0, 0, 0, 0);+ });+ const elsewhere = document.body.appendChild(document.createElement('div'));+ const view = render(<Fixture />);+ await waitFor(() => expect(view.container.querySelector('.model-hub-wire')).not.toBeNull());+ const settle = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ await settle();++ bounds.mockClear();+ fireEvent.scroll(elsewhere);+ await settle();+ expect(bounds).not.toHaveBeenCalled();++ const card = view.container.querySelector('[data-source-id="src_a"]') as Element;+ for (let index = 0; index < 5; index += 1) fireEvent.scroll(card);+ await settle();+ expect(bounds.mock.contexts.filter((element) => (element as HTMLElement).dataset.testid === 'graph-root')).toHaveLength(1);+ elsewhere.remove();+ });+it('lands every relation for an agent on the agent card midpoint', async () => {vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function bounds() {if (this.dataset.testid === 'graph-root') return rect(0, 0, 120, 100);diff --git a/ui/src/components/settings/models/SupplyGraph.tsx b/ui/src/components/settings/models/SupplyGraph.tsxindex 14c9853bd..19a189a62 100644--- a/ui/src/components/settings/models/SupplyGraph.tsx+++ b/ui/src/components/settings/models/SupplyGraph.tsx@@ -43,10 +43,21 @@ export const SupplyGraph: React.FC<{if (!container) return undefined;const measure = () => {const root = container.getBoundingClientRect();+ // Index each endpoint once per measurement, not once per relation.+ const sources = new Map<string, HTMLElement>();+ for (const element of container.querySelectorAll<HTMLElement>('[data-source-id]')) {+ const id = element.dataset.sourceId;+ if (id && !sources.has(id)) sources.set(id, element);+ }+ const backends = new Map<string, HTMLElement>();+ for (const element of container.querySelectorAll<HTMLElement>('[data-agent-backend]')) {+ const id = element.dataset.agentBackend;+ if (id && !backends.has(id)) backends.set(id, element);+ }const wires: DrawnRelation[] = [];for (const relation of relations) {- const source = Array.from(container.querySelectorAll<HTMLElement>('[data-source-id]')).find((element) => element.dataset.sourceId === relation.sourceId);- const backend = Array.from(container.querySelectorAll<HTMLElement>('[data-agent-backend]')).find((element) => element.dataset.agentBackend === relation.backend);+ const source = sources.get(relation.sourceId);+ const backend = backends.get(relation.backend);if (!source || !backend) continue;const sourceBounds = source.getBoundingClientRect();const backendBounds = backend.getBoundingClientRect();@@ -60,14 +71,33 @@ export const SupplyGraph: React.FC<{setDrawing({ width: root.width, height: root.height, wires });};measure();- const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure);+ // Scroll and resize bursts collapse into one measurement per frame.+ let frame: number | null = null;+ const schedule = () => {+ if (frame !== null) return;+ frame = requestAnimationFrame(() => {+ frame = null;+ measure();+ });+ };+ const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule);resize?.observe(container);- container.addEventListener('scroll', measure, true);- window.addEventListener('resize', measure);+ // The route pane scrolls outside this container; a sticky card moves then.+ // Only a scroller around or inside the graph can move an endpoint; a+ // dialog or panel elsewhere on the page cannot.+ const scroll = (event: Event) => {+ const target = event.target;+ if (target === document || (target instanceof Node && (target.contains(container) || container.contains(target)))) {+ schedule();+ }+ };+ window.addEventListener('scroll', scroll, true);+ window.addEventListener('resize', schedule);return () => {+ if (frame !== null) cancelAnimationFrame(frame);resize?.disconnect();- container.removeEventListener('scroll', measure, true);- window.removeEventListener('resize', measure);+ window.removeEventListener('scroll', scroll, true);+ window.removeEventListener('resize', schedule);};}, [containerRef, relations]);diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsindex 961d667ae..c478e56b5 100644--- a/ui/src/components/settings/models/gatewayAdoption.test.ts+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts@@ -52,7 +52,7 @@ describe('resumeGatewayAdoption', () => {expect(client.setAgentMode).not.toHaveBeenCalled();});- it('returns every detected native row for the selection dialog', async () => {+ it('returns only the carried native rows for the selection dialog', async () => {const client = api({scanMigration: vi.fn().mockResolvedValue({items: [@@ -65,12 +65,25 @@ describe('resumeGatewayAdoption', () => {await expect(adopt(client)).resolves.toMatchObject({ok: true,- candidates: [{ id: 'oauth' }, { id: 'keep' }],+ candidates: [{ id: 'oauth' }],});expect(client.applyMigration).not.toHaveBeenCalled();expect(client.setAgentMode).not.toHaveBeenCalled();});+ it('hands a standalone config blocker to the dialog instead of switching', async () => {+ const client = api({+ scanMigration: vi.fn().mockResolvedValue({+ items: [+ { id: 'broken', backend: 'claude', kind: 'api_key', masked_detail: '', proposed_action: 'reauth', selected: false, config_blocker: true },+ ],+ }),+ });++ await expect(adopt(client)).resolves.toMatchObject({ ok: true, candidates: [{ id: 'broken' }] });+ expect(client.setAgentMode).not.toHaveBeenCalled();+ });+it('starts an idle runtime before scanning the one backend', async () => {const client = api({ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('not_started')) });diff --git a/ui/src/components/settings/models/gatewayAdoption.ts b/ui/src/components/settings/models/gatewayAdoption.tsindex c4c2af5b1..f4107aa75 100644--- a/ui/src/components/settings/models/gatewayAdoption.ts+++ b/ui/src/components/settings/models/gatewayAdoption.ts@@ -1,3 +1,4 @@+import { isMigrationCandidate } from './migrationGrouping';import { apiFailure, type ModelsApi } from './modelsApi';import type { CollectionReadAuthority } from './collectionReadAuthority';import { resumeInstallAndStartRuntime } from './runtimeLifecycle';@@ -97,7 +98,9 @@ export async function resumeGatewayAdoption(try {const scan = await api.scanMigration();- const candidates = scan.items.filter((item) => item.backend === backend);+ // Rows the Hub cannot carry stay native and never hold the switch back; a+ // config blocker does, so the review opens and names the file to repair.+ const candidates = scan.items.filter((item) => item.backend === backend && isMigrationCandidate(item));return { ok: true, agent: current, runtime, candidates };} catch (error) {return {diff --git a/ui/src/components/settings/models/migrationGrouping.ts b/ui/src/components/settings/models/migrationGrouping.tsindex de1617ff4..ea0ef048b 100644--- a/ui/src/components/settings/models/migrationGrouping.ts+++ b/ui/src/components/settings/models/migrationGrouping.ts@@ -4,8 +4,9 @@// the same question the dialog asks — which backends may be taken over together,// and which rows a selection actually submits — without owning a second answer.// A group is the unit of consent, not a row: shared persisted assignments link-// backends into one custody boundary, and a single non-importable row inside a-// linked group blocks the whole group.+// backends into one custody boundary. Rows the Hub cannot carry are not shown at+// all — they stay native and never block their group — unless the backend's+// native config cannot be parsed at all.import type { TranslationKey } from '@/i18n/types';import type { AgentBackend, MigrationItem, MigrationScan } from './types';@@ -25,6 +26,12 @@ export const BACKEND_ORDER: AgentBackend[] = ['claude', 'codex', 'opencode'];export const isImportable = (item: MigrationItem) => item.proposed_action === 'import';+/**+ * A row the review has to show: one the Hub can carry, or a native config the+ * CLI cannot parse, which blocks its whole backend and must be repaired first.+ */+export const isMigrationCandidate = (item: MigrationItem) => isImportable(item) || item.config_blocker === true;+/*** The transitive closure of backends that share persisted assignments with any* of `backends`.@@ -80,9 +87,9 @@ export const scopedBackends = (* Two scopes, because an entry point asks two different questions. `eligible` says* which rows it was opened FROM: their backends, widened to their custody closures,* are what appears at all. `takeable` says which of the rows that appear it may- * actually take OVER — and a row in view that fails it blocks its group rather than- * being quietly left behind, because the server migrates a backend whole and refuses- * any batch that omits one of its rows. There is no half of a backend to take.+ * actually take OVER — and an importable row in view that fails it blocks its group+ * rather than being quietly left behind, because the server migrates every carried+ * credential of a backend together and refuses a batch that omits one.** Settings may take over everything the scan proposes importing, which is the* default and makes the second scope invisible there. Setup may not: it is scoped to@@ -94,16 +101,27 @@ export function groupMigrationCandidates(eligible: (item: MigrationItem) => boolean,takeable: (item: MigrationItem) => boolean = () => true,): MigrationGroup[] {- const scope = scopedBackends(items, eligible);- const candidates = items.filter((item) => scope.has(item.backend));+ // Only what the Hub can carry is a candidate. Everything else stays native,+ // shadowed by the Hub launch, so offering it would only show what cannot move,+ // except a config blocker, which holds its whole backend back.+ const carried = items.filter(isMigrationCandidate);+ const scope = scopedBackends(carried, eligible);+ const candidates = carried.filter((item) => scope.has(item.backend));const importableHere = (item: MigrationItem) => isImportable(item) && takeable(item);return BACKEND_ORDER.map((backend) => {const rows = candidates.filter((item) => item.backend === backend);const importRows = rows.filter(importableHere);- const required = requiredBackends(items, [backend]);+ const required = requiredBackends(carried, [backend]);const linkedRows = candidates.filter((item) => required.has(item.backend));const linkedImportRows = linkedRows.filter(importableHere);- const blockedRows = linkedRows.filter((item) => !importableHere(item));+ // A linked backend with nothing to carry can never join the batch, yet the+ // server still requires it: the shared credential it reads would be moved+ // out from under it. Its native rows explain why the group cannot move.+ const stranded = [...required].filter((linked) => !carried.some((item) => item.backend === linked));+ const blockedRows = [+ ...linkedRows.filter((item) => !importableHere(item)),+ ...items.filter((item) => stranded.includes(item.backend) && !isImportable(item)),+ ];return {backend,rows,@@ -111,7 +129,7 @@ export function groupMigrationCandidates(required,linkedImportRows,blockedRows,- blocked: blockedRows.length > 0,+ blocked: blockedRows.length > 0 || stranded.length > 0,};}).filter((group) => group.rows.length > 0);}diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex ba00a5ff7..eb5fc5ef7 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -545,6 +545,7 @@.model-hub-model-open:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }.model-hub-origin-help { width: 340px; max-width: calc(100vw - 32px); white-space: pre-line; font-size: 12px; line-height: 1.6; }.model-hub-route-origin-line { display: flex; gap: 12px; align-items: center; color: var(--muted); font-size: 12px; }+.model-hub-route-origin-now { flex-shrink: 0; margin-right: -4px; font-weight: 600; color: var(--foreground); }.model-hub-route-preview { display: flex; flex-direction: column; gap: 8px; padding: 16px; border-radius: 8px; background: var(--model-hub-mint-1a); color: var(--mint-ink); font-size: 12px; }.model-hub-route-preview[data-origin="passthrough"] { background: var(--model-hub-gold-1a); color: var(--gold-ink); }.model-hub-route-preview[data-origin="unconfigured"] { background: var(--model-hub-wash-08); color: var(--muted); }@@ -1035,6 +1036,8 @@box-shadow: var(--model-hub-dialog-shadow);}.model-hub-route-head { min-height: var(--model-hub-route-head-height); flex-shrink: 0; padding: 16px 20px; gap: 4px; border-color: var(--model-hub-wash-14); }+.model-hub-route-head-action { height: 26px; padding: 0 10px; font-size: 11.5px; }+.model-hub-route-head-action > svg { width: 13px; height: 13px; }.model-hub-route-close { width: 26px; height: 26px; margin: -5px -5px -5px 0; color: var(--model-hub-ink-59); }.model-hub-route-close > svg { width: 15px; height: 15px; }.model-hub-route-title {@@ -2224,6 +2227,12 @@gap: var(--model-hub-track-gap);align-items: start;}+ /* Beside the routes, providers stay in view while the Agent column scrolls,+ so every wire keeps both of its ends on screen. */+ .model-hub-upstream-card {+ position: sticky;+ top: 16px;+ }}.model-hub-wire {diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 5d342cbb0..9d83e413b 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -130,6 +130,7 @@ export type ModelsApi = {/** Resolution chain for one model. Hub mode only — direct answers `direct_mode`. */getAgentChain(backend: AgentBackend, model: string): Promise<AgentChain>;getAgentProvenance(backend: AgentBackend, model: string): Promise<TurnProvenance | null>;+ getTurnProvenance(turnId: string): Promise<TurnProvenance>;/** Complete overview chain projection for one Hub backend. */getAgentChains(backend: AgentBackend): Promise<AgentChain[]>;/** Total replacement of the exact stored chain. */@@ -605,6 +606,7 @@ export const modelsApi: ModelsApi = {jsonInit('POST', order === undefined ? undefined : { order }),).then((r) => r.agent),getAgentChain: (backend, model) => call<{ chain: AgentChain }>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`).then((r) => r.chain),+ getTurnProvenance: (turnId) => call<{ provenance: TurnProvenance }>(`/api/models/turns/${encodeURIComponent(turnId)}/provenance`).then((r) => r.provenance),getAgentProvenance: (backend, model) => call<{ provenance: TurnProvenance | null }>(`/api/models/agents/${backend}/provenance?model=${encodeURIComponent(model)}`).then((r) => r.provenance),getAgentChains: (backend) => call<{ chains: AgentChain[] }>(`/api/models/agents/${backend}/chains`).then((r) => r.chains),putAgentChain: (backend, model, body) => call<AgentChainMutation>(`/api/models/agents/${backend}/chain?model=${encodeURIComponent(model)}`, jsonInit('PUT', body)),diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.tsindex 5db7fd166..d64372522 100644--- a/ui/src/components/settings/models/repair.test.ts+++ b/ui/src/components/settings/models/repair.test.ts@@ -300,7 +300,6 @@ describe('the copy each remedy names', () => {'settings.models.guard.confirm.replaceKey','settings.models.guard.result.label','settings.models.guard.result.gapLabel',- 'settings.models.guard.result.hint.safe','settings.models.guard.result.hint.interrupt',])('has replacement guard copy in both locales for %s', (key) => {for (const bundle of [en, zh]) expect(typeof translated(bundle, key)).toBe('string');diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.tsindex ee08c922e..e4729f3df 100644--- a/ui/src/components/settings/models/serverCopy.test.ts+++ b/ui/src/components/settings/models/serverCopy.test.ts@@ -12,11 +12,13 @@ import { describe, expect, it } from 'vitest';import en from '../../../i18n/en.json';import zh from '../../../i18n/zh.json';import {+ callbackValueCarriesResult,catalogSaveFailureKey,modelsDevFillFailureKey,NATIVE_LOGIN_IN_PROGRESS_FAILURE,NATIVE_SUBSCRIPTION_EXISTS_FAILURE,oauthFailureKey,+ PASTE_REJECTED_KEY,oauthStartFailureKey,serverText,TIER_EDIT_MANAGED_FAILURE,@@ -173,6 +175,7 @@ describe('catalogSaveFailureKey', () => {['backend_model_id_invalid', 'saveIdInvalid'],['backend_model_duplicate', 'saveDuplicate'],['backend_model_locked', 'saveLocked'],+ ['backend_model_origin_immutable', 'saveOriginImmutable'],['backend_model_catalog_invalid', 'saveInvalid'],] as const;@@ -290,3 +293,24 @@ describe('modelsDevFillFailureKey', () => {}});});++describe('pasted OAuth callback value', () => {+ it('accepts an address that carries the provider answer, or a bare code', () => {+ expect(callbackValueCarriesResult('http://localhost:1455/auth/callback?code=abc&state=s')).toBe(true);+ expect(callbackValueCarriesResult('http://localhost:1455/auth/callback?error=access_denied')).toBe(true);+ expect(callbackValueCarriesResult(' abc#state ')).toBe(true);+ });++ it('refuses a page address that carries no answer', () => {+ expect(callbackValueCarriesResult('https://chatgpt.com/')).toBe(false);+ expect(callbackValueCarriesResult('https://auth.openai.com/log-in')).toBe(false);+ expect(callbackValueCarriesResult('http://localhost:1455/success?id_token=x')).toBe(false);+ expect(callbackValueCarriesResult('http://[broken')).toBe(false);+ });++ it('explains the refusal in both bundles', () => {+ for (const lng of ['en', 'zh'] as const) {+ expect(t(lng)(PASTE_REJECTED_KEY)).not.toBe(PASTE_REJECTED_KEY);+ }+ });+});diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.tsindex b84821a61..306f89152 100644--- a/ui/src/components/settings/models/serverCopy.ts+++ b/ui/src/components/settings/models/serverCopy.ts@@ -90,6 +90,31 @@ export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney): 'settings.models.oauth.error.finalize': 'settings.models.oauth.error.generic';+/**+ * The provider refused a pasted value without touching the flow (api.md+ * `submission_rejected`). Not a failure of the flow: it is still waiting, so the+ * dialog keeps the input and says what to paste instead.+ */+export const SUBMISSION_REJECTED_FAILURE = 'submission_rejected';+export const PASTE_REJECTED_KEY: TranslationKey = 'settings.models.oauth.callback.rejected';++/**+ * Whether a pasted callback address carries the provider's answer. The engine+ * reads `code` (or `error`) off the address and refuses anything without one, so+ * a page address copied from the provider's own site — the usual mistake — is+ * caught here before it costs a round trip. A bare value is sent as a code.+ */+export const callbackValueCarriesResult = (value: string): boolean => {+ const trimmed = value.trim();+ if (!/^https?:\/\//i.test(trimmed)) return trimmed.length > 0;+ try {+ const params = new URL(trimmed).searchParams;+ return Boolean(params.get('code')?.trim() || params.get('error')?.trim() || params.get('error_description')?.trim());+ } catch {+ return false;+ }+};+/** Start-route failures have not reached provider authorization yet. */export const NATIVE_SUBSCRIPTION_EXISTS_FAILURE = 'modelHub.errors.native_subscription_exists';export const NATIVE_LOGIN_IN_PROGRESS_FAILURE = 'modelHub.errors.native_login_in_progress';@@ -122,6 +147,8 @@ const CATALOG_SAVE_FAILURE_COPY: Readonly<Record<string, TranslationKey>> = {'modelHub.errors.backend_model_id_invalid': 'settings.models.gateway.catalog.saveIdInvalid','modelHub.errors.backend_model_duplicate': 'settings.models.gateway.catalog.saveDuplicate','modelHub.errors.backend_model_locked': 'settings.models.gateway.catalog.saveLocked',+ 'modelHub.errors.backend_model_origin_immutable':+ 'settings.models.gateway.catalog.saveOriginImmutable','modelHub.errors.backend_model_catalog_invalid': 'settings.models.gateway.catalog.saveInvalid',};diff --git a/ui/src/components/settings/models/subscriptionOptions.ts b/ui/src/components/settings/models/subscriptionOptions.tsindex 01187e2e3..56200fe0a 100644--- a/ui/src/components/settings/models/subscriptionOptions.ts+++ b/ui/src/components/settings/models/subscriptionOptions.ts@@ -77,10 +77,15 @@ export const recommendedSubscriptionChannel = (vendor: string): SupplyChannel =>export const initialSubscriptionChannel = (vendor: string, sources: Source[]): SupplyChannel =>nativeSubscriptionSlotTaken(vendor, sources) ? 'hub' : recommendedSubscriptionChannel(vendor);+/** The channels the chooser offers, recommended first. A ChatGPT subscription is+ * offered to the gateway only: Codex signing in natively is still honoured when it+ * is already there (detection, reauth), it is just no longer a choice to make. */export const subscriptionOptionOrder = (vendor: string): SupplyChannel[] =>- recommendedSubscriptionChannel(vendor) === 'hub'- ? ['hub', 'native_cli']- : ['native_cli', 'hub'];+ vendor === 'openai'+ ? ['hub']+ : recommendedSubscriptionChannel(vendor) === 'hub'+ ? ['hub', 'native_cli']+ : ['native_cli', 'hub'];/** Which channel the menu recommends, or `null` when the vendor has no native* channel to recommend against. A hub-held row carries no badge: 网关推荐 over thediff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 91010e49f..910978003 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -468,6 +468,9 @@ export type MigrationItem = {/** Server-computed transitive closure of backends sharing persisted shell* assignments. They must migrate together. Missing/empty means this backend. */required_backends?: AgentBackend[];+ /** The backend's native config cannot be parsed, so Hub mode would fail every+ * launch: the row blocks its whole consent group. Optional for older servers. */+ config_blocker?: boolean;};export type MigrationScan = { items: MigrationItem[] };@@ -593,7 +596,7 @@ export type TurnProvenance = {agent: AgentBackend;requested_model_id: string;outcome: 'served' | 'exhausted' | 'failed_terminal' | 'no_candidate' | 'canceled';- failed_attempts: Array<RecordedAttempt & { reason: ResolutionReason }>;+ failed_attempts: Array<RecordedAttempt & { reason: ResolutionReason; http_status?: number | null }>;served: RecordedAttempt | null;canceled_attempt: RecordedAttempt | null;terminal_error: {diff --git a/ui/src/components/settings/oauth/OAuthFlowParts.tsx b/ui/src/components/settings/oauth/OAuthFlowParts.tsxindex cef0c01c5..b63f79bb9 100644--- a/ui/src/components/settings/oauth/OAuthFlowParts.tsx+++ b/ui/src/components/settings/oauth/OAuthFlowParts.tsx@@ -4,23 +4,18 @@// rows instead of forking near-duplicate markup (reuse ladder: promote the// repeated pattern to a shared home).//-// These are presentation-only and i18n-agnostic: callers pass already--// translated strings and own the copy handler (which is where the defensive-// stopPropagation for the iOS radio-bounce bug lives — see BackendOAuthPanel).+// Copying is not one of those caller concerns: every caller wanted the same+// clipboard call, the same stopPropagation, and the same confirmation, so the+// row hands the value to the shared `CopyButton` and no caller owns a handler.import * as React from 'react';-import { Copy, ExternalLink } from 'lucide-react';+import { ExternalLink } from 'lucide-react';import { Button } from '@/components/ui/button';+import { CopyButton } from '@/components/ui/copy-button';import { Input } from '@/components/ui/input';-type CopyProps = {- /** Receives the click event so the caller can stop propagation. */- onCopy: (e: React.MouseEvent) => void;- copyLabel: string;-};-/** Auth URL as a cyan link chip + a copy button (remote/phone operation). */-export const OAuthLinkRow: React.FC<{ url: string } & CopyProps> = ({ url, onCopy, copyLabel }) => (+export const OAuthLinkRow: React.FC<{ url: string }> = ({ url }) => (<div className="flex flex-wrap items-center gap-2"><ahref={url}@@ -31,23 +26,17 @@ export const OAuthLinkRow: React.FC<{ url: string } & CopyProps> = ({ url, onCop<ExternalLink className="size-3 shrink-0" /><span className="break-all">{url}</span></a>- <Button type="button" variant="secondary" size="xs" onClick={onCopy}>- <Copy className="size-3" />- {copyLabel}- </Button>+ <CopyButton value={url} /></div>);/** Device code as a spaced mono chip + a copy button. */-export const OAuthDeviceCodeRow: React.FC<{ code: string } & CopyProps> = ({ code, onCopy, copyLabel }) => (+export const OAuthDeviceCodeRow: React.FC<{ code: string }> = ({ code }) => (<div className="flex flex-wrap items-center gap-2"><code className="rounded-md bg-cyan-soft/40 px-2.5 py-1 font-mono text-[14px] font-semibold tracking-[0.18em] text-cyan-ink">{code}</code>- <Button type="button" variant="secondary" size="xs" onClick={onCopy}>- <Copy className="size-3" />- {copyLabel}- </Button>+ <CopyButton value={code} /></div>);@@ -61,27 +50,41 @@ export const OAuthSubmitRow: React.FC<{placeholder?: string;submitLabel: string;submittingLabel: string;-}> = ({ id, value, onChange, onSubmit, submitting, placeholder, submitLabel, submittingLabel }) => (- <div className="flex gap-2">- <Input- id={id}- type="text"- autoComplete="off"- spellCheck={false}- placeholder={placeholder}- value={value}- onChange={(e) => onChange(e.target.value)}- className="font-mono"- disabled={submitting}- />- <Button- type="button"- variant="brand"- size="sm"- onClick={onSubmit}- disabled={submitting || !value.trim()}- >- {submitting ? submittingLabel : submitLabel}- </Button>- </div>-);+ /** Why the last submission was refused; the value stays editable for another try. */+ error?: string;+}> = ({ id, value, onChange, onSubmit, submitting, placeholder, submitLabel, submittingLabel, error }) => {+ const errorId = React.useId();+ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex gap-2">+ <Input+ id={id}+ type="text"+ autoComplete="off"+ spellCheck={false}+ placeholder={placeholder}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ className="font-mono"+ disabled={submitting}+ aria-invalid={error ? true : undefined}+ aria-describedby={error ? errorId : undefined}+ />+ <Button+ type="button"+ variant="brand"+ size="sm"+ onClick={onSubmit}+ disabled={submitting || !value.trim()}+ >+ {submitting ? submittingLabel : submitLabel}+ </Button>+ </div>+ {error && (+ <p id={errorId} role="alert" className="text-[12px] leading-relaxed text-destructive-ink">+ {error}+ </p>+ )}+ </div>+ );+};diff --git a/ui/src/components/settings/oauth/useBackendOAuth.ts b/ui/src/components/settings/oauth/useBackendOAuth.tsindex d83e9c077..3dd866b50 100644--- a/ui/src/components/settings/oauth/useBackendOAuth.ts+++ b/ui/src/components/settings/oauth/useBackendOAuth.ts@@ -225,14 +225,7 @@ export function useBackendOAuth({ backend, opencodeProviderId, onSuccess, onFailif (current(generation)) { owner.current.submitting = false; setSubmitting(false); }}};- const copy = async (text: string | null, event?: React.MouseEvent) => {- event?.preventDefault(); event?.stopPropagation();- if (!text) return;- try { await navigator.clipboard.writeText(text); showToast(t('common.copied'), 'success'); }- catch { showToast(t('common.copyFailed'), 'error'); }- };const isActive = state === 'starting' || state === 'awaiting_code' || state === 'verifying';return { state, url, deviceCode, callbackKind, code, setCode, submitting, starting, error, setError, hubOwnedAuth,- isActive, startFlow, cancelFlow, submitCallback, resetToIdle,- copyUrl: (e?: React.MouseEvent) => copy(url, e), copyDeviceCode: (e?: React.MouseEvent) => copy(deviceCode, e) };+ isActive, startFlow, cancelFlow, submitCallback, resetToIdle };}diff --git a/ui/src/components/settings/providers/BackendConnectionForm.tsx b/ui/src/components/settings/providers/BackendConnectionForm.tsxindex 1b88cb65c..14405b289 100644--- a/ui/src/components/settings/providers/BackendConnectionForm.tsx+++ b/ui/src/components/settings/providers/BackendConnectionForm.tsx@@ -474,8 +474,8 @@ export function BackendConnectionForm({ backend, provider, initialMethod = 'oaut{signedIn && <p className="connection-confirmed">{t('onboarding.connection.savedSubscription')}</p>}<div><Button variant="brand" onClick={() => void oauth.startFlow()} disabled={oauth.starting}><ExternalLink size={15} />{startLabel}</Button></div></div> : <div className="connection-auth-steps">- {oauth.deviceCode && <><Label>{t('onboarding.connection.copyDevice')}</Label><OAuthDeviceCodeRow code={oauth.deviceCode} onCopy={(event) => void oauth.copyDeviceCode(event)} copyLabel={t('common.copy')} /></>}- {oauth.url && <><Label>{t(oauth.deviceCode ? 'onboarding.connection.openDevice' : 'onboarding.connection.authorizeBrowser')}</Label><OAuthLinkRow url={oauth.url} onCopy={(event) => void oauth.copyUrl(event)} copyLabel={t('common.copy')} /></>}+ {oauth.deviceCode && <><Label>{t('onboarding.connection.copyDevice')}</Label><OAuthDeviceCodeRow code={oauth.deviceCode} /></>}+ {oauth.url && <><Label>{t(oauth.deviceCode ? 'onboarding.connection.openDevice' : 'onboarding.connection.authorizeBrowser')}</Label><OAuthLinkRow url={oauth.url} /></>}{oauth.deviceCode && oauth.url && <div><Button variant="brand" asChild><a href={oauth.url} target="_blank" rel="noopener noreferrer"><ExternalLink size={15} />{t(backend === 'codex' ? 'onboarding.connection.openChatGPT' : 'onboarding.connection.openProvider')}</a></Button></div>}{needsCode && <div className="connection-field"><Label htmlFor="connection-code">{t(backend === 'claude' ? 'settings.backends.claudeCallbackCodeLabel' : oauth.callbackKind === 'code' ? 'onboarding.connection.manualCode' : 'settings.backends.opencodeCallbackUrlLabel')}</Label><Input id="connection-code" value={oauth.code} onChange={(event) => oauth.setCode(event.target.value)} disabled={oauth.submitting} placeholder={backend === 'claude' ? 'code#state' : oauth.callbackKind === 'code' ? t('onboarding.connection.manualCodePlaceholder') : 'http://127.0.0.1:…/callback?code=…'} autoComplete="off" />diff --git a/ui/src/components/ui/button-variants.ts b/ui/src/components/ui/button-variants.tsindex 5f080126b..5121ff4ed 100644--- a/ui/src/components/ui/button-variants.ts+++ b/ui/src/components/ui/button-variants.ts@@ -74,6 +74,8 @@ export const buttonVariants = cva(accent: 'gap-1.5 border border-cyan/40 bg-cyan-soft text-cyan-ink hover:bg-cyan/15',},size: {+ // h-6 inline chips beside a chat notice (failure retry).+ '2xs': 'h-6 rounded-md px-2 text-[11px] [&_svg]:size-3',// h-8 toolbar buttons (LogsPanel/DoctorPanel/SettingsServicePage/AgentDetection toolbar).xs: 'h-8 px-3 text-[12px] [&_svg]:size-3.5',// h-9 config-inline CTAs (Slack/Discord/Telegram/...).diff --git a/ui/src/components/ui/copy-button.tsx b/ui/src/components/ui/copy-button.tsxnew file mode 100644index 000000000..f8ce81d39--- /dev/null+++ b/ui/src/components/ui/copy-button.tsx@@ -0,0 +1,72 @@+// The app's one copy control. It owns the clipboard call — including the+// non-secure-context fallback in `copyTextToClipboard`, which a raw+// `navigator.clipboard.writeText` call site silently lacks — and its own+// confirmation, so no caller has to re-derive either (reuse ladder: promote the+// repeated pattern to a shared home).+//+// Confirmation is inline rather than a toast on purpose: this button is used+// inside modal dialogs, where a toast is neither where the user is looking nor+// reliably above the overlay. Failure still raises a toast, because+// "copy it manually" is an instruction the button has no room for.+import * as React from 'react';+import { Check, Copy } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button, type ButtonProps } from '@/components/ui/button';+import { useToast } from '@/context/ToastContext';+import { cn, copyTextToClipboard } from '@/lib/utils';++const CONFIRMATION_MS = 1600;++export type CopyButtonProps = Omit<ButtonProps, 'children' | 'onClick' | 'value'> & {+ /** Text placed on the clipboard. */+ value: string;+ /** Visible label at rest. Defaults to `common.copy`; pass `null` for icon-only. */+ label?: string | null;+};++export const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(+ ({ value, label, className, variant = 'secondary', size = 'xs', type = 'button', ...props }, ref) => {+ const { t } = useTranslation();+ const { showToast } = useToast();+ const [copied, setCopied] = React.useState(false);+ const timerRef = React.useRef<number | null>(null);+ React.useEffect(() => () => {+ if (timerRef.current !== null) window.clearTimeout(timerRef.current);+ }, []);+ const restLabel = label === undefined ? (t('common.copy') as string) : label;+ const copiedLabel = t('common.copied') as string;+ const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {+ // A copy control often sits inside a row or label that reacts to clicks+ // (the iOS radio-bounce in the backend OAuth panel); copying must not also+ // pick that row.+ event.preventDefault();+ event.stopPropagation();+ void copyTextToClipboard(value).then((ok) => {+ if (!ok) {+ showToast(t('common.copyFailed') as string, 'error');+ return;+ }+ setCopied(true);+ if (timerRef.current !== null) window.clearTimeout(timerRef.current);+ timerRef.current = window.setTimeout(() => setCopied(false), CONFIRMATION_MS);+ });+ };+ return (+ <Button+ ref={ref}+ type={type}+ variant={variant}+ size={size}+ className={cn(copied && 'text-mint-ink', className)}+ aria-label={restLabel === null ? (t('common.copy') as string) : undefined}+ onClick={handleClick}+ {...props}+ >+ {copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}+ {restLabel !== null && (copied ? copiedLabel : restLabel)}+ </Button>+ );+ },+);+CopyButton.displayName = 'CopyButton';diff --git a/ui/src/components/workbench/AgentsPage.test.tsx b/ui/src/components/workbench/AgentsPage.test.tsxindex 9785f3112..c45b5f6d0 100644--- a/ui/src/components/workbench/AgentsPage.test.tsx+++ b/ui/src/components/workbench/AgentsPage.test.tsx@@ -152,12 +152,14 @@ function renderPage(instanceRole = 'owner' as InstanceRole,canManageAgents = false,capabilities,+ entry = '/agents',}: {remote?: boolean;instanceKind?: 'organization' | 'personal' | null;instanceRole?: InstanceRole;canManageAgents?: boolean;capabilities?: InstanceCapabilities;+ entry?: string;} = {},) {apiRef.current = api;@@ -166,7 +168,7 @@ function renderPage(<InstanceAuthorizationContext.Providervalue={{ remote, instanceKind, instanceRole, capabilities: effectiveCapabilities }}>- <MemoryRouter initialEntries={['/agents']}>+ <MemoryRouter initialEntries={[entry]}><AgentsPage /></MemoryRouter></InstanceAuthorizationContext.Provider>,@@ -214,6 +216,34 @@ describe('AgentsPage load requests follow the rank that can serve them', () => {});});+describe('AgentsPage contextual selection', () => {+ it('opens the Agent named by ?agent= instead of the default one', async () => {+ const agentA = brief('agent-a', 'A');+ const agentB = brief('agent-b', 'B');+ const getVibeAgent = vi.fn().mockImplementation((name: string) =>+ Promise.resolve(fullAgent(name === 'agent-b' ? agentB : agentA, `${name} loaded`)));+ const api = makeApi(vi.fn().mockResolvedValue(listResult([agentA, agentB])), getVibeAgent);+ const view = renderPage(api, { entry: '/agents?agent=agent-b' });++ await waitFor(() => expect(screen.getByDisplayValue('B')).toBeTruthy());+ // The default selection never runs: a read for `agent-a` would be spent on+ // a panel the param immediately replaces.+ expect(getVibeAgent.mock.calls.map(([name]) => name)).toEqual(['agent-b']);+ view.unmount();+ });++ it('leaves the default selection alone when ?agent= names an Agent the list does not have', async () => {+ const agentA = brief('agent-a', 'A');+ const getVibeAgent = vi.fn().mockResolvedValue(fullAgent(agentA, 'A loaded'));+ const api = makeApi(vi.fn().mockResolvedValue(listResult([agentA])), getVibeAgent);+ const view = renderPage(api, { entry: '/agents?agent=agent-gone' });++ await waitFor(() => expect(screen.getByDisplayValue('A')).toBeTruthy());+ expect(getVibeAgent.mock.calls.map(([name]) => name)).toEqual(['agent-a']);+ view.unmount();+ });+});+describe('Organization access summary presentation', () => {it('renders the summary as a self-contained card', async () => {const listVibeAgents = vi.fn().mockResolvedValue(listResult(brief('claude', '')));diff --git a/ui/src/components/workbench/AgentsPage.tsx b/ui/src/components/workbench/AgentsPage.tsxindex 5d6af20eb..907e00469 100644--- a/ui/src/components/workbench/AgentsPage.tsx+++ b/ui/src/components/workbench/AgentsPage.tsx@@ -280,6 +280,10 @@ export const AgentsPage: React.FC = () => {// NOT written back to the memory.const [searchParams] = useSearchParams();const tabParam = searchParams.get('tab');+ // ``?agent=`` names the Agent a contextual caller wants open (Model Hub's+ // "Agent needs attention" list). Like ``?tab=`` it is a destination rather+ // than a remembered choice, so it wins over the default auto-selection.+ const agentParam = searchParams.get('agent');const [agentsTab, setAgentsTab] = useState<AgentsTabKey>(() => resolveAgentsTab(tabParam));// One-way URL -> state, keyed on the param so a later user tab click isn't// yanked back: both a contextual link arriving while this page is already@@ -1120,10 +1124,15 @@ export const AgentsPage: React.FC = () => {agents.length === 0) return;const available = agents.filter((agent) => !coordinator.retired.has(agent.name));+ // A contextual caller's ``?agent=`` is an explicit destination; the default+ // is only a fallback for an empty detail panel, so it must not spend a read+ // on an Agent the param is about to supersede.+ if (agentParam && available.some((agent) => agent.name === agentParam)) return;const target = (defaultName && available.find((a) => a.name === defaultName)) || available[0];if (target) void selectAgent(target.name, false, true);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [defaultName, agents]);+ }, [defaultName, agents, agentParam]);+// If the selection clears (agent deleted, or a refresh dropped it) drop the// mobile drill state too — otherwise the list stays max-lg:hidden with no@@ -1246,6 +1255,21 @@ export const AgentsPage: React.FC = () => {[beginSelectedIntent, clearResourceError],);+ // Applied once per value: the list arrives after mount, so this waits for the+ // named Agent to exist rather than sending a read for a name the page cannot+ // show — and a later user pick is not yanked back to the param.+ const appliedAgentParamRef = useRef<string | null>(null);+ useEffect(() => {+ if (!agentParam) {+ appliedAgentParamRef.current = null;+ return;+ }+ if (appliedAgentParamRef.current === agentParam) return;+ if (!agents.some((agent) => agent.name === agentParam)) return;+ appliedAgentParamRef.current = agentParam;+ void selectAgent(agentParam, true);+ }, [agentParam, agents, selectAgent]);+const dismissSelected = useCallback(() => {const coordinator = selectedCoordinatorRef.current;beginSelectedIntent(null);diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex fe76448ac..232f707f6 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -60,6 +60,7 @@ import {vaultCallbackStatusKey,} from '../../lib/chatTrigger';import { AnnotationMessage } from './AnnotationMessage';+import { FailureDetails } from './FailureDetails';import { FailureRetry } from './FailureRetry';import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';import { RoleAvatar } from './RoleAvatar';@@ -4860,14 +4861,17 @@ export const MessageRow = memo(function MessageRow({<div className="group/message flex max-w-[min(92%,860px)] flex-col items-start gap-1"><div className="inline-flex w-fit max-w-full items-start gap-1.5 rounded-2xl rounded-tl-md border border-gold/30 bg-gold/[0.08] px-3 py-1.5 text-[12px] text-gold-ink"><Bell className="mt-px size-3 shrink-0" />- <span className="min-w-0 break-words">- <span className="font-semibold">{t(isVaultNotification ? 'chat.source.vault' : 'chat.notifyLabel')}</span>- {vaultStatusKey && (- <span className="font-normal text-gold-ink/80"> · {t(vaultStatusKey)}</span>- )}- {resultPresentation.body && (- <span className="font-normal text-gold-ink/80"> · {resultPresentation.body}</span>- )}+ <span className="flex min-w-0 flex-col">+ <span className="min-w-0 break-words">+ <span className="font-semibold">{t(isVaultNotification ? 'chat.source.vault' : 'chat.notifyLabel')}</span>+ {vaultStatusKey && (+ <span className="font-normal text-gold-ink/80"> · {t(vaultStatusKey)}</span>+ )}+ {resultPresentation.body && (+ <span className="font-normal text-gold-ink/80"> · {resultPresentation.body}</span>+ )}+ </span>+ <FailureDetails message={message} /></span></div>{onFailureRetry && (diff --git a/ui/src/components/workbench/FailureDetails.test.tsx b/ui/src/components/workbench/FailureDetails.test.tsxnew file mode 100644index 000000000..9e3171d9b--- /dev/null+++ b/ui/src/components/workbench/FailureDetails.test.tsx@@ -0,0 +1,154 @@+/** @vitest-environment jsdom */+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createInstance } from 'i18next';+import { I18nextProvider, initReactI18next } from 'react-i18next';++import type { WorkbenchMessage } from '../../context/ApiContext';+import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';+import { ToastProvider } from '../../context/ToastProvider';+import { DENIED_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';+import zh from '../../i18n/zh.json';+import { ApiCallError, modelsApi } from '../settings/models/modelsApi';+import type { TurnProvenance } from '../settings/models/types';+import { FailureDetails } from './FailureDetails';+import { resetFailureDetailsCache } from './failureDetailsReads';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'zh', resources: { zh: { translation: zh } }, interpolation: { escapeValue: false },+});+const notice = {+ id: 'notice', session_id: 'session', type: 'notify', author: 'agent', source: 'agent',+ text: '模型连接中断', content: {},+ metadata: { event: 'backend_failure', failure_id: 'failed', turn_id: 'turn-1' },+} as WorkbenchMessage;++const record = {+ contract_version: 1,+ turn_id: 'turn-1',+ ts: '2026-09-23T08:00:00Z',+ agent: 'opencode',+ requested_model_id: 'grok-4.6',+ outcome: 'failed_terminal',+ failed_attempts: [+ { source_id: 'src_a', configured_model_id: 'grok-4.6', channel: 'hub', reason: 'rate_limited', http_status: 429 },+ ],+ served: null,+ canceled_attempt: null,+ terminal_error: {+ source_id: 'src_b', configured_model_id: 'grok-4.6-beta', channel: 'hub',+ reason: 'invalid_parameter', stream_started: false, http_status: 400, upstream_error_code: 'model_not_found',+ },+ model_supply_state: null,+ blockers: [{ source_id: 'src_c', model_id: 'grok-4.6', reason: 'source_missing' }],+} as unknown as TurnProvenance;++beforeEach(() => {+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([{ id: 'src_a', display_name: 'xAI 官方' }] as never);+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); resetFailureDetailsCache(); });++function mount(message: WorkbenchMessage | WorkbenchMessage[] = notice, canManage = true) {+ const authorization = {+ remote: true, instanceKind: null, instanceRole: null,+ capabilities: { ...DENIED_INSTANCE_CAPABILITIES, can_chat: true, can_manage_instance: canManage },+ };+ const messages = Array.isArray(message) ? message : [message];+ render(+ <I18nextProvider i18n={i18n}><ToastProvider>+ <InstanceAuthorizationContext.Provider value={authorization}>+ {messages.map((item) => <FailureDetails key={item.id} message={item} />)}+ </InstanceAuthorizationContext.Provider>+ </ToastProvider></I18nextProvider>,+ );+}++describe('failed-turn upstream details', () => {+ it('stays hidden for a notice that is not a linked backend failure', () => {+ const read = vi.spyOn(modelsApi, 'getTurnProvenance');+ mount({ ...notice, metadata: { event: 'backend_failure' } } as WorkbenchMessage);+ expect(screen.queryByRole('button', { name: '查看详情' })).toBeNull();+ expect(read).not.toHaveBeenCalled();+ });++ it('does not read Model Hub provenance for a chat-only role', () => {+ const read = vi.spyOn(modelsApi, 'getTurnProvenance');+ mount(notice, false);+ expect(screen.queryByRole('button', { name: '查看详情' })).toBeNull();+ expect(read).not.toHaveBeenCalled();+ });++ it('shares one Sources read across the notices of a transcript', async () => {+ vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue(record);+ const sources = vi.mocked(modelsApi.listSources);+ mount([notice, { ...notice, id: 'second', metadata: { ...notice.metadata, turn_id: 'turn-2' } } as WorkbenchMessage]);+ expect(await screen.findAllByRole('button', { name: '查看详情' })).toHaveLength(2);+ expect(sources).toHaveBeenCalledTimes(1);+ });++ it('expands to the upstream status, error code and reason for every attempt', async () => {+ const read = vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue(record);+ mount();+ fireEvent.click(await screen.findByRole('button', { name: '查看详情' }));+ expect(read).toHaveBeenCalledExactlyOnceWith('turn-1');+ expect(screen.getByText('上游 API 拒绝了 grok-4.6 的请求。')).toBeTruthy();+ expect(screen.getByText('xAI 官方 · grok-4.6')).toBeTruthy();+ expect(screen.getByText('429')).toBeTruthy();+ expect(screen.getByText('触发限流')).toBeTruthy();+ // A source the Sources list no longer names still shows its stable id.+ expect(screen.getByText('src_b · grok-4.6-beta')).toBeTruthy();+ expect(screen.getByText('400')).toBeTruthy();+ expect(screen.getByText('model_not_found')).toBeTruthy();+ expect(screen.getByText('请求参数被拒绝')).toBeTruthy();+ expect(screen.getByText(/供应商已不存在/)).toBeTruthy();+ expect(screen.getByText(/由上游供应商的 API 返回/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: '收起详情' }));+ expect(screen.queryByText('429')).toBeNull();+ });++ it.each([+ new ApiCallError('provenance_unavailable', 'models.provenance.direct_mode'),+ new ApiCallError('provenance_unavailable', 'models.provenance.attribution_ambiguous'),+ new ApiCallError('turn_not_found', 'not found'),+ new Error('offline'),+ ])('offers no details when the record cannot be shown (%s)', async (error) => {+ const read = vi.spyOn(modelsApi, 'getTurnProvenance').mockRejectedValue(error);+ mount();+ await act(async () => { await Promise.resolve(); });+ expect(read).toHaveBeenCalledOnce();+ expect(screen.queryByRole('button', { name: '查看详情' })).toBeNull();+ });++ it('reads again once a live notice\'s Turn has been settled', async () => {+ vi.useFakeTimers();+ try {+ const read = vi.spyOn(modelsApi, 'getTurnProvenance')+ .mockRejectedValueOnce(new ApiCallError('turn_not_found', 'not found'))+ .mockResolvedValue(record);+ mount();+ await act(async () => { await Promise.resolve(); });+ expect(screen.queryByRole('button', { name: '查看详情' })).toBeNull();+ await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });+ expect(read).toHaveBeenCalledTimes(2);+ expect(screen.getByRole('button', { name: '查看详情' })).toBeTruthy();+ } finally {+ vi.useRealTimers();+ }+ });++ it('names Avibe-side terminal failures and localizes every blocker reason', async () => {+ vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue({+ ...record,+ failed_attempts: [],+ terminal_error: { ...record.terminal_error, reason: 'engine_down', http_status: null, upstream_error_code: null },+ blockers: [{ source_id: 'src_a', model_id: 'grok-4.6', reason: 'cooldown' }],+ } as unknown as TurnProvenance);+ mount();+ fireEvent.click(await screen.findByRole('button', { name: '查看详情' }));+ expect(screen.getByText('grok-4.6 的请求失败了,原因见下方。')).toBeTruthy();+ expect(screen.queryByText(/上游 API 拒绝/)).toBeNull();+ expect(screen.queryByText(/由上游供应商的 API 返回/)).toBeNull();+ expect(screen.getByText(/冷却中/)).toBeTruthy();+ });+});diff --git a/ui/src/components/workbench/FailureDetails.tsx b/ui/src/components/workbench/FailureDetails.tsxnew file mode 100644index 000000000..9df5486e2--- /dev/null+++ b/ui/src/components/workbench/FailureDetails.tsx@@ -0,0 +1,177 @@+// The "what actually happened upstream" half of a backend-failure notice.+//+// The notice itself is one sentence of Avibe copy; this reads the Turn's Model+// Hub provenance record (the notice's `turn_id` is the record's key) and lays+// out every attempt the gateway made: which source, which model, the upstream+// HTTP status and machine error code, and why it moved on. That is what lets a+// user see the refusal came from the upstream API and not from the gateway.+//+// Raw upstream response prose is never retained — the record keeps closed+// machine codes and status only, so a credential echoed in an error body can+// never reach the transcript. The details say so rather than implying more.+import * as React from 'react';+import { ChevronDown, ChevronRight } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { WorkbenchMessage } from '../../context/ApiContext';+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';+import { isRetryableFailureNotice } from '../../lib/chatMessageTypes';+import type { TurnProvenance } from '../settings/models/types';+import { ApiCallError } from '../settings/models/modelsApi';+import { CopyButton } from '../ui/copy-button';+import { readNames, readRecord } from './failureDetailsReads';++type Row = {+ key: string;+ source: string;+ model: string | null;+ status: number | null;+ code: string | null;+ reason: string;+};++const RECORD_RETRIES = 3;+const RECORD_RETRY_MS = 1_000;++type Detail = { record: TurnProvenance; names: Record<string, string> };++// Drawn as the notice bubble's second line. The record is read up front, and+// a turn with no readable record (direct mode, no gateway record, an ambiguous+// attribution, a failed read) offers no details at all rather than a toggle+// that opens onto an apology.+export function FailureDetails({ message }: { message: WorkbenchMessage }) {+ const { t } = useTranslation();+ const [open, setOpen] = React.useState(false);+ const [detail, setDetail] = React.useState<Detail | null>(null);+ // The record names Sources and routes, so it is Model Hub management data:+ // a chat-only role gets the notice and its retry, not a read bound to fail.+ const { capabilities } = useInstanceAuthorization();+ const eligible = capabilities.can_manage_instance && isRetryableFailureNotice(message);+ const turnId = typeof message.metadata?.turn_id === 'string' ? message.metadata.turn_id : '';++ React.useEffect(() => {+ if (!eligible || !turnId) return;+ let active = true;+ let retry: ReturnType<typeof setTimeout> | undefined;+ setDetail(null);+ const load = async (attempt: number) => {+ try {+ const record = await readRecord(turnId);+ // Names are a courtesy: a role that cannot read Sources, or a source+ // deleted since, still gets the stable id.+ const names = await readNames();+ if (active) setDetail({ record, names });+ } catch (error) {+ // A live notice can arrive before its Turn is settled; the record+ // appears moments later. Anything else to show is shown as nothing.+ if (active && error instanceof ApiCallError && error.code === 'turn_not_found' && attempt < RECORD_RETRIES) {+ retry = setTimeout(() => { void load(attempt + 1); }, RECORD_RETRY_MS * 2 ** attempt);+ }+ }+ };+ void load(0);+ return () => {+ active = false;+ clearTimeout(retry);+ };+ }, [eligible, turnId]);++ if (!eligible || !turnId || !detail) return null;++ // Blockers carry the event-reason vocabulary (`cooldown`, `credential_expired`,+ // …); only a source detail arrives as a full i18n key.+ const blockerLabel = (reason: string): string => {+ if (reason === 'native_cli_unavailable') return t('models.probe.native_cli_unavailable');+ if (reason.includes('.')) return t(reason, { defaultValue: reason });+ return t(`chat.failureDetails.reason.${reason}`, { defaultValue: reason });+ };++ const rows = (record: TurnProvenance, names: Record<string, string>): Row[] => {+ const name = (id: string | null) => (id ? names[id] ?? id : '—');+ const attempts: Row[] = record.failed_attempts.map((entry, index) => ({+ key: `attempt:${index}`,+ source: name(entry.source_id),+ model: entry.configured_model_id,+ status: entry.http_status ?? null,+ code: null,+ reason: t(`chat.failureDetails.reason.${entry.reason}`, { defaultValue: entry.reason }),+ }));+ const terminal = record.terminal_error;+ if (terminal) {+ attempts.push({+ key: 'terminal',+ source: name(terminal.source_id),+ model: terminal.configured_model_id,+ status: terminal.http_status ?? null,+ code: terminal.upstream_error_code ?? null,+ reason: t(`settings.models.routing.errorReason.${terminal.reason}`),+ });+ }+ return attempts;+ };++ const body = (() => {+ const { record, names } = detail;+ const attempts = rows(record, names);+ // A terminal failure is an upstream refusal only when the upstream refused+ // the parameters; an engine, protocol or tool failure is Avibe's side.+ const outcome = record.outcome === 'failed_terminal' && record.terminal_error?.reason !== 'invalid_parameter'+ ? 'failed_local'+ : record.outcome;+ const upstreamFacts = attempts.some((row) => row.status !== null || row.code !== null);+ return (+ <div className="flex flex-col gap-2">+ <p className="text-gold-ink">+ {t(`chat.failureDetails.outcome.${outcome}`, { model: record.requested_model_id })}+ </p>+ {attempts.length > 0 && (+ <ol className="flex flex-col gap-1.5">+ {attempts.map((row) => (+ <li key={row.key} className="flex flex-col gap-0.5 rounded-md border border-gold/25 bg-gold/[0.06] px-2.5 py-1.5">+ <span className="font-mono text-gold-ink">{row.source} · {row.model ?? '—'}</span>+ <span className="flex flex-wrap gap-x-3 gap-y-0.5 text-gold-ink/70">+ <span>{t('chat.failureDetails.httpStatus')}: <span className="font-mono text-gold-ink">{row.status ?? '—'}</span></span>+ {row.code && <span>{t('chat.failureDetails.errorCode')}: <span className="font-mono text-gold-ink">{row.code}</span></span>}+ <span>{t('chat.failureDetails.reasonLabel')}: <span className="text-gold-ink">{row.reason}</span></span>+ </span>+ </li>+ ))}+ </ol>+ )}+ {record.blockers.length > 0 && (+ <div className="flex flex-col gap-1">+ <span className="text-gold-ink/70">{t('chat.failureDetails.blockers')}</span>+ <ul className="flex flex-col gap-0.5">+ {record.blockers.map((blocker, index) => (+ <li key={index} className="font-mono text-gold-ink">+ {names[blocker.source_id] ?? blocker.source_id} · {blocker.model_id}+ <span className="font-sans text-gold-ink/70"> — {blockerLabel(blocker.reason)}</span>+ </li>+ ))}+ </ul>+ </div>+ )}+ {upstreamFacts && <p className="text-gold-ink/70">{t('chat.failureDetails.upstreamNote')}</p>}+ <span className="flex items-center gap-2 text-gold-ink/70">+ <span className="font-mono">{record.turn_id}</span>+ <CopyButton value={JSON.stringify(record, null, 2)} label={t('chat.failureDetails.copyRecord') as string} />+ </span>+ </div>+ );+ })();++ return (+ <>+ <button+ type="button"+ className="mt-0.5 inline-flex items-center gap-0.5 self-start rounded text-[12px] text-gold-ink/80 hover:text-gold-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ >+ {open ? <ChevronDown className="size-3" aria-hidden /> : <ChevronRight className="size-3" aria-hidden />}+ {t(open ? 'chat.failureDetails.hide' : 'chat.failureDetails.show')}+ </button>+ {open && <div className="mt-1.5 text-[12px] leading-relaxed">{body}</div>}+ </>+ );+}diff --git a/ui/src/components/workbench/FailureRetry.tsx b/ui/src/components/workbench/FailureRetry.tsxindex 11e0de4c7..6051dafdc 100644--- a/ui/src/components/workbench/FailureRetry.tsx+++ b/ui/src/components/workbench/FailureRetry.tsx@@ -31,7 +31,7 @@ export function FailureRetry({return (<Buttontype="button"- size="sm"+ size="2xs"variant="secondary"disabled={disabled || sending || admitted}aria-busy={sending}@@ -47,7 +47,7 @@ export function FailureRetry({}}}>- {admitted ? <Check className="size-3.5" /> : <RotateCcw className="size-3.5" />}+ {admitted ? <Check /> : <RotateCcw />}{t(admitted ? 'chat.retryRequested' : 'common.retry')}</Button>);diff --git a/ui/src/components/workbench/failureDetailsReads.test.ts b/ui/src/components/workbench/failureDetailsReads.test.tsnew file mode 100644index 000000000..48e7f6ffc--- /dev/null+++ b/ui/src/components/workbench/failureDetailsReads.test.ts@@ -0,0 +1,24 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { modelsApi } from '../settings/models/modelsApi';+import type { TurnProvenance } from '../settings/models/types';+import { RECORDS_LIMIT, readRecord, resetFailureDetailsCache } from './failureDetailsReads';++describe('failureDetailsReads', () => {+ afterEach(() => {+ resetFailureDetailsCache();+ vi.restoreAllMocks();+ });++ it('keeps only the most recently read Turn records', async () => {+ const read = vi.spyOn(modelsApi, 'getTurnProvenance')+ .mockImplementation(async (turnId) => ({ turn_id: turnId } as unknown as TurnProvenance));+ for (let index = 0; index <= RECORDS_LIMIT; index += 1) await readRecord(`turn_${index}`);+ expect(read).toHaveBeenCalledTimes(RECORDS_LIMIT + 1);++ await readRecord(`turn_${RECORDS_LIMIT}`);+ expect(read).toHaveBeenCalledTimes(RECORDS_LIMIT + 1);+ await readRecord('turn_0');+ expect(read).toHaveBeenCalledTimes(RECORDS_LIMIT + 2);+ });+});diff --git a/ui/src/components/workbench/failureDetailsReads.ts b/ui/src/components/workbench/failureDetailsReads.tsnew file mode 100644index 000000000..3067e004b--- /dev/null+++ b/ui/src/components/workbench/failureDetailsReads.ts@@ -0,0 +1,40 @@+import { modelsApi } from '../settings/models/modelsApi';+import type { Source, TurnProvenance } from '../settings/models/types';++const sourceNames = (sources: Source[]): Record<string, string> =>+ Object.fromEntries(sources.map((source) => [source.id, source.display_name]));++// A transcript can hold many failure notices; they share one Sources read and+// each Turn's record is read once, however often its row remounts. A record+// is immutable once written, and a failed read is dropped so a later mount+// may try again. Only the most recently read records are kept, so a long+// session paging through chats holds a bounded set.+const NAMES_TTL_MS = 30_000;+export const RECORDS_LIMIT = 200;+let namesRead: { at: number; value: Promise<Record<string, string>> } | null = null;+const records = new Map<string, Promise<TurnProvenance>>();++export function readNames(): Promise<Record<string, string>> {+ if (!namesRead || Date.now() - namesRead.at > NAMES_TTL_MS) {+ namesRead = { at: Date.now(), value: modelsApi.listSources().then(sourceNames, () => ({})) };+ }+ return namesRead.value;+}++export function readRecord(turnId: string): Promise<TurnProvenance> {+ let read = records.get(turnId);+ if (read) {+ records.delete(turnId);+ } else {+ read = modelsApi.getTurnProvenance(turnId);+ read.catch(() => { if (records.get(turnId) === read) records.delete(turnId); });+ }+ records.set(turnId, read);+ if (records.size > RECORDS_LIMIT) records.delete(records.keys().next().value as string);+ return read;+}++export function resetFailureDetailsCache(): void {+ namesRead = null;+ records.clear();+}diff --git a/ui/src/context/ToastProvider.tsx b/ui/src/context/ToastProvider.tsxindex 926248e9d..8ecc02aaa 100644--- a/ui/src/context/ToastProvider.tsx+++ b/ui/src/context/ToastProvider.tsx@@ -99,8 +99,11 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childrereturn (<ToastContext.Provider value={value}>{children}- {/* Toast container - fixed at bottom right; lifted above mobile bottom nav */}- <div className="fixed bottom-[calc(5.5rem+env(safe-area-inset-bottom))] right-4 z-50 flex flex-col gap-2 md:bottom-4">+ {/* Toast container - fixed at bottom right; lifted above mobile bottom nav.+ Above z-50 on purpose: Radix portals its dialog overlay/content to+ document.body at z-50, and a later sibling of #root wins a z-index tie,+ so a toast raised from inside a modal painted behind the overlay. */}+ <div className="fixed bottom-[calc(5.5rem+env(safe-area-inset-bottom))] right-4 z-[100] flex flex-col gap-2 md:bottom-4">{toasts.map((toast) => (<divkey={toast.id}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex f79432693..c38a5ff52 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -929,8 +929,8 @@"1.detail": "When your Claude subscription is exhausted, it moves to the next source you added and the conversation continues.","2": "One key supplies several backends","2.detail": "The same API key can serve Claude Code, Codex and OpenCode at once.",- "3": "Decide per backend and per model",- "3.detail": "You can specify which source each model on each backend uses."+ "3": "Mix and match models freely",+ "3.detail": "Pair any backend with any model from any source."},"note": {"perBackend": "Switch one backend at a time — the others stay direct. You can switch back at any time."@@ -976,8 +976,8 @@"summary_one": "{{count}} Agent needs attention","summary_other": "{{count}} Agents need attention","modelMissing": "No model selected",- "routeMissing": "No route configured for this model",- "degraded": "Model supply degraded",+ "routeMissing": "{{model}} is not a known model name. Change this Agent's model, or add a route for {{model}}.",+ "degraded": "Some sources are unavailable; requests fall back to the next one","waiting": "Waiting for a source to recover","interrupted": "No source is available for this model"},@@ -1021,6 +1021,7 @@"remove": "Remove {{model}}","reorder": "Reorder {{model}}","removeConfirm": "Remove",+ "removeTitle": "Remove {{model}}?","empty": "No models yet. Add the first one.","noMatch": "No model matches this search","legacy": "This model engine build does not offer an editable model list yet. These are the models it currently exposes.",@@ -1036,7 +1037,8 @@"saveConflict": "This list changed elsewhere while you were editing. Your changes were replayed onto the newer list; check it and save again.","saveIdInvalid": "A model ID in this list is not valid for this backend. Remove the model and add it again.","saveDuplicate": "Two models in this list share the same ID. Remove one, then save again.",- "saveLocked": "This list disagrees with a model the server owns. It was re-read from the server; check it and save again.",+ "saveLocked": "A model in this list is marked as built into this backend, which does not publish it. The list was re-read from the server; remove that model and add it again.",+ "saveOriginImmutable": "This model is already in this list and cannot be added again as a new one. The list was re-read from the server; edit the entry it already has instead.","saveInvalid": "A model in this list has a value this backend will not accept. Check its fields, then save again.","grabbed_one": "Grabbed {{model}}, position {{position}} of {{count}}.","grabbed_other": "Grabbed {{model}}, position {{position}} of {{count}}.",@@ -1245,6 +1247,7 @@"passthrough": "Passthrough","unconfigured": "Unconfigured"},+ "originNow": "Current","help": {"automatic": "Matched by model name.\nSource order follows {{backend}} default routing.","manual": "This model has a saved, fixed route.\nDefault routing does not change it. Restore automatic in route settings to follow defaults.",@@ -1461,6 +1464,8 @@"confirm": "Replace","replaced": "Hop {{position}} replaced."},+ "editModel": "Edit model",+ "removeModel": "Remove model","sourceMissing": "Source missing","invalidAfterRefresh": "This edited hop is unavailable after the refresh. Replace or remove it before saving.","reorder": {@@ -1591,8 +1596,7 @@"native": {"label": "Use natively","desc": {- "claude": "Claude Code uses this subscription directly; the credential stays on this machine.",- "chatgpt": "Codex signs in with this ChatGPT account directly."+ "claude": "Claude Code uses this subscription directly; the credential stays on this machine."}},"hub": {@@ -1605,15 +1609,13 @@},"badge": {"recommended": "Recommended",- "secondary": "Second choice",- "supportedNotRecommended": "Supported, not recommended"+ "secondary": "Second choice"},"tos": {"claude": "The subscription terms authorize only you, inside Claude's official clients. Supplying it to other Agents is out-of-scope use and the account may be restricted."},"hint": {- "claude": "You can have both — add them one at a time.",- "chatgpt": "Nothing takes over when the quota runs out, and usage stays invisible."+ "claude": "You can have both — add them one at a time."},"signIn": "Sign in","cancel": "Cancel",@@ -1646,7 +1648,8 @@"hint": "After you sign in and approve, paste the code back here"},"callback": {- "hint": "After signing in, paste the callback URL your browser landed on"+ "hint": "After signing in, paste the callback URL your browser landed on",+ "rejected": "That isn't the callback address. Paste the full address from the browser bar after you approve (it contains code=), then submit again."},"deviceCode": {"hint": "Enter the device code on that page; this continues automatically"@@ -1707,24 +1710,24 @@"migration": {"open": "Migrate configuration","title": "Migrate to the Model Hub",- "subtitle": "Import authentication saved in configuration files, shell startup files, or supported credential stores, without reading runtime environment values. After migration, Model Hub will manage the selected authentication.",+ "subtitle": "Import authentication saved in configuration files, shell startup files, or supported credential stores. After migration, Model Hub will manage the selected authentication.","empty": "No configuration found to migrate.","sharedFiles": "These backends share authentication saved in files and must migrate together: {{backends}}. Changing one selection updates the others.","scanFailed": "Couldn't scan native configs, please retry","applyFailed": "Migration failed, please retry","blocked": {- "config": "Check this CLI's saved configuration, then scan again.",- "environment": "This environment-based authentication cannot be imported. Save the key in a supported configuration file, then scan again.",- "credential": "This credential could not be read or is not supported. Check credential access and the saved authentication format, then scan again.",- "dynamic_shell": "This file uses expressions or commands that cannot be safely read. Save the required authentication as literal values in a supported configuration file, then scan again. Migration never executes shell code.",- "ambiguous_shell": "Conflicting saved assignments were found. Resolve the assignments in the listed files to an unambiguous literal value, then scan again.",- "unreadable": "This source file could not be read. Check that it exists and that Avibe has read access, then scan again.",- "reference": "A referenced variable has no unambiguous saved literal value. Configure and save the corresponding key in the listed configuration or shell startup file, then scan again.",- "helper": "Credentials supplied by a command cannot be imported. Save them in a supported static configuration or add the source manually in Model Hub.",- "token": "This login token or authentication format cannot be imported. Add a source in Model Hub or sign in again for that source.",- "headers": "Custom credential headers cannot be imported. Use a supported authentication method or add the source manually in Model Hub.",- "transport": "Model Hub can't use this authentication method yet, so it was skipped and the file is unchanged. You can add the provider again with a standard API key.",- "fallback": "This credential cannot be imported. Use the existing Add flow in Model Hub to add this source manually."+ "config": "The config file is malformed.",+ "environment": "Keys in environment variables can't be migrated yet.",+ "credential": "This authentication type isn't supported.",+ "dynamic_shell": "The key comes from a command and can't be read.",+ "ambiguous_shell": "The key differs between files.",+ "unreadable": "No permission to read this file.",+ "reference": "The referenced variable has no value.",+ "helper": "The key comes from a script and can't be read.",+ "token": "This login token isn't supported.",+ "headers": "Custom request headers aren't supported.",+ "transport": "The gateway can't send this key that way.",+ "fallback": "Can't be migrated. Add it manually."},"applying": "Migrating…","errors": {@@ -1900,7 +1903,6 @@"position": "Order #{{n}}"},"hint": {- "safe": "These models still have another source available.","interrupt": "Some models will be left with no usable source."},"gap": {@@ -1912,7 +1914,6 @@"label": "Removed hops","gapLabel": "Models left with no source","hint": {- "safe": "These models still have another source available.","interrupt": "Some models now have no usable source."}},@@ -2092,6 +2093,7 @@"submission_failed": "Couldn't submit what you pasted, please retry","ambiguous_engine_binding": "Couldn't tell which account signed in — do one at a time, then retry","binding_failed": "That account is already used by another source",+ "account_already_added": "This account is already added. Sign in with a different account to add another subscription.","expired": "Authorization timed out, please reconnect"},"probe": {@@ -4377,6 +4379,44 @@"showMore": "Show {{count}} more attachments","collapse": "Collapse attachments"}+ },+ "failureDetails": {+ "show": "Show details",+ "hide": "Hide details",+ "outcome": {+ "served": "{{model}} was eventually served.",+ "exhausted": "Every source for {{model}} failed upstream.",+ "failed_terminal": "The upstream API rejected the request for {{model}}.",+ "failed_local": "The request for {{model}} failed; see the reason below.",+ "no_candidate": "No source could serve {{model}} when the request was made.",+ "canceled": "The request for {{model}} was canceled."+ },+ "httpStatus": "HTTP status",+ "errorCode": "Error code",+ "reasonLabel": "Reason",+ "blockers": "Sources that were unavailable",+ "upstreamNote": "These codes come from the upstream provider's API. Avibe keeps the status and error code but never stores the provider's raw response text, because it can echo credentials.",+ "copyRecord": "Copy record",+ "reason": {+ "quota_exhausted": "Quota exhausted",+ "cooldown": "Cooling down",+ "rate_limited": "Rate limited",+ "server_error": "Upstream server error",+ "network": "Network error",+ "recovery": "Recovering",+ "manual": "Switched manually",+ "credential_expired": "Credential expired",+ "credential_revoked": "Credential revoked",+ "balance_exhausted": "Balance exhausted",+ "account_banned": "Account suspended",+ "permission_denied": "Permission denied",+ "unclassified_error": "Unclassified upstream error",+ "no_enabled_source": "No source is enabled",+ "no_eligible_source": "No source can serve this model",+ "route_unconfigured": "No route configured",+ "source_missing": "Source no longer exists",+ "model_unsupported": "Model not offered by this source"+ }}},"vaults": {diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.tsindex 4690dd2bd..e15cb47d0 100644--- a/ui/src/i18n/keyCoverage.test.ts+++ b/ui/src/i18n/keyCoverage.test.ts@@ -877,6 +877,7 @@ const NON_KEY_LITERALS = ['modelHub.errors.backend_model_id_invalid','modelHub.errors.backend_model_in_route','modelHub.errors.backend_model_locked',+ 'modelHub.errors.backend_model_origin_immutable','modelHub.errors.candidate_suppliers_changed','modelHub.errors.engine_down','modelHub.errors.models_dev_unavailable',diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 5e11f33c2..eae8af048 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -924,13 +924,13 @@"refreshAgents": "重新检测 Agent 后端"},"benefits": {- "title": "切换到模型网关,你会多出三件事",+ "title": "切换到模型网关,有三大益处","1": "额度用尽不断线","1.detail": "Claude 订阅用满时,自动切换到下一个供应商,对话继续。","2": "一个 Key 用于多个后端","2.detail": "同一个 API Key 可以同时给 Claude Code、Codex、OpenCode 用。",- "3": "按后端、按模型自己定",- "3.detail": "哪个后端的哪个模型使用哪个供应商,都可以逐条指定。"+ "3": "模型搭配随心所欲",+ "3.detail": "哪个后端使用哪个供应商的哪个模型,都可以任意搭配。"},"note": {"perBackend": "逐个后端切换,互不影响——其余后端保持直连。切换后随时可以切换回直连。"@@ -976,8 +976,8 @@"summary_one": "{{count}} 个 Agent 需关注","summary_other": "{{count}} 个 Agent 需关注","modelMissing": "未选择模型",- "routeMissing": "此模型未配置路由",- "degraded": "模型供应已降级",+ "routeMissing": "{{model}} 模型名不存在,请修改此 agent 的模型名或添加 {{model}} 模型的路由",+ "degraded": "部分供应商不可用,请求已自动切换到其他供应商","waiting": "等待供应商恢复","interrupted": "此模型没有可用供应商"},@@ -1021,6 +1021,7 @@"remove": "移除 {{model}}","reorder": "调整 {{model}} 的顺序","removeConfirm": "移除",+ "removeTitle": "移除 {{model}}?","empty": "还没有模型,先添加一个。","noMatch": "没有匹配的模型","legacy": "当前模型引擎版本还不支持编辑模型列表,以下是它当前提供的模型。",@@ -1036,7 +1037,8 @@"saveConflict": "编辑期间该列表在别处发生了变更。你的改动已重放到新列表上,请确认后重新保存。","saveIdInvalid": "列表中有模型 ID 不适用于这个后端。请移除该模型后重新添加。","saveDuplicate": "列表中有两个模型使用了相同的 ID,请移除其中一个后重新保存。",- "saveLocked": "该列表与服务端自有的模型不一致。已重新读取服务器上的列表,请确认后重新保存。",+ "saveLocked": "列表中有模型被标记为该后端内置,但这个后端并不提供它。已重新读取服务器上的列表,请移除该模型后重新添加。",+ "saveOriginImmutable": "这个模型已经在列表里了,不能作为新模型重新添加。已重新读取服务器上的列表,请直接编辑已有的那一项。","saveInvalid": "列表中某个模型的字段值不被这个后端接受,请检查后重新保存。","grabbed_one": "已抓起 {{model}},第 {{position}} / {{count}} 位。","grabbed_other": "已抓起 {{model}},第 {{position}} / {{count}} 位。",@@ -1245,6 +1247,7 @@"passthrough": "透传","unconfigured": "未配置"},+ "originNow": "当前","help": {"automatic": "已按模型名自动匹配。\n供应商顺序跟随 {{backend}} 的默认路由。","manual": "此模型已保存固定路由。\n不随默认路由调整,可在路由设置中恢复自动。",@@ -1461,6 +1464,8 @@"confirm": "替换","replaced": "已替换第 {{position}} 个路由项。"},+ "editModel": "编辑模型",+ "removeModel": "删除模型","sourceMissing": "供应商不存在","invalidAfterRefresh": "这个路由项在刷新后的供应商中不可用。替换或移除后再保存。","reorder": {@@ -1591,8 +1596,7 @@"native": {"label": "由 Agent 管理","desc": {- "claude": "Claude Code 直接用这个订阅,凭据只留在本机。",- "chatgpt": "Codex 直接用这个 ChatGPT 账号登录。"+ "claude": "Claude Code 直接用这个订阅,凭据只留在本机。"}},"hub": {@@ -1605,15 +1609,13 @@},"badge": {"recommended": "推荐",- "secondary": "次选",- "supportedNotRecommended": "支持,不推荐"+ "secondary": "次选"},"tos": {"claude": "订阅条款只授权你本人在 Claude 官方客户端里使用。转供其他 Agent 属于超范围使用,账号可能被限制。"},"hint": {- "claude": "两条都要也可以,分两次添加。",- "chatgpt": "额度用完不会自动切换,也看不到用量。"+ "claude": "两条都要也可以,分两次添加。"},"signIn": "去登录","cancel": "取消",@@ -1646,7 +1648,8 @@"hint": "登录同意后,把页面给的授权码粘贴回来"},"callback": {- "hint": "登录后,把浏览器最终停留的回调地址粘贴回来"+ "hint": "登录后,把浏览器最终停留的回调地址粘贴回来",+ "rejected": "这不是授权完成后的回调地址。请粘贴登录同意后浏览器地址栏里的完整网址(包含 code=),改好后重新提交。"},"deviceCode": {"hint": "在那个页面输入设备码,这里会自动继续"@@ -1707,24 +1710,24 @@"migration": {"open": "迁移配置","title": "迁移到模型网关",- "subtitle": "导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证,不读取运行中的环境变量。迁移后,所选认证由模型网关管理。",+ "subtitle": "导入配置文件、Shell 启动文件或受支持凭据库中已保存的认证。迁移后,所选认证由模型网关管理。","empty": "没有检测到可迁移的配置。","sharedFiles": "这些后端共用文件中保存的认证,需要一起迁移:{{backends}}。勾选或取消其中一个,会同时更新全部关联后端。","scanFailed": "扫描 Agent 配置失败,请重试","applyFailed": "迁移失败,请重试","blocked": {- "config": "请检查此 CLI 已保存的配置,再重新扫描。",- "environment": "暂时无法导入此环境变量认证。请将密钥保存到受支持的配置文件,再重新扫描。",- "credential": "无法读取此凭据,或其认证形式暂不受支持。请检查凭据访问权限和已保存的认证格式,再重新扫描。",- "dynamic_shell": "此文件通过表达式或命令设置认证,无法安全读取。请将需要迁移的认证以固定值保存到受支持的配置文件,再重新扫描。迁移不会执行 Shell 代码。",- "ambiguous_shell": "列出的文件中存在互相冲突的赋值。请确认应使用的固定值,统一相关配置后重新扫描。",- "unreadable": "无法读取此配置文件。请检查文件是否存在,以及 Avibe 是否有读取权限,再重新扫描。",- "reference": "引用的变量没有明确的已保存固定值。请在列出的配置文件或 Shell 启动文件中配置并保存对应的密钥,再重新扫描。",- "helper": "无法导入由命令提供的凭据。请将凭据保存为受支持的静态配置,或在模型网关中手动添加供应商。",- "token": "此登录令牌或认证格式暂不支持导入。请在模型网关中添加供应商,或为该供应商重新登录。",- "headers": "暂不支持导入自定义认证请求头。请使用受支持的认证方式,或在模型网关中手动添加供应商。",- "transport": "模型网关暂不支持这里的认证方式,已跳过,原文件未改动。可以改用供应商的标准 API Key 重新添加。",- "fallback": "暂时无法导入此认证,请使用模型网关现有的添加流程手动添加供应商。"+ "config": "配置文件格式有误。",+ "environment": "环境变量里的密钥暂不支持迁移。",+ "credential": "不支持这种认证方式。",+ "dynamic_shell": "密钥由命令生成,无法读取。",+ "ambiguous_shell": "多个文件里的密钥不一致。",+ "unreadable": "没有读取这个文件的权限。",+ "reference": "引用的变量找不到值。",+ "helper": "密钥由脚本生成,无法读取。",+ "token": "不支持这种登录令牌。",+ "headers": "不支持自定义请求头。",+ "transport": "网关无法按这种方式发送密钥。",+ "fallback": "暂不支持迁移,请手动添加。"},"applying": "迁移中…","errors": {@@ -1900,7 +1903,6 @@"position": "顺序 #{{n}}"},"hint": {- "safe": "这些模型还有其他供应商可用。","interrupt": "有模型会因此没有可用供应商。"},"gap": {@@ -1912,7 +1914,6 @@"label": "已移除的路由项","gapLabel": "已经没有可用供应商的模型","hint": {- "safe": "这些模型仍有其他供应商可用。","interrupt": "有模型现在没有可用供应商。"}},@@ -2092,6 +2093,7 @@"submission_failed": "粘贴的内容没能提交,请重试","ambiguous_engine_binding": "分不清登录的是哪个账号,请一次只登一个再重试","binding_failed": "该账号已被另一个供应商使用",+ "account_already_added": "这个账号已经添加过了,不能重复添加。要添加另一个订阅,请登录其他账号。","expired": "授权超时,请重新连接"},"probe": {@@ -4377,6 +4379,44 @@"showMore": "显示其余 {{count}} 个附件","collapse": "收起附件"}+ },+ "failureDetails": {+ "show": "查看详情",+ "hide": "收起详情",+ "outcome": {+ "served": "{{model}} 最终已成功响应。",+ "exhausted": "{{model}} 的所有供应商在上游都失败了。",+ "failed_terminal": "上游 API 拒绝了 {{model}} 的请求。",+ "failed_local": "{{model}} 的请求失败了,原因见下方。",+ "no_candidate": "请求时没有可以提供 {{model}} 的供应商。",+ "canceled": "{{model}} 的请求已取消。"+ },+ "httpStatus": "HTTP 状态码",+ "errorCode": "错误码",+ "reasonLabel": "原因",+ "blockers": "当时不可用的供应商",+ "upstreamNote": "以上状态码与错误码均由上游供应商的 API 返回。Avibe 会保留状态码和错误码,但不会保存供应商返回的原始报文,因为其中可能包含凭据。",+ "copyRecord": "复制记录",+ "reason": {+ "quota_exhausted": "额度用尽",+ "cooldown": "冷却中",+ "rate_limited": "触发限流",+ "server_error": "上游服务器错误",+ "network": "网络错误",+ "recovery": "恢复中",+ "manual": "手动切换",+ "credential_expired": "凭据已过期",+ "credential_revoked": "凭据已吊销",+ "balance_exhausted": "余额不足",+ "account_banned": "账号被封禁",+ "permission_denied": "无权限",+ "unclassified_error": "未分类的上游错误",+ "no_enabled_source": "没有已启用的供应商",+ "no_eligible_source": "没有能提供该模型的供应商",+ "route_unconfigured": "尚未配置路由",+ "source_missing": "供应商已不存在",+ "model_unsupported": "该供应商不提供此模型"+ }}},"vaults": {diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 15f6bea96..3501eb856 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -875,6 +875,7 @@"source_not_found": "Model source not found.","flow_not_found": "Authorization flow not found.","flow_expired": "Authorization flow expired.",+ "submission_rejected": "That is not the authorization callback address. Paste the full address shown after authorizing.","discovery_failed": "Could not validate or discover this source.","ambiguous_source": "Connected, but we could not identify the model interface.","inventory_unavailable": "The interface was confirmed, but its model list is unavailable.",@@ -890,7 +891,8 @@"backend_model_catalog_invalid": "The backend model list contains invalid fields.","backend_model_id_invalid": "This backend model ID is invalid.","backend_model_duplicate": "Each backend model ID may appear only once.",- "backend_model_locked": "Claude Code Default and built-in model origins cannot be changed.",+ "backend_model_locked": "Only a model this backend publishes can be listed as built into it.",+ "backend_model_origin_immutable": "This model is already in this backend's list and cannot be added again as a new one. Edit the entry it already has instead.","backend_model_in_route": "Clear this model's route before removing it from the backend model list.","backend_model_conflict": "This backend model changed elsewhere. Reload the list and retry.","candidate_suppliers_changed": "The available suppliers changed. Reload the model choices and confirm again.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex a145d6b3a..f40930c19 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -875,6 +875,7 @@"source_not_found": "未找到模型供应商。","flow_not_found": "未找到授权流程。","flow_expired": "授权流程已过期。",+ "submission_rejected": "这不是授权完成后的回调地址,请粘贴授权后地址栏里的完整网址。","discovery_failed": "无法验证或识别此供应商。","ambiguous_source": "已连接,但无法确认这是哪种模型接口。","inventory_unavailable": "接口已确认,但暂时无法获取模型清单。",@@ -890,7 +891,8 @@"backend_model_catalog_invalid": "Backend 模型列表中包含无效字段。","backend_model_id_invalid": "这个 Backend 模型 ID 无效。","backend_model_duplicate": "同一个 Backend 模型 ID 只能出现一次。",- "backend_model_locked": "不能修改 Claude Code 的 Default 项或内置模型的来源类型。",+ "backend_model_locked": "只有该 Backend 自带的模型才能标记为它的内置模型。",+ "backend_model_origin_immutable": "这个模型已经在该 Backend 的列表里了,不能作为新模型重新添加。请直接编辑已有的那一项。","backend_model_in_route": "请先清空该模型的路由,再从 Backend 模型列表中移除。","backend_model_conflict": "该 Backend 模型已在其他位置发生变更,请重新加载后再试。","candidate_suppliers_changed": "可用供应商已发生变化,请刷新模型选项后重新确认。",diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 3a5aef58f..283ad4c8b 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -6,6 +6,7 @@ import loggingimport reimport secretsimport threading+import urllib.parseimport uuidfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timedelta, timezone@@ -23,6 +24,7 @@ from core.handlers.model_hub.adapter import (ObservationDiscovery,ObservationOutcome,OAuthFlowState,+ OAuthSubmissionRejectedError,OriginNotAllowedError,RawCallOutcome,RawOutcomeKind,@@ -86,6 +88,7 @@ _OAUTH_ENDPOINTS = {"xai": ("/xai-auth-url", "xai", "xai"),}+# The local surface the pinned engine serves a hub-held subscription on.## A subscription's protocol is not a fact about the vendor's public API — it is a@@ -537,9 +540,9 @@ def _anthropic_wrapperless_error_kind(if _request_error_rejects_credential(status, error):return "rejected"identifiers = _error_identifiers(error)- if status in _REQUEST_ERROR_STATUSES and not (- _REQUEST_ERROR_IDENTIFIERS | _MODEL_ERROR_IDENTIFIERS- ).isdisjoint(identifiers):+ if status in _REQUEST_ERROR_STATUSES and not (_REQUEST_ERROR_IDENTIFIERS | _MODEL_ERROR_IDENTIFIERS).isdisjoint(+ identifiers+ ):return "accepted"if status in _AUTHENTICATION_ERROR_STATUSES and not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(identifiers):return "rejected"@@ -559,9 +562,9 @@ def _openai_wrapperless_error_kind(identifiers = _payload_identifiers(payload)if not identifiers:return None- if status in _REQUEST_ERROR_STATUSES and not (- _REQUEST_ERROR_IDENTIFIERS | _MODEL_ERROR_IDENTIFIERS- ).isdisjoint(identifiers):+ if status in _REQUEST_ERROR_STATUSES and not (_REQUEST_ERROR_IDENTIFIERS | _MODEL_ERROR_IDENTIFIERS).isdisjoint(+ identifiers+ ):return "accepted"if status in _AUTHENTICATION_ERROR_STATUSES and not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(identifiers):return "rejected"@@ -643,8 +646,7 @@ def _parse_protocol_authenticated_evidence(top_level_identifiers = _payload_identifiers(payload)if (not oauth- and- status in _AUTHENTICATION_ERROR_STATUSES+ and status in _AUTHENTICATION_ERROR_STATUSESand not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(top_level_identifiers)):return evidence(@@ -752,6 +754,7 @@ async def _probe_protocol_response(headers.pop("Authorization")headers["x-api-key"] = secretclient_timeout = aiohttp.ClientTimeout(total=timeout)+async def observe() -> _ProtocolEvidence:async with aiohttp.ClientSession(timeout=client_timeout) as session:async with session.post(@@ -762,7 +765,11 @@ async def _probe_protocol_response() as response:body = await response.content.read(64 * 1024)return _parse_protocol_authenticated_evidence(- protocol, response.status, body, vendor=vendor, request_root=root,+ protocol,+ response.status,+ body,+ vendor=vendor,+ request_root=root,)try:@@ -798,9 +805,7 @@ def _response_shape_proves_protocol(if protocol == "anthropic":error = body.get("error")return body.get("type") == "message" or (- body.get("type") == "error"- and isinstance(error, dict)- and isinstance(error.get("type"), str)+ body.get("type") == "error" and isinstance(error, dict) and isinstance(error.get("type"), str))error = body.get("error")if protocol == "openai_responses":@@ -833,9 +838,9 @@ def _openai_family_elimination_proof(exclusion. Transient upstream failures do not qualify."""- if not {- protocol for protocol in considered_protocols if protocol not in _OPENAI_FAMILY_PROTOCOLS- }.issubset(ruled_out_protocols):+ if not {protocol for protocol in considered_protocols if protocol not in _OPENAI_FAMILY_PROTOCOLS}.issubset(+ ruled_out_protocols+ ):return Nonecandidate = responses.get("openai_responses")@@ -1075,6 +1080,7 @@ def _probe_oauth_protocol_response(status_code=404,)headers["Authorization"] = "Bearer $TOKEN$"+def request(probe_headers: dict[str, str]) -> _ProtocolEvidence:payload = client.management_request("POST",@@ -1394,9 +1400,7 @@ class CLIProxyEngineAdapter:loop = asyncio.get_running_loop()recovery_deadline: float | None = Nonerecovery_delay = _INSTALL_RECOVERY_INITIAL_DELAY_SECONDS- claimed_target: dict[str, str] | None = (- dict(expected_target) if expected_target is not None else None- )+ claimed_target: dict[str, str] | None = dict(expected_target) if expected_target is not None else Nonedef persist_claim(target: dict[str, str]) -> None:nonlocal claim_owned, claimed_target@@ -1431,10 +1435,7 @@ class CLIProxyEngineAdapter:)breakexcept EngineUnavailableError as exc:- if (- expected_target is None- or exc.reason != INSTALL_ALREADY_RUNNING_REASON- ):+ if expected_target is None or exc.reason != INSTALL_ALREADY_RUNNING_REASON:raiseif self._installation_stopping:await self._abandon_install_claim(@@ -1451,9 +1452,7 @@ class CLIProxyEngineAdapter:)remaining = recovery_deadline - nowif remaining <= 0:- logger.error(- "Model Hub runtime recovery gave up waiting for the shared install lock"- )+ logger.error("Model Hub runtime recovery gave up waiting for the shared install lock")raise EngineUnavailableError("models.engine.install_failed",reason=INSTALL_RECOVERY_TIMEOUT_REASON,@@ -1564,11 +1563,7 @@ class CLIProxyEngineAdapter:on_resolved: Callable[[dict[str, str]], None] | None = None,) -> EngineEnsureResult:async with self._routing_lock:- installer = (- self.supervisor.installer.offline_copy()- if offline- else self.supervisor.installer- )+ installer = self.supervisor.installer.offline_copy() if offline else self.supervisor.installerif expected_target is None and on_resolved is None:if force:install = await asyncio.to_thread(@@ -1623,10 +1618,7 @@ class CLIProxyEngineAdapter:if status.health is EngineHealth.INSTALLING:return statusstart_after_install_task = self._start_after_install_task- if (- start_after_install_task is not None- and not start_after_install_task.done()- ):+ if start_after_install_task is not None and not start_after_install_task.done():start_after_install_task.cancel()await asyncio.to_thread(self.supervisor.disable)return await self.status()@@ -1797,6 +1789,7 @@ class CLIProxyEngineAdapter:async with self._routing_lock:await self._transports_idle.wait()+def publish_grant(running: EngineClient | None):return (*self.state_store.activate_oauth_auth_file(credential_ref), running)@@ -1817,14 +1810,8 @@ class CLIProxyEngineAdapter:try:inventory = await run_owned_in_thread(_auth_inventory, client)except EngineClientError as exc:- raise EngineStateError(- "OAuth activation could not inspect the engine"- ) from exc- matching = [- auth- for auth in inventory.values()- if auth.name == auth_name or auth.identity == auth_name- ]+ raise EngineStateError("OAuth activation could not inspect the engine") from exc+ matching = [auth for auth in inventory.values() if auth.name == auth_name or auth.identity == auth_name]if len(matching) > 1:raise EngineStateError("OAuth activation auth record is ambiguous")if matching:@@ -1854,14 +1841,8 @@ class CLIProxyEngineAdapter:try:inventory = await run_owned_in_thread(_auth_inventory, client)except EngineClientError as exc:- raise EngineStateError(- "OAuth activation could not inspect the engine"- ) from exc- matching = [- auth- for auth in inventory.values()- if auth.name == auth_name or auth.identity == auth_name- ]+ raise EngineStateError("OAuth activation could not inspect the engine") from exc+ matching = [auth for auth in inventory.values() if auth.name == auth_name or auth.identity == auth_name]if len(matching) > 1:raise EngineStateError("OAuth activation auth record is ambiguous")if not matching:@@ -1899,9 +1880,7 @@ class CLIProxyEngineAdapter:try:inventory = await run_owned_in_thread(_auth_inventory, client)except EngineClientError as exc:- raise EngineStateError(- "OAuth credential validation could not inspect the engine"- ) from exc+ raise EngineStateError("OAuth credential validation could not inspect the engine") from excauth_name = str(metadata.get("auth_name") or "")matches = [auth@@ -1967,11 +1946,7 @@ class CLIProxyEngineAdapter:if isinstance(prefix, str) and prefix:return prefixrecord = next(- (- source- for source in self.state_store.list_sources()- if source.credential_ref == credential_ref- ),+ (source for source in self.state_store.list_sources() if source.credential_ref == credential_ref),None,)return record.prefix if record is not None and record.prefix else None@@ -2027,7 +2002,7 @@ class CLIProxyEngineAdapter:The observation seam determines protocol from upstream responses, so thelegacy temporary record uses a neutral engine-store protocol marker.- Explicit Bearer is restricted to the Anthropic interface. Neither marker+ Explicit Bearer is restricted to Anthropic interfaces. Neither markersupplies authentication evidence; observation still needs upstream proof."""@@ -2057,11 +2032,7 @@ class CLIProxyEngineAdapter:self.state_store.credential_metadata_if_present,credential_ref,)- auth_name = (- metadata.get("auth_name")- if metadata is not None and metadata.get("kind") == "oauth"- else None- )+ auth_name = metadata.get("auth_name") if metadata is not None and metadata.get("kind") == "oauth" else Noneif auth_name:if metadata.get("activation_state") != "staged":@@ -2224,7 +2195,11 @@ class CLIProxyEngineAdapter:if auth_scheme is not None:for protocol in protocol_order:validate_api_key_auth_scheme(- normalized_vendor, protocol, base_url, secret, auth_scheme,+ normalized_vendor,+ protocol,+ base_url,+ secret,+ auth_scheme,)elif credential_kind == "oauth":if normalized_base_url is not None:@@ -2582,14 +2557,31 @@ class CLIProxyEngineAdapter:submitted = value.strip()if not submitted:raise EngineStateError("OAuth submission is empty")- # A transport failure after submission begins cannot prove whether- # the engine wrote grant material.+ is_redirect = submitted.startswith(("http://", "https://"))+ if is_redirect and not any(+ answer.strip()+ for key, answer in urllib.parse.parse_qsl(urllib.parse.urlsplit(submitted).query)+ if key in {"code", "error", "error_description"}+ ):+ # The one rejection that provably writes nothing and leaves the+ # session waiting: an address carrying no answer at all, which+ # the engine would refuse before reading its session. Decided+ # here, where the value is known, not from an engine status+ # that several different refusals share.+ logger.info(+ "OAuth submission carries no code: flow=%s provider=%s",+ flow.flow_id,+ flow.callback_provider,+ )+ raise OAuthSubmissionRejectedError(flow_id)+ # Any failure after submission begins cannot prove whether the+ # engine wrote grant material.flow.grant_write_possible = Truepayload: dict[str, str] = {"provider": flow.callback_provider,"state": flow.engine_state,}- if submitted.startswith(("http://", "https://")):+ if is_redirect:payload["redirect_url"] = submittedelse:payload["code"] = submitted@@ -2601,7 +2593,10 @@ class CLIProxyEngineAdapter:"/oauth-callback",payload=payload,)- except (EngineClientError, EngineUnavailableError):+ except EngineClientError:+ self._fail_flow(flow, "models.oauth.submission_failed")+ return flow.snapshot()+ except EngineUnavailableError:self._fail_flow(flow, "models.oauth.submission_failed")return flow.snapshot()flow.state = "verifying"@@ -2691,13 +2686,32 @@ class CLIProxyEngineAdapter:flow.grant_write_possible = Trueinventory = await asyncio.to_thread(_auth_inventory, client)provider_records = [record for record in inventory.values() if record.provider == flow.auth_provider]- candidates = [+ try:+ foreign = await asyncio.to_thread(self._foreign_bound_identities, provider_records, flow.source_id)+ except EngineStateError:+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)+ self._fail_flow(flow, "models.oauth.binding_failed")+ return+ changed = [recordfor record in provider_recordsif flow.before_auth_fingerprints.get(record.identity) != record.fingerprint]- if not candidates and len(provider_records) == 1:+ # A record that did not exist before this flow is the login it produced.+ # Accounts other Sources already hold keep changing in the background+ # (refresh, status), so they only count when nothing new appeared: then+ # the login rewrote an existing file, which is either this Source's own+ # account (re-auth) or an account another Source already owns.+ fresh = [record for record in changed if record.identity not in flow.before_auth_fingerprints]+ candidates = fresh or [record for record in changed if record.identity not in foreign]+ if not fresh and candidates and len(candidates) != len(changed):+ # Existing records of this and another Source both changed: the+ # login may have rewritten either, so neither can be named.+ candidates = changed+ if not candidates and not changed and len(provider_records) == 1:candidates = provider_records+ if not candidates and changed:+ candidates = changedif len(candidates) != 1:if not candidates:flow.state = "verifying"@@ -2706,6 +2720,21 @@ class CLIProxyEngineAdapter:self._fail_flow(flow, "models.oauth.ambiguous_engine_binding")returnauth = candidates[0]+ foreign_accounts = {+ record.account_id for record in provider_records if record.identity in foreign and record.account_id+ }+ if auth.identity in foreign or (auth.account_id and auth.account_id in foreign_accounts):+ # The same account is already a Source. A new file for it is this+ # flow's own material and is removed; an existing one belongs to the+ # other Source and is never touched.+ if auth.identity not in flow.before_auth_fingerprints and await self._delete_auth_files(auth.name):+ self._set_retained_material(flow, RetainedMaterialDisposition.NONE)+ elif auth.identity in foreign:+ self._set_retained_material(flow, RetainedMaterialDisposition.FOREIGN_SOURCE_REF)+ else:+ self._set_retained_material(flow, RetainedMaterialDisposition.UNKNOWN)+ self._fail_flow(flow, "models.oauth.account_already_added")+ returntry:existing_credential_ref = await asyncio.to_thread(self.state_store.oauth_credential_ref,@@ -2815,6 +2844,34 @@ class CLIProxyEngineAdapter:flow.state = "success"self._release_provider(flow)+ def _foreign_bound_identities(self, records: Sequence[_AuthRecord], source_id: str) -> set[str]:+ """Identities of auth records another Source's credential is bound to."""+ foreign: set[str] = set()+ for record in records:+ credential_ref = self.state_store.oauth_credential_ref(record.name)+ if credential_ref is None:+ continue+ owner = self.state_store.credential_metadata(credential_ref).get("source_id")+ if owner and owner != source_id:+ foreign.add(record.identity)+ return foreign++ async def _delete_auth_files(self, auth_name: str) -> bool:+ def remove(client: EngineClient | None) -> bool:+ try:+ if client is not None:+ client.management_request("DELETE", "/auth-files", query={"name": auth_name})+ self.state_store.delete_oauth_auth_file(auth_name)+ except (EngineClientError, EngineStateError):+ return False+ return True++ # Atomic with the engine lifecycle, like ``_cleanup_oauth_material``.+ try:+ return await asyncio.to_thread(self.supervisor.with_engine_excluded, remove)+ except EngineUnavailableError:+ return False+async def _cleanup_oauth_material(self, auth_name: str, credential_ref: str) -> bool:def remove_grant(client: EngineClient | None) -> bool:engine_delete_succeeded = True@@ -3011,8 +3068,7 @@ def _discovered_models(continuecoalesced[value] = tuple(dict.fromkeys(held + supported_parameters))return tuple(- DiscoveredModel(id=model_id, supported_parameters=parameters)- for model_id, parameters in coalesced.items()+ DiscoveredModel(id=model_id, supported_parameters=parameters) for model_id, parameters in coalesced.items())diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.pyindex 6402ad219..1d25fc773 100644--- a/vibe/model_hub_runtime/api_key_vendors.py+++ b/vibe/model_hub_runtime/api_key_vendors.py@@ -55,8 +55,10 @@ def validate_api_key_auth_scheme(A missing protocol is only for an unbound observation credential. A missingsecret is only for the credentialless contrast of an already validated- transport. The pinned CPA sends ordinary custom Claude keys as Bearer, but- interprets ``sk-ant-oat`` anywhere in a key as OAuth independently of kind.+ transport. Bearer is the Anthropic interface's custom-origin header, for any+ vendor not pinned to another protocol. The pinned CPA sends ordinary custom+ Claude keys as Bearer, but interprets ``sk-ant-oat`` anywhere in a key as+ OAuth independently of kind."""if auth_scheme is None:return None@@ -64,7 +66,9 @@ def validate_api_key_auth_scheme(if (auth_scheme != "bearer"or not isinstance(vendor, str)- or vendor.strip().lower() != "anthropic"+ or not vendor.strip()+ # Any Anthropic interface: custom relays and Anthropic-pinned vendors.+ or pinned_api_key_protocol(vendor) not in (None, "anthropic")or protocol not in (None, "anthropic")):raise ValueError