Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(models): keep model hub dormant by default (#1019)

Call Whiteb2c454a79fb5
diff --git a/config/v2_config.py b/config/v2_config.py
index 3064c24dd..8aae2f8c2 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -7,7 +7,7 @@ import threading
from dataclasses import dataclass, field, fields
from datetime import datetime
from pathlib import Path
-from typing import List, Literal, Optional, Union
+from typing import List, Literal, Mapping, Optional, Union
from config import paths
from config.platform_registry import (
@@ -92,6 +92,14 @@ DEFAULT_CHAT_MESSAGE_FONT_SIZE_PX = 14
MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
DEFAULT_AGENT_PROGRESS_STYLE = "off"
+MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"
+
+
+def is_model_hub_enabled(environ: Optional[Mapping[str, str]] = None) -> bool:
+ """Return the backend-authoritative Model Hub release capability."""
+
+ source = os.environ if environ is None else environ
+ return source.get(MODEL_HUB_ENABLED_ENV, "").strip().lower() in {"1", "true", "yes", "on"}
def _validate_optional_datetime(value: object, field_path: str) -> Optional[str]:
@@ -677,15 +685,6 @@ class ModelHubConfig:
)
subscription_hub_experimental: bool = False
- @classmethod
- def fresh(cls) -> "ModelHubConfig":
- return cls(
- agents={
- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
- for backend in ("claude", "codex", "opencode")
- }
- )
-
@classmethod
def from_payload(cls, payload: dict) -> "ModelHubConfig":
if not isinstance(payload, dict):
@@ -1011,8 +1010,8 @@ class V2Config:
model_hub_payload = payload.get("model_hub")
if model_hub_payload is None:
- # Existing installs predate Model Hub and must remain in Direct mode
- # until the user explicitly migrates. Fresh defaults seed Hub mode.
+ # Existing installs predate Model Hub and remain in Direct mode until
+ # the user explicitly opts in after the release capability is enabled.
model_hub = ModelHubConfig()
else:
model_hub = ModelHubConfig.from_payload(model_hub_payload)
diff --git a/core/controller.py b/core/controller.py
index 62a74037d..e0d7c407c 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -226,18 +226,7 @@ class Controller:
self.session_turns = SessionTurnManager(self)
- # The controller is the single Model Hub aggregate and engine owner.
- # The UI process reaches this instance through the internal Unix socket.
- from core.handlers.model_hub import create_default_service
- from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
- from modules.agents.model_hub import ModelHubRuntimeRouter
-
- self.model_hub_service = create_default_service()
- self.model_hub_turn_gateway = ModelHubTurnGateway(self.model_hub_service)
- self.model_hub_runtime = ModelHubRuntimeRouter(
- service=self.model_hub_service,
- turn_gateway=self.model_hub_turn_gateway,
- )
+ self._init_model_hub()
# Initialize core modules
self._init_modules()
@@ -287,6 +276,30 @@ class Controller:
# workbench sidebar dot doesn't show a phantom green forever.
self.session_turns.reset_stale()
+ def _init_model_hub(self) -> None:
+ """Create the Model Hub aggregate only for an explicit release opt-in."""
+
+ from config.v2_config import is_model_hub_enabled
+
+ self.model_hub_service = None
+ self.model_hub_turn_gateway = None
+ self.model_hub_runtime = None
+ if not is_model_hub_enabled():
+ return
+
+ # The controller is the single Model Hub aggregate and engine owner.
+ # The UI process reaches this instance through the internal Unix socket.
+ from core.handlers.model_hub import create_default_service
+ from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+ from modules.agents.model_hub import ModelHubRuntimeRouter
+
+ self.model_hub_service = create_default_service()
+ self.model_hub_turn_gateway = ModelHubTurnGateway(self.model_hub_service)
+ self.model_hub_runtime = ModelHubRuntimeRouter(
+ service=self.model_hub_service,
+ turn_gateway=self.model_hub_turn_gateway,
+ )
+
def _init_modules(self):
"""Initialize core modules"""
runtime_clients: Dict[str, BaseIMClient] = IMFactory.create_clients(self.config)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 79f889ad1..44e06d142 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -1310,12 +1310,7 @@ class ModelHubService:
self.oauth_flows.forget(flow_id)
async def runtime_status(self) -> dict:
- try:
- status = await self._engine_call(self.adapter.start())
- except ModelHubError as exc:
- if exc.code != "engine_down":
- raise
- status = await self._engine_call(self.adapter.status())
+ status = await self._engine_call(self.adapter.status())
return _runtime_payload(status)
def migration_scan(self) -> dict:
diff --git a/core/internal_server.py b/core/internal_server.py
index 449380708..97b5f9451 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -428,9 +428,15 @@ def create_app(controller: "Controller") -> FastAPI:
async def _model_hub(request: Request) -> Any:
"""Dispatch UI operations to the controller-owned Model Hub aggregate."""
+ from config.v2_config import is_model_hub_enabled
from core.handlers.model_hub import ModelHubError
from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+ if not is_model_hub_enabled():
+ return JSONResponse(
+ status_code=404,
+ content={"ok": False, "contract_version": 1, "error": "feature_disabled"},
+ )
body = await _safe_json(request)
operation = body.get("operation") if isinstance(body, dict) else None
payload = body.get("payload") if isinstance(body, dict) else None
diff --git a/core/services/settings.py b/core/services/settings.py
index 5112d45ca..68d76c3ad 100644
--- a/core/services/settings.py
+++ b/core/services/settings.py
@@ -79,7 +79,7 @@ def default_config() -> V2Config:
claude=ClaudeConfig(enabled=True, cli_path="claude"),
codex=CodexConfig(enabled=False, cli_path="codex"),
),
- model_hub=ModelHubConfig.fresh(),
+ model_hub=ModelHubConfig(),
)
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index dac31716f..bf37a0226 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -6,7 +6,7 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
-from config.v2_config import ModelHubConfig
+from config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig
from core.handlers.model_hub.adapter import OAuthFlowState
from core.handlers.model_hub.events import BoundedEventLog
from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter
@@ -17,7 +17,12 @@ from core.handlers.model_hub.service import ModelHubService, UnavailableEngineAd
class MemoryStore:
def __init__(self, *, experimental: bool = False):
- self.config = ModelHubConfig.fresh()
+ self.config = ModelHubConfig(
+ agents={
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
+ for backend in ("claude", "codex", "opencode")
+ }
+ )
self.config.subscription_hub_experimental = experimental
def load(self) -> ModelHubConfig:
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
index 77b70edbe..748da58e0 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -34,6 +34,11 @@ from vibe.ui_server import app
CONTRACTS = Path("docs/plans/model-hub-contracts")
[email protected](autouse=True)
+def _enable_model_hub(monkeypatch):
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
class MemoryStore:
def __init__(self) -> None:
self.config = ModelHubConfig(
diff --git a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
index fa603e750..87bc7afbd 100644
--- a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import pytest
+
from tests.scenario_harness.model_hub_native_oauth import (
HubOAuthScenarioHarness,
NativeOAuthScenarioHarness,
@@ -11,6 +13,11 @@ from vibe.ui_server import app
BASE_URL = "http://127.0.0.1:15131"
[email protected](autouse=True)
+def _enable_model_hub(monkeypatch):
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
def _client(monkeypatch, service):
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
client = app.test_client()
diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.py
new file mode 100644
index 000000000..c4decbb91
--- /dev/null
+++ b/tests/test_controller_model_hub_gate.py
@@ -0,0 +1,104 @@
+from __future__ import annotations
+
+import asyncio
+import json
+
+import pytest
+
+from config.v2_config import V2Config
+from core.controller import Controller
+from modules.agents.model_hub import resolve_model_hub_launch, resolve_opencode_overlay_launch
+
+
+def test_controller_leaves_model_hub_aggregate_absent_by_default(monkeypatch):
+ import core.handlers.model_hub as model_hub
+
+ factory_calls = 0
+
+ def create_service():
+ nonlocal factory_calls
+ factory_calls += 1
+ return object()
+
+ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
+ monkeypatch.setattr(model_hub, "create_default_service", create_service)
+ controller = Controller.__new__(Controller)
+
+ controller._init_model_hub()
+
+ assert controller.model_hub_service is None
+ assert controller.model_hub_turn_gateway is None
+ assert controller.model_hub_runtime is None
+ assert factory_calls == 0
+
+
+def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeypatch):
+ import core.handlers.model_hub as model_hub
+ import core.handlers.model_hub.turn_gateway as turn_gateway
+ import modules.agents.model_hub as agent_model_hub
+
+ service = object()
+ calls = []
+
+ class Gateway:
+ def __init__(self, value):
+ calls.append(("gateway", value))
+ self.service = value
+
+ class Router:
+ def __init__(self, *, service, turn_gateway):
+ calls.append(("router", service, turn_gateway))
+ self.service = service
+ self.turn_gateway = turn_gateway
+
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+ monkeypatch.setattr(model_hub, "create_default_service", lambda: service)
+ monkeypatch.setattr(turn_gateway, "ModelHubTurnGateway", Gateway)
+ monkeypatch.setattr(agent_model_hub, "ModelHubRuntimeRouter", Router)
+ controller = Controller.__new__(Controller)
+
+ controller._init_model_hub()
+
+ assert controller.model_hub_service is service
+ assert controller.model_hub_turn_gateway.service is service
+ assert controller.model_hub_runtime.service is service
+ assert controller.model_hub_runtime.turn_gateway is controller.model_hub_turn_gateway
+ assert calls == [
+ ("gateway", service),
+ ("router", service, controller.model_hub_turn_gateway),
+ ]
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_disabled_controller_resolver_is_direct_without_loading_model_hub_config(
+ monkeypatch,
+ backend,
+):
+ def corrupt_config(*_args, **_kwargs):
+ raise json.JSONDecodeError("corrupt model_hub config", "{", 1)
+
+ monkeypatch.setattr(V2Config, "load", classmethod(corrupt_config))
+ controller = Controller.__new__(Controller)
+ controller.model_hub_runtime = None
+
+ launch = asyncio.run(resolve_model_hub_launch(controller, backend, f"{backend}-native"))
+
+ assert launch.backend == backend
+ assert launch.channel == "direct"
+ assert launch.requested_model == f"{backend}-native"
+ assert launch.target_model == f"{backend}-native"
+ assert launch.runtime_model == f"{backend}-native"
+
+
+def test_disabled_controller_opencode_overlay_resolver_is_direct_without_config_read(monkeypatch):
+ def corrupt_config(*_args, **_kwargs):
+ raise json.JSONDecodeError("corrupt model_hub config", "{", 1)
+
+ monkeypatch.setattr(V2Config, "load", classmethod(corrupt_config))
+ controller = Controller.__new__(Controller)
+ controller.model_hub_runtime = None
+
+ launch = asyncio.run(resolve_opencode_overlay_launch(controller, "openai/gpt-direct", None))
+
+ assert launch.channel == "direct"
+ assert launch.runtime_model == "openai/gpt-direct"
diff --git a/tests/test_core_services_settings.py b/tests/test_core_services_settings.py
index eae500b39..1a5010f8e 100644
--- a/tests/test_core_services_settings.py
+++ b/tests/test_core_services_settings.py
@@ -59,6 +59,11 @@ def test_default_config_is_fresh_and_needs_setup():
# default leaking in and persisting a phantom Slack transport on skip.
assert config.platforms.enabled == []
assert config.platforms.primary == "avibe"
+ assert {agent.mode for agent in config.model_hub.agents.values()} == {"direct"}
+
+ from vibe.runtime import default_config as runtime_default_config
+
+ assert {agent.mode for agent in runtime_default_config().model_hub.agents.values()} == {"direct"}
def test_load_config_or_default_returns_default_without_persisting(isolated_state, tmp_path):
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 2ad2e126b..8b9f898c8 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -235,7 +235,8 @@ def test_health_endpoint():
assert resp.json() == {"ok": True, "service": "vibe-remote-internal", "version": 1}
-def test_model_hub_rpc_uses_controller_owned_service():
+def test_model_hub_rpc_uses_controller_owned_service(monkeypatch):
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
controller = _build_controller_double()
controller.model_hub_service = MagicMock()
controller.model_hub_service.list_sources.return_value = [{"id": "src_owned"}]
@@ -256,6 +257,31 @@ def test_model_hub_rpc_uses_controller_owned_service():
controller.model_hub_service.list_sources.assert_called_once_with()
+def test_model_hub_rpc_is_stably_disabled_without_touching_service(monkeypatch):
+ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
+ controller = _build_controller_double()
+ controller.model_hub_service = MagicMock()
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post(
+ "/internal/model-hub",
+ json={"operation": "list_sources", "payload": {}},
+ )
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 404
+ assert response.json() == {
+ "ok": False,
+ "contract_version": 1,
+ "error": "feature_disabled",
+ }
+ assert controller.model_hub_service.mock_calls == []
+
+
async def _publish_event_round_trip():
from core import inbox_events
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index e6fae378c..930482eec 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -33,6 +33,11 @@ from vibe.ui_server import app
CONTRACTS = Path("docs/plans/model-hub-contracts")
[email protected](autouse=True)
+def _enable_model_hub_for_existing_contract_tests(monkeypatch):
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
+
+
def _schema(name: str) -> dict:
return json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
@@ -228,16 +233,21 @@ def test_default_service_uses_real_native_oauth_adapter(monkeypatch, tmp_path):
assert service.native_oauth_adapter._agent_auth_service is agent_auth_service
-def test_runtime_status_starts_engine_before_reporting_health(tmp_path):
+def test_runtime_status_observes_engine_without_starting_it(tmp_path):
class LifecycleAdapter(FakeAdapter):
def __init__(self):
super().__init__()
self.start_calls = 0
+ self.status_calls = 0
async def start(self):
self.start_calls += 1
return await super().start()
+ async def status(self):
+ self.status_calls += 1
+ return await super().status()
+
adapter = LifecycleAdapter()
service = ModelHubService(
store=MemoryStore(),
@@ -249,7 +259,8 @@ def test_runtime_status_starts_engine_before_reporting_health(tmp_path):
runtime = asyncio.run(service.runtime_status())
- assert adapter.start_calls == 1
+ assert adapter.start_calls == 0
+ assert adapter.status_calls == 1
assert runtime["status"]["health"] == "ok"
assert runtime["status"]["verified"] is True
@@ -270,10 +281,10 @@ def test_runtime_status_reports_packaged_engine_manifest(tmp_path):
]
-def test_runtime_status_falls_back_when_engine_cannot_start(tmp_path):
- class StartFailureAdapter(FakeAdapter):
+def test_runtime_status_reports_observed_not_installed_state(tmp_path):
+ class NotInstalledAdapter(FakeAdapter):
async def start(self):
- raise RuntimeError("engine cannot start")
+ raise AssertionError("runtime_status must not start the engine")
async def status(self):
return EngineStatus(
@@ -287,7 +298,7 @@ def test_runtime_status_falls_back_when_engine_cannot_start(tmp_path):
service = ModelHubService(
store=MemoryStore(),
- adapter=StartFailureAdapter(),
+ adapter=NotInstalledAdapter(),
events=BoundedEventLog(tmp_path / "events.json"),
oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
@@ -387,6 +398,113 @@ def test_ui_model_hub_rpc_preserves_controller_error_contract():
assert exc_info.value.detail == "modelHub.errors.mode_switch_blocked"
+ ("method", "path"),
+ [
+ ("GET", "/api/models/sources"),
+ ("POST", "/api/models/sources"),
+ ("PATCH", "/api/models/sources/src_test0001"),
+ ("DELETE", "/api/models/sources/src_test0001"),
+ ("POST", "/api/models/sources/src_test0001/test"),
+ ("GET", "/api/models/priority"),
+ ("PUT", "/api/models/priority"),
+ ("GET", "/api/models/agents"),
+ ("PATCH", "/api/models/agents/claude/mode"),
+ ("PUT", "/api/models/agents/claude/mappings"),
+ ("PUT", "/api/models/agents/opencode/menu"),
+ ("POST", "/api/models/custom-models"),
+ ("DELETE", "/api/models/custom-models"),
+ ("GET", "/api/models/events?limit=invalid"),
+ ("POST", "/api/models/oauth/start"),
+ ("GET", "/api/models/oauth/status/oaf_test0001"),
+ ("POST", "/api/models/oauth/submit"),
+ ("POST", "/api/models/oauth/cancel"),
+ ("POST", "/api/models/migration/scan"),
+ ("POST", "/api/models/migration/apply"),
+ ("GET", "/api/models/runtime/status"),
+ ],
+)
+def test_disabled_model_hub_rest_surface_returns_feature_disabled_without_runtime_work(
+ monkeypatch,
+ method,
+ path,
+):
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+ from vibe.model_hub_runtime.supervisor import EngineSupervisor
+
+ remote_service_calls = []
+ installer_calls = []
+ supervisor_calls = []
+
+ def unexpected_remote_access_read():
+ raise AssertionError("disabled Model Hub must short-circuit before remote access config")
+
+ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
+ monkeypatch.setattr(ui_server, "_load_remote_access_config", unexpected_remote_access_read)
+ monkeypatch.setattr(
+ "vibe.model_hub_client.ModelHubRemoteService",
+ lambda: remote_service_calls.append(True),
+ )
+ monkeypatch.setattr(
+ EngineRuntimeManager,
+ "ensure",
+ lambda *_args, **_kwargs: installer_calls.append(True),
+ )
+ monkeypatch.setattr(
+ EngineSupervisor,
+ "ensure_running",
+ lambda *_args, **_kwargs: supervisor_calls.append(True),
+ )
+ client = app.test_client()
+
+ response = getattr(client, method.lower())(path, json={})
+
+ assert response.status_code == 404
+ assert response.get_json() == {
+ "ok": False,
+ "contract_version": 1,
+ "error": "feature_disabled",
+ }
+ assert remote_service_calls == []
+ assert installer_calls == []
+ assert supervisor_calls == []
+
+
[email protected](("env_value", "expected"), [(None, False), ("0", False), ("1", True)])
+def test_config_capability_exactly_projects_backend_model_hub_gate(monkeypatch, env_value, expected):
+ from config.v2_config import is_model_hub_enabled
+
+ if env_value is None:
+ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
+ else:
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", env_value)
+
+ response = app.test_client().get("/api/config")
+
+ assert response.status_code == 200
+ enabled = response.get_json()["capabilities"]["model_hub"]["enabled"]
+ assert enabled is expected
+ assert enabled is is_model_hub_enabled()
+
+
+def test_disabled_gate_preserves_existing_model_hub_config_bytes(monkeypatch):
+ from config import paths
+ from core.services.settings import default_config
+
+ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)
+ config = default_config()
+ config.model_hub.subscription_hub_experimental = True
+ config.save()
+ config_path = paths.get_config_path()
+ before = config_path.read_bytes()
+ client = app.test_client()
+
+ assert client.get("/api/config").status_code == 200
+ assert client.get("/api/models/sources").status_code == 404
+
+ assert config_path.read_bytes() == before
+
+
def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
"""Scenarios: MH-PRI-001, MH-OAUTH-A-001, MH-OAUTH-ERR-001."""
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 31ea4a381..fc660bcf9 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -4,9 +4,11 @@ import json
from dataclasses import fields
from pathlib import Path
+import pytest
from jsonschema import Draft7Validator, FormatChecker
from config.v2_config import (
+ MODEL_HUB_ENABLED_ENV,
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubMappingConfig,
@@ -16,6 +18,7 @@ from config.v2_config import (
ModelHubSourceStateConfig,
ModelHubSourceUsageConfig,
V2Config,
+ is_model_hub_enabled,
)
from core.services.settings import default_config
from vibe import api
@@ -130,13 +133,23 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
assert api.config_to_payload(updated)["model_hub"] == api_payload["model_hub"]
-def test_legacy_config_defaults_direct_while_fresh_config_defaults_hub():
+def test_legacy_and_fresh_configs_both_default_direct():
payload = api.config_to_payload(default_config(), include_secrets=True)
payload.pop("model_hub")
legacy = V2Config.from_payload(payload)
assert {agent.mode for agent in legacy.model_hub.agents.values()} == {"direct"}
- assert {agent.mode for agent in default_config().model_hub.agents.values()} == {"hub"}
+ assert {agent.mode for agent in default_config().model_hub.agents.values()} == {"direct"}
+
+
[email protected]("value", ["1", "true", "TRUE", "yes", "on"])
+def test_model_hub_release_capability_accepts_explicit_truthy_values(value):
+ assert is_model_hub_enabled({MODEL_HUB_ENABLED_ENV: value}) is True
+
+
[email protected]("value", ["", "0", "false", "no", "off", "unexpected"])
+def test_model_hub_release_capability_defaults_and_fails_closed(value):
+ assert is_model_hub_enabled({MODEL_HUB_ENABLED_ENV: value}) is False
def test_hub_subscription_requires_server_recorded_consent():
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 67697d7e2..77cc00bae 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -69,11 +69,15 @@ const ShowPageRoute = lazy(() =>
import('./components/apps/ShowPageRoute').then((m) => ({ default: m.ShowPageRoute })),
);
// Settings → Models (Model Hub, L4). Lazy so its code + framer-motion Reorder
-// stay out of the main entry — the surface is nav-gated until its backend
-// dependencies land (see models/featureFlags.ts).
+// stay out of the main entry. The backend capability gate below must accept the
+// route before React renders this lazy component and requests its chunk.
const SettingsModelsPage = lazy(() =>
import('./components/settings/models/SettingsModelsPage').then((m) => ({ default: m.SettingsModelsPage })),
);
+import {
+ LegacyModelHubRoute,
+ ModelHubCapabilityGate,
+} from './components/settings/models/ModelHubCapabilityGate';
import { hasConfiguredPlatformCredentials } from './lib/platforms';
import { isIosDevice, isStandalonePwa } from './lib/platform';
import {
@@ -594,9 +598,11 @@ const router = createBrowserRouter(
<Route
path="/admin/settings/models"
element={
- <Suspense fallback={<AppsRouteFallback />}>
- <SettingsModelsPage />
- </Suspense>
+ <ModelHubCapabilityGate>
+ <Suspense fallback={<AppsRouteFallback />}>
+ <SettingsModelsPage />
+ </Suspense>
+ </ModelHubCapabilityGate>
}
/>
<Route path="/admin/settings/dependencies" element={<SettingsDependenciesPage />} />
@@ -622,7 +628,7 @@ const router = createBrowserRouter(
<Route path="/settings/backends/opencode" element={<Navigate to="/admin/settings/backends/opencode" replace />} />
<Route path="/settings/backends/claude" element={<Navigate to="/admin/settings/backends/claude" replace />} />
<Route path="/settings/backends/codex" element={<Navigate to="/admin/settings/backends/codex" replace />} />
- <Route path="/settings/models" element={<Navigate to="/admin/settings/models" replace />} />
+ <Route path="/settings/models" element={<LegacyModelHubRoute />} />
<Route path="/settings/dependencies" element={<Navigate to="/admin/settings/dependencies" replace />} />
<Route path="/settings/messaging" element={<Navigate to="/admin/settings/messaging" replace />} />
<Route path="/settings/diagnostics" element={<Navigate to="/admin/settings/diagnostics" replace />} />
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 5fb254aea..a77ec9606 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -4,7 +4,7 @@ import { ArrowLeft, Bot, ChevronDown, Cpu, FolderTree, Globe, Grid2x2, Hash, Inb
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
-import { MODEL_HUB_NAV_ENABLED } from './settings/models/featureFlags';
+import { modelHubEnabledFromConfig } from './settings/models/featureFlags';
import { useApi } from '../context/ApiContext';
import { useStatus } from '../context/StatusContext';
import { useWorkbenchInbox } from '../context/WorkbenchInboxContext';
@@ -263,6 +263,7 @@ export const AppShell: React.FC = () => {
}, [location.pathname]);
const hasChannelPlatforms = enabledPlatforms.some((platform) => platformSupportsChannels(config, platform));
+ const modelHubEnabled = modelHubEnabledFromConfig(config);
const isRunning = status.state === 'running';
if (location.pathname === '/setup') {
@@ -299,10 +300,8 @@ export const AppShell: React.FC = () => {
{ to: '/admin/users', label: t('nav.users'), icon: MessageCircle },
],
},
- // 模型 (Model Hub, L4): sits between 通讯平台 and 后端. Nav-gated until its
- // backend dependencies land (MODEL_HUB_NAV_ENABLED); the route is always
- // registered for direct access + review.
- ...(MODEL_HUB_NAV_ENABLED
+ // 模型 (Model Hub, L4): the backend release capability is the only authority.
+ ...(modelHubEnabled
? [
{
to: '/admin/settings/models',
diff --git a/ui/src/components/settings/models/MigrationBanner.test.ts b/ui/src/components/settings/models/MigrationBanner.test.ts
new file mode 100644
index 000000000..d2101261c
--- /dev/null
+++ b/ui/src/components/settings/models/MigrationBanner.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { scanMigrationWhenEnabled } from './MigrationBanner';
+
+describe('scanMigrationWhenEnabled', () => {
+ it('does not issue a migration scan while Model Hub is disabled', async () => {
+ const scan = vi.fn(async () => ({ items: [] }));
+
+ await expect(scanMigrationWhenEnabled(false, scan)).resolves.toBeNull();
+ expect(scan).not.toHaveBeenCalled();
+ });
+
+ it('issues one scan after the backend capability is enabled', async () => {
+ const result = { items: [] };
+ const scan = vi.fn(async () => result);
+
+ await expect(scanMigrationWhenEnabled(true, scan)).resolves.toBe(result);
+ expect(scan).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/src/components/settings/models/MigrationBanner.tsx b/ui/src/components/settings/models/MigrationBanner.tsx
index c1ba80074..d27f46ba7 100644
--- a/ui/src/components/settings/models/MigrationBanner.tsx
+++ b/ui/src/components/settings/models/MigrationBanner.tsx
@@ -14,12 +14,19 @@ import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMig
import { MigrationDialog } from './MigrationDialog';
import { modelsApi } from './modelsApi';
import type { MigrationItem } from './types';
+import { useModelHubCapability } from './useModelHubCapability';
+
+export const scanMigrationWhenEnabled = async (
+ enabled: boolean,
+ scan: typeof modelsApi.scanMigration = modelsApi.scanMigration,
+) => (enabled ? scan() : null);
export const MigrationBanner: React.FC<{
/** Bubble the applied count so a host page can refresh sources/agents. */
onApplied?: (applied: number) => void;
}> = ({ onApplied }) => {
const { t } = useTranslation();
+ const modelHubEnabled = useModelHubCapability();
const [importable, setImportable] = React.useState<MigrationItem[]>([]);
const [dialogOpen, setDialogOpen] = React.useState(false);
@@ -34,11 +41,14 @@ export const MigrationBanner: React.FC<{
}, []);
React.useEffect(() => {
+ if (modelHubEnabled !== true) {
+ setImportable([]);
+ return;
+ }
let cancelled = false;
- modelsApi
- .scanMigration()
+ scanMigrationWhenEnabled(true)
.then((scan) => {
- if (cancelled || !aliveRef.current) return;
+ if (cancelled || !aliveRef.current || scan === null) return;
// reauth rows need the interactive OAuth flow and can't be bulk-applied,
// so they don't count as importable (they'd open a dead-end dialog).
const items = scan.items.filter((i) => i.proposed_action !== 'reauth');
@@ -56,9 +66,9 @@ export const MigrationBanner: React.FC<{
return () => {
cancelled = true;
};
- }, [scanToken]);
+ }, [modelHubEnabled, scanToken]);
- if (importable.length === 0 || dismissed) return null;
+ if (modelHubEnabled !== true || importable.length === 0 || dismissed) return null;
const dismiss = () => {
writeMigrationDismissed(importable);
diff --git a/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsx b/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsx
new file mode 100644
index 000000000..314e39885
--- /dev/null
+++ b/ui/src/components/settings/models/ModelHubCapabilityGate.test.tsx
@@ -0,0 +1,56 @@
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it } from 'vitest';
+
+import {
+ MODEL_HUB_DISABLED_REDIRECT,
+ MODEL_HUB_SETTINGS_PATH,
+ ModelHubRenderBoundary,
+ modelHubRouteTarget,
+} from './ModelHubCapabilityGate';
+
+describe('Model Hub capability route gate', () => {
+ it('redirects both current and legacy model routes while disabled', () => {
+ expect(modelHubRouteTarget(MODEL_HUB_SETTINGS_PATH, false)).toBe(MODEL_HUB_DISABLED_REDIRECT);
+ expect(modelHubRouteTarget('/settings/models', false)).toBe(MODEL_HUB_DISABLED_REDIRECT);
+ });
+
+ it('does not render the Models child while disabled or unresolved', () => {
+ let childRenders = 0;
+ const ModelsChunk = () => {
+ childRenders += 1;
+ return <div>models chunk</div>;
+ };
+
+ const disabledHtml = renderToStaticMarkup(
+ <ModelHubRenderBoundary enabled={false} disabled={<div>disabled</div>}>
+ <ModelsChunk />
+ </ModelHubRenderBoundary>,
+ );
+ const unresolvedHtml = renderToStaticMarkup(
+ <ModelHubRenderBoundary enabled={null}>
+ <ModelsChunk />
+ </ModelHubRenderBoundary>,
+ );
+
+ expect(disabledHtml).toContain('disabled');
+ expect(unresolvedHtml).toBe('');
+ expect(childRenders).toBe(0);
+ });
+
+ it('renders the Models child only after the backend enables it', () => {
+ let childRenders = 0;
+ const ModelsChunk = () => {
+ childRenders += 1;
+ return <div>models chunk</div>;
+ };
+
+ expect(
+ renderToStaticMarkup(
+ <ModelHubRenderBoundary enabled>
+ <ModelsChunk />
+ </ModelHubRenderBoundary>,
+ ),
+ ).toContain('models chunk');
+ expect(childRenders).toBe(1);
+ });
+});
diff --git a/ui/src/components/settings/models/ModelHubCapabilityGate.tsx b/ui/src/components/settings/models/ModelHubCapabilityGate.tsx
new file mode 100644
index 000000000..c4936ec3e
--- /dev/null
+++ b/ui/src/components/settings/models/ModelHubCapabilityGate.tsx
@@ -0,0 +1,42 @@
+import * as React from 'react';
+import { Navigate } from 'react-router-dom';
+
+import { useModelHubCapability } from './useModelHubCapability';
+
+export const MODEL_HUB_SETTINGS_PATH = '/admin/settings/models';
+export const MODEL_HUB_DISABLED_REDIRECT = '/admin/settings/backends';
+
+export const modelHubRouteTarget = (requestedPath: string, enabled: boolean): string =>
+ enabled ? requestedPath : MODEL_HUB_DISABLED_REDIRECT;
+
+export const ModelHubRenderBoundary: React.FC<{
+ enabled: boolean | null;
+ disabled?: React.ReactNode;
+ children: React.ReactNode;
+}> = ({ enabled, disabled = null, children }) => {
+ if (enabled === null) return null;
+ return enabled ? children : disabled;
+};
+
+export const ModelHubCapabilityGate: React.FC<{ children: React.ReactNode }> = ({ children }) => {
+ const enabled = useModelHubCapability();
+ return (
+ <ModelHubRenderBoundary
+ enabled={enabled}
+ disabled={<Navigate to={MODEL_HUB_DISABLED_REDIRECT} replace />}
+ >
+ {children}
+ </ModelHubRenderBoundary>
+ );
+};
+
+export const LegacyModelHubRoute: React.FC = () => {
+ const enabled = useModelHubCapability();
+ if (enabled === null) return null;
+ return (
+ <Navigate
+ to={modelHubRouteTarget(MODEL_HUB_SETTINGS_PATH, enabled)}
+ replace
+ />
+ );
+};
diff --git a/ui/src/components/settings/models/featureFlags.test.ts b/ui/src/components/settings/models/featureFlags.test.ts
new file mode 100644
index 000000000..bed7ecc2a
--- /dev/null
+++ b/ui/src/components/settings/models/featureFlags.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { modelHubEnabledFromConfig } from './featureFlags';
+
+describe('modelHubEnabledFromConfig', () => {
+ it('uses the backend capability as the only enabled value', () => {
+ const config = { capabilities: { model_hub: { enabled: true } } };
+
+ expect(modelHubEnabledFromConfig(config)).toBe(true);
+ expect(modelHubEnabledFromConfig(config)).toBe(config.capabilities.model_hub.enabled);
+ });
+
+ it.each([
+ undefined,
+ {},
+ { capabilities: {} },
+ { capabilities: { model_hub: {} } },
+ { capabilities: { model_hub: { enabled: false } } },
+ { capabilities: { model_hub: { enabled: 'true' } } },
+ ])('fails closed for missing or malformed backend capability: %o', (config) => {
+ expect(modelHubEnabledFromConfig(config)).toBe(false);
+ });
+});
diff --git a/ui/src/components/settings/models/featureFlags.ts b/ui/src/components/settings/models/featureFlags.ts
index 357ea3730..d26242fe7 100644
--- a/ui/src/components/settings/models/featureFlags.ts
+++ b/ui/src/components/settings/models/featureFlags.ts
@@ -1,21 +1,17 @@
-// Model Hub UI — feature flags.
-//
-// All feature lanes are merged (L2 REST API #963, L3 injection #976, L4 page
-// #966, L5 menus #977) and the integration seams are closed (agent-supply v1.2
-// builtin_models / standard_vendors, so the UI no longer hardcodes any menu or
-// vendor list). The documented flip sequence below is therefore complete — the
-// surfaces ship ON against the real endpoints (integration LI, 2026-07-24):
-// 1. L2 API merged → MODELS_API_MODE = 'live' ✓ (done here)
-// 2. L2/L3 both merged → MODEL_HUB_NAV_ENABLED = true ✓ (done here)
-// 3. L5 menus merged → MODEL_MENUS_ENABLED = true ✓ (done here)
-// subscription_hub_experimental stays OFF — it is a consent-gated behavior, not
-// a UI-readiness flag. Live end-to-end verification is the post-merge Incus pass.
+// Model Hub UI capability projection. Availability is owned by the backend and
+// arrives in GET /api/config; the browser has no independent release switch.
-/**
- * Advertises the 设置 → 模型 entry in the admin sidebar. ON now that the surface
- * is backed by the real endpoints; the route is also reachable by direct URL.
- */
-export const MODEL_HUB_NAV_ENABLED = true;
+export const modelHubEnabledFromConfig = (config: unknown): boolean => {
+ if (!config || typeof config !== 'object') return false;
+ const capabilities = (config as { capabilities?: unknown }).capabilities;
+ if (!capabilities || typeof capabilities !== 'object') return false;
+ const modelHub = (capabilities as { model_hub?: unknown }).model_hub;
+ return Boolean(
+ modelHub &&
+ typeof modelHub === 'object' &&
+ (modelHub as { enabled?: unknown }).enabled === true,
+ );
+};
/**
* 'mock' serves typed fixtures from `mockData.ts`; 'live' calls the real
diff --git a/ui/src/components/settings/models/useModelHubCapability.ts b/ui/src/components/settings/models/useModelHubCapability.ts
new file mode 100644
index 000000000..7182ff35a
--- /dev/null
+++ b/ui/src/components/settings/models/useModelHubCapability.ts
@@ -0,0 +1,25 @@
+import * as React from 'react';
+
+import { useApi } from '@/context/ApiContext';
+import { modelHubEnabledFromConfig } from './featureFlags';
+
+export const useModelHubCapability = (): boolean | null => {
+ const { getConfig } = useApi();
+ const [enabled, setEnabled] = React.useState<boolean | null>(null);
+
+ React.useEffect(() => {
+ let cancelled = false;
+ getConfig()
+ .then((config) => {
+ if (!cancelled) setEnabled(modelHubEnabledFromConfig(config));
+ })
+ .catch(() => {
+ if (!cancelled) setEnabled(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [getConfig]);
+
+ return enabled;
+};
diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
index a7e5b7874..f651125d0 100644
--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
@@ -21,7 +21,7 @@ import { BackendOAuthPanel } from '../BackendOAuthPanel';
import { BackendTestPanel } from '../BackendTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
-import { MODEL_HUB_NAV_ENABLED } from '../models/featureFlags';
+import { useModelHubCapability } from '../models/useModelHubCapability';
import { SegmentedRadio } from '../shared/SegmentedRadio';
import { useBackendRuntime } from '../shared/useBackendRuntime';
import { useOAuthFlowLock } from '../shared/useOAuthFlowLock';
@@ -37,6 +37,7 @@ export const ClaudeProviderConfig: React.FC<{
}> = ({ hideEnableToggle } = {}) => {
const { t } = useTranslation();
const api = useApi();
+ const modelHubEnabled = useModelHubCapability();
const { showToast } = useToast();
// Runtime state — CLI detection + lifecycle. Shared with Codex /
@@ -228,7 +229,7 @@ export const ClaudeProviderConfig: React.FC<{
/>
{/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
- {MODEL_HUB_NAV_ENABLED && <BackendSupplyModeCard backend="claude" />}
+ {modelHubEnabled === true && <BackendSupplyModeCard backend="claude" />}
{authLoading ? (
<div className="text-sm text-muted">{t('common.loading')}</div>
diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsx
index 739448be1..6e1d3981e 100644
--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx
+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx
@@ -14,7 +14,7 @@ import { BackendOAuthPanel } from '../BackendOAuthPanel';
import { BackendTestPanel } from '../BackendTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
-import { MODEL_HUB_NAV_ENABLED } from '../models/featureFlags';
+import { useModelHubCapability } from '../models/useModelHubCapability';
import { SegmentedRadio } from '../shared/SegmentedRadio';
import { surfaceBackendNotices } from '../shared/surfaceBackendNotices';
import { useBackendRuntime } from '../shared/useBackendRuntime';
@@ -28,6 +28,7 @@ export const CodexProviderConfig: React.FC<{
}> = ({ hideEnableToggle } = {}) => {
const { t } = useTranslation();
const api = useApi();
+ const modelHubEnabled = useModelHubCapability();
const { showToast } = useToast();
// Runtime state — shared across all backend pages via the hook. Adds
@@ -226,7 +227,7 @@ export const CodexProviderConfig: React.FC<{
/>
{/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
- {MODEL_HUB_NAV_ENABLED && <BackendSupplyModeCard backend="codex" />}
+ {modelHubEnabled === true && <BackendSupplyModeCard backend="codex" />}
<Card>
<CardContent className="flex flex-col gap-5 p-6">
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index b0299bae7..ffeb42fec 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -33,7 +33,7 @@ import { BackendOAuthPanel } from '../BackendOAuthPanel';
import { OpencodeProviderTestPanel } from '../OpencodeProviderTestPanel';
import { BackendRuntimeCard } from '../shared/BackendRuntimeCard';
import { BackendSupplyModeCard } from '../models/BackendSupplyModeCard';
-import { MODEL_HUB_NAV_ENABLED } from '../models/featureFlags';
+import { useModelHubCapability } from '../models/useModelHubCapability';
import { OpencodePermissionSetup } from '../shared/OpencodePermissionSetup';
import { useBackendRuntime } from '../shared/useBackendRuntime';
import { useOpencodePermission } from '../shared/useOpencodePermission';
@@ -165,6 +165,7 @@ export const OpencodeProviderConfig: React.FC<{
}> = ({ hideEnableToggle } = {}) => {
const { t } = useTranslation();
const api = useApi();
+ const modelHubEnabled = useModelHubCapability();
const { showToast } = useToast();
// Runtime state — shared with Claude / Codex pages via the hook.
@@ -798,7 +799,7 @@ export const OpencodeProviderConfig: React.FC<{
/>
{/* Model Hub 供给方式 card (L5); flag-gated until the hub feature is advertised. */}
- {MODEL_HUB_NAV_ENABLED && <BackendSupplyModeCard backend="opencode" />}
+ {modelHubEnabled === true && <BackendSupplyModeCard backend="opencode" />}
{/* Card 2 — provider catalog. */}
<Card>
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index 0910522f6..73292dd34 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -20,6 +20,7 @@ import { ToggleSwitch } from '../settings/SettingsPrimitives';
import { BackendProviderConfig } from '../settings/providers/BackendProviderConfig';
import { OpencodePermissionSetup } from '../settings/shared/OpencodePermissionSetup';
import { MigrationBanner } from '../settings/models/MigrationBanner';
+import { useModelHubCapability } from '../settings/models/useModelHubCapability';
import type { BackendId as RuntimeBackendId } from '../settings/shared/useBackendRuntime';
import { useOpencodePermission } from '../settings/shared/useOpencodePermission';
import { Button } from '../ui/button';
@@ -72,6 +73,7 @@ const normalizeAgents = (source: any): Record<string, AgentState> => {
export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, onBack, isPage = false, onSave }) => {
const { t } = useTranslation();
const api = useApi();
+ const modelHubEnabled = useModelHubCapability();
const [agents, setAgents] = useState<Record<string, AgentState>>(normalizeAgents(data));
const permission = useOpencodePermission({ autoFetchStatus: true });
const [installingAgents, setInstallingAgents] = useState<Record<string, boolean>>({});
@@ -255,7 +257,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
native CLI configs into the Hub. Wizard-only — the Settings → Backends
page already surfaces this via BackendSupplyModeCard. Self-hides when
nothing is importable or the hub isn't reachable yet. */}
- {!isPage && <MigrationBanner />}
+ {!isPage && modelHubEnabled === true && <MigrationBanner />}
<div className="flex flex-col gap-3 rounded-xl border border-border bg-background px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
diff --git a/vibe/runtime.py b/vibe/runtime.py
index f8bc3398c..344e60258 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -137,7 +137,7 @@ def default_config():
claude=ClaudeConfig(enabled=True, cli_path="claude"),
codex=CodexConfig(enabled=False, cli_path="codex"),
),
- model_hub=ModelHubConfig.fresh(),
+ model_hub=ModelHubConfig(),
)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 11500b982..ce30ac410 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2080,6 +2080,17 @@ def start_api_request_timer():
return None
+def reject_disabled_model_hub_api():
+ """Keep the unreleased Model Hub REST surface dormant by default."""
+
+ from config.v2_config import is_model_hub_enabled
+
+ if request.path.startswith("/api/models/") and not is_model_hub_enabled():
+ return jsonify({"ok": False, "contract_version": 1, "error": "feature_disabled"}), 404
+ return None
+
+
@app.before_request
def enforce_remote_access_cookie():
config = _load_remote_access_config()
@@ -3007,6 +3018,7 @@ def doctor_get():
@app.route("/api/config", methods=["GET"])
def config_get():
from vibe import api
+ from config.v2_config import is_model_hub_enabled
from core.services import settings as settings_service
# On a truly fresh install no config file exists yet, but the setup
@@ -3016,7 +3028,9 @@ def config_get():
# default is never mistaken for a completed setup. The write side
# (``save_config``) already creates the file on the first real save.
config = settings_service.load_config_or_default()
- return jsonify(api.config_to_payload(config))
+ payload = api.config_to_payload(config)
+ payload["capabilities"] = {"model_hub": {"enabled": is_model_hub_enabled()}}
+ return jsonify(payload)
_MODEL_HUB_SERVICE = None