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): remove provider tier controls and resolver filtering (#1945)
Call White488c1c354c60
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 11d19bdce..7ed75a067 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -86,7 +86,6 @@ from .events import (EventReason,build_resolution_event,contains_credential_material,- redact_credential_material,)from .errors import ModelDiscoveryErrorfrom .identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL, canonical_model_id, normalized_model_id@@ -174,7 +173,6 @@ PROBE_RESULT_CONTRACT_VERSION = 10_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15_SOURCE_PROBE_TIMEOUT_SECONDS = 60_REORDER_ORDER_UNSET = object()-_REASONING_EFFORT_TELEMETRY_MAX_BYTES = 256# Settlement generations are minted per attempt start and live only in this# runtime's ledger, which restarts with the process. Every generation this# runtime mints is therefore strictly greater than this pre-attempt value, and@@ -434,56 +432,6 @@ class HandleSettlement:HandleTerminationOrigin = Literal["downstream_cancel", "upstream_terminal"]-@dataclass(frozen=True)-class ExactReasoningEffortRequest:- request: Mapping[str, Any]- stripped_efforts: tuple[str, ...] = ()- declared_efforts: tuple[str, ...] = ()---def _bounded_reasoning_effort_telemetry(value: object) -> str:- """Redact and fold an untrusted effort value into bounded telemetry."""-- if not isinstance(value, str):- if value is None:- return "<null>"- if isinstance(value, bool):- return "<bool>"- if isinstance(value, int):- return "<int>"- if isinstance(value, float):- return "<float>"- if isinstance(value, list):- return "<list>"- if isinstance(value, Mapping):- return "<dict>"- return "<non-string>"-- redacted = redact_credential_material(value)- encoded = redacted.encode("utf-8")- if len(encoded) <= _REASONING_EFFORT_TELEMETRY_MAX_BYTES:- return redacted- digest = hashlib.sha256(encoded).hexdigest()- suffix = f"... [sha256:{digest}]"- preview_bytes = _REASONING_EFFORT_TELEMETRY_MAX_BYTES - len(- suffix.encode("utf-8")- )- preview = encoded[:preview_bytes].decode("utf-8", errors="ignore")- return f"{preview}{suffix}"---def _bounded_declared_effort_telemetry(values: Iterable[str]) -> tuple[str, ...]:- redacted = tuple(redact_credential_material(value) for value in values)- payload = json.dumps(- redacted,- ensure_ascii=False,- separators=(",", ":"),- )- if len(payload.encode("utf-8")) <= _REASONING_EFFORT_TELEMETRY_MAX_BYTES:- return redacted- return (_bounded_reasoning_effort_telemetry(payload),)--AttemptObserver = Callable[[str,@@ -6883,72 +6831,6 @@ class ModelHubService:)return ResolutionDecision("fallback", reason="credential_revoked")- @staticmethod- def _request_for_exact_reasoning_effort(- request: Mapping[str, Any],- source: ModelHubSourceConfig,- model_id: str,- ) -> ExactReasoningEffortRequest:- model = next((item for item in source.models if item.id == model_id), None)- declared = tuple(model.reasoning_efforts) if model is not None else ()- supported = set(declared)-- payload = dict(request)- changed = False- stripped: list[str] = []-- def note_stripped(value: object) -> None:- safe_value = _bounded_reasoning_effort_telemetry(value)- if safe_value not in stripped:- stripped.append(safe_value)-- direct = payload.get("reasoning_effort")- if "reasoning_effort" in payload and not (- isinstance(direct, str) and direct in supported- ):- payload.pop("reasoning_effort")- changed = True- note_stripped(direct)- reasoning = payload.get("reasoning")- nested = reasoning.get("effort") if isinstance(reasoning, Mapping) else None- if (- isinstance(reasoning, Mapping)- and "effort" in reasoning- and not (isinstance(nested, str) and nested in supported)- ):- filtered_reasoning = dict(reasoning)- filtered_reasoning.pop("effort")- if filtered_reasoning:- payload["reasoning"] = filtered_reasoning- else:- payload.pop("reasoning")- changed = True- note_stripped(nested)- if not changed:- return ExactReasoningEffortRequest(request=request)- if isinstance(request, ModelHubRequest):- filtered_request: Mapping[str, Any] = ModelHubRequest(- payload,- protocol=request.protocol,- headers=request.headers,- )- else:- filtered_request = payload- safe_declared = _bounded_declared_effort_telemetry(declared)- logger.info(- "Stripped undeclared Model Hub reasoning effort(s) %s for source %s "- "model %s; declared tiers: %s",- stripped,- source.id,- model_id,- list(safe_declared),- )- return ExactReasoningEffortRequest(- request=filtered_request,- stripped_efforts=tuple(stripped),- declared_efforts=safe_declared,- )-async def resolve(self,*,@@ -7026,12 +6908,6 @@ class ModelHubService:if source is None or target_model is None:raise AssertionError("runnable hop must have an exact identity")verification_pending = source.verification_pending- exact_reasoning_request = self._request_for_exact_reasoning_effort(- request,- source,- target_model,- )- exact_request = exact_reasoning_request.requestif source.supply_channel == "native_cli":self._emit_switch(agent=event_agent,@@ -7065,15 +6941,15 @@ class ModelHubService:False,None,None,- exact_reasoning_request.stripped_efforts,- exact_reasoning_request.declared_efforts,+ (),+ (),)try:handle, outcome, cancelled = await self._invoke(source=source,model_id=target_model,- request=exact_request,+ request=request,stream=stream,backend=backend,requested_model_id=model_id,@@ -7125,7 +7001,7 @@ class ModelHubService:handle, outcome, cancelled = await self._invoke(source=source,model_id=target_model,- request=exact_request,+ request=request,stream=stream,backend=backend,requested_model_id=model_id,diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 6939a6f73..d6f1a84e9 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1124,12 +1124,12 @@ An unknown `turn_id` returns `turn_not_found`. The server derives ambiguous abselive from “known turn, no exact record”; it does not persist a placeholder and neverguesses which attempt belonged to the turn.-When exact-match forwarding removes a requested reasoning effort, that exact attempted-hop carries both `stripped_reasoning_efforts` and the declaration consulted in-`declared_reasoning_efforts`. The paired fields appear only on the failed, served,-terminal, or canceled attempt where a strip actually occurred; they never leak onto a-fallback hop or another turn. The same redacted source/model, stripped effort, and-declared-tier facts are written to the application logger without changing chat copy.+Historical exact-match forwarding records can carry `stripped_reasoning_efforts`+and `declared_reasoning_efforts` on the exact attempt that stripped them. These+paired fields remain readable. The owner amendment of 2026-09-08 removes the+resolver's inventory-based effort filtering: new attempts preserve caller intent+and do not emit stripping fields or logs. Engine translation is a separate boundary,+documented in `../model-hub-reasoning-intent.md`, not inferred from this telemetry.## Resolution eventsdiff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.mdindex 6312a6cb9..d9a2765ee 100644--- a/docs/plans/model-hub-e2e-test-plan.md+++ b/docs/plans/model-hub-e2e-test-plan.md@@ -52,7 +52,7 @@ Out of scope (documented, not dropped silently):| B7 | sole owned default source + exact one-hop manual route, verified by reads → delete source → guard 409 → echo plan → force | actual inherited supply gap; impact report lists interrupted agents; malformed echo rejected; canonical route and exact captured default order restored independently (only the owned deleted ID may be omitted) | assert || B8 | force transport asymmetry (`?force=` vs body) | document current split (B6 issue); decide normalization | baseline || B9 | refetch after upstream inventory change | added/removed diff; **`discovered_at` preserved for pre-existing models** (currently overwritten — fix-first, see B-list) | fix-first |-| B10 | open Advanced settings, inspect catalog-managed tiers; edit user/null tiers; reload a v6 row and refresh | default inventory hides capability details; advanced catalog edits return 409 `source_model_tiers_managed` with exact provenance; user tiers remain editable; refresh restores catalog truth and emits one redacted override event | assert |+| B10 | inspect provider inventory and add/remove a manual model | no reasoning column, provenance badge, tier editor or empty advanced toggle; manual creation needs only a model ID. Compatibility API tests retain existing metadata ownership coverage | assert || B11 | trigger each of: `mapping_target_unavailable`, `runtime_in_use`, `source_nonce_conflict`, `reauth_confirmation_required`, `turn_not_found` | UI renders human copy, never the raw `modelHub.errors.*` string (B1 — fix-first; baseline expected-fail) | fix-first |### C. OAuth lifecycle (C30–C40, partial by §1)@@ -75,7 +75,7 @@ Out of scope (documented, not dropped silently):| D7 | stream interrupt after first output | terminal frame injected per protocol; **no replay/failover**; source still settles; next turn resolves hop1 (takeover pill visible) | assert || D8 | cooldown `retry_at` elapses | next resolve recovers source, chain returns to hop0, `recover` event | assert || D9 | all hops failing | 503 `mapping_target_unavailable` + waiting copy with retry_at | assert |-| D10 | chat selects effort `high`; fallback hop declares tiers `[]` | upstream capture strips effort only for that hop; the exact served attempt records the stripped value and declared tiers in turn provenance | assert |+| D10 | chat selects effort `high`; fallback hop declares tiers `[]` | each exact adapter attempt retains the requested effort; turn provenance identifies the serving hop without inventing stripping. This fixture covers the Avibe gateway/adapter boundary, not the proxy engine translator | assert || D11 | `POST /{backend}/v1/messages/count_tokens` | currently 404 `not_found_error` (D-2 decision: fix or document impact on Claude Code auto-compact) | baseline || D12 | env/catalog injection for claude/codex/opencode | `ANTHROPIC_BASE_URL/TOKEN` only for claude; codex catalog neutralized 4 keys; opencode overlay model projection shape | assert || D13 | member role matrix | member can PUT chains/PATCH mode; cannot create/delete source, start runtime, read usage (B15) — assert the dead-ends are at least *visible* errors, not silent UI | assert |diff --git a/docs/plans/model-hub-reasoning-intent.md b/docs/plans/model-hub-reasoning-intent.mdnew file mode 100644index 000000000..045c2fc2e--- /dev/null+++ b/docs/plans/model-hub-reasoning-intent.md@@ -0,0 +1,50 @@+# Provider inventory and reasoning intent++Owner decision: 2026-09-08 12:33 +08. This supersedes the Source tier editor+and the resolver's exact-declaration forwarding rule, not model-menu selection,+subscription OAuth, credential replacement, or routing policy.++## Contract++- Provider inventory exposes model identity and inventory actions, not a second+ reasoning configuration surface. This holds for every metadata provenance and+ both discovered and manual models. Remove the empty advanced toggle as well.+- Manual creation needs only the model ID. It sends an empty capability list+ through the existing API and does not fetch upstream inventory.+- Removing controls does not rewrite stored capability metadata, remove models,+ alter existing routes or change another consumer's compatibility API.+- The shared resolver forwards the caller's reasoning request unchanged to the+ managed adapter for each exact Source/model attempt. Capability declarations+ are not an allowlist. Fallback and credential retry start from the same caller+ intent, preserving protocol, headers and non-effort fields.+- Protocol errors keep their existing terminal behavior. No silent fallback or+ synthesized effort is added. Historical stripping telemetry remains readable;+ new resolver attempts do not claim stripping that no longer happens.++## Proxy engine boundary++This change proves forwarding through Avibe's gateway and resolver to its+adapter. It does not claim end-to-end preservation through the pinned proxy+engine's translators. CLIProxyAPI v7.2.149 (`2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`)+has a second capability policy: `internal/modelconfig/model_info.go` marks+configured API-key models non-user-defined, and `internal/thinking/apply.go`+can strip thinking for models with no registered capability or validate a+configured level list. Removing the Avibe filter alone cannot close that gap.++Source model registration is intentionally unchanged here: simply omitting its+thinking metadata can make the engine strip more parameters, not fewer. A+separate engine policy/release change needs verification with a local mock+upstream across protocol families before an end-to-end guarantee is possible.+No live credentials or operational Avibe instance are required or used.++## Evidence++- Unit: every valid provenance shape, empty/mismatched capability metadata,+ direct and nested effort, Anthropic thinking, and absence of reasoning intent.+- Scenario: MH-EFFORT-001 and D10 traverse the HTTP turn gateway and exact+ adapter attempts; existing API capability ownership remains covered by B10.+- UI: inventory and manual-add controls independent of capability metadata;+ existing provider management, mutation settlement, OAuth and replacement.+- Browser: isolated English/Chinese desktop/mobile provider fixture, with no+ live API access. Full local Incus and proxy-engine wire verification remain+ separate evidence layers, not inferred from a fake adapter.diff --git a/docs/plans/model-hub-save-first-testing.md b/docs/plans/model-hub-save-first-testing.mdindex 362fbdd4a..7ec838849 100644--- a/docs/plans/model-hub-save-first-testing.md+++ b/docs/plans/model-hub-save-first-testing.md@@ -68,9 +68,9 @@ discovery. Its loading indicator belongs to the add operation; only explicitrefetch can animate the refetch button. Post-write local projection reads arenot upstream model fetching.-Reasoning levels are capability declarations consumed by managed model-registration, not the effort setting for a conversation. Keep the data and-editor, but show them only after opening Advanced settings. The default-inventory shows model identities and ordinary model actions. In the advanced-view, "Avibe preset levels" identifies capability metadata provenance without-implying that a discovered model itself came from a built-in inventory.+The owner amendment at 12:33 on 2026-09-08 supersedes the advanced-only tier+editor: remove reasoning levels, provenance badges and their editor from the+provider inventory entirely. The now-empty Advanced settings toggle is removed+too. Saved capability metadata and compatibility APIs remain available to their+other consumers; this UI change does not rewrite them. See+[Reasoning intent](model-hub-reasoning-intent.md) for the forwarding boundary.diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex 7362421d8..4e59c780f 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -7,8 +7,12 @@ observation gate in the API-key add dialog and the always-visible Source-modelcapability column below. Add saves a concrete protocol configuration andattempts inventory discovery, without requiring either discovery or a modeltest to succeed. An independent Test dialog selects a real saved model and-reports only that invocation. Capability declarations remain under Advanced-settings; ordinary model addition never fetches the upstream inventory.+reports only that invocation. The owner's 12:33 amendment removes the provider+reasoning column, all provenance badges, its editors and the now-empty Advanced+settings toggle. This supersedes the older tier-editor frames and decisions below;+the provider inventory is not a reasoning configuration surface. Stored capability+metadata and model-menu reasoning selection remain separate. See+`model-hub-reasoning-intent.md`. Ordinary model addition never fetches upstream inventory.Subscription OAuth and credential replacement retain their existing lifecycle.Companion to `model-hub.md`. That file is the **behaviour** authority; this one isdiff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex ca133aa29..6a42b18ae 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -543,7 +543,7 @@ for hop in C, in effective-plan order:continueattempted = true- result = invoke_exact(hop.source_id, hop.model_id, exact_reasoning_effort(hop))+ result = invoke_exact(hop.source_id, hop.model_id, original_request)if result == served: return SERVED(hop)if result == canceled: return CANCELEDif result is terminal_request_error: return FAILED_TERMINAL(result)@@ -568,9 +568,14 @@ repairs or rewrites configuration.`invoke_exact` preserves chain order. A `native_cli` hop uses the sanctioned backend'ssingleton local login; a `hub` hop uses the local Gateway and may be cross-vendor. The-system never prepends native supply or chooses a model. If the requested reasoning-effort exactly appears in the configured hop model's `reasoning_efforts`, pass that one-value; otherwise omit the effort field, with no approximation or downgrade.+system never prepends native supply or chooses a model. Owner amendment (2026-09-08):+the shared resolver passes the original reasoning intent to the adapter on every+attempt, including credential retries and provider fallback. Source inventory+capability metadata is not a forwarding allowlist: an absent declaration does not+establish unsupported reasoning. The resolver neither removes nor approximates the+requested value. Protocol translation remains the managed adapter's responsibility;+the separate engine boundary and remaining compatibility limitations are recorded in+[Reasoning intent](model-hub-reasoning-intent.md).Parameter, protocol, and tool-compatibility failures are terminal without fallthrough.A local Gateway start, listener, or process loss at **any** request phase is terminaldiff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.pyindex 81bc741af..e14c33261 100644--- a/tests/e2e/test_model_hub_routing.py+++ b/tests/e2e/test_model_hub_routing.py@@ -1004,10 +1004,10 @@ def test_d6_server_error_ignores_retry_after_and_uses_flat_cooldown()-def test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop(+def test_d10_reasoning_intent_survives_exact_provider_fallback(tmp_path,) -> None:- """D10: the per-turn gateway records the exact hop whose effort it strips."""+ """D10: provider fallback preserves intent without inventing strip telemetry."""async def exercise() -> None:first = source(@@ -1044,7 +1044,7 @@ def test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop()service = service_for(tmp_path, MemoryModelHubStore(config), adapter)gateway = ModelHubTurnGateway(service)- turn_id = "turn_d10_strip"+ turn_id = "turn_d10_intent"base_url, token = await gateway.endpoint("codex",process_scope="/repo",@@ -1074,7 +1074,10 @@ def test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop("effort": "high","summary": "auto",}- assert adapter.requests[1]["reasoning"] == {"summary": "auto"}+ assert adapter.requests[1]["reasoning"] == {+ "effort": "high",+ "summary": "auto",+ }gateway.correlation.settle(turn_id,settled_by=SETTLED_BY_TERMINAL_RESULT,@@ -1087,8 +1090,6 @@ def test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop("source_id": second.id,"configured_model_id": "relay-model","channel": "hub",- "stripped_reasoning_efforts": ["high"],- "declared_reasoning_efforts": [],}asyncio.run(exercise())diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 5c7854b82..72aa6d732 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -585,11 +585,11 @@ scenarios:layer: scenariotest: tests/scenarios/model_hub/test_model_hub_turn_contract_scenarios.py::test_mh_static_credential_failure_does_not_retry_or_claim_takeover- id: MH-EFFORT-001- name: An undeclared requested effort is omitted from the exact-hop request and the turn still completes+ name: Unknown Source capability preserves requested reasoning intentstatus: coveredkind: compatibilitylayer: scenario- test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_effort_001_undeclared_effort_is_omitted_and_turn_completes+ test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_effort_001_unknown_capability_preserves_intent_and_turn_completes- id: MH-TURN-RESULT-001name: All terminal outcomes are closed schema-valid provenance productsstatus: covered@@ -838,11 +838,11 @@ scenarios:owning_layer: future live-turn suite (turn gateway)evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81- id: D10- name: Stripped reasoning effort is attributed to the exact fallback attempt+ name: Reasoning intent survives exact-provider fallback without strip telemetrystatus: assertkind: compatibilitylayer: e2e-auto- test: tests/e2e/test_model_hub_routing.py::test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop+ test: tests/e2e/test_model_hub_routing.py::test_d10_reasoning_intent_survives_exact_provider_fallback- id: D11name: Claude token counting behavior is documented at the gatewaystatus: skipdiff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pyindex 6aa5f8a9e..ef9092645 100644--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -637,10 +637,10 @@ def test_mh_res_live_004_hub_subscription_falls_back_to_api_key_within_turn(asyncio.run(exercise())-def test_mh_effort_001_undeclared_effort_is_omitted_and_turn_completes(+def test_mh_effort_001_unknown_capability_preserves_intent_and_turn_completes(tmp_path: Path,) -> None:- """MH-EFFORT-001: an undeclared effort is omitted from the exact-hop request and the turn still completes."""+ """MH-EFFORT-001: unknown Source capability does not erase caller intent."""async def exercise() -> None:adapter = AdapterBoundaryFake(@@ -672,7 +672,7 @@ def test_mh_effort_001_undeclared_effort_is_omitted_and_turn_completes(assert body == b'{"ok":true}'assert len(adapter.requests) == 1assert "reasoning_effort" not in adapter.requests[0]- assert adapter.requests[0]["reasoning"] == {"summary": "auto"}+ assert adapter.requests[0]["reasoning"] == {"effort": "low", "summary": "auto"}finally:await gateway.close()diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex aada12478..486542ab1 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -2,7 +2,6 @@ from __future__ import annotationsimport asyncioimport copy-import hashlibimport jsonfrom collections import dequefrom datetime import datetime, timezone@@ -43,7 +42,6 @@ from core.handlers.model_hub.classification import ()from core.handlers.model_hub.events import (BoundedEventLog,- redact_credential_material,)from core.handlers.model_hub.errors import ModelDiscoveryErrorfrom core.handlers.model_hub.provenance import (@@ -832,12 +830,17 @@ def test_401_retry_depends_on_credential_capability_not_source_kind(tmp_path):))service, store, _ = _service(tmp_path, config, adapter)+ request = ModelHubRequest(+ {"reasoning": {"effort": "high", "summary": "auto"}},+ protocol="openai_responses",+ headers={"x-test": "preserved"},+ )resolved = asyncio.run(service.resolve(backend="claude",model_id="claude-opus-4-6",- request={},+ request=request,))@@ -846,15 +849,26 @@ def test_401_retry_depends_on_credential_capability_not_source_kind(tmp_path):(source.id, "claude-opus-4-6"),]assert adapter.capability_queries == ["cred_refresh401"]+ assert len(adapter.invocation_requests) == 2+ for attempt in adapter.invocation_requests:+ assert attempt == request+ assert attempt.protocol == request.protocol+ assert attempt.headers == request.headersassert resolved.source_id == source.idassert store.load().sources[0].state.status == "standby"-def test_runtime_filters_reasoning_effort_for_each_exact_hop(tmp_path):[email protected](("efforts", "provenance"), [+ ([], None), ([], "catalog"),+ *[(efforts, provenance) for efforts in (["low"], ["high"])+ for provenance in ("user", "catalog", "upstream")],+])+def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, efforts, provenance):first = _source("src_effort001", ("upstream-first",))second = _source("src_effort002", ("upstream-second",))first.models[0].reasoning_efforts = ["high"]- second.models[0].reasoning_efforts = ["low"]+ second.models[0].reasoning_efforts = efforts+ second.models[0].reasoning_efforts_source = provenanceconfig = _config([first, second])config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(hops=(@@ -907,16 +921,26 @@ def test_runtime_filters_reasoning_effort_for_each_exact_hop(tmp_path):"effort": "high","summary": "auto",}- assert adapter.invocation_requests[1]["reasoning"] == {"summary": "auto"}+ assert adapter.invocation_requests[1] == request+ assert request["reasoning"] == {"effort": "high", "summary": "auto"}assert adapter.invocation_requests[1].protocol == "openai_responses"assert adapter.invocation_requests[1].headers == {"x-test": "preserved"}started = [attempt for attempt in observed_attempts if attempt[4] is None]assert [attempt[0] for attempt in started] == [first.id, second.id]assert started[0][6:] == ((), ())- assert started[1][6:] == (("high",), ("low",))---def test_runtime_omits_unsupported_direct_reasoning_effort(tmp_path):+ assert started[1][6:] == ((), ())++[email protected]("payload", [+ {"reasoning_effort": "high"},+ {"reasoning_effort": "future-tier"},+ {"reasoning": {"effort": "high", "summary": "auto"}},+ {"thinking": {"type": "enabled", "budget_tokens": 4096}},+ {"thinking": {"type": "adaptive"}, "output_config": {"effort": "max"}},+ {"reasoning": {"summary": "auto"}},+ {},+])+def test_runtime_preserves_request_when_provider_capability_is_unknown(tmp_path, payload):source = _source("src_effort003", ("upstream-model",))config = _config([source])config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(@@ -936,7 +960,7 @@ def test_runtime_omits_unsupported_direct_reasoning_effort(tmp_path):)service, _store, _ = _service(tmp_path, config, adapter)request = ModelHubRequest(- {"reasoning_effort": "high"},+ copy.deepcopy(payload),protocol="openai_chat",headers={"x-test": "preserved"},)@@ -950,160 +974,13 @@ def test_runtime_omits_unsupported_direct_reasoning_effort(tmp_path):)assert resolved.source_id == source.id- assert "reasoning_effort" not in adapter.invocation_requests[0]+ assert adapter.invocation_requests[0] == payload+ assert request == payloadassert adapter.invocation_requests[0].protocol == "openai_chat"assert adapter.invocation_requests[0].headers == {"x-test": "preserved"}-def test_reasoning_effort_strip_log_redacts_values_and_names_declared_tiers(- tmp_path,- caplog,-):- source = _source("src_effortlog1", ("upstream-model",))- source.models[0].reasoning_efforts = ["low", "high"]- config = _config([source])- config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(- hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)- )- adapter = FakeAdapter()- adapter.outcomes.append(- RawCallOutcome(- kind=RawOutcomeKind.SUCCESS,- http_status=200,- error_code=None,- redacted_message=None,- stream_started=False,- model_id="upstream-model",- source_id=source.id,- )- )- service, _store, _ = _service(tmp_path, config, adapter)-- with caplog.at_level("INFO", logger="core.handlers.model_hub.service"):- asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-6",- request={- "reasoning_effort": (- "authorization: sk-test-strip-secret-material"- )- },- )- )-- assert "sk-test-strip-secret-material" not in caplog.text- assert "[redacted]" in caplog.text- assert "declared tiers: ['low', 'high']" in caplog.text---def test_reasoning_effort_telemetry_is_utf8_bounded_after_redaction(caplog):- source = _source("src_effortbound", ("upstream-model",))- long_declared = "层级" * 200- source.models[0].reasoning_efforts = ["low", long_declared]- long_stripped = (- "深度" * 200 + " authorization: sk-test-strip-secret-material"- )-- with caplog.at_level("INFO", logger="core.handlers.model_hub.service"):- result = ModelHubService._request_for_exact_reasoning_effort(- {"reasoning_effort": long_stripped},- source,- "upstream-model",- )-- [stripped] = result.stripped_efforts- [declared] = result.declared_efforts- safe_stripped = redact_credential_material(long_stripped)- stripped_digest = hashlib.sha256(safe_stripped.encode("utf-8")).hexdigest()- declared_payload = json.dumps(- ("low", long_declared),- ensure_ascii=False,- separators=(",", ":"),- )- declared_digest = hashlib.sha256(declared_payload.encode("utf-8")).hexdigest()- assert len(stripped.encode("utf-8")) <= 256- assert len(declared.encode("utf-8")) <= 256- assert stripped.endswith(f"[sha256:{stripped_digest}]")- assert declared.endswith(f"[sha256:{declared_digest}]")- assert hashlib.sha256(long_stripped.encode("utf-8")).hexdigest() not in stripped- assert long_stripped not in caplog.text- assert long_declared not in caplog.text- assert "sk-test-strip-secret-material" not in caplog.text- assert stripped in caplog.text- assert declared in caplog.text---def test_reasoning_effort_telemetry_bounds_many_short_declared_tiers():- source = _source("src_effortmany", ("upstream-model",))- source.models[0].reasoning_efforts = [- f"tier-{index:04d}" for index in range(1_000)- ]-- result = ModelHubService._request_for_exact_reasoning_effort(- {"reasoning_effort": "undeclared"},- source,- "upstream-model",- )-- [declared] = result.declared_efforts- assert len(declared.encode("utf-8")) <= 256- assert declared.endswith("]")- assert "[sha256:" in declared---def test_reasoning_effort_telemetry_preserves_short_values_exactly():- source = _source("src_effortshort", ("upstream-model",))- source.models[0].reasoning_efforts = ["low", "high"]-- result = ModelHubService._request_for_exact_reasoning_effort(- {"reasoning_effort": "ultra"},- source,- "upstream-model",- )-- assert result.stripped_efforts == ("ultra",)- assert result.declared_efforts == ("low", "high")--- ("request_payload", "expected_request", "expected_stripped"),- [- ({"reasoning_effort": ""}, {}, ("",)),- ({"reasoning_effort": 7}, {}, ("<int>",)),- (- {"reasoning": {"effort": ["high"], "summary": "auto"}},- {"reasoning": {"summary": "auto"}},- ("<list>",),- ),- (- {"reasoning": {"effort": None}},- {},- ("<null>",),- ),- ],- ids=("direct-empty", "direct-int", "nested-list", "nested-null"),-)-def test_reasoning_effort_telemetry_records_every_stripped_value(- request_payload,- expected_request,- expected_stripped,-):- source = _source("src_efforttype", ("upstream-model",))- source.models[0].reasoning_efforts = ["high"]-- result = ModelHubService._request_for_exact_reasoning_effort(- request_payload,- source,- "upstream-model",- )-- assert result.request == expected_request- assert result.stripped_efforts == expected_stripped- assert result.declared_efforts == ("high",)---def test_runtime_filters_reasoning_effort_forms_independently(tmp_path):+def test_runtime_leaves_protocol_reasoning_validation_to_the_adapter(tmp_path):source = _source("src_effort004", ("upstream-model",))source.models[0].reasoning_efforts = ["high"]config = _config([source])@@ -1142,7 +1019,7 @@ def test_runtime_filters_reasoning_effort_forms_independently(tmp_path):assert resolved.source_id == source.idassert adapter.invocation_requests[0]["reasoning_effort"] == "high"- assert adapter.invocation_requests[0]["reasoning"] == {"summary": "auto"}+ assert adapter.invocation_requests[0]["reasoning"] == {"effort": "ultra", "summary": "auto"}def test_runtime_inherits_exact_passthrough_without_aliasing_api_inventory():diff --git a/ui/e2e/b-source-detail.spec.ts b/ui/e2e/b-source-detail.spec.tsindex 9a0fe597c..587e6cfea 100644--- a/ui/e2e/b-source-detail.spec.ts+++ b/ui/e2e/b-source-detail.spec.ts@@ -5,7 +5,6 @@// The source these specs act on is created through the API, not through the Add// dialog: their subject is what happens AFTER a source exists, and re-driving// Add here would report Add's failures under a rename test's name.-import type { Source } from './support/api';import { hub as copy } from './support/copy';import { E2E_SOURCE_PREFIX, mockBaseUrl } from './support/env';import {@@ -17,61 +16,7 @@ import {requireSource,test,} from './support/fixtures';-import type { ModelHubPage } from './support/hub';import { anthropicInventory } from './support/mock';-import { PROTOCOL_TIER_SUGGESTIONS } from './support/vocabulary';--type Supplied = Source['models'][number];-type ManagedRung = 'upstream' | 'catalog';--/**- * The lock this UI can show only exists once the server has stamped the rung.- * The ladder ships, so a running instance that leaves the row editable is one- * whose build predates it — the pre-ladder behavior, not a product failure- * here. `test.fixme` rather than `test.skip`: the report names the instance's- * missing rung, and the same spec asserts on an up-to-date one with no edit.- */-const requireManagedRung = (- model: Supplied | undefined,- modelId: string,- rung: ManagedRung,-): boolean => {- const stamped = model?.reasoning_efforts_source;- if (stamped === rung) return true;- // `test.fixme` is the skip the report should show; the return is what- // keeps this body from then asserting a lock the instance cannot draw.- test.fixme(- true,- `this instance did not stamp reasoning_efforts_source=${rung} on ${modelId}`- + ` (got ${stamped === undefined ? 'absent' : JSON.stringify(stamped)}); `- + 'locked editor and provenance badge cannot be reached on this instance.',- );- return false;-};--const expectLockedRow = async (- page: ModelHubPage,- modelId: string,- rung: ManagedRung,-): Promise<void> => {- const cell = page.managedTierCell(modelId, rung);- await expect(cell).toBeVisible();- await expect(cell).toContainText(copy(`sourceDetail.tiers.managed.${rung}`));- await expect(page.tierAddAffordance(modelId)).toHaveCount(0);- await expect(page.modelRow(modelId).getByRole('textbox')).toHaveCount(0);- await expect(page.tierSuggestions(modelId)).toHaveCount(0);- await cell.click();- await expect(page.modelRow(modelId).getByRole('textbox')).toHaveCount(0);- await expect(page.tierSuggestions(modelId)).toHaveCount(0);- for (const tier of await page.tierChips(modelId).allTextContents()) {- await expect(- page.modelRow(modelId).getByRole('button', {- name: copy('sourceDetail.tiers.remove', { tier }),- exact: true,- }),- ).toHaveCount(0);- }-};test.describe('B · the source detail panel', () => {test.beforeEach(async ({ api, mock }) => {@@ -97,7 +42,6 @@ test.describe('B · the source detail panel', () => {await hub.goto();await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();await expect(hub.sourceDetailDialog).toBeVisible();await hub.manageMenuTrigger(before).click();@@ -144,7 +88,6 @@ test.describe('B · the source detail panel', () => {await hub.goto();await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.action.refetch'), exact: true }).click();@@ -168,7 +111,7 @@ test.describe('B · the source detail panel', () => {// test the formatter.});- test('B10 · a model added by hand carries its tiers, and can be taken back out', async ({ hub, mock, api }) => {+ test('B10 · a model can be added and removed without configuring reasoning', async ({ hub, mock, api }) => {await mock.configure({auth: 'ok',protocol: 'anthropic',@@ -180,7 +123,6 @@ test.describe('B · the source detail panel', () => {await hub.goto();await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.action.addModel'), exact: true }).click();@@ -188,16 +130,7 @@ test.describe('B · the source detail panel', () => {const draft = hub.manualDraftRow;await expect(draft).toBeVisible();await draft.getByPlaceholder(copy('sourceDetail.col.id'), { exact: true }).fill('e2e-by-hand');- // Tiers are free text committed with Enter — the product says so in the- // placeholder, and this is the path a user actually takes.- const tierInput = draft.getByPlaceholder(copy('sourceDetail.tiers.inputHint'), { exact: true });- await tierInput.fill('e2e-low');- await tierInput.press('Enter');- await tierInput.fill('e2e-high');- await tierInput.press('Enter');- // Typed, then thought better of: removing a tier before committing must- // actually drop it, not just hide the chip.- await draft.getByRole('button', { name: copy('sourceDetail.tiers.remove', { tier: 'e2e-high' }), exact: true }).click();+ await expect(draft.getByRole('textbox')).toHaveCount(1);await draft.getByRole('button', { name: copy('sourceDetail.action.addModel'), exact: true }).click();@@ -206,8 +139,6 @@ test.describe('B · the source detail panel', () => {// Provenance is visible, because a hand-added model behaves differently on// the next refetch than a discovered one.await expect(row).toContainText(copy('sourceDetail.entry.manual'));- await expect(row).toContainText('e2e-low');- await expectVisibleWithout(row, 'e2e-high');await expect.poll(async () =>@@ -216,7 +147,7 @@ test.describe('B · the source detail panel', () => {?.models.find((model) => model.id === 'e2e-by-hand')?.reasoning_efforts,{ timeout: 15_000 },)- .toEqual(['e2e-low']);+ .toEqual([]);// And back out again. No route runs through it, so nothing guards this.await row.getByRole('button', { name: `${copy('sourceDetail.row.remove')} e2e-by-hand`, exact: true }).click();@@ -228,184 +159,4 @@ test.describe('B · the source detail panel', () => {await expect(hub.modelRow('e2e-discovered')).toBeVisible();});- // B10 grows the provenance cases the spec's D-5 decision added: the editor- // is a door only when the server does not own the list. Locked rows, the- // badge that says which rung owns them, ghost suggestions matching the- // protocol vocabulary, and the 409 copy that must never offer a retry.-- test('B10 · ghost suggestions match the protocol vocabulary', async ({ hub, mock, api }) => {- await mock.configure({- auth: 'ok',- protocol: 'anthropic',- models_endpoint: 'ok',- models: anthropicInventory(['e2e-vocab']),- });- const name = `${E2E_SOURCE_PREFIX}tier-vocab`;- const source = await requireSource(api, name, mockBaseUrl());- const model = source.models.find((entry) => entry.id === 'e2e-vocab');- expect(model, 'The precondition source did not take the seeded inventory, so there is no editor to open.').toBeTruthy();- const expected = PROTOCOL_TIER_SUGGESTIONS[source.protocol];- expect(expected, `no suggestion list for protocol ${source.protocol}`).toBeTruthy();- if (!expected) return;-- await hub.goto();- await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();- await hub.tierCell('e2e-vocab').click();-- await expect(hub.modelRow('e2e-vocab').getByRole('textbox')).toBeVisible();- await expect(hub.tierSuggestions('e2e-vocab')).toHaveText([...expected]);- await expect(hub.managedTierCell('e2e-vocab', 'upstream')).toHaveCount(0);- await expect(hub.managedTierCell('e2e-vocab', 'catalog')).toHaveCount(0);- });-- test('B10 · a catalog-declared model shows its provenance and cannot be edited', async ({ hub, mock, api }) => {- // `claude-opus-4-6` is a real builtin-catalog id. A server that has landed- // the provenance ladder stamps it `catalog` and re-applies the catalog- // list on every refresh; a server that has not leaves the field absent- // and the row editable — which is the pre-ladder behavior, not a lock- // this UI can show.- const catalogId = 'claude-opus-4-6';- const siblingId = 'e2e-not-in-catalog';- await mock.configure({- auth: 'ok',- protocol: 'anthropic',- models_endpoint: 'ok',- models: anthropicInventory([catalogId, siblingId]),- });- const name = `${E2E_SOURCE_PREFIX}tier-catalog`;- const source = await requireSource(api, name, mockBaseUrl());- const catalogModel = source.models.find((entry) => entry.id === catalogId);- expect(catalogModel, 'The precondition source did not take the catalog id, so there is no row to lock.').toBeTruthy();- if (!requireManagedRung(catalogModel, catalogId, 'catalog')) return;-- await hub.goto();- await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();- await expectLockedRow(hub, catalogId, 'catalog');-- // Locking is per model: the sibling the catalog does not know stays a door.- await hub.tierCell(siblingId).click();- await expect(hub.modelRow(siblingId).getByRole('textbox')).toBeVisible();- });-- test('B10 · an upstream-declared model shows its provenance and cannot be edited', async ({ hub, mock, api }) => {- // OpenRouter-shape `supported_parameters` carrying a reasoning signal is- // the v1 capture the spec names. The id is deliberately not a catalog- // entry, so a server that has landed rung 1 stamps `upstream` rather- // than falling through to rung 2.- const upstreamId = 'e2e-reasoner';- const siblingId = 'e2e-no-signal';- await mock.configure({- auth: 'ok',- protocol: 'anthropic',- models_endpoint: 'ok',- models: [- {- id: upstreamId,- type: 'model',- display_name: `${upstreamId} (upstream label)`,- supported_parameters: ['reasoning'],- },- ...anthropicInventory([siblingId]),- ],- });- const name = `${E2E_SOURCE_PREFIX}tier-upstream`;- const source = await requireSource(api, name, mockBaseUrl());- const upstreamModel = source.models.find((entry) => entry.id === upstreamId);- expect(upstreamModel, 'The precondition source did not take the seeded reasoner, so there is no row to lock.').toBeTruthy();- if (!requireManagedRung(upstreamModel, upstreamId, 'upstream')) return;-- await hub.goto();- await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();- await expectLockedRow(hub, upstreamId, 'upstream');-- await hub.tierCell(siblingId).click();- await expect(hub.modelRow(siblingId).getByRole('textbox')).toBeVisible();- });-- for (const locale of ['en', 'zh'] as const) {- test(`B10 · a managed-tier refusal is a sentence in ${locale}, not a retry`, async ({ hub, mock, api, page }) => {- // The UI does not offer the write on a locked row, so the authentic- // browser path is a state race: the editor is open because this client- // still believes the row is editable, and the PATCH comes back as the- // server owning the list. Intercepting that one call is how the copy is- // reached on an instance whose build predates the guard — and remains- // the path on one that has it, because a locked row never sends the- // write. The instance's language is not saved; Chinese is a- // config-GET rewrite for this page only.- if (locale === 'zh') {- await page.route('**/api/config', async (route) => {- if (route.request().method() !== 'GET') {- await route.continue();- return;- }- const response = await route.fetch();- await route.fulfill({- response,- json: { ...(await response.json() as Record<string, unknown>), language: 'zh' },- });- });- }- await page.route('**/api/models/sources/*/models/*', async (route) => {- if (route.request().method() !== 'PATCH') {- await route.continue();- return;- }- await route.fulfill({- status: 409,- json: { ok: false, error: 'source_model_tiers_managed' },- });- });-- await mock.configure({- auth: 'ok',- protocol: 'anthropic',- models_endpoint: 'ok',- models: anthropicInventory(['e2e-refusal']),- });- const name = `${E2E_SOURCE_PREFIX}tier-refusal-${locale}`;- const source = await requireSource(api, name, mockBaseUrl());- const expected = PROTOCOL_TIER_SUGGESTIONS[source.protocol];- expect(expected, `no suggestion list for protocol ${source.protocol}`).toBeTruthy();- const first = expected![0];- expect(first, 'the protocol vocabulary is empty, so there is no suggestion to click').toBeTruthy();- if (!first) return;-- await hub.goto();- await hub.openSource(source.id);- await hub.sourceDetailDialog.getByRole('button', { name: copy('sourceDetail.advanced'), exact: true }).click();- await expect(- hub.sourceDetailDialog.getByRole('button', {- name: copy('sourceDetail.action.refetch', undefined, locale),- exact: true,- }),- ).toBeVisible();-- await hub.tierCell('e2e-refusal').click();- await expect(hub.modelRow('e2e-refusal').getByRole('textbox')).toBeVisible();- await hub.modelRow('e2e-refusal').getByRole('button', {- name: copy('sourceDetail.tiers.suggest', { tier: first }, locale),- exact: true,- }).click();-- await expect(hub.tierFailure('e2e-refusal', 'managed')).toBeVisible();- await expect(hub.tierFailure('e2e-refusal', 'managed')).toHaveText(- copy('sourceDetail.fail.tierManaged', undefined, locale),- );- await expect(hub.tierFailure('e2e-refusal', 'retryable')).toHaveCount(0);- await expect(- hub.modelRow('e2e-refusal').getByRole('button', {- name: copy('sourceDetail.retry', undefined, locale),- exact: true,- }),- ).toHaveCount(0);- await expectVisibleWithout(- hub.modelRow('e2e-refusal'),- copy('sourceDetail.fail.tier', undefined, locale),- );- await expect(hub.tierChips('e2e-refusal')).toHaveCount(0);- });- }});diff --git a/ui/e2e/model-provider/provider.spec.ts b/ui/e2e/model-provider/provider.spec.tsindex e02ced9ff..c0980b08c 100644--- a/ui/e2e/model-provider/provider.spec.ts+++ b/ui/e2e/model-provider/provider.spec.ts@@ -8,6 +8,8 @@ for (const lang of ['en', 'zh'] as const) {await page.goto('/e2e/model-provider/fixture.html?lang=' + lang);await expect(page.getByText('Example relay', { exact: true })).toBeVisible();await expect(page.getByText('high', { exact: true })).toHaveCount(0);+ await expect(page.locator('[data-tier-provenance]')).toHaveCount(0);+ await expect(page.getByRole('button', { name: /Advanced settings|高级设置/ })).toHaveCount(0);await page.getByRole('button', { name: 'Add provider fixture' }).click();await page.getByRole('textbox', { name: 'Base URL', exact: true }).fill('https://relay.example/v1');await page.getByLabel(text('addKey.field.apiKey'), { exact: true }).fill('fixture-placeholder');@@ -25,10 +27,12 @@ for (const lang of ['en', 'zh'] as const) {await page.getByRole('button', { name: lang === 'en' ? 'Close' : '关闭', exact: true }).first().click();await page.getByRole('button', { name: text('sourceDetail.action.addModel'), exact: true }).click();await page.getByPlaceholder(text('sourceDetail.col.id'), { exact: true }).fill('manual-model');+ await expect(page.locator('[data-manual-model-draft]').getByRole('textbox')).toHaveCount(1);+ await page.locator('.model-hub-source-detail').screenshot({ path: info.outputPath('manual-model.png') });await page.getByRole('button', { name: text('sourceDetail.action.addModel'), exact: true }).last().click();await expect(page.getByText('manual-model', { exact: true })).toBeVisible();expect(await page.getByTestId('calls').textContent()).not.toContain('refetch');- await page.screenshot({ path: info.outputPath('inventory.png') });+ await page.locator('.model-hub-source-detail').screenshot({ path: info.outputPath('inventory.png') });expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);});diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 51d52ae57..8d0e2d377 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -601,7 +601,7 @@ describe('SettingsModelsPage surface branches', () => {expect(screen.queryByText(/^Switch to the gateway and you gain three things$|^切换到模型网关,你会多出三件事$/i)).toBeNull();});- it('keeps tier-editor Escape local to the provider dialog', async () => {+ it('keeps manual-model draft Escape local to the provider dialog', async () => {const editableSource: Source = {...retainedSource,models: [{ id: 'model-a', display_name: null, origin: 'manual', reasoning_efforts: ['high'], reasoning_efforts_source: 'user' }],@@ -612,17 +612,8 @@ describe('SettingsModelsPage surface branches', () => {const sourceOpener = (await screen.findByText('Retained source')).closest('button') as HTMLButtonElement;await user.click(sourceOpener);const sourceDialog = await screen.findByRole('dialog', { name: 'Retained source' });- await user.click(within(sourceDialog).getByRole('button', { name: /Advanced settings|高级设置/ }));- await user.click(within(sourceDialog).getByRole('button', { name: /high/i }));- const tierInput = within(sourceDialog).getByPlaceholderText(/Enter to add|回车添加/i);- await user.type(tierInput, 'draft');- await user.keyboard('{Escape}');-- expect(screen.getByRole('dialog', { name: 'Retained source' })).toBeTruthy();- expect(within(sourceDialog).queryByPlaceholderText(/Enter to add|回车添加/i)).toBeNull();-await user.click(within(sourceDialog).getByRole('button', { name: /^Add model$|^添加模型$/i }));- let manualDraft = sourceDialog.querySelector('[data-manual-model-draft]');+ const manualDraft = sourceDialog.querySelector('[data-manual-model-draft]');const modelIdInput = within(manualDraft as HTMLElement).getByPlaceholderText(/^Model ID$|^模型 ID$/i);await user.type(modelIdInput, 'draft-model');await user.keyboard('{Escape}');@@ -630,15 +621,6 @@ describe('SettingsModelsPage surface branches', () => {expect(screen.getByRole('dialog', { name: 'Retained source' })).toBeTruthy();expect(sourceDialog.querySelector('[data-manual-model-draft]')).toBeNull();- await user.click(within(sourceDialog).getByRole('button', { name: /^Add model$|^添加模型$/i }));- manualDraft = sourceDialog.querySelector('[data-manual-model-draft]');- const draftTierInput = within(manualDraft as HTMLElement).getByPlaceholderText(/Enter to add|回车添加/i);- await user.type(draftTierInput, 'draft');- await user.keyboard('{Escape}');-- expect(screen.getByRole('dialog', { name: 'Retained source' })).toBeTruthy();- expect((draftTierInput as HTMLInputElement).value).toBe('');-await user.keyboard('{Escape}');await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Retained source' })).toBeNull());await waitFor(() => expect(document.activeElement).toBe(sourceOpener));diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex a9bc5fbf2..3401fb9c2 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -2,7 +2,7 @@import { readFileSync } from 'node:fs';import { join } from 'node:path';import * as React from 'react';-import { cleanup, fireEvent, render as renderRaw, screen, waitFor, within } from '@testing-library/react';+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { I18nextProvider } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -22,27 +22,15 @@ import { GuardGapList } from './GuardGapList';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, repairAction, type RepairKind } from './repair';import { SourceDetailPanel } from './SourceDetailPanel';import { SourceMutationReport } from './SourceMutationReport';-import { MANAGED_TIER_SOURCES, type ManagedTierSource } from './tierMutation';-import { TIER_SUGGESTIONS } from './tierSuggestions';import {COOLDOWN_DETAIL_KEYS,ERROR_DETAIL_KEYS,NEEDS_ACTION_DETAIL_KEYS,- SOURCE_PROTOCOLS,SOURCE_STATUSES,} from './types';import type { Source, SourceDetailKey, SourceKind, SourceProtocol, SupplyChannel } from './types';import { useSourceMutationReport } from './useSourceMutationReport';-// Existing tier/editor invariants exercise the explicit advanced surface.-// Default inventory behavior is tested separately with renderRaw below.-const render = (ui: React.ReactNode) => {- const view = renderRaw(ui);- const advanced = screen.queryByRole('button', { name: /Advanced settings|高级设置/ });- if (advanced) fireEvent.click(advanced);- return view;-};-const source: Source = {id: 'src_detail',last_discovered_at: '2026-08-11T08:00:00Z',@@ -160,14 +148,6 @@ const ReportOwnedPanel: React.FC<ReportOwnedPanelProps> = (props) => {);};type MutationScheduler = <T>(work: () => Promise<T>) => Promise<T>;-const serializedTrack = (): MutationScheduler => {- const writes = createPendingWrites(() => {});- return async <T,>(work: () => Promise<T>): Promise<T> => {- let result!: T;- await writes.track(source.id, async () => { result = await work(); });- return result;- };-};const renderPanel = (adoptedBy: Source['adopted_by'] = undefined) => render(<ToastProvider>@@ -184,22 +164,6 @@ const renderProtocol = (protocol: SourceProtocol, models: Source['models'] = sou</I18nextProvider></ToastProvider>,);-/** Read by the class the stylesheet owns: the ghost chip has no other identity. */-const suggestedTiers = () => Array.from(document.querySelectorAll('.model-hub-source-tier-suggest'))- .map((chip) => chip.textContent?.trim() ?? '');-/** The tiers the row actually carries, in either branch that draws them. */-const chipTiers = () => Array.from(document.querySelectorAll('.model-hub-source-tier-chip'))- .map((chip) => chip.textContent?.trim() ?? '');-/**- * What the badge on a locked row says, per rung. Spelled out rather than read- * back through `i18n.t`: a bundle missing the entry returns the key from both- * sides of that comparison, so it would pass while the user reads- * 「settings.models.sourceDetail.tiers.managed.upstream」.- */-const MANAGED_BADGE: Readonly<Record<ManagedTierSource, RegExp>> = {- upstream: /^From provider$|^供应商声明$/,- catalog: /^Avibe preset levels$|^Avibe 预置档位$/,-};const EchoPanel: React.FC<{reconcile?: () => Promise<SourceMutationLanding['verdict'] | void> | SourceMutationLanding['verdict'] | void;@@ -254,18 +218,27 @@ afterEach(() => {});describe('SourceDetailPanel', () => {- it('keeps capability details out of the default inventory without removing advanced controls', async () => {- renderRaw(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);- expect(screen.queryByRole('button', { name: /high/i })).toBeNull();- await userEvent.click(screen.getByRole('button', { name: /Advanced settings|高级设置/ }));- expect(screen.getByRole('button', { name: /high/i })).toBeTruthy();+ it.each(['upstream', 'catalog', 'user', null] as const)('keeps provider inventory independent of %s reasoning metadata', async (provenance) => {+ const model = { ...source.models[0], reasoning_efforts_source: provenance };+ const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts');+ renderProtocol('anthropic', [model]);+ const row = screen.getByText('model-a').closest('.model-hub-source-table-row')!;+ expect(row.textContent).not.toMatch(/high|preset|预置|声明/);+ expect(screen.queryByRole('button', { name: /Advanced settings|高级设置/ })).toBeNull();+ expect(row.querySelector('[data-tier-provenance]')).toBeNull();+ expect(within(row as HTMLElement).getByRole('button', { name: /Remove|移除/ })).toBeTruthy();+ await userEvent.click(screen.getByRole('button', { name: /^Add model$|^添加模型$/i }));+ const draft = screen.getByPlaceholderText(/^Model ID$|^模型 ID$/i).closest('[data-manual-model-draft]')!;+ expect(within(draft as HTMLElement).getAllByRole('textbox')).toHaveLength(1);+ expect(update).not.toHaveBeenCalled();+ expect(model.reasoning_efforts).toEqual(['high']);});it('never presents a manual model write as an upstream refetch', async () => {const pending = new Promise<Source>(() => {});const add = vi.spyOn(modelsApi, 'addCustomModel').mockReturnValue(pending);const refetch = vi.spyOn(modelsApi, 'refreshSource');- renderRaw(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);const user = userEvent.setup();await user.click(screen.getByRole('button', { name: /Add model|添加模型/ }));await user.type(screen.getByPlaceholderText(/Model ID|模型 ID/), 'manual-model');@@ -280,7 +253,7 @@ describe('SourceDetailPanel', () => {it('shows refetch progress only on refetch while a manual draft is open', async () => {vi.spyOn(modelsApi, 'refreshSource').mockReturnValue(new Promise(() => {}));const add = vi.spyOn(modelsApi, 'addCustomModel');- renderRaw(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><ReportOwnedPanel source={source} trackMutation={immediateTrack} onReauth={noReauth} /></I18nextProvider>);await userEvent.click(screen.getByRole('button', { name: /Add model|添加模型/ }));const refetch = screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i });await userEvent.click(refetch);@@ -319,26 +292,7 @@ describe('SourceDetailPanel', () => {expect(filteredRow.hidden).toBe(false);});- it('keeps a row-local tier failure answerable while search filters the row', async () => {- vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));- renderPanel();- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'draft{Enter}');- const failure = await screen.findByText(/tier was not saved|档位没保存上/i);- const row = failure.closest('.model-hub-source-table-row') as HTMLElement;-- const search = screen.getByRole('textbox', { name: /Search model IDs|搜索模型 ID/i });- await userEvent.type(search, 'missing-model');- expect(row.hidden).toBe(true);- expect(document.activeElement).toBe(search);-- await userEvent.clear(search);- expect(row.hidden).toBe(false);- expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();- expect(document.activeElement).toBe(search);- });-- it('keeps the detail surface to inventory, entry kind, tiers, and refetch', () => {+ it('keeps the detail surface focused on model inventory and provider management', () => {renderPanel();expect(screen.queryByText(/latency|延迟|enrollment|protocol|协议/i)).toBeNull();expect(screen.queryByText(/^Standby$|^待命$/i)).toBeNull();@@ -932,14 +886,6 @@ describe('SourceDetailPanel', () => {expect(screen.queryByRole('button', { name: /^Refetch$|^重新拉取$/i })).toBeNull();});- it('discards an uncommitted tier on Escape', async () => {- renderPanel();- await userEvent.click(screen.getByRole('button', { name: /high/i }));- const input = screen.getByPlaceholderText(/Enter to add|回车添加/i);- await userEvent.type(input, 'draft{Escape}');- expect(screen.queryByDisplayValue('draft')).toBeNull();- });-it('opens the manual model draft in the table and keeps Add disabled while blank', async () => {renderPanel();await userEvent.click(screen.getAllByRole('button', { name: /^Add model$|^添加模型$/i })[0]);@@ -964,9 +910,9 @@ describe('SourceDetailPanel', () => {.closest('[data-manual-model-draft]') as HTMLElement;await userEvent.type(within(draft).getByPlaceholderText(/^Model ID$|^模型 ID$/i), 'model-b');await userEvent.click(within(draft).getByRole('button', { name: /^Add model$|^添加模型$/i }));- // The failure line is the fourth cell, and the only one that has to be+ // The failure line is the third cell, and the only one that has to be// waited for; the count is what proves the band is fully seeded.- await waitFor(() => { expect(draft.children.length).toBe(4); });+ await waitFor(() => { expect(draft.children.length).toBe(3); });const cells = Array.from(draft.children).map((cell) => cell.className);expect(cells.filter((name) => /(?:col|row)-(?:span|start|end)-/.test(name))).toEqual([]);@@ -1008,41 +954,17 @@ describe('SourceDetailPanel', () => {expect(reconcile).toHaveBeenCalledOnce();});- it('serializes a tier write and a refetch for the same Source', async () => {- const tierResponse = deferred<Source>();- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockReturnValueOnce(tierResponse.promise);- const refreshed = {- ...source,- models: [...source.models, { id: 'model-b', display_name: null, origin: 'discovered' as const, reasoning_efforts: [], reasoning_efforts_source: null }],- };- const refetch = vi.spyOn(modelsApi, 'refreshSource').mockResolvedValueOnce({ source: refreshed, discovered: refreshed.models.length });- renderEchoPanel(vi.fn(), serializedTrack());-- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');- await waitFor(() => expect(update).toHaveBeenCalledOnce());- await userEvent.click(screen.getByRole('button', { name: /^Refetch$|^重新拉取$/i }));- expect(refetch).not.toHaveBeenCalled();-- tierResponse.resolve({- ...source,- models: [{ ...source.models[0], reasoning_efforts: ['high', 'low'] }],- });- await waitFor(() => expect(refetch).toHaveBeenCalledOnce());- expect(await screen.findByText('model-b')).toBeTruthy();- });-it('orders every full-Source mutation family through the same Source queue', async () => {const writes = createPendingWrites(() => {});const started: string[] = [];- const families = ['tier', 'refetch', 'add', 'remove', 'edit', 'delete'];+ const families = ['refetch', 'add', 'remove', 'edit', 'delete'];const gates = families.map(() => deferred<void>());const runs = families.map((name, index) => writes.track(source.id, async () => {started.push(name);await gates[index].promise;}));- await waitFor(() => expect(started).toEqual(['tier']));+ await waitFor(() => expect(started).toEqual(['refetch']));for (let index = 0; index < gates.length; index += 1) {gates[index].resolve();await waitFor(() => expect(started).toEqual(families.slice(0, index + 2)));@@ -1057,7 +979,6 @@ describe('SourceDetailPanel', () => {expect(detail).toMatch(/const remove = \(model: SuppliedModel, confirmation\?: GuardConfirmation\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);expect(detail).toMatch(/const submitEdit = \(draft: SourceEditDraft, patch: SourcePatch, plan: ManageGuardPlan \| null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);expect(detail).toMatch(/const submitDelete = \(plan: ManageGuardPlan \| null\)[\s\S]*?return trackMutation\(async \(latest, settlement\)/);- expect(detail).toMatch(/const commit = async[\s\S]*?setSaving\(true\)[\s\S]*?trackMutation\(async \(latest, settlement\)[\s\S]*?tierMutationPayload\(latest/);});it('routes every JSX management gesture through the stage authority', () => {@@ -1109,314 +1030,6 @@ describe('SourceDetailPanel', () => {await waitFor(() => expect(screen.queryByText('model-a')).toBeNull());});- it('keeps a rejected tier draft and offers an inline retry', async () => {- vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));- renderPanel();- await userEvent.click(screen.getByRole('button', { name: /high/i }));- const input = screen.getByPlaceholderText(/Enter to add|回车添加/i);- await userEvent.type(input, 'draft{Enter}');- expect(await screen.findByText(/tier was not saved|档位没保存上/i)).toBeTruthy();- expect((input as HTMLInputElement).value).toBe('draft');- expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();- });-- it('keeps an existing tier removal clickable while the editor input has focus', async () => {- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockResolvedValueOnce({- ...source,- models: [{ ...source.models[0], reasoning_efforts: [] }],- });- renderPanel();- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'draft');- await userEvent.click(screen.getByRole('button', { name: /Remove high|移除 high/i }));-- await waitFor(() => expect(update).toHaveBeenCalledWith(source.id, 'model-a', []));- });-- it('leaves a resting row to its model and the tiers it already carries', () => {- renderProtocol('openai_responses');- expect(suggestedTiers()).toEqual([]);- expect(screen.queryByText(/sent exactly as typed|按你输入的原样发送/i)).toBeNull();- // The add affordance is not absent from the row, only from what a resting row- // draws — keeping the box it reserves is what lets revealing it move nothing.- const cell = screen.getByRole('button', { name: /high/i });- expect(cell.querySelector('.model-hub-source-tier-add.model-hub-source-tier-reveal')).toBeTruthy();- });-- // The suggestion set is discovered from its total protocol Record, so a protocol- // added later fails here until that table decides what it offers — and what it- // decides is what the open editor draws, minus whatever the model already has.- it('offers exactly the tiers its proved protocol names, and only while editing', async () => {- for (const protocol of SOURCE_PROTOCOLS) {- renderProtocol(protocol);- expect(suggestedTiers()).toEqual([]);- await userEvent.click(screen.getByRole('button', { name: /high/i }));- expect(suggestedTiers()).toEqual(TIER_SUGGESTIONS[protocol].filter((tier) => tier !== 'high'));- cleanup();- }- });-- // Rungs 1 and 2 of the provenance ladder are the server's own declaration,- // re-applied on every refresh. There is nothing to add and nothing to delete,- // so the cell stops being a way in rather than becoming a disabled one — and- // it says which rung, because a row that just refused to open would leave- // "why" as the user's problem.- it.each(MANAGED_TIER_SOURCES)('locks a %s-declared row down to what it already carries', async (provenance) => {- renderProtocol('anthropic', [{ ...source.models[0], reasoning_efforts_source: provenance }]);-- const cell = document.querySelector(`[data-tier-provenance="${provenance}"]`) as HTMLElement | null;- expect(cell).toBeTruthy();- expect(chipTiers()).toEqual(['high']);- expect(within(cell as HTMLElement).getByText(MANAGED_BADGE[provenance])).toBeTruthy();-- // No door in, and none of the affordances the editor would have brought.- await userEvent.click(cell as HTMLElement);- expect(screen.queryByPlaceholderText(/Enter to add|回车添加/i)).toBeNull();- expect(document.querySelector('.model-hub-source-tier-add')).toBeNull();- expect(screen.queryByRole('button', { name: /^Remove high$|^移除 high$/ })).toBeNull();- expect(suggestedTiers()).toEqual([]);- });-- it('keeps a locked row legible when the server declared no tiers at all', () => {- renderProtocol('anthropic', [{ ...source.models[0], reasoning_efforts: [], reasoning_efforts_source: 'upstream' }]);-- const cell = document.querySelector('[data-tier-provenance="upstream"]') as HTMLElement | null;- expect(within(cell as HTMLElement).getByText(/No tiers set|未设置档位/i)).toBeTruthy();- expect(within(cell as HTMLElement).getByText(MANAGED_BADGE.upstream)).toBeTruthy();- });-- // The pencil is a second door into the same editor, so a locked row has to- // close it too — a manual entry whose id matches a catalog model is locked- // exactly like a discovered one. Removing the model is a different question.- it('closes the pencil on a locked manual model while removal stays offered', () => {- renderProtocol('anthropic', [{ ...source.models[0], origin: 'manual', reasoning_efforts_source: 'catalog' }]);-- expect(screen.queryByRole('button', { name: /reasoning tiers for model-a|model-a 的推理强度/i })).toBeNull();- expect(screen.getByRole('button', { name: /Remove model-a|移除 model-a/i })).toBeTruthy();- });-- it.each([- ['a user-declared list', 'user' as const],- ['an explicitly unclaimed list', null],- ['a server that predates the field', undefined],- ])('leaves %s editable, suggestions and all', async (_case, provenance) => {- renderProtocol('anthropic', [{- ...source.models[0],- ...(provenance === undefined ? {} : { reasoning_efforts_source: provenance }),- }]);-- expect(document.querySelector('[data-tier-provenance]')).toBeNull();- await userEvent.click(screen.getByRole('button', { name: /high/i }));- expect(suggestedTiers()).toEqual(TIER_SUGGESTIONS.anthropic.filter((tier) => tier !== 'high'));- });-- // Defensive, and reachable: a refresh can apply a rung while the editor is- // open, another surface can change the source, and the call can come from- // outside this page. The generic "The tier was not saved" would offer a retry- // that cannot succeed, which is the one thing this user must not be invited to do.- it('explains a refusal that says the server owns the list, and offers no retry', async () => {- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(- new ApiCallError('bad_request', 'modelHub.errors.source_model_tiers_managed', true, [], [], [], 409),- );- renderPanel();- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');-- await waitFor(() => expect(update).toHaveBeenCalled());- expect(await screen.findByText(/tiers are set automatically|档位是自动确定的/i)).toBeTruthy();- expect(screen.queryByText(/tier was not saved|档位没保存上/i)).toBeNull();- expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();- expect(chipTiers()).toEqual(['high']);- });-- // The same conclusion by the other road: the write failed for its own reasons- // and the row was managed by the time the rollback's re-read came back. "Try- // again" would replay a write `tierMutationPayload` now declines, so the notice- // that survives is the one that explains the lock — and it goes back to being a- // retry if the server ever hands the list back, which is why the branch reads- // provenance instead of freezing a verdict when the write failed.- it('turns a pending retry into the locked explanation when provenance arrives after the failure', async () => {- vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));- const panel = (models: Source['models']) => (- <ToastProvider>- <I18nextProvider i18n={i18n}>- <ReportOwnedPanel source={{ ...source, models }} trackMutation={immediateTrack} onReauth={noReauth} />- </I18nextProvider>- </ToastProvider>- );- const { rerender } = render(panel(source.models));- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');- expect(await screen.findByText(/tier was not saved|档位没保存上/i)).toBeTruthy();- expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();-- rerender(panel([{ ...source.models[0], reasoning_efforts_source: 'upstream' }]));-- expect(document.querySelector('[data-tier-provenance="upstream"]')).toBeTruthy();- expect(await screen.findByText(/tiers are set automatically|档位是自动确定的/i)).toBeTruthy();- expect(screen.queryByText(/tier was not saved|档位没保存上/i)).toBeNull();- expect(screen.queryByRole('button', { name: /^Try again$|^重试$/i })).toBeNull();-- rerender(panel([{ ...source.models[0], reasoning_efforts_source: 'user' }]));-- expect(screen.getByRole('button', { name: /^Try again$|^重试$/i })).toBeTruthy();- });-- // The copy obligation checked where the copy is actually read. A bundle- // missing an entry reaches the user as the key itself, and these four strings- // are the only thing on the surface that says why an edit is unavailable.- it.each(['en', 'zh'] as const)('renders provenance and refusal copy as sentences in %s', async (lng) => {- const spoken = i18n.language;- await i18n.changeLanguage(lng);- try {- vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(- new ApiCallError('bad_request', 'modelHub.errors.source_model_tiers_managed', true, [], [], [], 409),- );- renderProtocol('anthropic', [- source.models[0],- { id: 'model-b', display_name: null, origin: 'discovered', reasoning_efforts: ['high'], reasoning_efforts_source: 'upstream' },- { id: 'model-c', display_name: null, origin: 'discovered', reasoning_efforts: ['high'], reasoning_efforts_source: 'catalog' },- ]);-- expect(screen.getByText(lng === 'en' ? 'From provider' : '供应商声明')).toBeTruthy();- expect(screen.getByText(lng === 'en' ? 'Avibe preset levels' : 'Avibe 预置档位')).toBeTruthy();-- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');- const refusal = await screen.findByText(- lng === 'en'- ? "This model's tiers are set automatically, so the change was not saved"- : '这个模型的档位是自动确定的,这次改动没有保存',- );- expect(refusal).toBeTruthy();- } finally {- cleanup();- await i18n.changeLanguage(spoken);- }- });-- it('adds a suggested tier through the same write typing it would take', async () => {- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockResolvedValueOnce({- ...source,- models: [{ ...source.models[0], reasoning_efforts: ['high', 'low'] }],- });- renderProtocol('openai_responses');- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.click(screen.getByRole('button', { name: /^Add low$|^添加 low$/ }));-- await waitFor(() => expect(update).toHaveBeenCalledWith(source.id, 'model-a', ['high', 'low']));- });-- it('keeps a suggestion out of the draft and off the wire until it is clicked', async () => {- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts');- renderProtocol('openai_chat');- await userEvent.click(screen.getByRole('button', { name: /high/i }));-- expect(suggestedTiers().length).toBeGreaterThan(0);- expect((screen.getByPlaceholderText(/Enter to add|回车添加/i) as HTMLInputElement).value).toBe('');- expect(update).not.toHaveBeenCalled();- });-- it('collapses the editor on Escape and on a click elsewhere', async () => {- renderProtocol('openai_responses');- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.keyboard('{Escape}');- await waitFor(() => expect(screen.queryByPlaceholderText(/Enter to add|回车添加/i)).toBeNull());- expect(suggestedTiers()).toEqual([]);-- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.click(screen.getByRole('heading', { name: source.display_name as string }));- await waitFor(() => expect(screen.queryByPlaceholderText(/Enter to add|回车添加/i)).toBeNull());- });-- it('hands the editor to the row that was clicked instead of opening a second one', async () => {- renderProtocol('openai_responses', [- source.models[0],- { id: 'model-b', display_name: null, origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },- ]);- await userEvent.click(screen.getByRole('button', { name: /high/i }));- expect(screen.getAllByPlaceholderText(/Enter to add|回车添加/i)).toHaveLength(1);-- await userEvent.click(screen.getByRole('button', { name: /No tiers set|未设置档位/i }));-- const inputs = screen.getAllByPlaceholderText(/Enter to add|回车添加/i);- expect(inputs).toHaveLength(1);- expect(document.activeElement).toBe(inputs[0]);- });-- // An editor is a place the keyboard moves around in, not only lands in. Keyed- // to the input's own blur, the collapse made every control inside it- // pointer-only: Tab left the field and took the editor with it.- it('lets the keyboard reach a suggestion and stays open around the write', async () => {- // Whichever tier the protocol happens to offer first: what is under test is- // that Tab lands on a suggestion at all, so naming one would make this fail- // for a vocabulary change that never touched the focus rule.- const [first] = TIER_SUGGESTIONS.openai_responses.filter((tier) => tier !== 'high');- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockResolvedValueOnce({- ...source,- models: [{ ...source.models[0], reasoning_efforts: ['high', first] }],- });- renderProtocol('openai_responses');- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.tab();- const suggestion = screen.getByRole('button', { name: new RegExp(`^Add ${first}$|^添加 ${first}$`) });- expect(document.activeElement).toBe(suggestion);-- await userEvent.keyboard('{Enter}');- await waitFor(() => expect(update).toHaveBeenCalledWith(source.id, 'model-a', ['high', first]));- // The chip it was standing on is gone; focus is back on the one control the- // edit state cannot lose, not on the body with the editor closed behind it.- const input = screen.getByPlaceholderText(/Enter to add|回车添加/i);- expect(document.activeElement).toBe(input);- });-- it('returns focus to the row it collapsed when Escape asked for it', async () => {- renderProtocol('openai_responses');- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.keyboard('{Escape}');- await waitFor(() => expect(screen.queryByPlaceholderText(/Enter to add|回车添加/i)).toBeNull());- expect(document.activeElement).toBe(screen.getByRole('button', { name: /high/i }));- });-- // A write that was rolled back is the row's unfinished business, and "Try again"- // is the only answer to it — so moving the editor elsewhere, which answers- // nothing, cannot be what takes the answer away.- it('keeps a failed write answerable after the editor moves to another row', async () => {- const update = vi.spyOn(modelsApi, 'updateModelReasoningEfforts').mockRejectedValueOnce(new Error('write failed'));- renderProtocol('openai_responses', [- source.models[0],- { id: 'model-b', display_name: null, origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },- ]);- await userEvent.click(screen.getByRole('button', { name: /high/i }));- await userEvent.type(screen.getByPlaceholderText(/Enter to add|回车添加/i), 'low{Enter}');- expect(await screen.findByText(/tier was not saved|档位没保存上/i)).toBeTruthy();-- await userEvent.click(screen.getByRole('button', { name: /No tiers set|未设置档位/i }));- expect(screen.getAllByPlaceholderText(/Enter to add|回车添加/i)).toHaveLength(1);- expect(screen.getByText(/tier was not saved|档位没保存上/i)).toBeTruthy();-- update.mockResolvedValueOnce({ ...source, models: [{ ...source.models[0], reasoning_efforts: ['high', 'low'] }] });- await userEvent.click(screen.getByRole('button', { name: /^Try again$|^重试$/i }));- await waitFor(() => expect(update).toHaveBeenLastCalledWith(source.id, 'model-a', ['high', 'low']));- await waitFor(() => expect(screen.queryByText(/tier was not saved|档位没保存上/i)).toBeNull());- });-- // Hover is a reveal, not a layout change, and the row answers it with fill- // alone. Asserted against the stylesheet because jsdom resolves neither a media- // query nor a hover state, and this half of the interaction is CSS-owned.- it('reveals the add affordance on hover without moving the row', () => {- const css = readFileSync(join(process.cwd(), 'src/components/settings/models/modelHubSurface.css'), 'utf8');- const pointer = css.slice(css.indexOf('@media (hover: hover)'), css.indexOf('@media (hover: none)'));- const touch = css.slice(css.indexOf('@media (hover: none)'));- expect(pointer).toMatch(/\.model-hub-source-table-row:hover \{ background: var\(--model-hub-wash-0a\); \}/);- expect(pointer).toMatch(/\.model-hub-source-tier-reveal \{ opacity: 0;/);- expect(pointer).toMatch(/\.model-hub-source-table-row:hover \.model-hub-source-tier-reveal,[\s\S]*?opacity: 1;/);- expect(pointer).not.toMatch(/display: none|height|padding|margin|border/);- expect(pointer).toMatch(/\.model-hub-source-row-action \{ opacity: 0;/);- expect(pointer).not.toMatch(/\.model-hub-source-row-actions \{ opacity: 0;/);- expect(touch).toMatch(/\.model-hub-source-tier-reveal \{ display: none; \}/);- });-it('bounds refetch notices inside the fixed-height detail dialog', () => {const css = readFileSync(join(process.cwd(), 'src/components/settings/models/modelHubSurface.css'), 'utf8');const notices = css.match(/\.model-hub-source-notices\s*\{([^}]*)\}/)?.[1] ?? '';@@ -1424,28 +1037,6 @@ describe('SourceDetailPanel', () => {expect(notices).toContain('overflow-y: auto');});- // The reveal is a paint, so what a tap has to find cannot be part of it: the- // cell owns the row's band whatever it is drawing, which is what lets the pill- // be removed on touch and lets a model with no tiers still be a target at all.- it('gives the tier cell the row band to be tapped in, whichever branch is drawing', () => {- const css = readFileSync(join(process.cwd(), 'src/components/settings/models/modelHubSurface.css'), 'utf8');- const base = css.slice(0, css.indexOf('@media (hover: hover)'));- expect(base).toMatch(/\.model-hub-source-tier-cell \{\s*min-height: calc\(var\(--model-hub-source-table-row-height\) - 2 \* var\(--model-hub-source-table-padding-y\)\);\s*\}/);- const pointer = css.slice(css.indexOf('@media (hover: hover)'), css.indexOf('@media (hover: none)'));- const touch = css.slice(css.indexOf('@media (hover: none)'), css.indexOf('.model-hub-source-tier-empty'));- for (const branch of [pointer, touch]) expect(branch).not.toMatch(/height/);-- // And the class is on the control the tap opens, for a model with tiers and- // for one without — CSS nobody wears is not a hit area.- renderProtocol('openai_responses', [- source.models[0],- { id: 'model-b', display_name: null, origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null },- ]);- for (const name of [/high/i, /No tiers set|未设置档位/i]) {- expect(screen.getByRole('button', { name }).className).toContain('model-hub-source-tier-cell');- }- });-it('explains standby beside the label rather than in a place the reader must find', async () => {renderPanel([]);expect(screen.getByText(i18n.t('settings.models.upstream.state.standby'))).toBeTruthy();diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex 3b9c10c8f..1a65d6f9c 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -1,6 +1,6 @@import * as React from 'react';import * as DialogPrimitive from '@radix-ui/react-dialog';-import { FlaskConical, Info, Loader2, LogIn, MoreHorizontal, Pencil, Plus, RefreshCw, Search, Settings2, Trash2, X } from 'lucide-react';+import { FlaskConical, Info, Loader2, LogIn, MoreHorizontal, Plus, RefreshCw, Search, Trash2, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -47,15 +47,7 @@ import {import { handOffProviderTab } from './providerTab';import { reconcileUnknownWrite } from './reconcileUnknownWrite';import { REPAIR_DESTINATION, REPAIR_LABEL_KEY, reauthBodyKey, reauthCost, repairAction } from './repair';-import { tierEditRefusedAsManaged } from './serverCopy';import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';-import {- managedTierSource,- tierMutationPayload,- type ManagedTierSource,- type TierMutationIntent,-} from './tierMutation';-import { TIER_SUGGESTIONS } from './tierSuggestions';import { useDeadlineClock } from './useDeadlineClock';import { SourceTestDialog } from './SourceTestDialog';import { ACCENT_ICON, ACCENT_TILE, sourceVisual } from './vendorMeta';@@ -64,7 +56,6 @@ import type {RouteHopRef,Source,SourcePatch,- SourceProtocol,SuppliedModel,SupplyGap,} from './types';@@ -154,277 +145,6 @@ type SourceReconciliation =| { kind: 'source'; source: Source }| { kind: 'gone'; sources: Source[]; snapshot: number };-/** The badge that says which rung declared a locked model's tiers. */-const TIER_PROVENANCE_LABEL_KEY: Readonly<Record<ManagedTierSource, string>> = {- upstream: 'settings.models.sourceDetail.tiers.managed.upstream',- catalog: 'settings.models.sourceDetail.tiers.managed.catalog',-};--/**- * A tier write that did not land, and whether anything is left to try.- *- * `retryable` carries the intent because "Try again" has to replay the exact- * write the rollback undid. `managed` carries none on purpose: the server owns- * that model's declaration, so there is no version of this write that succeeds,- * and offering a button that re-asks a settled question would be the one wrong- * affordance to put in front of this user.- */-type TierFailure =- | { kind: 'retryable'; intent: TierMutationIntent }- | { kind: 'managed' };--const TierEditor: React.FC<{- model: SuppliedModel;- protocol: SourceProtocol;- editing: boolean;- onEdit: () => void;- onClose: () => void;- onMutating: () => void;- trackMutation: TrackSourceMutation;-}> = ({ model, protocol, editing, onEdit, onClose, onMutating, trackMutation }) => {- const { t } = useTranslation();- const managed = managedTierSource(model.reasoning_efforts_source);- const [tiers, setTiers] = React.useState(model.reasoning_efforts ?? []);- const [draft, setDraft] = React.useState('');- const [saving, setSaving] = React.useState(false);- const [failed, setFailed] = React.useState<TierFailure | null>(null);- const [returnFocus, setReturnFocus] = React.useState(false);- const inputRef = React.useRef<HTMLInputElement>(null);- const cellRef = React.useRef<HTMLButtonElement>(null);- React.useEffect(() => setTiers(model.reasoning_efforts ?? []), [model.reasoning_efforts]);- // Which row is open belongs to the table, not to the row — that is what makes- // "one editor at a time" structural rather than a convention every collapse- // path has to remember. What the row drops on the way out is the uncommitted- // draft, and only that: a rolled-back write is not a draft, so it stays with- // the row that produced it (below) rather than with whoever holds the editor.- React.useEffect(() => { if (!editing) setDraft(''); }, [editing]);- // Escape is the one collapse the keyboard asks for, so it is the one that owes- // a place to land; a click elsewhere already chose one.- React.useEffect(() => {- if (editing || !returnFocus) return;- cellRef.current?.focus();- setReturnFocus(false);- }, [editing, returnFocus]);-- const commit = async (intent: TierMutationIntent): Promise<boolean> => {- if (saving) return false;- setSaving(true);- // Every in-editor control is transient — a suggestion becomes a chip, a chip- // disappears — so acting on one has to hand focus back to the field that- // outlives them all, before the element holding it unmounts onto the body.- (inputRef.current ?? cellRef.current)?.focus();- try {- return await trackMutation(async (latest, settlement) => {- const payload = tierMutationPayload(latest, model.id, intent);- if (!payload) {- settlement.release();- return false;- }- const { previous, next } = payload;- onMutating();- setFailed(null);- setTiers(next);- if (previous.length === next.length && previous.every((tier, index) => tier === next[index])) {- settlement.release();- return true;- }- try {- const echoed = await modelsApi.updateModelReasoningEfforts(latest.id, model.id, next);- await settlement.source(echoed);- return true;- } catch (error) {- setTiers(previous);- const refusal = apiFailure(error);- setFailed(tierEditRefusedAsManaged(refusal) ? { kind: 'managed' } : { kind: 'retryable', intent });- if (refusal?.code === 'source_not_found') await settlement.gone(latest.id);- // A managed refusal re-reads for the same reason every other failed- // write does, and one more: this client believed the row was editable- // and the server says otherwise, so the read is what replaces the- // stale editor with the provenance the server actually holds.- else await settlement.unread();- return false;- }- });- } finally {- setSaving(false);- }- };- const add = async () => {- const value = draft.trim();- if (!value || tiers.includes(value)) return;- if (await commit({ kind: 'add', tier: value })) setDraft('');- };- const retry = async () => {- if (failed?.kind !== 'retryable') return;- const { intent } = failed;- if (await commit(intent) && intent.kind === 'add' && draft.trim() === intent.tier) setDraft('');- };- // A rolled-back write is the row's own unfinished business: the tier list is- // already back to what the server holds, and "Try again" is the only way forward- // from there. So the notice renders in whichever state the row is in and leaves- // only through a write that lands — never because the editor closed or moved on.- //- // A refusal is the exception, and the one that outlives the editor: the re-read- // it triggers turns the row into the locked one below, so its notice has to be- // rendered by that branch too, or the only explanation the user gets would- // disappear at the moment the row changes under them.- //- // Provenance can also reach that branch after an ordinary failure — the re-read- // the rollback triggers, or a refresh from anywhere else, comes back with the- // server owning the list — and it answers the retry the same way the refusal- // did: `tierMutationPayload` declines a managed model, so the button would- // replay a write that can no longer land. Which notice to show is therefore read- // from the row's current provenance rather than frozen when the write failed;- // that also lets the retry come back untouched if the server hands the list back.- const failure = failed && (managed || failed.kind === 'managed' ? (- <span data-tier-failure="managed" className="model-hub-source-tier inline-flex items-center gap-1.5 text-destructive-ink">- {t('settings.models.sourceDetail.fail.tierManaged')}- </span>- ) : (- <span data-tier-failure="retryable" className="model-hub-source-tier inline-flex items-center gap-1.5 text-destructive-ink">- {t('settings.models.sourceDetail.fail.tier')}- <button type="button" disabled={saving} onClick={() => void retry()} className="font-semibold underline underline-offset-2 disabled:opacity-50">{t('settings.models.sourceDetail.retry')}</button>- </span>- ));- // Rung 1 and 2 of the provenance ladder are the server's declaration, re-applied- // on every refresh: there is nothing for the user to add and nothing to delete,- // so the cell stops being a way in rather than becoming a disabled one. It says- // which rung instead — a row that simply refused to open would leave "why" as- // the user's problem.- if (managed) {- return (- <div className="flex min-w-0 flex-col gap-1.5">- <div data-tier-provenance={managed} className="model-hub-source-tier-cell flex min-w-0 flex-wrap items-center gap-1.5">- {tiers.length > 0 ? tiers.map((tier) => (- <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex rounded-full border border-border font-mono text-foreground">{tier}</span>- )) : <span className="model-hub-source-tier-empty">{t('settings.models.sourceDetail.tiers.empty')}</span>}- <span- title={t('settings.models.sourceDetail.tiers.managedHint') as string}- className="model-hub-source-pill model-hub-source-entry-pill w-fit rounded-full border font-semibold"- >- {t(TIER_PROVENANCE_LABEL_KEY[managed])}- </span>- </div>- {failure}- </div>- );- }- if (!editing) {- // The whole cell is the edit entry, which is what lets the add affordance be- // drawn only under a pointer: 20 rows each carrying a permanent 「+ 添加档位」- // pill turn an inventory table into a wall of buttons. It stays in the box it- // reserves rather than being removed from it, so revealing it moves nothing.- return (- <div className="flex min-w-0 flex-col gap-1.5">- <button- ref={cellRef}- type="button"- className="model-hub-source-tier-cell flex min-w-0 flex-wrap items-center gap-1.5 text-left"- onClick={onEdit}- >- {tiers.length > 0 ? tiers.map((tier) => (- <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex rounded-full border border-border font-mono text-foreground">{tier}</span>- )) : <span className="model-hub-source-tier-empty">{t('settings.models.sourceDetail.tiers.empty')}</span>}- <span className="model-hub-source-tier model-hub-source-tier-add model-hub-source-tier-reveal inline-flex rounded-full border font-semibold">{t(tiers.length > 0 ? 'settings.models.sourceDetail.tiers.add' : 'settings.models.sourceDetail.tiers.addFirst')}</span>- </button>- {failure}- </div>- );- }- const suggestions = TIER_SUGGESTIONS[protocol].filter((tier) => !tiers.includes(tier));- // The editor collapses when focus leaves the editor, not when the input alone- // does. Keyed to the input, every control inside had to defend itself against- // its own focus — which a pointer can fake by refusing it and a keyboard- // cannot, so Tab closed the row before it could reach a suggestion at all.- // Containment is that same rule stated once, at the boundary it is about.- return (- <div- data-source-dialog-local-escape- className="flex min-w-0 flex-col gap-1.5"- onBlur={(event) => { if (!event.currentTarget.contains(event.relatedTarget)) onClose(); }}- onKeyDown={(event) => {- if (event.key !== 'Escape') return;- event.preventDefault();- setDraft('');- setReturnFocus(true);- onClose();- }}- >- <div className="flex min-w-0 flex-wrap items-center gap-1.5">- {tiers.map((tier) => (- <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex items-center gap-1 rounded-full border border-border font-mono text-foreground">- {tier}- <button type="button" disabled={saving} onClick={() => void commit({ kind: 'remove', tier })} aria-label={t('settings.models.sourceDetail.tiers.remove', { tier }) as string} className="text-muted hover:text-foreground disabled:opacity-50">- <X className="size-2.5" />- </button>- </span>- ))}- <Input- ref={inputRef}- autoFocus- value={draft}- onChange={(event) => setDraft(event.target.value)}- onKeyDown={(event) => { if (event.key === 'Enter') { event.preventDefault(); void add(); } }}- disabled={saving}- placeholder={t('settings.models.sourceDetail.tiers.inputHint') as string}- className="model-hub-source-tier h-7 w-28 rounded-full border-mint/40 px-2.5"- />- {/* A suggestion adds through the same path typing it would take. */}- {suggestions.map((tier) => (- <button- key={tier}- type="button"- disabled={saving}- onClick={() => void commit({ kind: 'add', tier })}- aria-label={t('settings.models.sourceDetail.tiers.suggest', { tier }) as string}- className="model-hub-source-tier model-hub-source-tier-suggest inline-flex rounded-full border font-mono disabled:opacity-50"- >- {tier}- </button>- ))}- {failure}- </div>- {/* The two questions a free-text field cannot answer by itself: whether- anything validates what is typed, and what an empty row costs. */}- <p className="model-hub-source-tier-note">{t('settings.models.sourceDetail.tiers.note')}</p>- </div>- );-};--const DraftTiers: React.FC<{- tiers: string[];- onChange: (tiers: string[]) => void;-}> = ({ tiers, onChange }) => {- const { t } = useTranslation();- const [draft, setDraft] = React.useState('');- const add = () => {- const value = draft.trim();- if (!value || tiers.includes(value)) return;- onChange([...tiers, value]);- setDraft('');- };- return (- <div className="flex min-w-0 flex-wrap items-center gap-1.5">- {tiers.map((tier) => (- <span key={tier} className="model-hub-source-tier model-hub-source-tier-chip inline-flex items-center gap-1 rounded-full border border-border font-mono text-foreground">- {tier}- <button type="button" onClick={() => onChange(tiers.filter((item) => item !== tier))} aria-label={t('settings.models.sourceDetail.tiers.remove', { tier }) as string} className="text-muted hover:text-foreground"><X className="size-2.5" /></button>- </span>- ))}- <Input- value={draft}- onChange={(event) => setDraft(event.target.value)}- onKeyDown={(event) => {- if (event.key === 'Enter') { event.preventDefault(); add(); }- if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); setDraft(''); event.currentTarget.blur(); }- }}- placeholder={t('settings.models.sourceDetail.tiers.inputHint') as string}- className="model-hub-source-tier h-7 w-36 rounded-full border-mint/40 px-2.5"- />- </div>- );-};-export const SourceDetailPanel: React.FC<{source: Source;trackMutation: TrackSourceMutation;@@ -455,12 +175,10 @@ export const SourceDetailPanel: React.FC<{const busy = pendingAction !== null;const refetching = pendingAction === 'refetch';const [testing, setTesting] = React.useState(false);- const [advanced, setAdvanced] = React.useState(false);const [confirmingReauth, setConfirmingReauth] = React.useState(false);const [replacingKey, setReplacingKey] = React.useState(false);const [manageStage, dispatchManageStage] = React.useReducer(transitionManageStage, { kind: 'idle' });- const [manualDraft, setManualDraft] = React.useState<{ modelId: string; tiers: string[]; failed: boolean; retryRead: boolean } | null>(null);- const [editingTiers, setEditingTiers] = React.useState<string | null>(null);+ const [manualDraft, setManualDraft] = React.useState<{ modelId: string; failed: boolean; retryRead: boolean } | null>(null);const [guard, setGuard] = React.useState<GuardedAction | null>(null);const [result, setResult] = React.useState<{ added: string[]; removed: string[] } | null>(null);const [refetchFailed, setRefetchFailed] = React.useState(false);@@ -581,7 +299,7 @@ export const SourceDetailPanel: React.FC<{const echoed = await modelsApi.addCustomModel(latest.id, {model_id: modelId,display_name: null,- reasoning_efforts: draft.tiers,+ reasoning_efforts: [],});setManualDraft(null);setResult(null);@@ -935,7 +653,7 @@ export const SourceDetailPanel: React.FC<{: t('settings.models.gateway.modelCount', { count: source.models.length });return (- <div className="model-hub-source-detail" data-advanced={advanced}>+ <div className="model-hub-source-detail"><section className="model-hub-source-bar flex shrink-0 items-center border-b border-border bg-surface"><span className={cn('model-hub-source-tile flex shrink-0 items-center justify-center', ACCENT_TILE[accent])}><Icon className={cn('size-[18px]', ACCENT_ICON[accent])} /></span><div className="model-hub-source-copy flex min-w-0 flex-1 flex-col">@@ -970,35 +688,19 @@ export const SourceDetailPanel: React.FC<{{repairDestination === 'replace_key_dialog' && <Button size="xs" className="model-hub-source-action" data-repair-kind={repair} data-repair-destination={repairDestination} disabled={busy} onClick={() => setReplacingKey(true)}>{t(REPAIR_LABEL_KEY.replace_key)}</Button>}{source.supply_channel === 'hub' && <Button variant="outline" size="xs" className="model-hub-source-action" data-repair-kind={repairDestination === 'refetch_button' ? repair : undefined} data-repair-destination={repairDestination === 'refetch_button' ? repairDestination : undefined} disabled={busy} onClick={() => void refetch()} aria-busy={refetching}>{refetching ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}{source.kind === 'api_key' && source.supply_channel === 'hub' && <Button variant="outline" size="xs" className="model-hub-source-action" disabled={busy} onClick={() => setTesting(true)}><FlaskConical />{t('settings.models.sourceTest.open')}</Button>}- <Button variant="ghost" size="xs" className="model-hub-source-action" aria-expanded={advanced}- disabled={busy} onClick={() => { setAdvanced((value) => !value); setEditingTiers(null); }}>- <Settings2 />{t('settings.models.sourceDetail.advanced')}- </Button>- {source.kind === 'api_key' && <Button size="xs" className="model-hub-source-action" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', tiers: [], failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}+ {source.kind === 'api_key' && <Button size="xs" className="model-hub-source-action" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}<SourceManageMenu source={source} busy={busy || manageStage.kind !== 'idle'} onEdit={beginEdit} onDelete={beginDelete} /></div></section><section className="model-hub-source-table flex min-h-0 flex-1 flex-col overflow-hidden bg-surface"><div className="model-hub-source-table-head hidden border-b border-border font-semibold md:grid">- <span className="truncate">{t('settings.models.sourceDetail.col.id')}</span>{advanced && <span className="flex min-w-0 items-center gap-1"><span className="truncate">{t('settings.models.sourceDetail.col.tiers')}</span><Info className="model-hub-ink-59 size-[13px] shrink-0" /></span>}<span />+ <span className="truncate">{t('settings.models.sourceDetail.col.id')}</span><span /></div><div className="model-hub-source-table-scroll min-h-0 flex-1 overflow-y-auto">{filteredModels.length === 0 && !manualDraft && <p className="px-5 py-12 text-center text-[12px] text-muted">{t(normalizedQuery ? 'settings.models.sourceDetail.searchEmpty' : source.last_discovered_at ? 'settings.models.sourceDetail.empty' : 'settings.models.sourceDetail.emptyNeverFetched')}</p>}{models.map((model) => (<div key={model.id} hidden={!visibleModelIds.has(model.id)} className="model-hub-source-table-row grid gap-3 border-b border-border last:border-b-0 md:items-center md:gap-y-0"><span className="flex min-w-0 items-center gap-2"><span className="model-hub-source-model truncate font-mono text-foreground" title={model.id}>{model.id}</span>{model.origin !== 'discovered' && <span className="model-hub-source-pill model-hub-source-entry-pill model-hub-source-entry-pill--manual w-fit rounded-full border font-semibold">{t('settings.models.sourceDetail.entry.manual')}</span>}{result?.added.includes(model.id) && <span className="model-hub-accent-pill--mint model-hub-source-pill rounded-full border px-2 py-0.5 font-semibold">{t('settings.models.sourceDetail.refetch.added')}</span>}</span>- {advanced && <TierEditor- model={model}- protocol={source.protocol}- editing={editingTiers === model.id}- onEdit={() => setEditingTiers(model.id)}- // Guarded against the row it is closing: the outgoing editor's blur- // lands after the incoming row's click, so an unguarded close would- // collapse the editor the user just opened.- onClose={() => setEditingTiers((current) => (current === model.id ? null : current))}- onMutating={() => { setResult(null); setRefetchFailed(false); }}- trackMutation={trackMutation}- />}<div className="model-hub-source-row-actions flex items-center justify-end gap-1">{removeFailure?.modelId === model.id && <span className="model-hub-source-tier text-right text-destructive-ink">{t('settings.models.sourceDetail.fail.removeModel')} <button type="button" disabled={busy} onClick={() => {if (!removeFailure.retryRead) void remove(model);@@ -1008,11 +710,7 @@ export const SourceDetailPanel: React.FC<{.finally(() => setPendingAction(null));}}} className="font-semibold underline underline-offset-2">{t('settings.models.sourceDetail.retry')}</button></span>}- {/* The pencil is a second door into the same tier editor, so a locked- row has to close it too — a manual entry whose id matches a- catalog model is locked exactly like a discovered one. Removing- the model itself is a different question and stays offered. */}- {model.origin === 'manual' && <>{advanced && !managedTierSource(model.reasoning_efforts_source) && <button type="button" disabled={busy} aria-label={t('settings.models.sourceDetail.row.edit', { model: model.id }) as string} title={t('settings.models.sourceDetail.row.edit', { model: model.id }) as string} className="model-hub-source-row-action grid place-items-center text-muted hover:bg-surface-2 hover:text-foreground" onClick={() => setEditingTiers(model.id)}><Pencil className="size-3.5" /></button>}<ManualModelMenu model={model} busy={busy} onRemove={() => void remove(model)} /></>}+ {model.origin === 'manual' && <ManualModelMenu model={model} busy={busy} onRemove={() => void remove(model)} />}</div></div>))}@@ -1034,7 +732,6 @@ export const SourceDetailPanel: React.FC<{placeholder={t('settings.models.sourceDetail.col.id') as string}className="model-hub-source-manual-id model-hub-source-model h-8 min-w-0 font-mono"/><span className="model-hub-source-pill model-hub-source-entry-pill model-hub-source-entry-pill--manual w-fit rounded-full border font-semibold">{t('settings.models.sourceDetail.entry.manual')}</span></span>- {advanced && <DraftTiers tiers={manualDraft.tiers} onChange={(tiers) => setManualDraft((current) => current ? { ...current, tiers, failed: false, retryRead: false } : current)} />}<div className="flex justify-end gap-2"><Button variant="ghost" size="xs" disabled={busy} onClick={() => setManualDraft(null)}>{t('common.cancel')}</Button><Button size="xs" disabled={busy || !manualDraft.modelId.trim() || source.models.some((model) => model.id === manualDraft.modelId.trim())} onClick={() => void addManualModel()}>{pendingAction === 'add_model' && <Loader2 className="animate-spin" />}{manualDraft.failed ? t('settings.models.sourceDetail.retry') : t('settings.models.sourceDetail.action.addModel')}</Button>diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex e166ea867..77be57133 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -176,7 +176,7 @@--model-hub-source-radius: 0px;--model-hub-source-action-radius: 7px;--model-hub-source-table-row-height: 40px;- --model-hub-source-table-columns: minmax(0, 1fr) minmax(120px, 180px) 64px;+ --model-hub-source-table-columns: minmax(0, 1fr) auto;--model-hub-source-table-gap: 12px;--model-hub-source-table-padding-x: 20px;--model-hub-source-table-padding-y: 7px;@@ -1309,9 +1309,6 @@padding-inline: var(--model-hub-source-table-padding-x);}-.model-hub-source-detail[data-advanced="false"] :is(.model-hub-source-table-head, .model-hub-source-table-row, .model-hub-source-table-draft) {- grid-template-columns: minmax(0, 1fr) auto;-}/* The columns are what a heading makes a claim about, so only the bands readagainst that heading take them. */.model-hub-source-table-head,@@ -1344,18 +1341,12 @@min-height: var(--model-hub-source-table-row-height);padding-block: var(--model-hub-source-table-padding-y);}-/* The draft is a form, not a row, so it stops claiming the row's columns.- Sharing them cannot work: the trailing track is cut for two 26px icon buttons,- the draft's controls are words instead — 取消 plus 添加模型 measure 128px, and- more than that in English — and the only cell with room to pay for the- difference is the shared 1fr, which would slide the tier cell out from under- the header it is read against. Two lines instead: the model id over the full- width, then the tier editor beside controls sized by their own labels. Height- follows that content, as it does for a row whose tier editor is open. */+/* The draft spans the table width, with commands on their own trailing line. */.model-hub-source-table-draft {grid-template-columns: minmax(0, 1fr) auto;padding-block: var(--model-hub-source-table-padding-y);}+.model-hub-source-table-draft > .flex { grid-column: 1 / -1; }/* Stated as a span to both edges rather than as a column count: the count is alayout decision that has already changed once, and a cell carrying `col-span-3`through that change is how the failure line ends up in an implicit fourth@@ -1390,64 +1381,12 @@flex-shrink: 0;}.model-hub-source-tier { font-size: var(--model-hub-source-tier-size); }-.model-hub-source-tier-chip {- --model-hub-source-chip-fill: var(--model-hub-wash-0f);- background: var(--model-hub-source-chip-fill);- padding: var(--model-hub-source-chip-padding-y) var(--model-hub-source-chip-padding-x);-}-/* The affordance for adding a tier is a chip too, hollow rather than filled —- as plain mint text it read as a caption in the middle of a chip row. */-.model-hub-source-tier-add {- padding: var(--model-hub-source-chip-padding-y) var(--model-hub-source-chip-padding-x);- border-color: var(--model-hub-wash-24);- color: var(--muted);-}-/* A suggestion is a value this source has not declared, so it is drawn as the- absence of one: the saved chip's box with a hairline outline instead of a- fill. It is never a vocabulary — clicking one types it, and typing anything- else remains equally valid. */-.model-hub-source-tier-suggest {- padding: var(--model-hub-source-chip-padding-y) var(--model-hub-source-chip-padding-x);- border-color: var(--model-hub-wash-24);- border-style: dashed;- color: var(--model-hub-ink-73);-}-.model-hub-source-tier-suggest:hover { border-color: var(--model-hub-wash-33); color: var(--foreground); }-.model-hub-source-tier-note {- color: var(--model-hub-ink-8c);- font-size: var(--model-hub-source-tier-size);- line-height: 15px;-}-/* The cell is the way into the editor, so its box is the row's band rather than- whatever its contents happen to measure — a model with no tiers offers only a- 10.5px caption, and a touch device is shown no pill at all. Owned here, once,- outside both hover branches: the target a tap has to find cannot be decided by- what the row is currently drawing. */-.model-hub-source-tier-cell {- min-height: calc(var(--model-hub-source-table-row-height) - 2 * var(--model-hub-source-table-padding-y));-}-/* The row's add affordance is drawn only while a pointer is on the row. It keeps- the box it reserves either way, so revealing it moves no chip and changes no- row height — the row answers a hover with fill alone. A keyboard reaches the- cell by focus and gets the same reveal; a touch device has no hover to answer- with, so the pill is removed there rather than left as a blank gap, which the- cell can afford because the tappable box is the cell's own, not the pill's. */@media (hover: hover) {.model-hub-source-table-row:hover { background: var(--model-hub-wash-0a); }- .model-hub-source-tier-reveal { opacity: 0; transition: opacity 120ms ease; }- .model-hub-source-table-row:hover .model-hub-source-tier-reveal,- .model-hub-source-tier-cell:focus-visible .model-hub-source-tier-reveal { opacity: 1; }.model-hub-source-row-action { opacity: 0; transition: opacity 120ms ease; }.model-hub-source-table-row:hover .model-hub-source-row-action,.model-hub-source-table-row:focus-within .model-hub-source-row-action { opacity: 1; }}-@media (hover: none) {- .model-hub-source-tier-reveal { display: none; }-}-.model-hub-source-tier-empty {- color: var(--model-hub-ink-59);- font-size: var(--model-hub-source-age-size);-}/* Entry pills are fills, not outlines, and the two origins differ by weight offill and ink rather than by border. */.model-hub-source-entry-pill {diff --git a/ui/src/components/settings/models/sourceModelContract.test.ts b/ui/src/components/settings/models/sourceModelContract.test.tsindex b32e82b99..7248ad618 100644--- a/ui/src/components/settings/models/sourceModelContract.test.ts+++ b/ui/src/components/settings/models/sourceModelContract.test.ts@@ -20,7 +20,6 @@ describe('Source model wire contract', () => {const enumeratedFields = modelSchema.required.filter((field: string) => Array.isArray(modelSchema.properties[field]?.enum),);- const detail = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), 'SourceDetailPanel.tsx'), 'utf8');for (const model of models) {expect(modelSchema.required.every((field: string) => Object.hasOwn(model, field))).toBe(true);@@ -28,7 +27,6 @@ describe('Source model wire contract', () => {for (const field of enumeratedFields) {expect(new Set(models.map((model) => model[field as keyof typeof model]))).toEqual(new Set(modelSchema.properties[field].enum));- expect(detail).toContain(`model.${field}`);}});});