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): distinguish subscriptions and show account identity (#2162)
Call White99056530d484
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex f4933f580..80cc6a970 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -553,6 +553,14 @@ class EngineAdapter(Protocol):"""...+ def subscription_account_label(self, source_id: str, vendor: str, credential_ref: str) -> str | None:+ """Read optional public account metadata from this source's bound grant.++ This local presentation read never starts the engine, refreshes a grant,+ or exports credential material. Missing/unsafe metadata returns None.+ """+ ...+async def retarget_api_key_credential(self,credential_ref: str,diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex c131964f7..0b24c6fcc 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -443,6 +443,9 @@ class UnavailableEngineAdapter:async def credential_auth_scheme(self, credential_ref: str) -> str | None:raise EngineUnavailableError+ def subscription_account_label(self, source_id: str, vendor: str, credential_ref: str) -> str | None:+ return None+async def provision_transient_credential(self, vendor: str, secret: str, base_url: str | None,*, auth_scheme: str | None = None, on_reserved: Callable[[str], None] | None = None,@@ -2165,11 +2168,20 @@ class ModelHubService:source: ModelHubSourceConfig,*,previous: Optional[ModelHubConfig] = None,+ display_name_defaulted: bool = False,) -> None:previous = previous or self.store.load()config = self._clone_config(previous)if any(item.id == source.id for item in config.sources):raise ModelHubError("migration_item_conflict", status=409)+ if source.kind == "subscription" and display_name_defaulted:+ names = {item.display_name for item in config.sources}+ seed = source.display_name+ number = 2+ while source.display_name in names:+ suffix = f" {number}"+ source.display_name = f"{seed[:64 - len(suffix)]}{suffix}"+ number += 1config.sources.append(source)self._apply_source_placement(config, source)await self._commit_synced(previous, config)@@ -2257,6 +2269,20 @@ class ModelHubService:for model in payload["models"]:model.setdefault("retired", False)payload["adopted_by"] = self._adopted_by(source.id, config)+ return self._source_account_payload(payload)++ def _source_account_payload(self, payload: dict) -> dict:+ # Resolve from the current binding on every presentation, including+ # pre-existing subscriptions and grants changed by re-authentication.+ # Adapters without this optional metadata surface retain persisted labels.+ reader = getattr(self.adapter, "subscription_account_label", None)+ if (+ callable(reader)+ and payload["kind"] == "subscription"+ and payload["supply_channel"] == "hub"+ and payload.get("credential_ref")+ ):+ payload["account_label"] = reader(payload["id"], payload["vendor"], payload["credential_ref"])return payloaddef _source_creation_result(self, source: dict) -> dict:@@ -2268,7 +2294,7 @@ class ModelHubService:"adopted_by": self._adopted_by(source["id"]),}return {- "source": source,+ "source": self._source_account_payload(source),"added_to": self._added_to(source["id"]),"adopted_by": self._adopted_by(source["id"]),}@@ -2283,6 +2309,7 @@ class ModelHubService:oauth_ref: str,channel: Literal["native_cli", "hub"],vendor: str,+ display_name_defaulted: bool = False,completed_flow: Optional[OAuthFlowState] = None,idempotent: bool = False,) -> dict:@@ -2476,6 +2503,7 @@ class ModelHubService:await self._commit_new_source_locked(source,previous=previous,+ display_name_defaulted=display_name_defaulted,)persisted = Truetry:@@ -3006,6 +3034,7 @@ class ModelHubService:await self._create_oauth_source([],display_name=seeded_source_name(binding.vendor),+ display_name_defaulted=True,billing="monthly",created_at=self.now().isoformat(),oauth_ref=flow_id,@@ -3060,6 +3089,7 @@ class ModelHubService:vendor = normalize_model_hub_vendor_id(vendor)except ValueError:raise ModelHubError("discovery_failed") from None+ display_name_defaulted = not payload.get("display_name")display_name = payload.get("display_name") or seeded_source_name(vendor)if kind not in {"subscription", "api_key"}:raise ModelHubError("discovery_failed")@@ -3149,6 +3179,7 @@ class ModelHubService:await self._create_oauth_source(manual_models,display_name=display_name,+ display_name_defaulted=display_name_defaulted,billing=cast(Literal["monthly", "metered"], billing),created_at=self.now().isoformat(),oauth_ref=oauth_ref,diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex f4933f580..80cc6a970 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -553,6 +553,14 @@ class EngineAdapter(Protocol):"""...+ def subscription_account_label(self, source_id: str, vendor: str, credential_ref: str) -> str | None:+ """Read optional public account metadata from this source's bound grant.++ This local presentation read never starts the engine, refreshes a grant,+ or exports credential material. Missing/unsafe metadata returns None.+ """+ ...+async def retarget_api_key_credential(self,credential_ref: str,diff --git a/docs/plans/model-hub-source-identity.md b/docs/plans/model-hub-source-identity.mdnew file mode 100644index 000000000..e5a752de9--- /dev/null+++ b/docs/plans/model-hub-source-identity.md@@ -0,0 +1,61 @@+# Model Hub source identity++## Change contract++- When a new subscription would receive an existing vendor default name,+ allocate the first available numbered name (`OpenAI`, `OpenAI 2`, …) under+ the existing source mutation lock. Carry whether the create request defaulted+ the name into the commit path; preserve explicit names even when they equal+ the vendor default. Preserve existing names, source IDs, routes, and OAuth+ retry idempotency.+- Reuse `Source.account_label` for optional subscription display metadata.+ Hub metadata must come from the credential bound to that exact source,+ vendor, and engine prefix, with email preferred over a provider username.+ Read existing subscriptions as well as new ones, without another login,+ engine startup, upstream request, or credential export.+- Missing, malformed, or unreadable display metadata means no account label;+ it does not prevent source listing or imply authentication failure. Never+ substitute another source's identity or a credential/account ID.+ Reject non-UTF-8-encodable labels and compare labels and stored tokens after+ the same whitespace normalization.+- Show the account on its own line in source cards and details. A single eye+ control in the source-list header hides account identities, endpoint URLs,+ and masked API keys together. Source details expose the same shared control+ in their header; do not add per-source or per-field eye buttons. Persist only+ the browser preference. Hidden metadata must be absent from DOM text,+ accessible labels, and hover titles, including endpoint-derived protocol+ prefixes in source details. Explicit editing forms remain editable.+ Keep each source row as one full-card opener and graph endpoint, so desktop+ wires retain the card's right-edge midpoint. The global eye must not open+ a source or highlight one source's wires.+ Let native button naming expose the rendered kind, protocol, state and+ visible metadata; do not replace that content with a name-only ARIA label.+- Order source-card badges as kind then protocol. API key is cyan, subscription+ retains its semantic accent, and protocol is neutral with no vendor/domain+ prefix. Endpoint details remain available separately.++## Validation++Use hermetic tests for allocation, OAuth replay, source-bound metadata reads,+provider shapes, missing/unsafe metadata, account switching, and privacy.+Run the config/contract suite, including byte-identical adapter-interface+mirrors and live-file authority closure, whenever changing the adapter boundary.+Exercise the React consumers and browser fixture in English and Chinese,+desktop and mobile, light and dark. Run the UI build and changed-file lint.+GitHub CI and the exact-head Codex review remain delivery gates.++The design editor is unavailable in this session. Reuse the established+Model Hub tokens and the supplied screenshot; compare actual browser renders.+Real-provider OAuth and local Incus acceptance remain separate from fixtures.++## Pinned provider evidence++CLIProxyAPI `v7.2.149` (`2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`)+writes a top-level `email` for Codex, Claude, Antigravity, and xAI. Its Kimi+token storage has no account email or username: `device_id` is not an account+identity and remains undisplayed. The reader also accepts an explicit+`username` supplied through the engine's flattened metadata hooks.++These are presentation fields only. Account IDs, subject IDs, organization+IDs, project IDs, device IDs, token claims, and filenames are not fallbacks.+The existing source contract and persisted config schema are unchanged.diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 159740556..887e3d815 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -392,4 +392,15 @@ scenarios:test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_authorized_config_envelope_and_completion_persistence_closed_loopsupporting_tests:- ui/src/components/onboarding/WizardCompletion.test.tsx+ - id: AUTH-SETUP-124+ name: Repeated subscription OAuth completion keeps distinct names and source-bound account metadata through HTTP replay+ status: covered+ kind: happy_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_subscription_identity_survives_oauth_completion_and_http_replay+ supporting_tests:+ - tests/test_model_hub_source_identity.py+ - ui/src/components/settings/models/SourceRow.test.tsx+ - ui/e2e/model-provider/provider.spec.tsnext_priority: []diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex f9b474618..d8c93962c 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -108,6 +108,71 @@ def test_auth_setup_catalog_priorities_reference_live_scenarios():assert set(catalog.get("next_priority", [])) <= live_ids[email protected]("vendor", ["openai", "anthropic", "gemini", "kimi", "xai"])[email protected]("identity_case", ["valid", "invalid_utf8", "token_whitespace"])+def test_subscription_identity_survives_oauth_completion_and_http_replay(monkeypatch, tmp_path, vendor, identity_case):+ """Scenario: AUTH-SETUP-124 — HTTP completion, custody, projection and replay."""+ from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+ from vibe.model_hub_runtime.state import EngineStateStore++ harness = HubOAuthScenarioHarness(tmp_path)+ harness.adapter.observation = replace(+ engine_served_observation("gemini", models=("identity-model",)),+ protocol={"openai": "openai_responses", "anthropic": "anthropic"}.get(vendor, "openai_chat"),+ )+ engine = EngineStateStore(tmp_path / "engine")+ runtime = CLIProxyEngineAdapter(supervisor=object(), state_store=engine)+ harness.adapter.subscription_account_label = runtime.subscription_account_label+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: harness.service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ headers = csrf_headers(client, base_url)+ created = []+ for index, email in enumerate(("[email protected]", "用户@example.com"), start=1):+ started = client.post(+ "/api/models/oauth/start", json={"vendor": vendor, "channel": "hub"},+ headers=headers, base_url=base_url,+ )+ assert started.status_code == 200+ flow = started.get_json()["flow"]+ ref = engine.bind_oauth_credential(flow["source_id"], vendor, f"account-{index}.json")+ identity = {"email": email}+ if identity_case == "invalid_utf8":+ identity = {"email": "\[email protected]"}+ elif identity_case == "token_whitespace":+ identity = {"username": "opaque-secret", "refresh_token": " opaque-secret "}+ engine.write_oauth_auth_file(f"account-{index}.json", {+ "type": _OAUTH_ENDPOINTS[vendor][2],+ "prefix": engine.credential_metadata(ref)["prefix"],+ # The pinned Kimi grant has a device ID, not an account label.+ **({"device_id": f"device-{index}"} if vendor == "kimi" else identity),+ "access_token": f"private-access-fixture-{index}",+ })+ harness.adapter.flows[flow["flow_id"]] = replace(+ harness.adapter.flows[flow["flow_id"]], state="success", credential_ref=ref,+ )+ endpoint = f"/api/models/oauth/status/{flow['flow_id']}"+ completed = client.get(endpoint, base_url=base_url)+ assert completed.status_code == 200+ source = completed.get_json()["source"]+ seed = seeded_source_name(vendor)+ assert source["display_name"] == (seed if index == 1 else f"{seed} {index}")+ assert source["account_label"] == (email if vendor != "kimi" and identity_case == "valid" else None)+ assert "private-access-fixture" not in json.dumps(completed.get_json())+ assert "opaque-secret" not in json.dumps(completed.get_json())+ assert client.get(endpoint, base_url=base_url).get_json()["source"] == source+ created.append(source)+ sources = client.get("/api/models/sources", base_url=base_url)+ assert sources.status_code == 200+ assert sources.get_json()["sources"] == created+ assert len(harness.store.config.sources) == 2+ assert len({source["id"] for source in created}) == 2+ assert [row["account_label"] for row in sources.get_json()["sources"]] == (+ ["[email protected]", "用户@example.com"] if vendor != "kimi" and identity_case == "valid" else [None, None]+ )+ assert harness.adapter.revoked == []++@pytest.mark.parametrize(("access", "role"),[("local", "owner"), ("personal", "owner"), ("organization", "owner"), ("organization", "member")],diff --git a/tests/test_model_hub_source_identity.py b/tests/test_model_hub_source_identity.pynew file mode 100644index 000000000..21550f22c--- /dev/null+++ b/tests/test_model_hub_source_identity.py@@ -0,0 +1,226 @@+"""Source identity stays source-bound and useful across repeated subscriptions."""++import asyncio+import json+from dataclasses import replace++import pytest++from config.v2_config import ModelHubConfig+from core.handlers.model_hub.service import seeded_source_name+from tests.test_model_hub_api import _service+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter, _OAUTH_ENDPOINTS+from vibe.model_hub_runtime.state import EngineStateStore+++async def _completed_flow(service, adapter, vendor):+ flow = (await service.oauth_start({"vendor": vendor, "channel": "hub"}))["flow"]+ adapter.flows[flow["flow_id"]] = replace(+ adapter.flows[flow["flow_id"]],+ state="success",+ credential_ref=f"cred_{flow['source_id']}",+ )+ return flow++[email protected]("vendor", ["openai", "anthropic"])+def test_subscription_names_are_allocated_at_commit_and_oauth_replays_keep_them(tmp_path, vendor):+ async def scenario():+ service, store, adapter = _service(tmp_path)+ first_flow = await _completed_flow(service, adapter, vendor)+ first = (await service.oauth_status(first_flow["flow_id"]))["source"]+ flows = [await _completed_flow(service, adapter, vendor) for _ in range(2)]+ created = await asyncio.gather(*(service.oauth_status(flow["flow_id"]) for flow in flows))+ seed = seeded_source_name(vendor)+ assert first["display_name"] == seed+ assert {result["source"]["display_name"] for result in created} == {f"{seed} 2", f"{seed} 3"}+ for flow, result in zip(flows, created):+ assert (await service.oauth_status(flow["flow_id"]))["source"] == result["source"]+ assert len(store.config.sources) == 3+ reloaded = ModelHubConfig.from_payload(store.config.to_payload())+ assert [row.display_name for row in reloaded.sources] == [seed, f"{seed} 2", f"{seed} 3"]+ assert adapter.revoked == []++ asyncio.run(scenario())+++def test_subscription_allocation_respects_reserved_names_and_explicit_custom_names(tmp_path):+ async def scenario():+ service, store, adapter = _service(tmp_path)+ for name in ("OpenAI", "OpenAI 2", "Work subscription"):+ flow = await _completed_flow(service, adapter, "openai")+ result = await service.create_source({+ "kind": "subscription", "vendor": "openai", "supply_channel": "hub",+ "display_name": name, "oauth_flow_ref": flow["flow_id"],+ })+ assert result["source"]["display_name"] == name+ flow = await _completed_flow(service, adapter, "openai")+ result = await service.oauth_status(flow["flow_id"])+ assert result["source"]["display_name"] == "OpenAI 3"+ assert [source.display_name for source in store.config.sources[:3]] == [+ "OpenAI", "OpenAI 2", "Work subscription",+ ]++ asyncio.run(scenario())+++def test_explicit_default_looking_names_are_preserved_and_omitted_names_are_allocated(tmp_path):+ async def scenario():+ service, store, adapter = _service(tmp_path)+ for _ in range(2):+ flow = await _completed_flow(service, adapter, "openai")+ result = await service.create_source({+ "kind": "subscription", "vendor": "openai", "supply_channel": "hub",+ "display_name": "OpenAI", "oauth_flow_ref": flow["flow_id"],+ })+ assert result["source"]["display_name"] == "OpenAI"+ assert (await service.oauth_status(flow["flow_id"]))["source"] == result["source"]+ flow = await _completed_flow(service, adapter, "openai")+ result = await service.create_source({+ "kind": "subscription", "vendor": "openai", "supply_channel": "hub",+ "oauth_flow_ref": flow["flow_id"],+ })+ assert result["source"]["display_name"] == "OpenAI 2"+ assert [source.display_name for source in store.config.sources] == ["OpenAI", "OpenAI", "OpenAI 2"]++ asyncio.run(scenario())+++def _bound_account(tmp_path, vendor="openai", **identity):+ store = EngineStateStore(tmp_path / "engine")+ source_id = "src_identity001"+ ref = store.bind_oauth_credential(source_id, vendor, "account.json")+ prefix = store.credential_metadata(ref)["prefix"]+ payload = {+ "type": _OAUTH_ENDPOINTS[vendor][2], "prefix": prefix,+ "access_token": "private-access-fixture", "refresh_token": "private-refresh-fixture",+ **identity,+ }+ store.write_oauth_auth_file("account.json", payload)+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=store)+ return store, adapter, source_id, ref, payload++[email protected]("vendor", ["openai", "anthropic", "gemini", "kimi", "xai"])+def test_account_metadata_is_read_without_starting_engine_or_mutating_credentials(tmp_path, vendor):+ store, adapter, source_id, ref, _ = _bound_account(+ tmp_path, vendor, email="用户@example.com", username="fixture-user",+ )+ before = {path: (path.read_bytes(), path.stat().st_mode) for path in store.root.rglob("*") if path.is_file()}+ assert adapter.subscription_account_label(source_id, vendor, ref) == "用户@example.com"+ assert {path: (path.read_bytes(), path.stat().st_mode) for path in before} == before+ assert adapter.subscription_account_label("src_other001", vendor, ref) is None+ other_vendor = "openai" if vendor != "openai" else "anthropic"+ assert adapter.subscription_account_label(source_id, other_vendor, ref) is None+++def test_kimi_device_metadata_is_not_presented_as_an_account(tmp_path):+ _, adapter, source_id, ref, _ = _bound_account(+ tmp_path, "kimi", device_id="device-fixture", scope="user",+ )+ assert adapter.subscription_account_label(source_id, "kimi", ref) is None+++ ("identity", "expected"),+ [+ ({"email": " [email protected] "}, "[email protected]"),+ ({"username": "小明"}, "小明"),+ ({"email": None, "username": "fixture-user"}, "fixture-user"),+ ({"email": {"nested": "[email protected]"}, "username": "fixture-user"}, "fixture-user"),+ ({"account_id": "account-123", "name": "private-access-fixture"}, None),+ ({"email": "not-an-email"}, None),+ ({"email": "line\[email protected]"}, None),+ ({"email": "\[email protected]"}, None),+ ({"email": "\[email protected]"}, None),+ ({"email": "\[email protected]", "username": "safe-user"}, "safe-user"),+ ({"username": "\udfff"}, None),+ ({"username": "用户😀"}, "用户😀"),+ ({"username": "Bearer abcdefghijklmnop"}, None),+ ({"username": "sk-abcdefghijk123"}, None),+ ({"username": "private-access-fixture"}, None),+ ({"email": "x" * 255 + "@example.com"}, None),+ ({"email": "", "username": ""}, None),+ ({}, None),+ ],+)+def test_only_safe_public_account_fields_are_projected(tmp_path, identity, expected):+ _, adapter, source_id, ref, _ = _bound_account(tmp_path, **identity)+ assert adapter.subscription_account_label(source_id, "openai", ref) == expected++[email protected]("token_field", ["access_token", "refresh_token", "id_token"])[email protected]("label_field", ["email", "username"])+def test_account_fields_cannot_publish_whitespace_wrapped_tokens(tmp_path, token_field, label_field):+ identity = {token_field: " \[email protected]\n ", label_field: "[email protected]"}+ _, adapter, source_id, ref, _ = _bound_account(tmp_path, **identity)+ assert adapter.subscription_account_label(source_id, "openai", ref) is None++[email protected]("failure", ["prefix", "provider", "missing", "corrupt", "file_mode", "directory_mode", "symlink"])+def test_unavailable_or_foreign_account_metadata_is_absent_and_never_repaired(tmp_path, failure):+ store, adapter, source_id, ref, payload = _bound_account(tmp_path, email="[email protected]")+ path = store.auth_dir / "account.json"+ if failure in {"prefix", "provider"}:+ payload["prefix" if failure == "prefix" else "type"] = "foreign"+ store.write_oauth_auth_file("account.json", payload)+ elif failure == "missing":+ path.unlink()+ elif failure == "corrupt":+ path.write_text("{")+ elif failure == "file_mode":+ path.chmod(0o644)+ elif failure == "directory_mode":+ store.auth_dir.chmod(0o755)+ elif failure == "symlink":+ target = tmp_path / "foreign.json"+ path.rename(target)+ path.symlink_to(target)+ assert adapter.subscription_account_label(source_id, "openai", ref) is None+ if failure == "file_mode":+ assert path.stat().st_mode & 0o777 == 0o644+ if failure == "directory_mode":+ assert store.auth_dir.stat().st_mode & 0o777 == 0o755+ if failure == "symlink":+ assert path.is_symlink()+++def test_missing_engine_metadata_does_not_create_state_directories(tmp_path):+ store = EngineStateStore(tmp_path / "absent")+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=store)+ assert adapter.subscription_account_label("src_identity001", "openai", "cred_missing01") is None+ assert not store.root.exists()+++def test_existing_source_and_creation_result_use_current_bound_account_without_persisting_secrets(tmp_path):+ async def scenario():+ service, config_store, fake = _service(tmp_path)+ flow = await _completed_flow(service, fake, "openai")+ original = (await service.oauth_status(flow["flow_id"]))["source"]+ source = config_store.config.sources[0]+ store = EngineStateStore(tmp_path / "engine")+ source.credential_ref = store.bind_oauth_credential(source.id, "openai", "current.json")+ source.account_label = "[email protected]"+ metadata = store.credential_metadata(source.credential_ref)+ runtime = CLIProxyEngineAdapter(supervisor=object(), state_store=store)+ fake.subscription_account_label = runtime.subscription_account_label+ payload = {+ "type": "codex", "prefix": metadata["prefix"], "email": "[email protected]",+ "access_token": "private-access-fixture",+ }+ store.write_oauth_auth_file("current.json", payload)+ saved = json.dumps(config_store.config.to_payload())+ listed = service.list_sources()[0]+ assert listed["id"] == original["id"]+ assert listed["account_label"] == "[email protected]"+ assert service._source_creation_result(source.to_payload())["source"] == listed+ assert "private-access-fixture" not in json.dumps(listed)+ payload.pop("email")+ store.write_oauth_auth_file("current.json", payload)+ assert service.list_sources()[0]["account_label"] is None+ payload["email"] = "[email protected]"+ store.write_oauth_auth_file("current.json", payload)+ assert service.list_sources()[0]["account_label"] == "[email protected]"+ assert json.dumps(config_store.config.to_payload()) == saved++ asyncio.run(scenario())diff --git a/ui/e2e/model-provider/fixture.tsx b/ui/e2e/model-provider/fixture.tsxindex 3e2ff6974..c503b87e3 100644--- a/ui/e2e/model-provider/fixture.tsx+++ b/ui/e2e/model-provider/fixture.tsx@@ -9,6 +9,8 @@ import '../../src/components/settings/models/modelHubSurface.css';import { Button } from '../../src/components/ui/button';import { AddApiKeyDialog } from '../../src/components/settings/models/AddApiKeyDialog';import { SourceDetailPanel } from '../../src/components/settings/models/SourceDetailPanel';+import { SourcesCard } from '../../src/components/settings/models/SourcesCard';+import { readyRegion } from '../../src/components/settings/models/regionRead';import { createSourceCollectionReadAuthority } from '../../src/components/settings/models/collectionReadAuthority';import { modelsApi } from '../../src/components/settings/models/modelsApi';import { readSurfaceLanding, type TrackSourceMutation } from '../../src/components/settings/models/mutationSettlement';@@ -96,4 +98,34 @@ export function Fixture() {</main></I18nextProvider>;}-createRoot(document.getElementById('root')!).render(<Fixture />);+const identitySources: Source[] = [+ {+ ...saved, id: 'src_identity001', display_name: 'OpenAI', vendor: 'openai', kind: 'subscription',+ protocol: 'openai_responses', base_url: null, billing: 'monthly', account_label: '[email protected]',+ verification_pending: null, adopted_by: [{ backend: 'codex', menu_model: 'gpt-5.6-luna' }],+ },+ {+ ...saved, id: 'src_identity002', display_name: 'OpenAI 2', vendor: 'openai', kind: 'subscription',+ protocol: 'openai_responses', base_url: null, billing: 'monthly',+ account_label: '[email protected]', verification_pending: null,+ },+ { ...saved, masked_credential: 'sk-…1234' },+];++function IdentityFixture() {+ const [selected, setSelected] = useState(identitySources[0]);+ return <I18nextProvider i18n={language}>+ <main className="mx-auto flex min-h-dvh max-w-[1100px] flex-col gap-5 bg-surface p-3 md:flex-row">+ <section data-testid="identity-cards" className="w-full shrink-0 self-start md:w-[400px]">+ <SourcesCard read={readyRegion(identitySources)} onOpenSource={setSelected}+ onRetry={() => {}} onAddApiKey={() => {}} onAddSubscription={() => {}} />+ </section>+ <section className="min-w-0 flex-1" data-testid="identity-detail">+ <SourceDetailPanel source={selected} trackMutation={async () => { throw new Error('Read-only fixture'); }}+ onReauth={() => {}} onMutationCommitted={async () => {}} />+ </section>+ </main>+ </I18nextProvider>;+}++createRoot(document.getElementById('root')!).render(params.has('identity') ? <IdentityFixture /> : <Fixture />);diff --git a/ui/e2e/model-provider/provider.spec.ts b/ui/e2e/model-provider/provider.spec.tsindex c0980b08c..8639c7b08 100644--- a/ui/e2e/model-provider/provider.spec.ts+++ b/ui/e2e/model-provider/provider.spec.ts@@ -2,6 +2,63 @@ import { expect, test } from '@playwright/test';import { hub } from '../support/copy';for (const lang of ['en', 'zh'] as const) {+ for (const theme of ['light', 'dark']) {+ test(`source identity, badge hierarchy and privacy: ${lang} ${theme}`, async ({ page }, info) => {+ const text = (key: string) => hub(key, undefined, lang);+ await page.route('**/api/**', (route) => route.abort());+ await page.goto(`/e2e/model-provider/fixture.html?identity=1&lang=${lang}&theme=${theme}`);+ const cards = page.getByTestId('identity-cards');+ const detail = page.getByTestId('identity-detail');+ const pills = cards.locator('[data-source-id] .model-hub-pill');+ await expect(pills).toHaveText([+ text('upstream.kind.subscription'), 'OpenAI Responses',+ text('upstream.kind.subscription'), 'OpenAI Responses',+ text('upstream.kind.apiKey'), 'OpenAI Chat Completions',+ ]);+ await expect(cards.getByText('[email protected]', { exact: true })).toBeVisible();+ const accountCard = cards.locator('[data-source-id="src_identity001"]');+ const apiCard = cards.locator('[data-source-id="src_fixture001"]');+ await expect(accountCard).toHaveAccessibleName(/first@example\.com/);+ await expect(apiCard).toHaveAccessibleName(/API [kK]ey.*OpenAI Chat Completions.*relay\.example\/v1.*sk-…1234/);+ await expect(detail.getByRole('heading', { name: 'OpenAI', exact: true })).toBeVisible();+ await cards.screenshot({ path: info.outputPath('identity-visible.png') });+ // One header control covers every source; no per-row or per-field eyes.+ await expect(cards.getByRole('button', { name: text('upstream.hidePrivateDetails') })).toHaveCount(1);+ await expect(cards.locator('[data-source-id] button')).toHaveCount(0);+ await cards.getByRole('button', { name: text('upstream.hidePrivateDetails') }).click();+ await expect(cards.getByText(lang === 'zh' ? '已隐藏' : 'Hidden', { exact: true })).toHaveCount(3);+ await expect(cards.locator('[data-source-id] .lucide-eye-off[aria-hidden="true"]')).toHaveCount(3);+ await expect(accountCard).not.toHaveAccessibleName(/first@example\.com/);+ await expect(apiCard).not.toHaveAccessibleName(/relay\.example|sk-…1234/);+ await expect(apiCard).toHaveAccessibleName(/API [kK]ey.*OpenAI Chat Completions.*(?:Hidden|已隐藏)/);+ await expect(detail.getByRole('heading', { name: 'OpenAI', exact: true })).toBeVisible();+ await expect(page.getByText('[email protected]', { exact: true })).toHaveCount(0);+ await expect(page.locator('[title*="@example.com"]')).toHaveCount(0);+ expect(await cards.innerHTML()).not.toContain('relay.example');+ expect(await cards.innerHTML()).not.toContain('sk-…1234');+ await page.reload();+ await expect(page.getByText('[email protected]', { exact: true })).toHaveCount(0);+ await cards.getByRole('button', { name: /^OpenAI 2 / }).click();+ await expect(detail.getByRole('heading', { name: 'OpenAI 2', exact: true })).toBeVisible();+ const show = detail.getByRole('button', { name: text('upstream.showPrivateDetails') });+ await show.focus();+ await page.keyboard.press('Enter');+ await expect(cards.getByText('[email protected]', { exact: true })).toBeVisible();+ await expect(detail.getByText('[email protected]', { exact: true })).toBeVisible();+ await cards.getByRole('button', { name: text('upstream.hidePrivateDetails') }).click();+ await cards.getByRole('button', { name: /^Example relay / }).click();+ await expect(detail.getByRole('heading', { name: 'Example relay', exact: true })).toBeVisible();+ expect(await detail.innerHTML()).not.toContain('relay.example');+ expect(await detail.innerHTML()).not.toContain('sk-…1234');+ await detail.getByRole('button', { name: text('upstream.showPrivateDetails') }).click();+ await expect(detail.getByText('https://relay.example/v1', { exact: true })).toBeVisible();+ await expect(detail.getByText('sk-…1234', { exact: true })).toBeVisible();+ await cards.getByRole('button', { name: text('upstream.hidePrivateDetails') }).click();+ await cards.screenshot({ path: info.outputPath('identity-hidden.png') });+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);+ });+ }+test('save, optional selected-model test and manual inventory: ' + lang, async ({ page }, info) => {const text = (key: string) => hub(key, undefined, lang);await page.route('**/api/**', (route) => route.abort());diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex e30d1d65e..f0593edf7 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -206,6 +206,7 @@ const renderEchoPanel = (afterEach(() => {cleanup();+ localStorage.clear();commits.length = 0;sourceSnapshot = 0;vi.restoreAllMocks();@@ -213,6 +214,26 @@ afterEach(() => {});describe('SourceDetailPanel', () => {+ it.each(['en', 'zh'])('hides endpoint, key and domain-derived metadata with one header control in %s', async (lng) => {+ const locale = i18n.cloneInstance({ lng });+ const { container } = render(<I18nextProvider i18n={locale}>+ <CommittedPanel source={{ ...source, masked_credential: 'sk-…1234' }} trackMutation={immediateTrack} onReauth={noReauth} />+ </I18nextProvider>);+ const hide = screen.getByRole('button', { name: locale.t('settings.models.upstream.hidePrivateDetails') });+ expect(hide.closest('.model-hub-source-bar')).not.toBeNull();+ expect(container.querySelector('.model-hub-source-metadata button')).toBeNull();+ await userEvent.click(hide);+ expect(container.innerHTML).not.toContain('relay.example');+ expect(container.innerHTML).not.toContain('sk-…1234');+ expect(screen.getByText('Anthropic Messages', { exact: true })).toBeTruthy();+ const show = screen.getByRole('button', { name: locale.t('settings.models.upstream.showPrivateDetails') });+ show.focus();+ await userEvent.keyboard(' ');+ expect(screen.getByText('https://relay.example/v1', { exact: true })).toBeTruthy();+ expect(screen.getByText('sk-…1234', { exact: true })).toBeTruthy();+ expect(screen.getByTitle('relay.example · Anthropic Messages')).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');diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex b6c12e925..25896ca0a 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -15,6 +15,8 @@ import { classifyModelHubFailure } from './asyncLifetime';import { Field } from './dialogFields';import { GuardImpact } from './GuardImpact';import { ModelHubInfoHint } from './ModelHubInfoHint';+import { SourcePrivateValue, SourcePrivacyToggle } from './SourcePrivacy';+import { useSourceDetailsHidden } from './sourcePrivacyPreference';import {assessSourceEdit,canEditSourceEndpoint,@@ -170,6 +172,7 @@ export const SourceDetailPanel: React.FC<{activeBackends?: ReadonlySet<AgentBackend>;}> = ({ source, trackMutation, onReauth, onMutationCommitted, headingRef, activeBackends }) => {const { t, i18n } = useTranslation();+ const detailsHidden = useSourceDetailsHidden();const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);const { Icon, accent } = sourceVisual(source);const [pendingAction, setPendingAction] = React.useState<'refetch' | 'add_model' | 'other' | null>(null);@@ -653,14 +656,14 @@ export const SourceDetailPanel: React.FC<{const providerIdentity = sourceProviderIdentity(source);const providerCopyKey = SOURCE_PROVIDER_COPY_KEYS[providerIdentity];const providerLabel = providerCopyKey ? t(providerCopyKey) : providerIdentity;- const interfaceLabel = `${providerLabel} · ${t(PROTOCOL_COPY_KEYS[source.protocol])}`;+ const protocolLabel = t(PROTOCOL_COPY_KEYS[source.protocol]);+ const interfaceLabel = detailsHidden ? protocolLabel : `${providerLabel} · ${protocolLabel}`;const credentialLabel = source.kind === 'api_key'? t('settings.models.sourceDetail.metadata.apiKey'): t('settings.models.sourceDetail.metadata.account');const credentialValue = source.kind === 'api_key'- ? source.masked_credential ?? '—'- : source.account_label ?? '—';- const endpoint = source.base_url ?? t('settings.models.sourceDetail.metadata.officialEndpoint');+ ? source.masked_credential+ : source.account_label;const lastFetched = source.last_discovered_at? formatRelativeTime(source.last_discovered_at, t): t('settings.models.sourceDetail.metadata.neverFetched');@@ -680,10 +683,15 @@ export const SourceDetailPanel: React.FC<{</div><p className="model-hub-source-summary truncate">{usageSummary}</p></div>+ {(source.base_url || credentialValue) && <SourcePrivacyToggle />}</section><dl className="model-hub-source-metadata grid shrink-0 grid-cols-2 gap-x-5 gap-y-3 border-b border-border bg-background px-5 py-3 sm:grid-cols-4">- <div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.endpoint')}</dt><dd className="truncate font-mono" title={endpoint as string}>{endpoint}</dd></div>- <div className="min-w-0"><dt>{credentialLabel}</dt><dd className="truncate font-mono" title={credentialValue}>{credentialValue}</dd></div>+ <div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.endpoint')}</dt><dd className="truncate font-mono">{source.base_url+ ? <SourcePrivateValue value={source.base_url} />+ : t('settings.models.sourceDetail.metadata.officialEndpoint')}</dd></div>+ <div className="min-w-0"><dt>{credentialLabel}</dt><dd className="font-mono">{credentialValue+ ? <SourcePrivateValue value={credentialValue} />+ : '—'}</dd></div><div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.type')}</dt><dd className="truncate" title={interfaceLabel}>{interfaceLabel}</dd></div><div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.lastFetched')}</dt><dd className="truncate">{lastFetched}</dd></div></dl>diff --git a/ui/src/components/settings/models/SourcePrivacy.tsx b/ui/src/components/settings/models/SourcePrivacy.tsxnew file mode 100644index 000000000..04830cd1c--- /dev/null+++ b/ui/src/components/settings/models/SourcePrivacy.tsx@@ -0,0 +1,38 @@+import { Eye, EyeOff } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Button } from '@/components/ui/button';+import { cn } from '@/lib/utils';+import { setSourceDetailsHidden, useSourceDetailsHidden } from './sourcePrivacyPreference';++export function SourcePrivateValue({ value, className }: { value: string; className?: string }) {+ const { t } = useTranslation();+ const hidden = useSourceDetailsHidden();+ return (+ <span className={cn('block min-w-0 truncate font-mono', className)} title={hidden ? undefined : value}>+ {hidden ? <span className="flex min-w-0 items-center gap-1">+ <EyeOff className="size-3 shrink-0" aria-hidden="true" />+ <span className="truncate">{t('settings.models.upstream.hiddenDetails')}</span>+ </span> : value}+ </span>+ );+}++export function SourcePrivacyToggle() {+ const { t } = useTranslation();+ const hidden = useSourceDetailsHidden();+ const action = t(hidden ? 'settings.models.upstream.showPrivateDetails' : 'settings.models.upstream.hidePrivateDetails');+ return (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="size-6 shrink-0 text-muted"+ aria-label={action}+ title={action}+ onClick={() => setSourceDetailsHidden(!hidden)}+ >+ {hidden ? <Eye className="size-3.5" /> : <EyeOff className="size-3.5" />}+ </Button>+ );+}diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsxindex b5fefd4dc..58ad35368 100644--- a/ui/src/components/settings/models/SourceRow.test.tsx+++ b/ui/src/components/settings/models/SourceRow.test.tsx@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import i18n from '@/i18n';import { SourceRow } from './SourceRow';+import { SourcePrivacyToggle } from './SourcePrivacy';import type { Source } from './types';const source: Source = {@@ -16,6 +17,7 @@ const source: Source = {afterEach(() => {cleanup();+ localStorage.clear();vi.useRealTimers();});@@ -38,7 +40,7 @@ describe('SourceRow', () => {await userEvent.click(opener);expect(onOpen).toHaveBeenCalledWith(source, opener);expect(screen.queryByText(/latency/i)).toBeNull();- expect(screen.getByText('Anthropic · Anthropic Messages')).toBeTruthy();+ expect(screen.getByText('Anthropic Messages')).toBeTruthy();});it('explains that a healthy source is not currently supplying a route', () => {@@ -46,8 +48,23 @@ describe('SourceRow', () => {expect(screen.getByText(/Available · not currently supplying|可用 · 当前未使用/i)).toBeTruthy();});- it('labels a custom upstream by host and protocol', () => {- render(+ it.each(['en', 'zh'])('includes all visible row metadata in the accessible name in %s', (lng) => {+ const locale = i18n.cloneInstance({ lng });+ render(<I18nextProvider i18n={locale}>+ <SourceRow source={{ ...source, base_url: 'https://relay.example/v1' }} onOpen={vi.fn()} />+ </I18nextProvider>);+ expect(screen.getByRole('button', { name: (name) => [+ 'Production',+ locale.t('settings.models.upstream.kind.apiKey'),+ 'Anthropic Messages',+ 'relay.example/v1',+ 'sk-ant-…1234',+ locale.t('settings.models.upstream.state.standby'),+ ].every((part) => name.includes(part)) })).toBeTruthy();+ });++ it('puts the highlighted API key badge before the neutral protocol without a host prefix', () => {+ const { container } = render(<I18nextProvider i18n={i18n}><SourceRowsource={{ ...source, vendor: 'custom', base_url: 'https://relay.example/v1' }}@@ -55,7 +72,74 @@ describe('SourceRow', () => {/></I18nextProvider>,);- expect(screen.getByText('relay.example · Anthropic Messages')).toBeTruthy();+ const pills = container.querySelectorAll('.model-hub-pill');+ expect(pills).toHaveLength(2);+ expect(pills[0].textContent).toMatch(/API key|API Key/);+ expect(pills[0].classList.contains('model-hub-accent-pill--cyan')).toBe(true);+ expect(pills[1].textContent).toBe('Anthropic Messages');+ expect(pills[1].getAttribute('title')).toBe('Anthropic Messages');+ // The endpoint remains in the independent connection-detail line.+ expect(screen.getByText('relay.example/v1 · sk-ant-…1234')).toBeTruthy();+ });++ it.each(['en', 'zh'])('hides accounts across cards without opening them, and remembers the preference in %s', async (lng) => {+ const locale = i18n.cloneInstance({ lng });+ const onOpen = vi.fn();+ const subscription: Source = {+ ...source, kind: 'subscription', display_name: 'OpenAI 2', vendor: 'openai',+ account_label: '账号@example.com', masked_credential: null,+ };+ const tree = <I18nextProvider i18n={locale}>+ <SourcePrivacyToggle />+ <SourceRow source={subscription} onOpen={onOpen} />+ <SourceRow source={{ ...subscription, id: 'src_b', display_name: 'OpenAI 3', account_label: '[email protected]' }} onOpen={onOpen} />+ </I18nextProvider>;+ const { container, unmount } = render(tree);+ const user = userEvent.setup();+ expect(container.querySelector('button button')).toBeNull();+ expect(container.querySelector('[data-source-account]')?.textContent).toBe('账号@example.com');+ expect(container.querySelector('.model-hub-pill')?.textContent).toBe(locale.t('settings.models.upstream.kind.subscription'));+ await user.click(screen.getByRole('button', { name: locale.t('settings.models.upstream.hidePrivateDetails') }));+ expect(onOpen).not.toHaveBeenCalled();+ expect(container.innerHTML).not.toContain('账号@example.com');+ expect(container.innerHTML).not.toContain('[email protected]');+ unmount();+ const remounted = render(tree);+ expect(remounted.container.innerHTML).not.toContain('账号@example.com');+ const reveal = screen.getByRole('button', { name: locale.t('settings.models.upstream.showPrivateDetails') });+ reveal.focus();+ await user.keyboard('{Enter}');+ expect(screen.getByText('账号@example.com')).toBeTruthy();+ expect(onOpen).not.toHaveBeenCalled();+ const opener = screen.getByRole('button', { name: /^OpenAI 2/ });+ await user.click(opener);+ expect(onOpen).toHaveBeenCalledWith(subscription, opener);+ });++ it('does not invent an account or add per-row controls', () => {+ const { container } = render(<I18nextProvider i18n={i18n}>+ <SourceRow source={{ ...source, kind: 'subscription', account_label: null }} onOpen={vi.fn()} />+ </I18nextProvider>);+ expect(container.querySelector('[data-source-account]')).toBeNull();+ expect(screen.getAllByRole('button')).toHaveLength(1);+ });++ it('still hides the account when browser storage rejects the preference', async () => {+ const { container } = render(<I18nextProvider i18n={i18n}>+ <SourcePrivacyToggle />+ <SourceRow source={{ ...source, kind: 'subscription', account_label: '[email protected]' }} onOpen={vi.fn()} />+ </I18nextProvider>);+ const storage = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new DOMException('Storage unavailable', 'QuotaExceededError');+ });+ try {+ await userEvent.click(screen.getByRole('button', { name: i18n.t('settings.models.upstream.hidePrivateDetails') }));+ expect(container.innerHTML).not.toContain('[email protected]');+ } finally {+ storage.mockRestore();+ await userEvent.click(screen.getByRole('button', { name: i18n.t('settings.models.upstream.showPrivateDetails') }));+ }+ expect(screen.getByText('[email protected]')).toBeTruthy();});it('uses the authoritative Source adoption to name an active supplying source', () => {diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsxindex d12ca6778..d17f8e561 100644--- a/ui/src/components/settings/models/SourceRow.tsx+++ b/ui/src/components/settings/models/SourceRow.tsx@@ -4,11 +4,8 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { PROTOCOL_COPY_KEYS } from './addApiKeyState';-import {- SOURCE_PROVIDER_COPY_KEYS,- sourceDetail,- sourceProviderIdentity,-} from './sourcePresentation';+import { sourceDetail } from './sourcePresentation';+import { SourcePrivateValue } from './SourcePrivacy';import { activeSourceAdoption, sourceStatePresentation } from './sourceStatePresentation';import { useDeadlineClock } from './useDeadlineClock';import { ACCENT_ICON, ACCENT_PILL, ACCENT_TILE, sourceVisual } from './vendorMeta';@@ -23,10 +20,7 @@ export const SourceRow: React.FC<{const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);const { Icon, accent } = sourceVisual(source);const detail = sourceDetail(source);- const providerIdentity = sourceProviderIdentity(source);- const providerCopyKey = SOURCE_PROVIDER_COPY_KEYS[providerIdentity];- const providerLabel = providerCopyKey ? t(providerCopyKey) : providerIdentity;- const interfaceLabel = `${providerLabel} · ${t(PROTOCOL_COPY_KEYS[source.protocol])}`;+ const interfaceLabel = t(PROTOCOL_COPY_KEYS[source.protocol]);const adoptedBy = activeSourceAdoption(source.adopted_by, activeBackends);const adoptedBackends = [...new Set((adoptedBy ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];const state = sourceStatePresentation(source.state, 'card', i18n.language, now, {@@ -59,17 +53,18 @@ export const SourceRow: React.FC<{<span className="min-w-0 flex-1"><span className="block min-w-0 truncate text-[12.5px] font-bold leading-[18px] text-foreground" title={source.display_name}>{source.display_name}</span><span className="mt-1 flex min-w-0 flex-wrap items-center gap-1.5">+ <span className={cn('model-hub-pill border', ACCENT_PILL[source.kind === 'api_key' ? 'cyan' : accent])}>+ {t(`settings.models.upstream.kind.${kindKey}`)}+ </span><spanclassName="model-hub-pill model-hub-source-interface-pill border"title={interfaceLabel}><span className="truncate">{interfaceLabel}</span></span>- <span className={cn('model-hub-pill border', ACCENT_PILL[accent])}>- {t(`settings.models.upstream.kind.${kindKey}`)}- </span></span>- {detail && <span className="model-hub-upstream-detail mt-1 block truncate font-mono text-[10.5px] leading-[14px]" title={detail}>{detail}</span>}+ {source.account_label && <span data-source-account><SourcePrivateValue value={source.account_label} className="model-hub-upstream-detail mt-1 text-[10.5px] leading-[14px]" /></span>}+ {detail && <SourcePrivateValue value={detail} className="model-hub-upstream-detail mt-1 text-[10.5px] leading-[14px]" />}{state.key && <span className={cn('mt-1 flex items-center gap-[5px] text-[10.5px] font-semibold', state.textClass)}><span className={cn('size-[5px] rounded-full', state.dotClass)} />{t(state.key, state.values)}diff --git a/ui/src/components/settings/models/SourcesCard.test.tsx b/ui/src/components/settings/models/SourcesCard.test.tsxindex 8ab0cd986..4238d3b68 100644--- a/ui/src/components/settings/models/SourcesCard.test.tsx+++ b/ui/src/components/settings/models/SourcesCard.test.tsx@@ -22,7 +22,10 @@ const retained: Source = {models: [],};-afterEach(cleanup);+afterEach(() => {+ cleanup();+ localStorage.clear();+});describe('SourcesCard footer', () => {it('fills a narrow overview column without preserving an intrinsic panel width', () => {@@ -39,7 +42,7 @@ describe('SourcesCard footer', () => {expect(panel?.children.item(1)?.className).not.toContain('overflow-y-auto');});- it('keeps the source title on its own line above the interface and kind tags', () => {+ it('keeps the source title on its own line above the kind and protocol tags', () => {render(<I18nextProvider i18n={i18n}><SourcesCard read={readyRegion([retained])} onRetry={vi.fn()} onOpenSource={vi.fn()} onAddApiKey={vi.fn()} onAddSubscription={vi.fn()} />@@ -49,7 +52,52 @@ describe('SourcesCard footer', () => {const title = screen.getByText('Retained source');expect(title.className).toContain('block');expect(title.nextElementSibling?.className).toContain('flex');- expect(title.closest('button')?.className).toContain('min-h-[96px]');+ expect(screen.getByRole('button', { name: /^Retained source/ }).className).toContain('min-h-[96px]');+ });++ it.each(['en', 'zh'])('uses one header toggle for all account, URL and key details in %s', async (lng) => {+ const locale = i18n.cloneInstance({ lng });+ const onOpenSource = vi.fn();+ const rows: Source[] = [+ { ...retained, base_url: 'https://private-relay.example/v1', masked_credential: 'sk-…7890' },+ { ...retained, id: 'src_account', kind: 'subscription', account_label: '[email protected]' },+ ];+ const tree = <I18nextProvider i18n={locale}>+ <SourcesCard read={readyRegion(rows)} onRetry={vi.fn()} onOpenSource={onOpenSource} onAddApiKey={vi.fn()} onAddSubscription={vi.fn()} />+ </I18nextProvider>;+ const view = render(tree);+ expect(screen.getByRole('button', { name: /private-relay\.example\/v1.*sk-…7890/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /owner@example\.com/ })).toBeTruthy();+ const toggle = screen.getByRole('button', { name: locale.t('settings.models.upstream.hidePrivateDetails') });+ expect(toggle.closest('[data-source-id]')).toBeNull();+ expect(view.container.querySelector('button button')).toBeNull();+ expect(view.container.querySelector('[data-source-id] button')).toBeNull();+ await userEvent.click(toggle);+ expect(onOpenSource).not.toHaveBeenCalled();+ for (const value of ['private-relay.example', 'sk-…7890', '[email protected]']) {+ expect(view.container.innerHTML).not.toContain(value);+ }+ expect(screen.queryByRole('button', { name: /private-relay\.example|sk-…7890|owner@example\.com/ })).toBeNull();+ expect(screen.getByRole('button', { name: (name) => [+ locale.t('settings.models.upstream.kind.apiKey'),+ 'Anthropic Messages',+ locale.t('settings.models.upstream.hiddenDetails'),+ ].every((part) => name.includes(part)) })).toBeTruthy();+ const placeholders = screen.getAllByText(lng === 'zh' ? '已隐藏' : 'Hidden', { exact: true });+ expect(placeholders).toHaveLength(2);+ for (const placeholder of placeholders) {+ expect(placeholder.previousElementSibling?.classList.contains('lucide-eye-off')).toBe(true);+ expect(placeholder.previousElementSibling?.getAttribute('aria-hidden')).toBe('true');+ }+ view.unmount();+ const remounted = render(tree);+ expect(remounted.container.innerHTML).not.toContain('private-relay.example');+ const reveal = screen.getByRole('button', { name: locale.t('settings.models.upstream.showPrivateDetails') });+ reveal.focus();+ await userEvent.keyboard('{Enter}');+ expect(screen.getByText('private-relay.example/v1 · sk-…7890')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(onOpenSource).not.toHaveBeenCalled();});it('exposes the upstream info note to keyboard activation and Escape dismissal', async () => {diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsxindex 5a416206d..199655b7b 100644--- a/ui/src/components/settings/models/SourcesCard.tsx+++ b/ui/src/components/settings/models/SourcesCard.tsx@@ -6,6 +6,7 @@ import { Button } from '@/components/ui/button';import { ModelHubInfoHint } from './ModelHubInfoHint';import { foldRegionRead, type RegionRead } from './regionRead';import { SourceRow } from './SourceRow';+import { SourcePrivacyToggle } from './SourcePrivacy';import type { AgentBackend, Source } from './types';export const SourcesCard: React.FC<{@@ -45,7 +46,10 @@ export const SourcesCard: React.FC<{className="model-hub-upstream-info"/></span>- {sources !== undefined && <span className="model-hub-pill model-hub-upstream-count border">{t('settings.models.upstream.count', { count: sources.length })}</span>}+ {sources !== undefined && <span className="flex items-center gap-2">+ {sources.some((source) => source.account_label || source.base_url || source.masked_credential) && <SourcePrivacyToggle />}+ <span className="model-hub-pill model-hub-upstream-count border">{t('settings.models.upstream.count', { count: sources.length })}</span>+ </span>}</div><div className="flex-1 space-y-2.5 p-3">{read.kind === 'loading' && sources === undefineddiff --git a/ui/src/components/settings/models/SupplyGraph.test.tsx b/ui/src/components/settings/models/SupplyGraph.test.tsxindex 42976f96f..a64c97ae0 100644--- a/ui/src/components/settings/models/SupplyGraph.test.tsx+++ b/ui/src/components/settings/models/SupplyGraph.test.tsx@@ -2,7 +2,11 @@import * as React from 'react';import { cleanup, fireEvent, render, waitFor } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';+import { I18nextProvider } from 'react-i18next';+import i18n from '@/i18n';+import { SourceRow } from './SourceRow';+import { SourcePrivacyToggle } from './SourcePrivacy';import { SupplyGraph } from './SupplyGraph';import type { SupplyRelation } from './supplyRelations';@@ -22,11 +26,19 @@ const rect = (left: number, top: number, width: number, height: number): DOMRecttoJSON: () => ({}),});-const Fixture: React.FC<{ relations?: SupplyRelation[] }> = ({ relations = [relation] }) => {+const Fixture: React.FC<{ relations?: SupplyRelation[]; withSourceCard?: boolean }> = ({ relations = [relation], withSourceCard = false }) => {const ref = React.useRef<HTMLDivElement>(null);return (<div ref={ref} data-testid="graph-root">- <div data-source-id="src_a" />+ {withSourceCard ? <I18nextProvider i18n={i18n}>+ <SourcePrivacyToggle />+ <SourceRow source={{+ id: 'src_a', last_discovered_at: null, kind: 'subscription', vendor: 'openai', display_name: 'OpenAI',+ protocol: 'openai_responses', base_url: null, supply_channel: 'hub', billing: 'monthly',+ state: { status: 'standby', retry_at: null, detail_key: null }, models: [],+ account_label: '[email protected]',+ }} onOpen={() => {}} />+ </I18nextProvider> : <div data-source-id="src_a" />}<div data-source-id="src_b" /><div data-agent-backend="claude" /><div data-agent-backend="codex" />@@ -41,6 +53,32 @@ afterEach(() => {});describe('SupplyGraph', () => {+ it('anchors to the whole SourceRow and distinguishes its focus from the global privacy control', async () => {+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function bounds() {+ if (this.dataset.testid === 'graph-root') return rect(0, 0, 600, 300);+ if (this.dataset.agentBackend === 'claude') return rect(450, 40, 100, 100);+ // A full-card endpoint includes the account row. An inner title/badge+ // button would have smaller bounds and must not own this graph hook.+ if (this.dataset.sourceId === 'src_a' && this.querySelector('[data-source-account]')) return rect(10, 10, 300, 120);+ if (this.tagName === 'BUTTON') return rect(60, 20, 200, 40);+ return rect(0, 0, 0, 0);+ });+ const view = render(<Fixture withSourceCard />);+ const path = await waitFor(() => {+ const element = view.container.querySelector<SVGPathElement>('.model-hub-wire');+ expect(element).not.toBeNull();+ return element as SVGPathElement;+ });+ expect(path.getAttribute('d')).toBe('M 310 70 C 380 70, 380 90, 450 90');+ const opener = view.getByRole('button', { name: /^OpenAI/ });+ fireEvent.focusIn(opener);+ await waitFor(() => expect(path.classList.contains('model-hub-wire--highlighted')).toBe(true));+ const eye = view.getByRole('button', { name: i18n.t('settings.models.upstream.hidePrivateDetails') });+ fireEvent.focusOut(opener, { relatedTarget: eye });+ fireEvent.focusIn(eye);+ await waitFor(() => expect(path.classList.contains('model-hub-wire--highlighted')).toBe(false));+ });+it('draws on the shared mount and re-measures when a nested card scrolls', async () => {let sourceTop = 10;vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function bounds() {diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex 676f94b99..ba00a5ff7 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -267,11 +267,11 @@.model-hub-source-interface-pill {min-width: 0;- max-width: 52%;+ max-width: 100%;flex: 0 1 auto;- border-color: var(--model-hub-cyan-4d);- background: var(--model-hub-cyan-1a);- color: var(--cyan-ink);+ border-color: var(--model-hub-wash-14);+ background: var(--model-hub-wash-0a);+ color: var(--muted);}.model-hub-ink-mint { color: var(--mint-ink); }diff --git a/ui/src/components/settings/models/sourcePresentation.ts b/ui/src/components/settings/models/sourcePresentation.tsindex c03ec76df..41b9f3483 100644--- a/ui/src/components/settings/models/sourcePresentation.ts+++ b/ui/src/components/settings/models/sourcePresentation.ts@@ -21,7 +21,6 @@ export const sourceProviderIdentity = (source: Pick<Source, 'vendor' | 'base_urlexport const sourceDetail = (source: Source): string | null => {const parts: string[] = [];- if (source.account_label) parts.push(source.account_label);if (source.base_url) {try {const url = new URL(source.base_url);diff --git a/ui/src/components/settings/models/sourcePrivacyPreference.ts b/ui/src/components/settings/models/sourcePrivacyPreference.tsnew file mode 100644index 000000000..fc0a270e3--- /dev/null+++ b/ui/src/components/settings/models/sourcePrivacyPreference.ts@@ -0,0 +1,42 @@+import { useSyncExternalStore } from 'react';++const STORAGE_KEY = 'avibe.model-hub.hide-private-details.v1';+const listeners = new Set<() => void>();+let hiddenInMemory: boolean | undefined;++const getHidden = () => {+ if (hiddenInMemory !== undefined) return hiddenInMemory;+ try {+ return localStorage.getItem(STORAGE_KEY) === 'true';+ } catch {+ return false;+ }+};++const subscribe = (listener: () => void) => {+ listeners.add(listener);+ const onStorage = (event: StorageEvent) => {+ if (event.key === STORAGE_KEY || event.key === null) {+ hiddenInMemory = undefined;+ listener();+ }+ };+ window.addEventListener('storage', onStorage);+ return () => {+ listeners.delete(listener);+ window.removeEventListener('storage', onStorage);+ };+};++export const setSourceDetailsHidden = (hidden: boolean) => {+ try {+ localStorage.setItem(STORAGE_KEY, String(hidden));+ hiddenInMemory = undefined;+ } catch {+ // Browser storage can be disabled; visibility still works for this page.+ hiddenInMemory = hidden;+ }+ listeners.forEach((listener) => listener());+};++export const useSourceDetailsHidden = () => useSyncExternalStore(subscribe, getHidden, () => true);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex c4ad7e97a..f79432693 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1176,6 +1176,9 @@"retry": "Retry","addSubscription": "Add subscription","addApiKey": "Add API key",+ "showPrivateDetails": "Show accounts and API connection details",+ "hidePrivateDetails": "Hide accounts and API connection details",+ "hiddenDetails": "Hidden","state": {"supplyingNative": "Supplying {{backend}} (native)","supplying": "Supplying {{backends}}",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 0b7861452..5e11f33c2 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1176,6 +1176,9 @@"retry": "重试","addSubscription": "添加订阅","addApiKey": "添加 API Key",+ "showPrivateDetails": "显示账号和 API 连接信息",+ "hidePrivateDetails": "隐藏账号和 API 连接信息",+ "hiddenDetails": "已隐藏","state": {"supplyingNative": "{{backend}} 正在使用(Agent 管理)","supplying": "{{backends}} 正在使用",diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 7ccda9e07..3a5aef58f 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -2538,6 +2538,14 @@ class CLIProxyEngineAdapter:self._oauth_flows[flow.flow_id] = flowreturn flow.snapshot()+ def subscription_account_label(self, source_id: str, vendor: str, credential_ref: str) -> str | None:+ endpoint = _OAUTH_ENDPOINTS.get(vendor)+ if endpoint is None:+ return None+ return self.state_store.oauth_account_label(+ credential_ref, source_id=source_id, vendor=vendor, auth_provider=endpoint[2],+ )+async def oauth_status(self, flow_id: str) -> OAuthFlowState:flow = self._get_flow(flow_id)async with flow.operation_lock:diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex dde02df3e..38cec0e7b 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -16,6 +16,7 @@ from typing import Any, Callable, Sequencefrom config.atomic_io import write_atomicfrom config.v2_config import normalize_model_hub_base_url+from core.handlers.model_hub.events import contains_credential_materialfrom core.handlers.model_hub.identifiers import model_id_without_credential_addressfrom vibe.model_hub_runtime.api_key_vendors import (official_api_key_base_url,@@ -958,6 +959,39 @@ class EngineStateStore:value = payload.get("auth_name") if payload.get("kind") == "oauth" else Nonereturn str(value) if value else None+ def oauth_account_label(+ self, credential_ref: str, *, source_id: str, vendor: str, auth_provider: str,+ ) -> str | None:+ """Project optional identity without changing custody or repairing files."""+ try:+ with self._lock:+ _validated_source_id(source_id)+ metadata = self._read_replacement_credential_document(credential_ref)+ if (+ metadata is None+ or metadata.get("kind") != "oauth"+ or metadata.get("source_id") != source_id+ or metadata.get("vendor") != vendor+ or metadata.get("activation_state") not in {None, "active"}+ or not self._private_credential_directory_present(self.auth_dir)+ ):+ return None+ auth_name = metadata.get("auth_name")+ if not isinstance(auth_name, str):+ return None+ auth_name = _validated_oauth_auth_name(auth_name)+ payload = json.loads(self._read_private_bytes(+ self.auth_dir / auth_name, "engine auth credential path is unsafe",+ ))+ if not isinstance(payload, dict):+ return None+ self._assert_oauth_payload_identity(metadata, auth_name, payload, auth_provider=auth_provider)+ return _oauth_account_label(payload)+ except (EngineStateError, OSError, ValueError, TypeError):+ # Display metadata is optional. A missing/unsafe grant stays under+ # its existing auth recovery policy; listing must not repair it.+ return None+def oauth_credential_ref(self, auth_name: str) -> str | None:normalized = auth_name.strip()with self._lock:@@ -1302,8 +1336,10 @@ class EngineStateStore:metadata: dict[str, Any],auth_name: str,payload: dict[str, Any],+ *,+ auth_provider: str | None = None,) -> dict[str, str]:- expected_provider = _oauth_provider_for_vendor(str(metadata.get("vendor") or ""))+ expected_provider = auth_provider or _oauth_provider_for_vendor(str(metadata.get("vendor") or ""))actual_provider = str(payload.get("type") or "").strip().lower()expected_prefix = str(metadata.get("prefix") or "").strip()actual_prefix = str(payload.get("prefix") or "").strip().strip("/")@@ -1341,6 +1377,34 @@ class EngineStateStore:raise EngineStateError(message)+def _oauth_account_label(payload: dict[str, Any]) -> str | None:+ """Only provider-declared public identity fields can become UI metadata."""+ secrets = {+ value.strip()+ for key in ("access_token", "refresh_token", "id_token")+ if isinstance(value := payload.get(key), str)+ }+ for key in ("email", "username"):+ value = payload.get(key)+ if not isinstance(value, str):+ continue+ candidate = value.strip()+ if (+ not candidate+ or len(candidate) > 254+ or any(+ ord(character) < 32 or ord(character) == 127 or 0xD800 <= ord(character) <= 0xDFFF+ for character in candidate+ )+ or contains_credential_material(candidate)+ or candidate in secrets+ or (key == "email" and re.fullmatch(r"[^@\s]+@[^@\s]+", candidate) is None)+ ):+ continue+ return candidate+ return None++def _credential_ref_auth_scheme(credential_ref: str) -> str | None:"""Decode private immutable transport identity; callers keep refs opaque."""if not isinstance(credential_ref, str) or _CREDENTIAL_REF_RE.fullmatch(credential_ref) is None: