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(model-hub): persist gateway enablement

cyhde16deb1bf18
diff --git a/config/v2_config.py b/config/v2_config.py
index 859d81542..e75ac9800 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -3269,6 +3269,7 @@ class ModelHubAgentSupplyConfig:
@dataclass
class ModelHubConfig:
+ enabled: bool = False
sources: list[ModelHubSourceConfig] = field(default_factory=list)
agents: dict[str, ModelHubAgentSupplyConfig] = field(
default_factory=lambda: {
@@ -3314,8 +3315,11 @@ class ModelHubConfig:
def from_payload(cls, payload: dict, *, repairing: bool = False) -> "ModelHubConfig":
if not isinstance(payload, dict):
raise ValueError("Config 'model_hub' must be an object")
- if set(payload) - {"sources", "agents"}:
+ if set(payload) - {"enabled", "sources", "agents"}:
raise ValueError("Config 'model_hub' contains unknown fields")
+ enabled = payload.get("enabled", False)
+ if not isinstance(enabled, bool):
+ raise ValueError("Config 'model_hub.enabled' must be a boolean")
sources_payload = payload.get("sources") or []
agents_payload = payload.get("agents") or {}
if not isinstance(sources_payload, list):
@@ -3391,6 +3395,7 @@ class ModelHubConfig:
f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'"
)
config = cls(
+ enabled=enabled,
sources=sources,
agents=agents,
)
@@ -3428,6 +3433,7 @@ class ModelHubConfig:
def to_payload(self) -> dict:
return {
+ "enabled": self.enabled,
"sources": [source.to_payload() for source in self.sources],
"agents": {backend: self.agents[backend].to_payload() for backend in MODEL_HUB_BACKENDS},
}
diff --git a/core/controller.py b/core/controller.py
index 56e27cc76..6ba5e8095 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1701,14 +1701,14 @@ class Controller:
"""Restore durable execution owners before any producer can admit work."""
model_hub_service = getattr(self, "model_hub_service", None)
- reconcile_model_hub = getattr(
+ recover_model_hub = getattr(
model_hub_service,
- "reconcile_runtime_installation",
+ "recover_runtime_intent",
None,
)
- if callable(reconcile_model_hub):
+ if callable(recover_model_hub):
try:
- await reconcile_model_hub()
+ await recover_model_hub()
except Exception:
logger.exception(
"Model Hub runtime recovery failed; continuing without it"
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 59daa972e..dc1f859f6 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -534,13 +534,14 @@ def _oauth_payload(
return payload
-def _runtime_payload(status: EngineStatus) -> dict:
+def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
# Import lazily to avoid the runtime adapter's dependency back on this service module.
from vibe.model_hub_runtime.installer import EngineRuntimeManager
manager = EngineRuntimeManager()
return {
"contract_version": 6,
+ "enabled": enabled,
"host_platform": status.host_platform or manager.host_platform(),
"manifest": manager.contract_manifest(),
"status": {
@@ -628,6 +629,7 @@ class ModelHubService:
self._engine_preparation_failed = False
self._runtime_install_reconcile_lock = asyncio.Lock()
self._runtime_install_reconciled = False
+ self._runtime_lifecycle_lock = asyncio.Lock()
@staticmethod
def _source(config: ModelHubConfig, source_id: str) -> ModelHubSourceConfig:
@@ -973,8 +975,19 @@ class ModelHubService:
self._runtime_install_reconciled = True
return recovered if isinstance(recovered, EngineStatus) else None
+ async def recover_runtime_intent(self) -> None:
+ """Restore the runtime only when the user left it enabled."""
+
+ async with self._runtime_lifecycle_lock:
+ await self.reconcile_runtime_installation()
+ if not self.store.load().enabled:
+ return
+ await self._prepare_engine_for_demand()
+ await self._engine_call(self.adapter.start())
+
async def stop(self) -> None:
- await self.adapter.stop()
+ async with self._runtime_lifecycle_lock:
+ await self.adapter.stop()
@staticmethod
def _credential_was_already_revoked(error: Exception) -> bool:
@@ -4580,48 +4593,66 @@ class ModelHubService:
status = await self.reconcile_runtime_installation()
if status is None:
status = await self._engine_call(self.adapter.status())
- return _runtime_payload(self._runtime_status_after_demand(status))
+ return _runtime_payload(
+ self._runtime_status_after_demand(status),
+ enabled=self.store.load().enabled,
+ )
async def runtime_install(self) -> dict:
- status = await self.reconcile_runtime_installation()
- if status is None:
- status = await self._engine_call(self.adapter.status())
- status = self._runtime_status_after_demand(status)
- if status.health is not EngineHealth.NOT_INSTALLED:
- return _runtime_payload(status)
- install = getattr(self.adapter, "install", None)
- if not callable(install):
- raise ModelHubError("engine_down", status=503)
- return _runtime_payload(await self._engine_call(install()))
+ async with self._runtime_lifecycle_lock:
+ status = await self.reconcile_runtime_installation()
+ if status is None:
+ status = await self._engine_call(self.adapter.status())
+ status = self._runtime_status_after_demand(status)
+ enabled = self.store.load().enabled
+ if status.health is not EngineHealth.NOT_INSTALLED:
+ return _runtime_payload(status, enabled=enabled)
+ install = getattr(self.adapter, "install", None)
+ if not callable(install):
+ raise ModelHubError("engine_down", status=503)
+ return _runtime_payload(
+ await self._engine_call(install()),
+ enabled=enabled,
+ )
async def runtime_start(self) -> dict:
- await self.reconcile_runtime_installation()
- await self._prepare_engine_for_demand()
- status = await self._engine_call(self.adapter.start())
- return _runtime_payload(status)
+ async with self._runtime_lifecycle_lock:
+ await self.reconcile_runtime_installation()
+ async with self._mutation_lock:
+ previous = self.store.load()
+ updated = self._clone_config(previous)
+ updated.enabled = True
+ self._save_projection_neutral(previous, updated)
+ await self._prepare_engine_for_demand()
+ status = await self._engine_call(self.adapter.start())
+ return _runtime_payload(status, enabled=True)
async def runtime_stop(self) -> dict:
- await self.reconcile_runtime_installation()
- async with self._mutation_lock:
- config = self.store.load()
- hub_backends = sorted(
- backend
- for backend, agent in config.agents.items()
- if agent.mode == "hub"
- )
- if hub_backends:
- raise ModelHubError(
- "runtime_in_use",
- status=409,
- data={"backends": hub_backends},
+ async with self._runtime_lifecycle_lock:
+ await self.reconcile_runtime_installation()
+ async with self._mutation_lock:
+ previous = self.store.load()
+ hub_backends = sorted(
+ backend
+ for backend, agent in previous.agents.items()
+ if agent.mode == "hub"
)
- stop_runtime = getattr(self.adapter, "stop_runtime", None)
- if not callable(stop_runtime):
- raise ModelHubError("engine_down", status=503)
- status = await self._engine_call(stop_runtime())
- if status.health is EngineHealth.INSTALLING:
- raise ModelHubError("runtime_busy", status=409)
- return _runtime_payload(status)
+ if hub_backends:
+ raise ModelHubError(
+ "runtime_in_use",
+ status=409,
+ data={"backends": hub_backends},
+ )
+ stop_runtime = getattr(self.adapter, "stop_runtime", None)
+ if not callable(stop_runtime):
+ raise ModelHubError("engine_down", status=503)
+ status = await self._engine_call(stop_runtime())
+ if status.health is EngineHealth.INSTALLING:
+ raise ModelHubError("runtime_busy", status=409)
+ updated = self._clone_config(previous)
+ updated.enabled = False
+ self._save_projection_neutral(previous, updated)
+ return _runtime_payload(status, enabled=False)
def migration_scan(self) -> dict:
config = self.store.load()
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 9c0d5af19..0160ba583 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -153,7 +153,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. |
| `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. |
| `migration-scan.schema.json` | Copy-only import of existing native CLI/provider configuration; not an internal contract migration. |
-| `runtime-dependency.schema.json` | Managed local Gateway asset, lifecycle, and health. |
+| `runtime-dependency.schema.json` | Managed local Gateway asset, persisted enablement intent, lifecycle, and health. |
| `guard-refusal.schema.json` | Shared guarded-mutation refusal whose two arrays are the exact plan echoed by a confirmed retry. |
| `api.md` | Routes, envelopes, exact Source order and Route-chain writes, guards, OAuth/import results, provenance, usage, and runtime status. |
| `api-response.schema.json` | Machine-readable response contract and real-response exercise for every route in `api.md`, at exact route-table parity. |
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 0f2566d12..475796dee 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -369,7 +369,7 @@
"allOf": [
{"$ref": "model-hub/runtime-dependency.schema.json"},
{
- "required": ["contract_version", "host_platform", "manifest", "status"],
+ "required": ["contract_version", "enabled", "host_platform", "manifest", "status"],
"properties": {
"status": {
"required": ["installed_version", "verified", "listening", "health", "last_check", "error_key"]
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index cd6192910..47dfe6a6b 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -54,10 +54,10 @@ compatibility path.
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same one-time matching and placement as Add Source; original files remain byte-identical. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 6; `not_started` is installed lazy-start idleness, not an alarm. |
+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 6 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
-| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Explicitly starts the managed engine. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
-| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
+| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
+| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
The removed global route `PUT /api/models/priority` has no replacement. Backend Source
order is explicit configuration through the sources route; exact per-model order is
@@ -219,6 +219,7 @@ every other existing field and enum meaning remains unchanged.
| `Source.adopted_by` | Source read assembler | Source cards and Source detail status | Complete unique persisted-reference projection sorted by backend then menu model; clients do not derive it from `hops`. |
| `AgentSupply.cli_present` | backend CLI detector | zero-installed-backend state | Boolean installation fact only; it does not imply login or process readiness. |
| `AgentSupply.model_supply[].has_runnable_hop` | exact-chain live annotator | backend-group collapse predicate | Uses the AgentChain runnability axiom rather than inferring liveness from configured membership. `chain_length: 0` forces false; a nonzero length may carry either value. |
+| `RuntimeDependency.enabled` | explicit runtime start/stop mutation | Gateway switch and service-start recovery | Persisted user intent, independent of observed process health. Missing in older config defaults to false; an older response without the field falls back to observed health in the UI. |
| `RuntimeDependency.host_platform` | server host detector | unsupported-host runtime pill | Names the Avibe host, not the browser; exact membership in `manifest.assets[].platform` decides install support. |
| `RuntimeDependency.status.error_key` | runtime installer | install-failed runtime state | Closed persisted i18n key: `settings.models.install.fail.detail` after installation fails; null after a new attempt begins and in every non-failure state. |
| `RouteHopRef.position` | guarded mutation planner | guarded-change hop row | One-based position in the named Route before the attempted mutation. |
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
index cde81a633..7c7b90289 100644
--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -2,12 +2,16 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/runtime-dependency.schema.json",
"title": "RuntimeDependency",
- "description": "v5 managed engine dependency manifest + server-owned installation and runtime status. not_installed -> installing -> not_started is the installation path; not_started is installed lazy-start idleness, and down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.",
+ "description": "v5 managed engine dependency manifest + persisted user intent + server-owned installation and runtime status. not_installed -> installing -> not_started is the installation path; not_started is installed lazy-start idleness, and down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.",
"type": "object",
"required": ["contract_version", "manifest", "status"],
"additionalProperties": false,
"properties": {
"contract_version": { "const": 6 },
+ "enabled": {
+ "type": "boolean",
+ "description": "Persisted user intent for the managed gateway. Missing on older payloads means clients must fall back to observed health."
+ },
"host_platform": {
"type": "string",
"pattern": "^[a-z0-9]+(?:-[a-z0-9_]+)+$",
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 8ab24f31e..9d3536381 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -818,7 +818,10 @@ dead-end error string.
2026-08-11).** `host_platform` is detected on the Avibe server, never from the browser,
and installation is supported exactly when it equals one
`manifest.assets[].platform`. The install route and status reads mirror this closed
-state set; prose cannot add another runtime health value.
+state set; prose cannot add another runtime health value. `RuntimeDependency.enabled`
+is orthogonal persisted user intent: it defaults to false when absent, explicit Start
+sets it true, explicit Stop sets it false, and service startup starts the runtime only
+when it is true. A transient process loss changes health, never this switch state.
| Decision | Meaning | Entry and exit rule | `status.error_key` |
| --- | --- | --- | --- |
diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.py
index 2f401301d..97c9c6cef 100644
--- a/tests/test_controller_im_ready.py
+++ b/tests/test_controller_im_ready.py
@@ -31,7 +31,7 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:
)
controller.runtime_work_supervisor = SimpleNamespace(activate=AsyncMock())
controller.model_hub_service = SimpleNamespace(
- reconcile_runtime_installation=AsyncMock()
+ recover_runtime_intent=AsyncMock()
)
controller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))
controller.cleanup_task = None
@@ -59,7 +59,7 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:
controller.session_turns.recover_persisted_agent_run_queue.assert_awaited_once_with()
controller.scheduled_task_service.recover_processing_requests.assert_called_once_with()
controller.runtime_work_supervisor.activate.assert_awaited_once_with()
- controller.model_hub_service.reconcile_runtime_installation.assert_awaited_once_with()
+ controller.model_hub_service.recover_runtime_intent.assert_awaited_once_with()
assert controller._delivery_recovery_complete.is_set()
@@ -180,7 +180,7 @@ def test_runtime_owner_recovery_isolates_optional_model_hub_failure(
) -> None:
controller = Controller.__new__(Controller)
controller.model_hub_service = SimpleNamespace(
- reconcile_runtime_installation=AsyncMock(
+ recover_runtime_intent=AsyncMock(
side_effect=OSError("runtime directory is unwritable")
)
)
@@ -197,7 +197,7 @@ def test_runtime_owner_recovery_isolates_optional_model_hub_failure(
with caplog.at_level("ERROR"):
asyncio.run(controller._recover_runtime_owners())
- controller.model_hub_service.reconcile_runtime_installation.assert_awaited_once_with()
+ controller.model_hub_service.recover_runtime_intent.assert_awaited_once_with()
controller.session_turns.recover_durable_delivery_state.assert_awaited_once_with(
service_restart=True
)
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index e09f5bdb8..a0bf202ef 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -826,6 +826,7 @@ def test_runtime_status_observes_engine_without_starting_it(tmp_path):
assert adapter.start_calls == 0
assert adapter.status_calls == 1
+ assert runtime["enabled"] is False
assert runtime["status"]["health"] == "ok"
assert runtime["status"]["verified"] is True
@@ -847,11 +848,13 @@ def test_runtime_status_reports_packaged_engine_manifest(tmp_path):
def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):
- service, _store, adapter = _service(tmp_path)
+ service, store, adapter = _service(tmp_path)
runtime = asyncio.run(service.runtime_start())
assert adapter.start_calls == 1
+ assert store.config.enabled is True
+ assert runtime["enabled"] is True
assert runtime["contract_version"] == 6
assert runtime["status"]["health"] == "ok"
_assert_valid("runtime-dependency.schema.json", runtime)
@@ -871,16 +874,40 @@ def test_runtime_stop_requires_every_backend_to_be_direct(tmp_path):
def test_runtime_stop_returns_explicit_not_started_state(tmp_path):
service, store, adapter = _service(tmp_path)
+ store.config.enabled = True
for agent in store.config.agents.values():
agent.mode = "direct"
runtime = asyncio.run(service.runtime_stop())
assert adapter.stop_runtime_calls == 1
+ assert store.config.enabled is False
+ assert runtime["enabled"] is False
assert runtime["status"]["health"] == "not_started"
_assert_valid("runtime-dependency.schema.json", runtime)
+def test_runtime_recovery_starts_only_for_persisted_user_intent(tmp_path):
+ service, store, adapter = _service(tmp_path)
+
+ asyncio.run(service.recover_runtime_intent())
+
+ assert adapter.start_calls == 0
+
+ store.config.enabled = True
+ restarted = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "restarted-events.json"),
+ oauth_flows=OAuthFlowRegistry(tmp_path / "restarted-oauth-flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "restarted-revocations.json"),
+ )
+
+ asyncio.run(restarted.recover_runtime_intent())
+
+ assert adapter.start_calls == 1
+
+
def test_runtime_start_syncs_sources_before_starting_once(tmp_path):
class OrderedAdapter(FakeAdapter):
def __init__(self):
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 22da27772..c50b86dea 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -1457,7 +1457,8 @@ def test_config_reload_migrates_v3_model_hub_shape_and_persists_backup(monkeypat
ModelHubConfig().agents["claude"].routes
)
persisted = json.loads(config_path.read_text(encoding="utf-8"))
- assert set(persisted["model_hub"]) == {"sources", "agents"}
+ assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}
+ assert persisted["model_hub"]["enabled"] is False
assert persisted["migration_sentinel"] == {"keep": True}
backups = list(config_path.parent.glob("config.json.bak-model-hub-migration-*"))
assert backups
@@ -2180,7 +2181,8 @@ def test_config_reload_does_not_overwrite_config_changed_during_migration(
assert loaded.show_duration is True
persisted = json.loads(config_path.read_text(encoding="utf-8"))
assert persisted["show_duration"] is True
- assert set(persisted["model_hub"]) == {"sources", "agents"}
+ assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}
+ assert persisted["model_hub"]["enabled"] is False
assert loaded.load_warnings and "changed during load" in loaded.load_warnings[0]
@@ -2212,7 +2214,8 @@ def test_config_reload_does_not_overwrite_config_changed_before_replace(
assert loaded.show_duration is True
persisted = json.loads(config_path.read_text(encoding="utf-8"))
assert persisted["show_duration"] is True
- assert set(persisted["model_hub"]) == {"sources", "agents"}
+ assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}
+ assert persisted["model_hub"]["enabled"] is False
assert loaded.load_warnings and "before replacement" in " ".join(loaded.load_warnings)
backups = list(config_path.parent.glob("config.json.bak-model-hub-migration-*"))
assert backups and any(backup.read_text(encoding="utf-8") == original for backup in backups)
@@ -2593,6 +2596,25 @@ def test_final_config_rejects_retired_global_priority_key():
ModelHubConfig.from_payload(payload)
+def test_model_hub_enabled_defaults_off_for_older_configs():
+ payload = ModelHubConfig().to_payload()
+ payload.pop("enabled")
+
+ loaded = ModelHubConfig.from_payload(payload)
+
+ assert loaded.enabled is False
+ assert loaded.to_payload()["enabled"] is False
+
+
[email protected]("value", [None, 0, 1, "false"])
+def test_model_hub_enabled_requires_a_boolean(value):
+ payload = ModelHubConfig().to_payload()
+ payload["enabled"] = value
+
+ with pytest.raises(ValueError, match="model_hub.enabled.*boolean"):
+ ModelHubConfig.from_payload(payload)
+
+
def test_agent_source_orders_validate_existence_eligibility_and_uniqueness():
source = {
**_schema("source.schema.json")["examples"][0],
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index df351ac73..b7f38ca6d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -274,6 +274,67 @@ describe('SettingsModelsPage surface branches', () => {
expect(await screen.findAllByRole('tab')).toHaveLength(3);
});
+ it('keeps the persisted gateway switch on while its process is unavailable', async () => {
+ const unavailable = {
+ ...runtime,
+ enabled: true,
+ status: { ...runtime.status, health: 'down' as const },
+ };
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([
+ directAgent('claude'),
+ directAgent('codex'),
+ directAgent('opencode'),
+ ]);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(unavailable);
+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SettingsModelsPage />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ const toggle = await screen.findByRole('switch', { name: /Turn model gateway off|关闭模型网关/i });
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ expect(await screen.findByText(/^Model gateway is enabled but unavailable$|^模型网关已开启,但当前不可用$/i)).toBeTruthy();
+ expect(screen.queryAllByRole('tab')).toHaveLength(0);
+ });
+
+ it('still allows persisted enablement to be turned off on an unsupported host', async () => {
+ const unsupported = {
+ ...runtime,
+ enabled: true,
+ manifest: { ...runtime.manifest, resolution: 'unsupported' as const },
+ status: { ...runtime.status, health: 'not_installed' as const },
+ };
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValue([]);
+ vi.spyOn(modelsApi, 'listAgents').mockResolvedValue([
+ directAgent('claude'),
+ directAgent('codex'),
+ directAgent('opencode'),
+ ]);
+ vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(unsupported);
+ vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
+ const stopped = { ...unsupported, enabled: false };
+ const stop = vi.spyOn(modelsApi, 'stopRuntime').mockResolvedValue(stopped);
+
+ render(
+ <ToastProvider>
+ <I18nextProvider i18n={i18n}>
+ <SettingsModelsPage />
+ </I18nextProvider>
+ </ToastProvider>,
+ );
+
+ const toggle = await screen.findByRole('switch', { name: /Turn model gateway off|关闭模型网关/i });
+ expect((toggle as HTMLButtonElement).disabled).toBe(false);
+ await userEvent.click(toggle);
+ await waitFor(() => expect(stop).toHaveBeenCalledOnce());
+ });
+
it('stops an unused running gateway and hides its retained configuration', async () => {
renderPage([retainedSource]);
const stopped = { ...runtime, status: { ...runtime.status, health: 'not_started' as const } };
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index 1907bf145..4d956212b 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -194,10 +194,12 @@ export const RuntimePill: React.FC<{
? 'starting'
: health === 'installing'
? 'starting'
+ : runtime.enabled && !runtimeIsRunning(runtime)
+ ? 'unavailable'
: health === 'ok'
? allDirect ? 'allDirect' : 'running'
- : health === 'degraded'
- ? 'degraded'
+ : health === 'degraded'
+ ? 'degraded'
: health === 'down'
? 'stopped'
: health === 'not_started'
@@ -229,6 +231,8 @@ const RuntimeClosedState: React.FC<{
? 'unread'
: health === 'installing'
? 'installing'
+ : runtime?.enabled && health !== null && !runtimeIsRunning(runtime)
+ ? 'enabledDown'
: health === 'not_installed' && runtime?.manifest.resolution === 'unsupported'
? 'unsupported'
: health === 'not_installed'
@@ -443,10 +447,13 @@ export const SettingsModelsPage: React.FC = () => {
degraded: (staleData) => staleData,
});
const runtimeHealth = retainedRuntime?.status.health ?? null;
- const runtimeSurfaceEnabled = retainedRuntime !== null
+ const runtimeRunning = retainedRuntime !== null
&& runtimeIsRunning(retainedRuntime)
&& runtimeRead.kind !== 'unread';
- const runtimeConfigurationVisible = runtimeSurfaceEnabled && !stoppingRuntime;
+ const runtimeEnabled = retainedRuntime !== null
+ && (retainedRuntime.enabled ?? runtimeIsRunning(retainedRuntime))
+ && runtimeRead.kind !== 'unread';
+ const runtimeConfigurationVisible = runtimeRunning && !stoppingRuntime;
React.useEffect(() => {
const runtimeCanRecover = runtimeRead.kind === 'unread'
|| (runtimeRead.kind === 'degraded' && runtimeRead.cause === 'read_failed')
@@ -845,8 +852,9 @@ export const SettingsModelsPage: React.FC = () => {
const directEmpty = modelsSurfaceKindFromReads(supplyRead, sourcesRead) === 'direct_empty';
const installedAgents = agents.filter((agent) => agent.cli_present);
const hubBackends = agents.filter((agent) => agent.mode === 'hub').map((agent) => agent.backend);
- const stopBlocked = runtimeSurfaceEnabled && (supplyRead.kind !== 'ready' || hubBackends.length > 0);
- const runtimeSwitchUnsupported = runtimeHealth === 'not_installed'
+ const stopBlocked = runtimeEnabled && (supplyRead.kind !== 'ready' || hubBackends.length > 0);
+ const runtimeSwitchUnsupported = !runtimeEnabled
+ && runtimeHealth === 'not_installed'
&& retainedRuntime?.manifest.resolution === 'unsupported';
const runtimeSwitchDisabled = startingRuntime
|| stoppingRuntime
@@ -858,12 +866,12 @@ export const SettingsModelsPage: React.FC = () => {
? supplyRead.kind === 'ready'
? t('settings.models.shell.toggle.stopBlocked', { names: hubBackends.join(', ') })
: t('settings.models.shell.toggle.stopUnavailable')
- : runtimeSurfaceEnabled
+ : runtimeEnabled
? t('settings.models.shell.toggle.turnOff')
: t('settings.models.shell.toggle.turnOn');
const toggleRuntime = () => {
if (runtimeSwitchDisabled) return;
- if (runtimeSurfaceEnabled) {
+ if (runtimeEnabled) {
void stopRuntime();
} else if (runtimeHealth === 'not_installed') {
setInstallOpen(true);
@@ -1144,7 +1152,7 @@ export const SettingsModelsPage: React.FC = () => {
{runtimeConfigurationVisible && !directEmpty && <TakeoverPill count={takeoverCount} />}
<span title={runtimeSwitchLabel}>
<ToggleSwitch
- enabled={runtimeSurfaceEnabled}
+ enabled={runtimeEnabled}
disabled={runtimeSwitchDisabled}
label={runtimeSwitchLabel}
onClick={toggleRuntime}
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index a0e071b71..6b5e4054e 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -502,6 +502,8 @@ export type RuntimeManifest = {
export type RuntimeDependency = {
contract_version: typeof CONTRACT_VERSION;
+ /** Persisted user intent. Older runtime payloads omit it. */
+ enabled?: boolean;
/** Server host platform, never the browser platform. */
host_platform?: string;
manifest: RuntimeManifest;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 37ab0dbbf..e6e02e13d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -667,6 +667,7 @@
"title": "Models",
"running": "Gateway running",
"stopped": "Gateway off",
+ "unavailable": "Gateway enabled, currently unavailable",
"degraded": "Gateway running degraded",
"unread": "Gateway status unavailable",
"notStarted": "Gateway off",
@@ -691,6 +692,10 @@
"title": "Model gateway is off",
"body": "The previous start did not become ready. Turn it on to try again."
},
+ "enabledDown": {
+ "title": "Model gateway is enabled but unavailable",
+ "body": "The enabled setting is saved. Turn it off and back on to retry now."
+ },
"notInstalled": {
"title": "Model gateway is not installed",
"body": "Turn it on to install the managed gateway component."
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index d17296768..6fb052182 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -667,6 +667,7 @@
"title": "模型",
"running": "网关运行中",
"stopped": "网关已关闭",
+ "unavailable": "网关已开启,当前不可用",
"degraded": "网关降级运行",
"unread": "网关状态未读到",
"notStarted": "网关已关闭",
@@ -691,6 +692,10 @@
"title": "模型网关已关闭",
"body": "上一次启动没有就绪。开启网关即可重试。"
},
+ "enabledDown": {
+ "title": "模型网关已开启,但当前不可用",
+ "body": "开启状态已经保存。关闭后重新开启即可立即重试。"
+ },
"notInstalled": {
"title": "模型网关尚未安装",
"body": "开启后会安装由 Avibe 管理的网关组件。"