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): add managed runtime install route (#1462)
Call White5822a49ed894
diff --git a/core/controller.py b/core/controller.pyindex 5ac21038a..1cfc7fb6f 100644--- a/core/controller.py+++ b/core/controller.py@@ -1501,6 +1501,20 @@ class Controller:async def _recover_runtime_owners(self) -> None:"""Restore durable execution owners before any producer can admit work."""+ model_hub_service = getattr(self, "model_hub_service", None)+ reconcile_model_hub = getattr(+ model_hub_service,+ "reconcile_runtime_installation",+ None,+ )+ if callable(reconcile_model_hub):+ try:+ await reconcile_model_hub()+ except Exception:+ logger.exception(+ "Model Hub runtime recovery failed; continuing without it"+ )+recover_deliveries = getattr(self.session_turns,"recover_durable_delivery_state",@@ -2690,7 +2704,11 @@ class Controller:await drain_activity()service_stops: list[asyncio.Task[None]] = []- for service_name in ("scheduled_task_service", "watch_service"):+ for service_name in (+ "model_hub_service",+ "scheduled_task_service",+ "watch_service",+ ):service = getattr(self, service_name, None)stop = getattr(service, "stop", None)if callable(stop):diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 3281a7d9b..ed26a7ada 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -33,6 +33,7 @@ class EngineHealth(str, Enum):DOWN = "down"NOT_STARTED = "not_started"NOT_INSTALLED = "not_installed"+ INSTALLING = "installing"@dataclass(frozen=True)@@ -43,6 +44,12 @@ class EngineStatus:listen_host: str # always "127.0.0.1"listen_port: int | Nonelast_check_iso: str | None+ host_platform: str | None = None+ error_key: str | None = None+++class RuntimePlatformUnsupportedError(RuntimeError):+ """The pinned managed runtime has no asset for the server host."""@dataclass(frozen=True)@@ -323,6 +330,10 @@ class InvokeHandle(Protocol):class EngineAdapter(Protocol):# --- lifecycle -------------------------------------------------------+ async def install(self) -> EngineStatus: ...++ async def recover_installation(self) -> EngineStatus: ...+async def ensure_installed(self) -> EngineStatus: ...async def start(self) -> EngineStatus: ...diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 79b88ea1f..b09b34d39 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -116,6 +116,8 @@ async def dispatch_model_hub_rpc(return await service.migration_apply(payload.get("item_ids"))if operation == "runtime_status":return await service.runtime_status()+ if operation == "runtime_install":+ return await service.runtime_install()if operation == "runtime_start":return await service.runtime_start()raise ModelHubError("source_not_found", status=404)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex c676928b9..baef6f1c8 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -48,6 +48,7 @@ from .adapter import (RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,+ RuntimePlatformUnsupportedError,ObservationDiscovery,ObservationOutcome,SOURCE_PROTOCOLS,@@ -196,6 +197,12 @@ class V2ModelHubConfigStore:class UnavailableEngineAdapter:"""Explicit fail-closed adapter for isolated callers and tests."""+ async def install(self) -> EngineStatus:+ return await self.status()++ async def recover_installation(self) -> EngineStatus:+ return await self.status()+async def ensure_installed(self) -> EngineStatus:return await self.status()@@ -528,9 +535,11 @@ def _runtime_payload(status: EngineStatus) -> 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": 5,- "manifest": EngineRuntimeManager().contract_manifest(),+ "host_platform": status.host_platform or manager.host_platform(),+ "manifest": manager.contract_manifest(),"status": {"installed_version": status.installed_version,"verified": status.verified,@@ -541,6 +550,11 @@ def _runtime_payload(status: EngineStatus) -> dict:),"health": status.health.value,"last_check": status.last_check_iso,+ "error_key": (+ status.error_key+ if status.health is EngineHealth.NOT_INSTALLED+ else None+ ),},}@@ -599,6 +613,8 @@ class ModelHubService:self._latest_source_attempt_generation: dict[str, int] = {}self._engine_synced = Falseself._engine_preparation_failed = False+ self._runtime_install_reconcile_lock = asyncio.Lock()+ self._runtime_install_reconciled = False@staticmethoddef _source(config: ModelHubConfig, source_id: str) -> ModelHubSourceConfig:@@ -664,6 +680,8 @@ class ModelHubService:raise ModelHubError("mode_switch_blocked", status=409) from Noneexcept ModelDiscoveryError:raise ModelHubError("discovery_failed", status=502) from None+ except RuntimePlatformUnsupportedError:+ raise ModelHubError("runtime_platform_unsupported", status=422) from Noneexcept EngineUnavailableError:raise ModelHubError("engine_down", status=503) from Noneexcept NativeOAuthUnavailableError:@@ -882,6 +900,22 @@ class ModelHubService:return replace(status, health=EngineHealth.DOWN)return status+ async def reconcile_runtime_installation(self) -> EngineStatus | None:+ if self._runtime_install_reconciled:+ return None+ async with self._runtime_install_reconcile_lock:+ if self._runtime_install_reconciled:+ return None+ recover = getattr(self.adapter, "recover_installation", None)+ recovered = None+ if callable(recover):+ recovered = await self._engine_call(recover())+ self._runtime_install_reconciled = True+ return recovered if isinstance(recovered, EngineStatus) else None++ async def stop(self) -> None:+ await self.adapter.stop()+@staticmethoddef _credential_was_already_revoked(error: Exception) -> bool:# The frozen adapter surface has no typed not-found result. Match the@@ -4269,10 +4303,25 @@ class ModelHubService:raise ModelHubError("engine_down", status=503) from Noneasync def runtime_status(self) -> dict:- status = await self._engine_call(self.adapter.status())+ 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))+ 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 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)diff --git a/core/managed_runtime.py b/core/managed_runtime.pyindex 923d6d352..255e6c268 100644--- a/core/managed_runtime.py+++ b/core/managed_runtime.py@@ -15,6 +15,7 @@ import tempfileimport threadingimport urllib.parseimport urllib.request+from collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom pathlib import Path, PurePosixPath, PureWindowsPathfrom sysconfig import get_platform@@ -36,6 +37,33 @@ logger = logging.getLogger(__name__)_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")_INSTALL_LOCKS: dict[str, threading.Lock] = {}_INSTALL_LOCKS_GUARD = threading.Lock()+_ENSURE_FAILURE_SUFFIXES = frozenset(+ {+ "archive_checksum_mismatch",+ "archive_download_failed",+ "archive_size_mismatch",+ "archive_unavailable",+ "archive_unavailable_offline",+ "archive_url_unsupported",+ "binary_checksum_mismatch",+ "binary_not_runnable",+ "binary_prepare_failed",+ "install_already_running",+ "install_claim_failed",+ "install_failed",+ "install_lock_failed",+ "install_missing_binary",+ "install_target_changed",+ "manifest_download_failed",+ "manifest_invalid",+ "manifest_missing",+ "manifest_unavailable",+ "manifest_unavailable_offline",+ "manifest_url_unsupported",+ "platform_unsupported",+ "pointer_write_failed",+ }+)@dataclass(frozen=True)@@ -99,7 +127,13 @@ class ManagedRuntimeManager:self._install_lock = install_lock_for(spec.runtime_id)self._install_file_lock_path = self.runtime_dir / ".install.lock"- def ensure(self, *, force: bool = False) -> dict[str, Any]:+ def ensure(+ self,+ *,+ force: bool = False,+ expected_target: Mapping[str, str] | None = None,+ on_resolved: Callable[[dict[str, str]], None] | None = None,+ ) -> dict[str, Any]:try:file_lock = self._acquire_mutation_lock()except Exception as exc: # noqa: BLE001@@ -123,6 +157,27 @@ class ManagedRuntimeManager:self._install_reason or self._reason("platform_unsupported"),manifest=manifest,)+ target = self._install_target_identity(manifest, archive)+ if expected_target is not None and dict(expected_target) != target:+ return self._failure(+ self._reason("install_target_changed"),+ manifest=manifest,+ archive=archive,+ )+ if on_resolved is not None:+ try:+ on_resolved(target)+ except Exception as exc: # noqa: BLE001+ logger.exception(+ "Failed to persist managed %s runtime install claim",+ self.spec.runtime_id,+ )+ return self._failure(+ self._reason("install_claim_failed"),+ manifest=manifest,+ archive=archive,+ message=str(exc),+ )install_dir = self._manifest_install_dir(manifest, archive)existing = self._verified_manifest_binary(install_dir, manifest, archive)@@ -563,6 +618,19 @@ class ManagedRuntimeManager:/ fingerprint)+ @staticmethod+ def _install_target_identity(+ manifest: ManagedRuntimeManifest,+ archive: ManagedRuntimeArchive,+ ) -> dict[str, str]:+ return {+ "manifest_sha256": manifest.digest,+ "runtime_version": manifest.runtime_version,+ "platform": archive.platform,+ "archive_sha256": archive.sha256,+ "binary_sha256": archive.binary_sha256,+ }+def _verified_manifest_binary(self,install_dir: Path,@@ -720,6 +788,7 @@ class ManagedRuntimeManager:"version": manifest.runtime_version,"platform": archive.platform,"install_dir": str(install_dir),+ "target": self._install_target_identity(manifest, archive),}def _failure(@@ -753,6 +822,11 @@ class ManagedRuntimeManager:def _reason(self, suffix: str) -> str:return f"{self.spec.runtime_id}_{suffix}"+ def _base_install_failure_reasons(self) -> frozenset[str]:+ """Return failures produced by the shared ``ensure`` implementation."""++ return frozenset(self._reason(suffix) for suffix in _ENSURE_FAILURE_SUFFIXES)+def _acquire_mutation_lock(self) -> MigrationFileLock | None:if not self._install_lock.acquire(blocking=False):return Nonediff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 3281a7d9b..ed26a7ada 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -33,6 +33,7 @@ class EngineHealth(str, Enum):DOWN = "down"NOT_STARTED = "not_started"NOT_INSTALLED = "not_installed"+ INSTALLING = "installing"@dataclass(frozen=True)@@ -43,6 +44,12 @@ class EngineStatus:listen_host: str # always "127.0.0.1"listen_port: int | Nonelast_check_iso: str | None+ host_platform: str | None = None+ error_key: str | None = None+++class RuntimePlatformUnsupportedError(RuntimeError):+ """The pinned managed runtime has no asset for the server host."""@dataclass(frozen=True)@@ -323,6 +330,10 @@ class InvokeHandle(Protocol):class EngineAdapter(Protocol):# --- lifecycle -------------------------------------------------------+ async def install(self) -> EngineStatus: ...++ async def recover_installation(self) -> EngineStatus: ...+async def ensure_installed(self) -> EngineStatus: ...async def start(self) -> EngineStatus: ...diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex a8672714d..e4950989c 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -984,11 +984,14 @@ when emitted.Every runtime response carries `host_platform`, and every status carries `error_key`.The server detects the Avibe host; clients never substitute the browser platform.-Installation is supported exactly when one `manifest.assets[].platform` equals-`host_platform`. An unsupported host leaves `health: "not_installed"`; the install-route fails before download with HTTP 422 and-`error: "runtime_platform_unsupported"`; the next status read remains truthful with-`error_key: null`.+`manifest.resolution` is the one host-admission projection: `resolved` means a trusted+inventory contains an exact `host_platform` asset; `unresolved` means no trusted local+inventory exists yet, so `version` and `source_sha` are absent and the network-backed+install admission remains reachable; `unsupported` means a trusted inventory exists+without an exact host asset. An unsupported host leaves `health: "not_installed"`;+the install route fails before creating an install claim or downloading with HTTP 422+and `error: "runtime_platform_unsupported"`; the next status read remains truthful+with `error_key: null` and no persisted install failure.`POST /api/models/runtime/install` is idempotent. Only `not_installed` on a supportedhost starts work: it clears the previous `error_key`, durably enters `installing` with@@ -1008,13 +1011,18 @@ carrier for the persisted failure; raw downloader or verifier text remains onlyscrubbed logs. `/start` never performs installation.On service bootstrap, persisted `installing` with no worker owned by the reconstructed-process is an orphaned install, never a live-job proof. Before runtime endpoints become-ready, the server first verifies the pinned target: a complete manifest-matching binary-settles directly at `not_started`; otherwise it discards only uncommitted staging,-atomically claims the singleton install lease, and restarts the pinned installation-from scratch while retaining `installing`. Failure to claim or schedule that recovery-settles at `not_installed` with the same closed `error_key`. Thus a page reload observes-a live owned job, while a service restart cannot strand the state permanently.+process is an orphaned install, never a live-job proof. Recovery atomically replaces the+claim generation before it re-resolves the pinned target through the shared installer+and verifies its exact identity before archive access. Every success, failure, and+abandon settlement is a compare-and-set against that generation; a stale owner cannot+clear or overwrite a newer owner's claim. A complete manifest-matching binary settles+directly at `not_started`; otherwise the owned recovery continues the pinned installation+while retaining `installing`. A transient collision with the shared install file lock is+retried with exponential backoff from 250 ms to 4 seconds for at most 30 seconds. Failure+to claim or schedule recovery, exhaustion of that bounded window, or another terminal+recovery failure settles the current generation at `not_installed` with the same closed+`error_key`. Thus a page reload observes a live owned job, while a service restart cannot+strand the state permanently.## Error codesdiff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex 84132fba7..6d3ad44af 100644--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json@@ -11,18 +11,43 @@"host_platform": {"type": "string","pattern": "^[a-z0-9]+(?:-[a-z0-9_]+)+$",- "description": "Server-authoritative platform key for the Avibe host, never the browser device. Installation is supported exactly when manifest.assets contains an exact platform match. OPTIONAL in the reusable schema and REQUIRED on runtime API payloads."+ "description": "Server-authoritative platform key for the Avibe host, never the browser device. Manifest admission is derived from manifest.resolution. OPTIONAL in the reusable schema and REQUIRED on runtime API payloads."},"manifest": {"type": "object",- "required": ["name", "version", "source_sha", "assets"],+ "required": ["name", "resolution", "assets"],"additionalProperties": false,+ "allOf": [+ {+ "if": {+ "properties": { "resolution": { "const": "unresolved" } },+ "required": ["resolution"]+ },+ "then": {+ "properties": { "assets": { "maxItems": 0 } },+ "not": {+ "anyOf": [+ { "required": ["version"] },+ { "required": ["source_sha"] }+ ]+ }+ },+ "else": {+ "required": ["version", "source_sha"]+ }+ }+ ],"properties": {"name": { "const": "cliproxyapi" },- "version": { "type": "string" },+ "resolution": {+ "enum": ["resolved", "unresolved", "unsupported"],+ "description": "resolved means a trusted inventory contains an exact host asset; unresolved means no trusted local inventory exists yet; unsupported means a trusted inventory exists without an exact host asset."+ },+ "version": { "type": "string", "minLength": 1 },"source_sha": { "type": "string", "pattern": "^[0-9a-f]{40}$" },"assets": {"type": "array",+ "description": "Trusted pinned assets. Empty is required for unresolved and is not evidence of unsupported host admission.","items": {"type": "object","required": ["platform", "url", "size_bytes", "sha256"],@@ -106,6 +131,7 @@"host_platform": "darwin-arm64","manifest": {"name": "cliproxyapi",+ "resolution": "resolved","version": "v7.2.95","source_sha": "f71ec0eb6776854457892452cf28c47f0d658251","assets": [diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.pyindex 85baeb5d6..6f8970e00 100644--- a/tests/test_controller_dispatch_loop.py+++ b/tests/test_controller_dispatch_loop.py@@ -562,6 +562,7 @@ async def test_runtime_work_stack_drains_run_activity_before_executor_stop() ->stopped.append("supervisor")controller.message_dispatcher = _Dispatcher()+ controller.model_hub_service = _Service("model-hub")controller.scheduled_task_service = _Service("tasks")controller.watch_service = _Service("watch")controller.runtime_work_supervisor = _Supervisor()@@ -569,8 +570,8 @@ async def test_runtime_work_stack_drains_run_activity_before_executor_stop() ->await controller._stop_runtime_work_stack()assert stopped[0:2] == ["quiesce", "activity"]- assert set(stopped[2:4]) == {"tasks", "watch"}- assert stopped[4] == "supervisor"+ assert set(stopped[2:5]) == {"model-hub", "tasks", "watch"}+ assert stopped[5] == "supervisor"def test_request_shutdown_keeps_loop_owned_supervisor_join_alive_after_grace() -> None:diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.pyindex 86544a4be..1444be266 100644--- a/tests/test_controller_im_ready.py+++ b/tests/test_controller_im_ready.py@@ -30,6 +30,9 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:recover_persisted_agent_run_queue=AsyncMock(return_value=[]),)controller.runtime_work_supervisor = SimpleNamespace(activate=AsyncMock())+ controller.model_hub_service = SimpleNamespace(+ reconcile_runtime_installation=AsyncMock()+ )controller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))controller.cleanup_task = Nonecontroller._delivery_recovery_complete = asyncio.Event()@@ -50,6 +53,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()assert controller._delivery_recovery_complete.is_set()@@ -165,6 +169,39 @@ def test_runtime_owner_recovery_fails_closed_after_delivery_failure() -> None:assert not controller._delivery_recovery_complete.is_set()+def test_runtime_owner_recovery_isolates_optional_model_hub_failure(+ caplog: pytest.LogCaptureFixture,+) -> None:+ controller = Controller.__new__(Controller)+ controller.model_hub_service = SimpleNamespace(+ reconcile_runtime_installation=AsyncMock(+ side_effect=OSError("runtime directory is unwritable")+ )+ )+ controller.session_turns = SimpleNamespace(+ recover_durable_delivery_state=AsyncMock(return_value=[]),+ recover_persisted_agent_run_queue=AsyncMock(return_value=[]),+ )+ controller.scheduled_task_service = SimpleNamespace(+ recover_processing_requests=Mock()+ )+ controller.runtime_work_supervisor = SimpleNamespace(activate=AsyncMock())+ controller._delivery_recovery_complete = asyncio.Event()++ with caplog.at_level("ERROR"):+ asyncio.run(controller._recover_runtime_owners())++ controller.model_hub_service.reconcile_runtime_installation.assert_awaited_once_with()+ controller.session_turns.recover_durable_delivery_state.assert_awaited_once_with(+ service_restart=True+ )+ 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()+ assert controller._delivery_recovery_complete.is_set()+ assert "Model Hub runtime recovery failed" in caplog.text++def test_runtime_ready_fails_closed_after_queue_recovery_failure() -> None:controller = Controller.__new__(Controller)controller.agent_service = SimpleNamespace(agents={})diff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.pyindex 6f058eead..b04da5780 100644--- a/tests/test_managed_runtime.py+++ b/tests/test_managed_runtime.py@@ -1,5 +1,6 @@from __future__ import annotations+import astimport hashlibimport ioimport json@@ -9,7 +10,10 @@ from pathlib import Pathimport pytestfrom core import managed_runtime+from core.git_runtime import GitRuntimeManagerfrom core.managed_runtime import ManagedRuntimeManager, ManagedRuntimeSpec+from core.memory.artifact import MemoryArtifactManager+from vibe.model_hub_runtime.installer import EngineRuntimeManagerclass FixtureRuntimeManager(ManagedRuntimeManager):@@ -19,6 +23,54 @@ class FixtureRuntimeManager(ManagedRuntimeManager):return binary.read_text(encoding="utf-8").strip()+def test_shared_ensure_failure_vocabulary_matches_reachable_reason_literals() -> None:+ module = ast.parse(Path("core/managed_runtime.py").read_text(encoding="utf-8"))+ manager = next(+ node+ for node in module.body+ if isinstance(node, ast.ClassDef) and node.name == "ManagedRuntimeManager"+ )+ methods = {+ node.name: node+ for node in manager.body+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ }+ reachable = {"ensure"}+ pending = ["ensure"]+ while pending:+ method = methods[pending.pop()]+ for node in ast.walk(method):+ if not isinstance(node, ast.Call):+ continue+ function = node.func+ if not (+ isinstance(function, ast.Attribute)+ and isinstance(function.value, ast.Name)+ and function.value.id == "self"+ and function.attr in methods+ and function.attr not in reachable+ ):+ continue+ reachable.add(function.attr)+ pending.append(function.attr)++ reason_suffixes = {+ node.args[0].value+ for method_name in reachable+ for node in ast.walk(methods[method_name])+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "self"+ and node.func.attr == "_reason"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and isinstance(node.args[0].value, str)+ }++ assert managed_runtime._ENSURE_FAILURE_SUFFIXES == reason_suffixes++@pytest.mark.parametrize(("include_direct_platform", "expected_platform"),[(False, "linux-amd64"), (True, "linux-x64")],@@ -75,11 +127,100 @@ def test_list_asset_manifest_prefers_direct_platform_then_falls_back_to_alias(manifest_path=manifest,)- result = manager.ensure()+ resolved_targets: list[dict[str, str]] = []+ result = manager.ensure(on_resolved=resolved_targets.append)assert result["ok"] is Trueassert result["changed"] is Trueassert result["platform"] == expected_platform+ assert resolved_targets == [result["target"]]assert Path(result["path"]).read_bytes() == binary_payloadassert manager.ensure()["changed"] is Falseassert manager.status()["installed"] is True+++def test_ensure_rejects_a_changed_resolved_target_before_archive_access(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ archive = tmp_path / "fixture.tar.gz"+ binary_payload = b"v1\n"+ with tarfile.open(archive, "w:gz") as tar:+ member = tarfile.TarInfo("fixture")+ member.mode = 0o755+ member.size = len(binary_payload)+ tar.addfile(member, io.BytesIO(binary_payload))+ manifest = tmp_path / "manifest.json"+ manifest.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "version": "v1",+ "source": "example/fixture",+ "archives": {+ "linux-x64": {+ "url": archive.as_uri(),+ "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),+ "binary_sha256": hashlib.sha256(binary_payload).hexdigest(),+ "bin_path": "fixture",+ }+ },+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "linux-x64")+ manager = FixtureRuntimeManager(+ spec=ManagedRuntimeSpec(+ runtime_id="fixture",+ manifest_resource="unused.json",+ version_field="version",+ default_bin_path="fixture",+ ),+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest,+ )+ expected_target = {+ "manifest_sha256": "0" * 64,+ "runtime_version": "v1",+ "platform": "linux-x64",+ "archive_sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),+ "binary_sha256": hashlib.sha256(binary_payload).hexdigest(),+ }+ monkeypatch.setattr(+ manager,+ "_resolve_manifest_archive",+ lambda _archive: (_ for _ in ()).throw(AssertionError("archive accessed")),+ )++ result = manager.ensure(expected_target=expected_target)++ assert result["ok"] is False+ assert result["reason"] == "fixture_install_target_changed"+++ ("manager_type", "expected_reason"),+ [+ (GitRuntimeManager, "git_manifest_missing"),+ (MemoryArtifactManager, "memory-runtime_manifest_missing"),+ (EngineRuntimeManager, "model_hub_engine_manifest_missing"),+ ],+)+def test_optional_ensure_hooks_leave_each_existing_subclass_default_unchanged(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ manager_type,+ expected_reason: str,+) -> None:+ monkeypatch.delenv("AVIBE_MEMORY_DEV_RUNTIME", raising=False)+ manager = manager_type(+ runtime_dir=tmp_path / manager_type.__name__,+ manifest_path=tmp_path / "missing-manifest.json",+ offline=True,+ )++ result = manager.ensure()++ assert result["ok"] is False+ assert result["reason"] == expected_reasondiff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 608c1e324..06d499c98 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -4,6 +4,7 @@ import astimport asyncioimport inspectimport json+import reimport textwrapfrom datetime import datetime, timezonefrom pathlib import Path@@ -30,6 +31,7 @@ from core.handlers.model_hub.adapter import (RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,+ RuntimePlatformUnsupportedError,SOURCE_PROTOCOLS,SourceObservation,)@@ -130,6 +132,7 @@ class FakeAdapter:self.orphan_cleanup_succeeds = Falseself.cancel_disposition = RetainedMaterialDisposition.NONEself.start_calls = 0+ self.install_calls = 0self.credential_count = 0self.observation: SourceObservation | None = Noneself.observed_protocol_orders: list[tuple[str, ...]] = []@@ -140,6 +143,13 @@ class FakeAdapter:async def ensure_installed(self):return await self.status()+ async def install(self):+ self.install_calls += 1+ return await self.status()++ async def recover_installation(self):+ return await self.status()+async def start(self):self.start_calls += 1return await self.status()@@ -641,6 +651,23 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):assert calls == [("runtime_start", None)]+def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):+ from vibe import model_hub_client++ calls = []++ async def rpc(operation, payload=None):+ calls.append((operation, payload))+ return {"contract_version": 5, "status": {"health": "installing"}}++ monkeypatch.setattr(model_hub_client, "_rpc", rpc)++ runtime = asyncio.run(ModelHubRemoteService().runtime_install())++ assert runtime["status"]["health"] == "installing"+ assert calls == [("runtime_install", None)]++def test_runtime_start_is_allowlisted_by_controller_rpc(tmp_path):from core.handlers.model_hub.rpc import dispatch_model_hub_rpc@@ -652,6 +679,46 @@ def test_runtime_start_is_allowlisted_by_controller_rpc(tmp_path):assert adapter.start_calls == 1+def test_runtime_install_is_allowlisted_by_controller_rpc(tmp_path):+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc++ class InstallingAdapter(FakeAdapter):+ async def install(self):+ self.install_calls += 1+ return EngineStatus(+ health=EngineHealth.INSTALLING,+ installed_version=None,+ verified=False,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso=None,+ )++ async def status(self):+ return EngineStatus(+ health=EngineHealth.NOT_INSTALLED,+ installed_version=None,+ verified=False,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso=None,+ )++ adapter = InstallingAdapter()+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ runtime = asyncio.run(dispatch_model_hub_rpc(service, "runtime_install", {}))++ assert runtime["status"]["health"] == "installing"+ assert adapter.install_calls == 1++def test_runtime_status_reports_observed_not_installed_state(tmp_path):class NotInstalledAdapter(FakeAdapter):async def start(self):@@ -683,7 +750,132 @@ def test_runtime_status_reports_observed_not_installed_state(tmp_path):"listening": None,"health": "not_installed","last_check": None,+ "error_key": None,+ }+++def test_runtime_install_enters_one_idempotent_server_owned_job(tmp_path):+ class InstallingAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.health = EngineHealth.NOT_INSTALLED++ async def install(self):+ self.install_calls += 1+ self.health = EngineHealth.INSTALLING+ return await self.status()++ async def status(self):+ return EngineStatus(+ health=self.health,+ installed_version=None,+ verified=False,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso=None,+ )++ adapter = InstallingAdapter()+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ first = asyncio.run(service.runtime_install())+ repeated = asyncio.run(service.runtime_install())+ reloaded = asyncio.run(service.runtime_status())++ assert adapter.install_calls == 1+ assert first == repeated == reloaded+ assert first["host_platform"]+ assert first["status"] == {+ "installed_version": None,+ "verified": False,+ "listening": None,+ "health": "installing",+ "last_check": None,+ "error_key": None,}+ _assert_valid("runtime-dependency.schema.json", first)+++ "health",+ [+ EngineHealth.NOT_STARTED,+ EngineHealth.OK,+ EngineHealth.DEGRADED,+ EngineHealth.DOWN,+ EngineHealth.INSTALLING,+ ],+)+def test_runtime_install_preserves_every_non_installable_state(tmp_path, health):+ class ExistingRuntimeAdapter(FakeAdapter):+ async def install(self):+ raise AssertionError("only not_installed may start installation")++ async def status(self):+ installed = health is not EngineHealth.INSTALLING+ return EngineStatus(+ health=health,+ installed_version="v7.2.95" if installed else None,+ verified=installed,+ listen_host="127.0.0.1",+ listen_port=15220 if health is EngineHealth.OK else None,+ last_check_iso=None,+ )++ service = ModelHubService(+ store=MemoryStore(),+ adapter=ExistingRuntimeAdapter(),+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ runtime = asyncio.run(service.runtime_install())++ assert runtime["status"]["health"] == health.value+++def test_runtime_install_rejects_unsupported_server_host_without_mutation(+ monkeypatch,+ tmp_path,+):+ class NotInstalledAdapter(FakeAdapter):+ async def install(self):+ raise RuntimePlatformUnsupportedError++ async def status(self):+ return EngineStatus(+ health=EngineHealth.NOT_INSTALLED,+ installed_version=None,+ verified=False,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso=None,+ )++ monkeypatch.setattr(+ "core.managed_runtime.runtime_platform_tag",+ lambda: "win32-x64",+ )+ service = ModelHubService(+ store=MemoryStore(),+ adapter=NotInstalledAdapter(),+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.runtime_install())++ assert exc_info.value.code == "runtime_platform_unsupported"+ assert exc_info.value.status == 422def test_discovery_probe_failure_is_not_reported_as_engine_down(tmp_path):@@ -1376,6 +1568,7 @@ def test_ui_model_hub_rpc_preserves_structured_guard_data():("POST", "/api/models/migration/scan"),("POST", "/api/models/migration/apply"),("GET", "/api/models/runtime/status"),+ ("POST", "/api/models/runtime/install"),("POST", "/api/models/runtime/start"),],)@@ -1451,6 +1644,54 @@ def test_final_model_hub_route_surface_has_observe_refresh_and_no_saved_test_rouassert all("/mappings" not in path for path in routes)+def test_models_live_api_calls_only_registered_server_routes():+ source = Path("ui/src/components/settings/models/modelsApi.ts").read_text(+ encoding="utf-8"+ )+ live_api = source.split("const liveApi: ModelsApi = {", 1)[1].split(+ "// ── Mock client",+ 1,+ )[0]+ path_pattern = re.compile(+ r"'(?P<single>/api/models/[^']*)'|`(?P<template>/api/models/[^`]*)`"+ )++ path_matches = list(path_pattern.finditer(live_api))+ assert len(path_matches) == len(re.findall(r"\bcall(?:<|\()", live_api))++ client_routes = set()+ for match in path_matches:+ raw_path = match.group("single") or match.group("template")+ path = re.sub(r"\$\{[^}]*\?[^}]+\}", "", raw_path)+ path = path.split("?", 1)[0]+ path = re.sub(r"\$\{[^}]+\}", "{param}", path)+ next_entry = re.search(+ r"^ [A-Za-z][A-Za-z0-9]*:",+ live_api[match.end() :],+ re.MULTILINE,+ )+ entry_tail = (+ live_api[match.end() : match.end() + next_entry.start()]+ if next_entry+ else live_api[match.end() :]+ )+ method_match = re.search(r"jsonInit\('(POST|PUT|PATCH|DELETE)'", entry_tail)+ client_routes.add((method_match.group(1) if method_match else "GET", path))++ server_routes = {+ (+ method,+ re.sub(r"\{[^}]+\}", "{param}", route.path),+ )+ for route in app.routes+ if route.path.startswith("/api/models/")+ for method in (route.methods or ())+ }++ assert client_routes+ assert client_routes <= server_routes++def test_unsaved_observation_route_returns_valid_result_and_revokes_transient_ref(monkeypatch,tmp_path,@@ -4338,6 +4579,63 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t_assert_valid("runtime-dependency.schema.json", runtime)+def test_runtime_install_route_is_reachable_and_persists_installing(+ monkeypatch,+ tmp_path,+):+ class InstallingAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.health = EngineHealth.NOT_INSTALLED++ async def install(self):+ self.install_calls += 1+ self.health = EngineHealth.INSTALLING+ return await self.status()++ async def status(self):+ return EngineStatus(+ health=self.health,+ installed_version=None,+ verified=False,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso=None,+ )++ adapter = InstallingAdapter()+ service = ModelHubService(+ store=MemoryStore(),+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"++ rejected = client.post("/api/models/runtime/install", base_url=base_url)+ accepted = client.post(+ "/api/models/runtime/install",+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )+ repeated = client.post(+ "/api/models/runtime/install",+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )+ reloaded = client.get("/api/models/runtime/status", base_url=base_url)++ assert rejected.status_code == 403+ assert accepted.status_code == repeated.status_code == reloaded.status_code == 200+ assert adapter.install_calls == 1+ assert accepted.get_json()["runtime"] == repeated.get_json()["runtime"]+ assert repeated.get_json()["runtime"] == reloaded.get_json()["runtime"]+ assert reloaded.get_json()["runtime"]["status"]["health"] == "installing"++def test_runtime_start_route_requires_remote_session(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))save_config(tmp_path)diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 68c280fcf..5749cc4ae 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -18,6 +18,7 @@ from types import SimpleNamespaceimport pytestimport yaml+from jsonschema import Draft7Validatorfrom core import managed_runtimefrom core.handlers.model_hub.adapter import (@@ -25,6 +26,7 @@ from core.handlers.model_hub.adapter import (OriginNotAllowedError,RawOutcomeKind,RetainedMaterialDisposition,+ RuntimePlatformUnsupportedError,SourceBinding,)from core.handlers.model_hub.classification import (@@ -33,12 +35,17 @@ from core.handlers.model_hub.classification import ()from core.handlers.model_hub.request import ModelHubRequestfrom core.handlers.model_hub.stream_wire import SSE_MAX_FRAME_BYTES, SSE_MAX_LINE_BYTES+from vibe.model_hub_runtime import adapter as runtime_adapter_modulefrom vibe.model_hub_runtime import client as client_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapterfrom vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnectionfrom vibe.model_hub_runtime.config import write_engine_config-from vibe.model_hub_runtime.installer import EngineRuntimeManagerfrom vibe.model_hub_runtime.environment import engine_subprocess_environment+from vibe.model_hub_runtime.installer import (+ EngineRuntimeManager,+ InstallClaimTransition,+ ManifestResolution,+)from vibe.model_hub_runtime.state import (EngineStateError,EngineStateStore,@@ -52,6 +59,28 @@ STREAM_TRANSPORT_BOUNDARIES = json.loads((MODEL_HUB_FIXTURES / "stream_transport_boundaries.json").read_text(encoding="utf-8"))["cases"]DEEP_JSON_ARRAY = b"[" * 10_000 + b"0" + b"]" * 10_000+RUNTIME_INSTALL_TARGET = {+ "manifest_sha256": "1" * 64,+ "runtime_version": "v7.2.95",+ "platform": "fixture-platform",+ "archive_sha256": "2" * 64,+ "binary_sha256": "3" * 64,+}+RUNTIME_INSTALL_GENERATION_A = "a" * 32+RUNTIME_INSTALL_GENERATION_B = "b" * 32+++def _create_runtime_install_claim(+ installer: EngineRuntimeManager,+ *,+ generation: str = RUNTIME_INSTALL_GENERATION_A,+) -> str:+ assert installer.transition_install_claim(+ InstallClaimTransition.CREATE,+ generation=generation,+ target=RUNTIME_INSTALL_TARGET,+ )+ return generationdef test_stream_prelude_does_not_charge_released_keepalives_to_frame_budget() -> None:@@ -403,6 +432,7 @@ def test_packaged_manifest_matches_frozen_runtime_dependency_values(assert manifest == {"name": "cliproxyapi",+ "resolution": "resolved","version": "v7.2.95","source_sha": "f71ec0eb6776854457892452cf28c47f0d658251","assets": [@@ -473,6 +503,256 @@ def test_contract_manifest_filters_unsupported_override_assets(assert unsupported["reason"] == "model_hub_engine_platform_unsupported"+def test_install_admission_fetches_an_uncached_remote_manifest(tmp_path: Path) -> None:+ archive, binary = _write_fixture_archive(tmp_path / "remote")+ manifest = _write_fixture_manifest(tmp_path / "remote", archive, binary)+ manager = EngineRuntimeManager(+ runtime_dir=tmp_path / "runtime",+ manifest_url=manifest.as_uri(),+ )++ assert manager.contract_manifest() == {+ "name": "cliproxyapi",+ "resolution": "unresolved",+ "assets": [],+ }+ installed = manager.ensure(+ on_resolved=lambda target: manager.transition_install_claim(+ InstallClaimTransition.CREATE,+ generation=RUNTIME_INSTALL_GENERATION_A,+ target=target,+ )+ )++ persisted = manager.install_state()+ assert installed["ok"] is True+ assert persisted is not None+ assert persisted["state"] == "installing"+ assert persisted["target"] == installed["target"]+ assert persisted["target"]["platform"] == manager.host_platform()+ assert manager.contract_manifest()["assets"]++[email protected]("transition", tuple(InstallClaimTransition), ids=lambda item: item.value)+def test_every_install_claim_transition_preserves_live_generation_ownership(+ tmp_path: Path,+ transition: InstallClaimTransition,+) -> None:+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ live_generations: set[str]++ if transition is InstallClaimTransition.CREATE:+ applied = manager.transition_install_claim(+ transition,+ generation=RUNTIME_INSTALL_GENERATION_B,+ target=RUNTIME_INSTALL_TARGET,+ )+ live_generations = {RUNTIME_INSTALL_GENERATION_B}+ elif transition is InstallClaimTransition.ADMISSION_FAILURE:+ applied = manager.transition_install_claim(+ transition,+ generation=RUNTIME_INSTALL_GENERATION_B,+ reason="fixture_admission_failure",+ )+ live_generations = set()+ else:+ _create_runtime_install_claim(manager)+ if transition is InstallClaimTransition.RESUME:+ applied = manager.transition_install_claim(+ transition,+ generation=RUNTIME_INSTALL_GENERATION_B,+ previous_generation=RUNTIME_INSTALL_GENERATION_A,+ target=RUNTIME_INSTALL_TARGET,+ )+ live_generations = {RUNTIME_INSTALL_GENERATION_B}+ elif transition is InstallClaimTransition.SETTLE_SUCCESS:+ applied = manager.transition_install_claim(+ transition,+ generation=RUNTIME_INSTALL_GENERATION_A,+ target=RUNTIME_INSTALL_TARGET,+ )+ live_generations = set()+ elif transition in {+ InstallClaimTransition.SETTLE_FAILURE,+ InstallClaimTransition.ABANDON,+ }:+ applied = manager.transition_install_claim(+ transition,+ generation=RUNTIME_INSTALL_GENERATION_A,+ target=RUNTIME_INSTALL_TARGET,+ reason=f"fixture_{transition.value}",+ )+ live_generations = set()+ else:+ raise AssertionError(f"unmodelled install claim transition: {transition}")++ assert applied is True+ state = manager.install_state()+ if state is not None and state["state"] == "installing":+ assert state["generation"] in live_generations+ else:+ assert not live_generations+ if transition is not InstallClaimTransition.SETTLE_SUCCESS:+ assert state is not None+ assert state["state"] == "not_installed"+ assert state["error_key"] == "settings.models.install.fail.detail"+++ "stale_settlement",+ tuple(+ transition+ for transition in InstallClaimTransition+ if transition+ not in {InstallClaimTransition.CREATE, InstallClaimTransition.RESUME}+ ),+ ids=lambda item: item.value,+)+def test_new_owner_claim_survives_every_stale_settlement(+ tmp_path: Path,+ stale_settlement: InstallClaimTransition,+) -> None:+ owner_a = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ owner_b = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ _create_runtime_install_claim(owner_a)+ assert owner_b.transition_install_claim(+ InstallClaimTransition.RESUME,+ generation=RUNTIME_INSTALL_GENERATION_B,+ previous_generation=RUNTIME_INSTALL_GENERATION_A,+ target=RUNTIME_INSTALL_TARGET,+ )++ kwargs = {}+ if stale_settlement is not InstallClaimTransition.SETTLE_SUCCESS:+ kwargs["reason"] = "fixture_stale_owner"+ target = (+ None+ if stale_settlement is InstallClaimTransition.ADMISSION_FAILURE+ else RUNTIME_INSTALL_TARGET+ )+ assert owner_a.transition_install_claim(+ stale_settlement,+ generation=RUNTIME_INSTALL_GENERATION_A,+ target=target,+ **kwargs,+ ) is False++ surviving = owner_b.install_state()+ assert surviving is not None+ assert surviving["state"] == "installing"+ assert surviving["generation"] == RUNTIME_INSTALL_GENERATION_B+ assert surviving["target"] == RUNTIME_INSTALL_TARGET++[email protected]("resolution", tuple(ManifestResolution), ids=lambda item: item.value)+def test_manifest_resolution_drives_admission_persistence_and_schema(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ resolution: ManifestResolution,+) -> None:+ archive, binary = _write_fixture_archive(tmp_path / "fixture")+ manifest_path = _write_fixture_manifest(tmp_path / "fixture", archive, binary)+ if resolution is ManifestResolution.UNRESOLVED:+ manager = EngineRuntimeManager(+ runtime_dir=tmp_path / "runtime",+ manifest_url=manifest_path.as_uri(),+ )+ else:+ if resolution is ManifestResolution.UNSUPPORTED:+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "win32-x64")+ elif resolution is not ManifestResolution.RESOLVED:+ raise AssertionError(f"unmodelled manifest resolution: {resolution}")+ manager = EngineRuntimeManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ offline=False,+ )++ supervisor = EngineSupervisor(+ installer=manager,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ projected = {"contract_version": 5, **supervisor.status()}+ schema = json.loads(+ Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(+ encoding="utf-8"+ )+ )+ Draft7Validator(schema).validate(projected)+ assert projected["manifest"]["resolution"] == resolution.value++ claim_calls = 0++ def persist_claim(target: dict[str, str]) -> None:+ nonlocal claim_calls+ claim_calls += 1+ assert manager.transition_install_claim(+ InstallClaimTransition.CREATE,+ generation=RUNTIME_INSTALL_GENERATION_A,+ target=target,+ )++ admitted = manager.ensure(on_resolved=persist_claim)+ state = manager.install_state()+ if resolution is ManifestResolution.UNSUPPORTED:+ assert admitted["ok"] is False+ assert admitted["reason"] == "model_hub_engine_platform_unsupported"+ assert claim_calls == 0+ assert state is None+ assert projected["status"]["health"] == "not_installed"+ assert projected["status"]["error_key"] is None+ else:+ assert admitted["ok"] is True+ assert claim_calls == 1+ assert state is not None+ assert state["state"] == "installing"+ assert state["error_key"] is None+++def test_every_runtime_install_failure_reason_has_a_non_collapsing_mapping(+ tmp_path: Path,+) -> None:+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)++ for reason in manager.install_failure_reasons():+ error = CLIProxyEngineAdapter._install_failure(reason)+ if reason == "model_hub_engine_platform_unsupported":+ assert isinstance(error, RuntimePlatformUnsupportedError)+ else:+ assert isinstance(error, EngineUnavailableError)+ assert error.reason == reason+++ ("live_owner", "resumable_claim"),+ [(False, False), (False, True), (True, False), (True, True)],+)+def test_installing_projection_matches_live_owner_or_resumable_claim(+ tmp_path: Path,+ live_owner: bool,+ resumable_claim: bool,+) -> None:+ async def run() -> None:+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ if resumable_claim:+ _create_runtime_install_claim(installer)+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )+ adapter._install_owner_active = live_owner++ status = await adapter.status()++ assert (status.health is EngineHealth.INSTALLING) is (+ live_owner or resumable_claim+ )++ asyncio.run(run())++@pytest.mark.parametrize(("host_platform", "asset_platform", "size_bytes", "archive_sha256", "binary_sha256"),[@@ -1043,7 +1323,14 @@ class _FixtureInstaller:return resultdef status(self):- return {"installed": True, "version": "v7.2.95"}+ return {+ "installed": True,+ "version": "v7.2.95",+ "install_dir": str(self.install_dir),+ }++ def resolve_engine_path(self):+ return self.binarydef contract_manifest(self):return {@@ -1079,7 +1366,7 @@ def _fixture_supervisor(("installed", "start_attempted", "running", "healthy", "expected"),[(False, False, False, False, "not_installed"),- (False, True, False, False, "down"),+ (False, True, False, False, "not_installed"),(True, False, False, False, "not_started"),(True, True, False, False, "down"),(True, True, True, False, "degraded"),@@ -1112,10 +1399,14 @@ def test_supervisor_status_distinguishes_all_runtime_health_states(assert supervisor.status()["status"]["health"] == expected-def test_supervisor_failed_first_install_reports_down(tmp_path: Path) -> None:+def test_supervisor_missing_runtime_stays_installable_after_start(tmp_path: Path) -> None:installer = SimpleNamespace(- ensure=lambda: {"ok": False, "reason": "fixture_install_failed"},- status=lambda: {"installed": False, "version": None},+ resolve_engine_path=lambda: None,+ status=lambda: {+ "installed": False,+ "version": None,+ "reason": "fixture_install_failed",+ },contract_manifest=lambda: {"name": "cliproxyapi", "version": "v7.2.95", "assets": []},)supervisor = EngineSupervisor(@@ -1126,7 +1417,36 @@ def test_supervisor_failed_first_install_reports_down(tmp_path: Path) -> None:with pytest.raises(EngineUnavailableError, match="models.engine.install_failed"):supervisor.ensure_running()- assert supervisor.status()["status"]["health"] == "down"+ assert supervisor.status()["status"]["health"] == "not_installed"+++def test_supervisor_keeps_installing_state_unverified_until_settlement(+ tmp_path: Path,+) -> None:+ installer = SimpleNamespace(+ status=lambda: {+ "installed": True,+ "version": "v7.2.95",+ "platform": "darwin-arm64",+ },+ install_state=lambda: {"state": "installing", "error_key": None},+ host_platform=lambda: "darwin-arm64",+ contract_manifest=lambda: {+ "name": "cliproxyapi",+ "version": "v7.2.95",+ "assets": [],+ },+ )+ supervisor = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )++ status = supervisor.status()["status"]++ assert status["health"] == "installing"+ assert status["installed_version"] is None+ assert status["verified"] is Falsedef test_supervisor_starts_checks_health_and_stops_mock_engine(@@ -1539,6 +1859,766 @@ def test_adapter_applies_changed_install_to_running_engine(asyncio.run(run())+def test_runtime_install_state_survives_adapter_reload_and_settles_once(+ tmp_path: Path,+) -> None:+ class BlockingInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.release = threading.Event()+ self.started = threading.Event()+ self.ensure_calls = 0+ self.binary = runtime_dir / "installed-engine"++ def ensure(+ self,+ *,+ force: bool = False,+ expected_target=None,+ on_resolved=None,+ ):+ del force+ assert expected_target is None+ self.ensure_calls += 1+ assert on_resolved is not None+ on_resolved(RUNTIME_INSTALL_TARGET)+ self.started.set()+ assert self.release.wait(timeout=2)+ self.binary.parent.mkdir(parents=True, exist_ok=True)+ self.binary.write_bytes(b"verified fixture")+ return {+ "ok": True,+ "changed": True,+ "path": str(self.binary),+ "install_dir": str(self.binary.parent),+ "version": "v7.2.95",+ }++ def resolve_engine_path(self):+ return self.binary if self.binary.is_file() else None++ def status(self):+ installed = self.resolve_engine_path() is not None+ return {+ "installed": installed,+ "version": "v7.2.95" if installed else None,+ "install_dir": str(self.binary.parent),+ "platform": self.host_platform(),+ "reason": None,+ }++ async def run() -> None:+ runtime_dir = tmp_path / "runtime"+ installer = BlockingInstaller(runtime_dir)+ supervisor = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ adapter = CLIProxyEngineAdapter(supervisor=supervisor)++ started = await adapter.install()+ await asyncio.to_thread(installer.started.wait, 2)+ repeated = await adapter.install()++ reloaded_installer = BlockingInstaller(runtime_dir)+ reloaded = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=reloaded_installer,+ state_store=EngineStateStore(tmp_path / "reloaded-state"),+ )+ )+ reloaded_status = await reloaded.status()++ assert started.health is EngineHealth.INSTALLING+ assert repeated.health is EngineHealth.INSTALLING+ assert reloaded_status.health is EngineHealth.INSTALLING+ assert installer.ensure_calls == 1++ installer.release.set()+ for _ in range(100):+ settled = await adapter.status()+ if settled.health is EngineHealth.NOT_STARTED:+ break+ await asyncio.sleep(0.01)+ else:+ raise AssertionError("installation did not settle")++ assert settled.verified is True+ assert settled.error_key is None+ assert reloaded_installer.install_state() is None++ asyncio.run(run())+++def test_cancelled_install_admission_keeps_owned_worker_and_shutdown_joins_it(+ tmp_path: Path,+) -> None:+ class BlockingInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.claim_entered = threading.Event()+ self.release_claim = threading.Event()+ self.worker_started = threading.Event()+ self.release_worker = threading.Event()+ self.ensure_calls = 0+ self.binary = runtime_dir / "installed-engine"++ def transition_install_claim(self, transition, **kwargs):+ if transition is InstallClaimTransition.CREATE:+ self.claim_entered.set()+ assert self.release_claim.wait(timeout=2)+ return super().transition_install_claim(transition, **kwargs)++ def ensure(+ self,+ *,+ force: bool = False,+ expected_target=None,+ on_resolved=None,+ ):+ del force+ assert expected_target is None+ self.ensure_calls += 1+ assert on_resolved is not None+ on_resolved(RUNTIME_INSTALL_TARGET)+ self.worker_started.set()+ assert self.release_worker.wait(timeout=2)+ self.binary.parent.mkdir(parents=True, exist_ok=True)+ self.binary.write_bytes(b"verified fixture")+ return {+ "ok": True,+ "changed": True,+ "path": str(self.binary),+ "install_dir": str(self.binary.parent),+ "version": "v7.2.95",+ }++ def resolve_engine_path(self):+ return self.binary if self.binary.is_file() else None++ def status(self):+ installed = self.resolve_engine_path() is not None+ return {+ "installed": installed,+ "version": "v7.2.95" if installed else None,+ "install_dir": str(self.binary.parent),+ "platform": self.host_platform(),+ "reason": None,+ }++ async def run() -> None:+ installer = BlockingInstaller(tmp_path / "runtime")+ supervisor = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ supervisor._start_attempted = True+ adapter = CLIProxyEngineAdapter(supervisor=supervisor)++ request = asyncio.create_task(adapter.install())+ assert await asyncio.to_thread(installer.claim_entered.wait, 2)+ request.cancel()+ installer.release_claim.set()+ with pytest.raises(asyncio.CancelledError):+ await request++ assert await asyncio.to_thread(installer.worker_started.wait, 2)+ repeated = await adapter.install()+ assert repeated.health is EngineHealth.INSTALLING+ assert installer.ensure_calls == 1++ stopping = asyncio.create_task(adapter.stop())+ await asyncio.sleep(0)+ assert stopping.done() is False+ installer.release_worker.set()+ await stopping++ assert installer.install_state() is None+ assert installer.resolve_engine_path() is not None+ assert (await adapter.status()).health is EngineHealth.NOT_STARTED++ asyncio.run(run())+++def test_install_finalization_never_projects_a_verified_installing_state(+ tmp_path: Path,+) -> None:+ class FinalizingInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.clear_entered = threading.Event()+ self.release_clear = threading.Event()+ self.binary = runtime_dir / "installed-engine"++ def ensure(+ self,+ *,+ force: bool = False,+ expected_target=None,+ on_resolved=None,+ ):+ del force+ assert expected_target is None+ assert on_resolved is not None+ on_resolved(RUNTIME_INSTALL_TARGET)+ self.binary.parent.mkdir(parents=True, exist_ok=True)+ self.binary.write_bytes(b"verified fixture")+ return {+ "ok": True,+ "changed": True,+ "path": str(self.binary),+ "install_dir": str(self.binary.parent),+ "version": "v7.2.95",+ }++ def resolve_engine_path(self):+ return self.binary if self.binary.is_file() else None++ def status(self):+ installed = self.resolve_engine_path() is not None+ return {+ "installed": installed,+ "version": "v7.2.95" if installed else None,+ "install_dir": str(self.binary.parent),+ "platform": self.host_platform(),+ "reason": None,+ }++ def transition_install_claim(self, transition, **kwargs):+ if transition is InstallClaimTransition.SETTLE_SUCCESS:+ self.clear_entered.set()+ assert self.release_clear.wait(timeout=2)+ return super().transition_install_claim(transition, **kwargs)++ async def run() -> None:+ installer = FinalizingInstaller(tmp_path / "runtime")+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ started = await adapter.install()+ assert started.health is EngineHealth.INSTALLING+ assert await asyncio.to_thread(installer.clear_entered.wait, 2)++ finalizing = await adapter.status()+ assert finalizing.health is EngineHealth.INSTALLING+ assert finalizing.installed_version is None+ assert finalizing.verified is False++ installer.release_clear.set()+ await adapter.stop()+ settled = await adapter.status()+ assert settled.health is EngineHealth.NOT_STARTED+ assert settled.verified is True++ asyncio.run(run())+++def test_orphaned_install_state_is_reclaimed_before_runtime_status(+ tmp_path: Path,+) -> None:+ class RecoveringInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.ensure_calls = 0+ self.expected_target = None+ self.binary = runtime_dir / "installed-engine"++ def ensure(+ self,+ *,+ force: bool = False,+ expected_target=None,+ on_resolved=None,+ ):+ del force+ self.ensure_calls += 1+ self.expected_target = expected_target+ assert expected_target == RUNTIME_INSTALL_TARGET+ assert on_resolved is not None+ on_resolved(RUNTIME_INSTALL_TARGET)+ self.binary.parent.mkdir(parents=True, exist_ok=True)+ self.binary.write_bytes(b"verified fixture")+ return {+ "ok": True,+ "changed": True,+ "path": str(self.binary),+ "install_dir": str(self.binary.parent),+ "version": "v7.2.95",+ }++ def resolve_engine_path(self):+ return self.binary if self.binary.is_file() else None++ def status(self):+ installed = self.resolve_engine_path() is not None+ return {+ "installed": installed,+ "version": "v7.2.95" if installed else None,+ "install_dir": str(self.binary.parent),+ "platform": self.host_platform(),+ "reason": None,+ }++ async def run() -> None:+ installer = RecoveringInstaller(tmp_path / "runtime")+ _create_runtime_install_claim(installer)+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ recovering = await adapter.recover_installation()++ assert recovering.health in {+ EngineHealth.INSTALLING,+ EngineHealth.NOT_STARTED,+ }+ for _ in range(100):+ settled = await adapter.status()+ if settled.health is EngineHealth.NOT_STARTED:+ break+ await asyncio.sleep(0.01)+ else:+ raise AssertionError("orphaned installation did not recover")++ assert installer.ensure_calls == 1+ assert installer.expected_target == RUNTIME_INSTALL_TARGET+ assert installer.install_state() is None++ asyncio.run(run())+++def test_recovery_retries_a_transient_shared_install_lock_collision(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ class RetryingInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.ensure_calls = 0+ self.first_collision = threading.Event()+ self.second_attempt = threading.Event()+ self.release = threading.Event()+ self.binary = runtime_dir / "installed-engine"++ def ensure(+ self,+ *,+ force: bool = False,+ expected_target=None,+ on_resolved=None,+ ):+ del force+ self.ensure_calls += 1+ assert expected_target == RUNTIME_INSTALL_TARGET+ if self.ensure_calls == 1:+ self.first_collision.set()+ return {+ "ok": False,+ "changed": False,+ "reason": "model_hub_engine_install_already_running",+ "skipped": True,+ }+ self.second_attempt.set()+ assert self.release.wait(timeout=2)+ assert on_resolved is not None+ on_resolved(RUNTIME_INSTALL_TARGET)+ self.binary.parent.mkdir(parents=True, exist_ok=True)+ self.binary.write_bytes(b"verified fixture")+ return {+ "ok": True,+ "changed": True,+ "path": str(self.binary),+ "install_dir": str(self.binary.parent),+ "version": "v7.2.95",+ }++ def resolve_engine_path(self):+ return self.binary if self.binary.is_file() else None++ def status(self):+ installed = self.resolve_engine_path() is not None+ return {+ "installed": installed,+ "version": "v7.2.95" if installed else None,+ "install_dir": str(self.binary.parent),+ "platform": self.host_platform(),+ "reason": None,+ }++ async def run() -> None:+ monkeypatch.setattr(+ runtime_adapter_module,+ "_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS",+ 0,+ )+ monkeypatch.setattr(+ runtime_adapter_module,+ "_INSTALL_RECOVERY_MAX_DELAY_SECONDS",+ 0,+ )+ installer = RetryingInstaller(tmp_path / "runtime")+ _create_runtime_install_claim(installer)+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ recovered = await adapter.recover_installation()++ assert recovered.health is EngineHealth.INSTALLING+ assert await asyncio.to_thread(installer.first_collision.wait, 2)+ assert await asyncio.to_thread(installer.second_attempt.wait, 2)+ assert (await adapter.status()).health is EngineHealth.INSTALLING+ installer.release.set()+ for _ in range(100):+ settled = await adapter.status()+ if settled.health is EngineHealth.NOT_STARTED:+ break+ await asyncio.sleep(0.01)+ else:+ raise AssertionError("installation recovery did not retry")++ assert installer.ensure_calls == 2+ assert installer.install_state() is None++ asyncio.run(run())+++def test_recovery_lock_wait_exhaustion_settles_terminal_with_backoff(+ caplog: pytest.LogCaptureFixture,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ class CollidingInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.ensure_calls = 0++ def ensure(self, **_kwargs):+ self.ensure_calls += 1+ return {+ "ok": False,+ "changed": False,+ "reason": "model_hub_engine_install_already_running",+ "skipped": True,+ }++ async def run() -> None:+ monkeypatch.setattr(runtime_adapter_module, "_INSTALL_RECOVERY_WAIT_SECONDS", 0.02)+ monkeypatch.setattr(+ runtime_adapter_module,+ "_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS",+ 0.001,+ )+ monkeypatch.setattr(+ runtime_adapter_module,+ "_INSTALL_RECOVERY_MAX_DELAY_SECONDS",+ 0.004,+ )+ installer = CollidingInstaller(tmp_path / "runtime")+ _create_runtime_install_claim(installer)+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ recovered = await adapter.recover_installation()+ assert recovered.health is EngineHealth.INSTALLING+ for _ in range(100):+ settled = await adapter.status()+ if settled.health is EngineHealth.NOT_INSTALLED:+ break+ await asyncio.sleep(0.005)+ else:+ raise AssertionError("bounded recovery did not settle")++ state = installer.install_state()+ assert installer.ensure_calls > 2+ assert adapter._install_owner_active is False+ assert settled.error_key == "settings.models.install.fail.detail"+ assert state is not None+ assert state["state"] == "not_installed"+ assert state["reason"] == "model_hub_engine_install_lock_timeout"++ with caplog.at_level(logging.WARNING):+ asyncio.run(run())+ assert sum("waiting up to" in record.message for record in caplog.records) == 1+ assert sum("gave up waiting" in record.message for record in caplog.records) == 1+++def test_recovery_schedule_failure_abandons_the_owned_generation(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ async def run() -> None:+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ _create_runtime_install_claim(installer)+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ def fail_schedule(**_kwargs) -> None:+ raise RuntimeError("fixture schedule failure")++ monkeypatch.setattr(adapter, "_start_install_task_locked", fail_schedule)++ recovered = await adapter.recover_installation()++ state = installer.install_state()+ assert recovered.health is EngineHealth.NOT_INSTALLED+ assert recovered.error_key == "settings.models.install.fail.detail"+ assert adapter._install_owner_active is False+ assert state is not None+ assert state["state"] == "not_installed"+ assert state["reason"] == "model_hub_engine_install_schedule_failed"++ asyncio.run(run())+++def test_platform_refusal_never_creates_or_settles_an_install_claim(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ async def run() -> None:+ archive, binary = _write_fixture_archive(tmp_path / "fixture")+ manifest_path = _write_fixture_manifest(tmp_path / "fixture", archive, binary)+ monkeypatch.setattr(managed_runtime, "runtime_platform_tag", lambda: "win32-x64")+ installer = EngineRuntimeManager(+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ offline=False,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ with pytest.raises(RuntimePlatformUnsupportedError):+ await adapter.install()++ assert installer.install_state() is None+ projected = await adapter.status()+ assert projected.health is EngineHealth.NOT_INSTALLED+ assert projected.error_key is None+ assert (+ adapter.supervisor.status()["manifest"]["resolution"]+ == ManifestResolution.UNSUPPORTED.value+ )++ asyncio.run(run())+++def test_every_pre_resolution_failure_persists_unless_platform_is_unsupported(+ tmp_path: Path,+) -> None:+ class FailedBeforeResolutionInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path, reason: str) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.failure_reason = reason++ def ensure(self, **_kwargs):+ return {+ "ok": False,+ "changed": False,+ "reason": self.failure_reason,+ }++ async def run() -> None:+ vocabulary = EngineRuntimeManager(+ runtime_dir=tmp_path / "vocabulary",+ offline=True,+ ).install_failure_reasons()+ for index, reason in enumerate(sorted(vocabulary)):+ installer = FailedBeforeResolutionInstaller(+ tmp_path / f"runtime-{index}",+ reason,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / f"state-{index}"),+ )+ )++ with pytest.raises((EngineUnavailableError, RuntimePlatformUnsupportedError)):+ await adapter.install()++ state = EngineRuntimeManager(+ runtime_dir=installer.runtime_dir,+ offline=True,+ ).install_state()+ projected = await adapter.status()+ if reason == "model_hub_engine_platform_unsupported":+ assert state is None+ assert projected.error_key is None+ else:+ assert state is not None+ assert state["state"] == "not_installed"+ assert state["reason"] == reason+ assert projected.error_key == "settings.models.install.fail.detail"++ asyncio.run(run())+++def test_runtime_start_consults_install_owner_before_starting(+ tmp_path: Path,+) -> None:+ async def run() -> None:+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ _create_runtime_install_claim(installer)+ supervisor = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ start_calls = 0++ def fail_start() -> None:+ nonlocal start_calls+ start_calls += 1+ raise AssertionError("installing runtime started")++ supervisor.ensure_running = fail_start # type: ignore[method-assign]+ adapter = CLIProxyEngineAdapter(supervisor=supervisor)++ status = await adapter.start()++ assert status.health is EngineHealth.INSTALLING+ assert status.listen_port is None+ assert start_calls == 0++ asyncio.run(run())+++def test_runtime_install_failure_persists_closed_error_key(tmp_path: Path) -> None:+ class FailedInstaller(EngineRuntimeManager):+ def __init__(self, runtime_dir: Path) -> None:+ super().__init__(runtime_dir=runtime_dir, offline=True)+ self.ensure_calls = 0++ def ensure(+ self,+ *,+ force: bool = False,+ expected_target=None,+ on_resolved=None,+ ):+ del force+ assert expected_target is None+ self.ensure_calls += 1+ assert on_resolved is not None+ on_resolved(RUNTIME_INSTALL_TARGET)+ return {"ok": False, "changed": False, "reason": "fixture-secret"}++ async def run() -> None:+ installer = FailedInstaller(tmp_path / "runtime")+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ started = await adapter.install()+ assert started.health is EngineHealth.INSTALLING++ for _ in range(100):+ settled = await adapter.status()+ if settled.health is EngineHealth.NOT_INSTALLED:+ break+ await asyncio.sleep(0.01)+ else:+ raise AssertionError("failed installation did not settle")++ reloaded = FailedInstaller(tmp_path / "runtime").install_state()+ assert installer.ensure_calls == 1+ assert settled.error_key == "settings.models.install.fail.detail"+ assert reloaded is not None+ assert reloaded["state"] == "not_installed"+ assert reloaded["error_key"] == "settings.models.install.fail.detail"++ asyncio.run(run())+++def test_runtime_install_failure_projects_terminal_when_settlement_write_fails(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ generation = _create_runtime_install_claim(installer)+ original_write = managed_runtime.write_json_atomic++ def fail_terminal_write(path: Path, payload: dict) -> None:+ if payload.get("state") == "not_installed":+ raise OSError("fixture settlement failure")+ original_write(path, payload)++ monkeypatch.setattr(managed_runtime, "write_json_atomic", fail_terminal_write)++ with pytest.raises(OSError, match="fixture settlement failure"):+ installer.transition_install_claim(+ InstallClaimTransition.SETTLE_FAILURE,+ generation=generation,+ target=RUNTIME_INSTALL_TARGET,+ reason="model_hub_engine_archive_download_failed",+ )++ projected = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ ).status()["status"]+ assert projected["health"] == "not_installed"+ assert projected["error_key"] == "settings.models.install.fail.detail"+ assert not installer.install_state_path.exists()+++def test_invalid_persisted_install_claim_fails_closed(tmp_path: Path) -> None:+ async def run() -> None:+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", offline=True)+ managed_runtime.write_json_atomic(+ installer.install_state_path,+ {+ "schema_version": 1,+ "state": "installing",+ "error_key": None,+ "target": {"runtime_version": "v7.2.95"},+ },+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "state"),+ )+ )++ settled = await adapter.recover_installation()++ assert settled.health is EngineHealth.NOT_INSTALLED+ assert settled.error_key == "settings.models.install.fail.detail"+ persisted = installer.install_state()+ assert persisted is not None+ assert persisted["state"] == "not_installed"+ assert persisted["error_key"] == "settings.models.install.fail.detail"+ assert persisted["reason"] == "model_hub_engine_install_claim_invalid"++ asyncio.run(run())++def test_adapter_stream_outcome_commits_at_model_output_boundary(tmp_path: Path) -> None:async def run() -> None:supervisor, store = _fixture_supervisor(tmp_path)@@ -3455,11 +4535,15 @@ def test_oauth_terminal_uncertainty_never_claims_cleanup(tmp_path: Path) -> Nonedef test_supervisor_fails_closed_with_direct_mode_escape(tmp_path: Path) -> None:class FailedInstaller:- def ensure(self):- return {"ok": False, "reason": "model_hub_engine_archive_checksum_mismatch"}+ def resolve_engine_path(self):+ return Nonedef status(self):- return {"installed": False, "version": None}+ return {+ "installed": False,+ "version": None,+ "reason": "model_hub_engine_archive_checksum_mismatch",+ }def contract_manifest(self):return {diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex be8fd0888..de74e2922 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -18,7 +18,7 @@ import type { AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {contract_version: 5,- manifest: { name: 'cliproxyapi', version: '1.0.0', source_sha: 'fixture', assets: [] },+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },};const AgentCard = (props: Omit<ComponentProps<typeof RuntimeAgentCard>, 'runtime'>) =>diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsxindex cc89f493a..95008fa54 100644--- a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx+++ b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx@@ -23,23 +23,25 @@ const runtime = (health: RuntimeDependency['status']['health'],withAsset = false,hostPlatform?: string,-): RuntimeDependency => ({- contract_version: 5,- // #1326 runtime-dependency shape; host evidence is consumed only when present.- ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),- manifest: {- name: 'cliproxyapi',- version: '1',- source_sha: 'a'.repeat(40),- assets: withAsset ? [{+): RuntimeDependency => {+ const assets = withAsset ? [{platform: 'darwin-arm64',url: 'https://example.invalid/runtime',size_bytes: 1,sha256: '0'.repeat(64),- }] : [],- },- status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },-});+ } as const] : [];+ const resolution = !withAsset+ ? 'unresolved' as const+ : hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;+ return {+ contract_version: 5,+ ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),+ manifest: resolution === 'unresolved'+ ? { name: 'cliproxyapi', resolution, assets: [] }+ : { name: 'cliproxyapi', resolution, version: '1', source_sha: 'a'.repeat(40), assets },+ status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },+ };+};const renderDialog = (runtimeValue: RegionRead<RuntimeDependency>, props: Partial<React.ComponentProps<typeof EnableGatewayDialog>> = {}) => render(<I18nextProvider i18n={i18n}>@@ -69,7 +71,13 @@ describe('EnableGatewayDialog', () => {expect(screen.getByRole('button', { name: 'Install and switch' })).toBeTruthy();});- it('shares the server-host installability predicate with the runtime pill', () => {+ it('keeps installation reachable while a remote manifest is uncached', () => {+ renderDialog(readyRegion(runtime('not_installed')));++ expect(screen.getByRole('button', { name: 'Install and switch' })).toBeTruthy();+ });++ it('shares the server manifest resolution with the runtime pill', () => {renderDialog(readyRegion(runtime('not_installed', true, 'linux-amd64')));expect(screen.queryByRole('button', { name: 'Install and switch' })).toBeNull();diff --git a/ui/src/components/settings/models/EnableGatewayDialog.tsx b/ui/src/components/settings/models/EnableGatewayDialog.tsxindex feeb9b41a..89672dbc2 100644--- a/ui/src/components/settings/models/EnableGatewayDialog.tsx+++ b/ui/src/components/settings/models/EnableGatewayDialog.tsx@@ -8,7 +8,7 @@ import type { CollectionReadAuthority } from './collectionReadAuthority';import { resumeGatewayAdoption, type GatewayAdoptionFailure } from './gatewayAdoption';import { modelsApi } from './modelsApi';import { foldRegionRead, readyRegion, type RegionRead } from './regionRead';-import { runtimeHasInstallAsset } from './runtimeLifecycle';+import { runtimeCanAttemptInstall } from './runtimeLifecycle';import type { AgentSupply, RuntimeDependency } from './types';import { BACKEND_ADOPTION_VENDOR_KEY } from './vendorMeta';@@ -43,7 +43,7 @@ export const EnableGatewayDialog: React.FC<{const runtimeValue = runtimeDecision.kind === 'ready' ? runtimeDecision.runtime : null;const runtimeUnavailable = runtimeValue === null;const needsInstall = runtimeValue?.status.health === 'not_installed';- const missing = Boolean(needsInstall && runtimeValue && runtimeHasInstallAsset(runtimeValue));+ const missing = Boolean(needsInstall && runtimeValue && runtimeCanAttemptInstall(runtimeValue));const installUnsupported = Boolean(needsInstall && !missing);const effectKeys = agent.backend === 'opencode'? ['1.opencode', '2.opencode', '3', '4'] as constdiff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsxindex c4bb573fd..d9408c938 100644--- a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx+++ b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx@@ -13,6 +13,7 @@ const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependencontract_version: 5,manifest: {name: 'cliproxyapi',+ resolution: 'resolved',version: '1',source_sha: 'sha',assets: [{ platform: 'darwin-arm64', url: 'https://example.invalid/runtime', size_bytes: 1, sha256: '0'.repeat(64) }],diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex 62efd05cc..2c2270871 100644--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -20,23 +20,25 @@ const runtime = (health: RuntimeDependency['status']['health'],withAsset = false,hostPlatform?: string,-): RuntimeDependency => ({- contract_version: 5,- // #1326 runtime-dependency shape: absent host keeps any server asset installable.- ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),- manifest: {- name: 'cliproxyapi',- version: '1',- source_sha: 'sha',- assets: withAsset ? [{+): RuntimeDependency => {+ const assets = withAsset ? [{platform: 'darwin-arm64',url: 'https://example.invalid/runtime',size_bytes: 1,sha256: '0'.repeat(64),- }] : [],- },- status: { installed_version: '1', verified: true, listening: null, health, last_check: null },-});+ } as const] : [];+ const resolution = !withAsset+ ? 'unresolved' as const+ : hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;+ return {+ contract_version: 5,+ ...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),+ manifest: resolution === 'unresolved'+ ? { name: 'cliproxyapi', resolution, assets: [] }+ : { name: 'cliproxyapi', resolution, version: '1', source_sha: 'a'.repeat(40), assets },+ status: { installed_version: '1', verified: true, listening: null, health, last_check: null },+ };+};const renderPill = (health: RuntimeDependency['status']['health'],@@ -84,11 +86,11 @@ describe('Model Hub runtime pill', () => {expect(renderPill('not_started')).toContain('<button');});- it('uses server host evidence when present and keeps absent-host installation available', () => {+ it('uses the server manifest resolution without re-deriving host support', () => {expect(renderPill('not_installed', { withAsset: true })).toContain(zh.settings.models.shell.notInstalled);expect(renderPill('not_installed', { withAsset: true })).toContain('<button');- expect(renderPill('not_installed')).toContain(zh.settings.models.shell.unsupported);- expect(renderPill('not_installed')).not.toContain('<button');+ expect(renderPill('not_installed')).toContain(zh.settings.models.shell.notInstalled);+ expect(renderPill('not_installed')).toContain('<button');expect(renderPill('not_installed', { withAsset: true, hostPlatform: 'linux-amd64' })).toContain(zh.settings.models.shell.unsupported);expect(renderPill('not_installed', { withAsset: true, hostPlatform: 'linux-amd64' })).not.toContain('<button');});diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 09cca6e79..356530f80 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -23,7 +23,7 @@ const directAgent = (backend: AgentBackend): AgentSupply => ({const runtime: RuntimeDependency = {contract_version: 5,- manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a'.repeat(40), assets: [] },+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: '1', verified: true, health: 'ok' },};diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex ea5f58b1d..a38b6dac9 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -56,7 +56,7 @@ import {unreadRegion,type RegionRead,} from './regionRead';-import { freshRuntimeProjection, pollRuntimeStatus, runtimeHasInstallAsset, startRuntimeWithStatusRefresh } from './runtimeLifecycle';+import { freshRuntimeProjection, pollRuntimeStatus, runtimeCanAttemptInstall, startRuntimeWithStatusRefresh } from './runtimeLifecycle';import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';import { useSourceMutationReport } from './useSourceMutationReport';import { backendVisual } from './vendorMeta';@@ -164,7 +164,7 @@ export const RuntimePill: React.FC<{const { runtime, authoritative } = projection;const health = runtime.status.health;const unread = read.kind === 'degraded' && read.cause === 'read_failed';- const canInstall = health === 'not_installed' && runtimeHasInstallAsset(runtime);+ const canInstall = health === 'not_installed' && runtimeCanAttemptInstall(runtime);const allDirect = authoritative && !starting && health === 'ok' && directCount !== undefined && directCount > 0;const key = unread? 'unread'diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsindex b8f3526e1..9fe532107 100644--- a/ui/src/components/settings/models/SupplyGraph.test.ts+++ b/ui/src/components/settings/models/SupplyGraph.test.ts@@ -8,7 +8,7 @@ import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './typesconst runtime: RuntimeDependency = {contract_version: 5,- manifest: { name: 'cliproxyapi', version: '1.0.0', source_sha: 'fixture', assets: [] },+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },};const buildSupplyRelations = (diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 29d285300..0faec4373 100644--- a/ui/src/components/settings/models/apiFailure.test.ts+++ b/ui/src/components/settings/models/apiFailure.test.ts@@ -34,7 +34,7 @@ describe('apiFailure — whether the route named the failure', () => {it('posts installation to the dedicated runtime route', async () => {const runtime = {contract_version: 5,- manifest: { name: 'cliproxyapi', version: '1', source_sha: 'sha', assets: [] },+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },} as const;let installInit: RequestInit | undefined;diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsindex 2440be817..378dd19af 100644--- a/ui/src/components/settings/models/gatewayAdoption.test.ts+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts@@ -15,7 +15,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({contract_version: 5,- manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a'.repeat(40), assets: [] },+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },});diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex 2cd77e10b..d68ca1cd0 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -356,6 +356,7 @@ export function buildMockRuntime(): RuntimeDependency {contract_version: 5,manifest: {name: 'cliproxyapi',+ resolution: 'resolved',version: 'v7.2.95',source_sha: 'f71ec0eb6776854457892452cf28c47f0d658251',assets: [],diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex f4864fd14..6caea51b8 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -1186,7 +1186,9 @@ export class MockStore {this.runtime.status.health = 'installing';this.runtime.status.error_key = null;setTimeout(() => {- this.runtime.status.installed_version = this.runtime.manifest.version;+ this.runtime.status.installed_version = this.runtime.manifest.resolution === 'unresolved'+ ? null+ : this.runtime.manifest.version;this.runtime.status.verified = true;this.runtime.status.health = 'not_started';}, 1200);diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.tsnew file mode 100644index 000000000..40e8a1135--- /dev/null+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import { runtimeCanAttemptInstall } from './runtimeLifecycle';+import type { RuntimeDependency } from './types';++const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({+ platform,+ url: `https://example.test/${platform}.tar.gz`,+ size_bytes: 1,+ sha256: 'a'.repeat(64),+});++const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({+ contract_version: 5,+ host_platform: 'darwin-arm64',+ manifest: resolution === 'unresolved'+ ? { name: 'cliproxyapi', resolution, assets: [] }+ : {+ name: 'cliproxyapi',+ resolution,+ version: 'v1',+ source_sha: 'b'.repeat(40),+ assets: [asset(resolution === 'resolved' ? 'darwin-arm64' : 'linux-amd64')],+ },+ status: {+ installed_version: null,+ verified: false,+ listening: null,+ health: 'not_installed',+ last_check: null,+ error_key: null,+ },+});++describe('runtimeCanAttemptInstall', () => {+ it('keeps an uncached remote manifest eligible for server admission', () => {+ expect(runtimeCanAttemptInstall(runtime('unresolved'))).toBe(true);+ });++ it('accepts resolved admission and rejects explicit unsupported admission', () => {+ expect(runtimeCanAttemptInstall(runtime('resolved'))).toBe(true);+ expect(runtimeCanAttemptInstall(runtime('unsupported'))).toBe(false);+ });+});diff --git a/ui/src/components/settings/models/runtimeLifecycle.ts b/ui/src/components/settings/models/runtimeLifecycle.tsindex 48c6be5c8..a0367f224 100644--- a/ui/src/components/settings/models/runtimeLifecycle.ts+++ b/ui/src/components/settings/models/runtimeLifecycle.ts@@ -47,11 +47,8 @@ export const agentHasLiveChainProjection = (agent: AgentSupply,): boolean => runtime !== null && runtimeIsRunning(runtime[FRESH_RUNTIME]) && agent.mode === 'hub';-export const runtimeHasInstallAsset = (runtime: RuntimeDependency): boolean => {- const host = 'host_platform' in runtime && typeof runtime.host_platform === 'string'- ? runtime.host_platform- : null;- return runtime.manifest.assets.some((asset) => host == null || asset.platform === host);+export const runtimeCanAttemptInstall = (runtime: RuntimeDependency): boolean => {+ return runtime.manifest.resolution !== 'unsupported';};const waitForPoll = (intervalMs: number): Promise<void> => new Promise((resolve) => {diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 41feda904..463bedcba 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -471,21 +471,30 @@ export type OAuthFlow = {// ── runtime-dependency.schema.json ──────────────────────────────────────export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_started' | 'not_installed' | 'installing';+type RuntimeManifestAsset = {+ platform: 'darwin-arm64' | 'darwin-x64' | 'linux-amd64' | 'linux-arm64';+ url: string;+ size_bytes: number;+ sha256: string;+};++export type RuntimeManifest = {+ name: 'cliproxyapi';+ resolution: 'unresolved';+ assets: [];+} | {+ name: 'cliproxyapi';+ resolution: 'resolved' | 'unsupported';+ version: string;+ source_sha: string;+ assets: RuntimeManifestAsset[];+};+export type RuntimeDependency = {contract_version: typeof CONTRACT_VERSION;/** Server host platform, never the browser platform. */host_platform?: string;- manifest: {- name: 'cliproxyapi';- version: string;- source_sha: string;- assets: Array<{- platform: 'darwin-arm64' | 'darwin-x64' | 'linux-amd64' | 'linux-arm64';- url: string;- size_bytes: number;- sha256: string;- }>;- };+ manifest: RuntimeManifest;status: {installed_version?: string | null;verified: boolean;diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex eb7ddc1f2..a51fc04ad 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -243,5 +243,8 @@ class ModelHubRemoteService:async def runtime_status(self) -> dict:return await _rpc("runtime_status")+ async def runtime_install(self) -> dict:+ return await _rpc("runtime_install")+async def runtime_start(self) -> dict:return await _rpc("runtime_start")diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 4efd10c23..b6edbec7b 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -2,12 +2,14 @@ from __future__ import annotationsimport asyncioimport json+import loggingimport secretsimport threading-from dataclasses import dataclass, field+import uuid+from dataclasses import dataclass, field, replacefrom datetime import datetime, timedelta, timezonefrom enum import Enum-from typing import Any, Mapping, Sequence+from typing import Any, Callable, Mapping, Sequenceimport aiohttp@@ -22,6 +24,7 @@ from core.handlers.model_hub.adapter import (RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,+ RuntimePlatformUnsupportedError,SOURCE_PROTOCOLS,SourceObservation,SourceBinding,@@ -36,6 +39,7 @@ from vibe.model_hub_runtime.client import (completed_handle,probe_models,)+from vibe.model_hub_runtime.installer import InstallClaimTransitionfrom vibe.model_hub_runtime.state import EngineStateError, EngineStateStorefrom vibe.model_hub_runtime.supervisor import (EngineSupervisor,@@ -50,6 +54,17 @@ _OAUTH_ENDPOINTS = {"codex": ("/codex-auth-url", "codex", "codex"),}_WEBUI_OAUTH_VENDORS = frozenset(_OAUTH_ENDPOINTS)+_INSTALL_ALREADY_RUNNING_REASON = "model_hub_engine_install_already_running"+_INSTALL_PLATFORM_UNSUPPORTED_REASON = "model_hub_engine_platform_unsupported"+_INSTALL_RECOVERY_TIMEOUT_REASON = "model_hub_engine_install_lock_timeout"+_INSTALL_RECOVERY_ABANDONED_REASON = "model_hub_engine_install_abandoned"+_INSTALL_RECOVERY_SCHEDULE_FAILED_REASON = "model_hub_engine_install_schedule_failed"+_INSTALL_RECOVERY_WAIT_SECONDS = 30.0+_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS = 0.25+_INSTALL_RECOVERY_MAX_DELAY_SECONDS = 4.0+++logger = logging.getLogger(__name__)class _ProtocolProof(Enum):@@ -535,39 +550,355 @@ class CLIProxyEngineAdapter:self.supervisor = supervisor or get_engine_supervisor()self.state_store = state_store or self.supervisor.state_storeself._routing_lock = asyncio.Lock()+ self._installation_lock = asyncio.Lock()+ self._install_task: asyncio.Task[None] | None = None+ self._install_admission: asyncio.Future[EngineStatus] | None = None+ self._install_owner_active = False+ self._installation_stopping = Falseself._oauth_flows: dict[str, _OAuthFlow] = {}self._active_oauth_providers: set[str] = set()self._oauth_lock = threading.RLock()- async def ensure_installed(self) -> EngineStatus:+ async def install(self) -> EngineStatus:+ await self.recover_installation()+ async with self._installation_lock:+ task = self._install_task+ admission = self._install_admission+ if task is not None and not task.done():+ if admission is None:+ return await self.status()+ else:+ status = await self.status()+ if status.health is not EngineHealth.NOT_INSTALLED:+ return status+ if self._installation_stopping:+ raise EngineUnavailableError(+ "models.engine.install_failed",+ reason="engine_stopping",+ )+ admission = asyncio.get_running_loop().create_future()+ self._install_admission = admission+ self._start_install_task_locked(+ generation=uuid.uuid4().hex,+ expected_target=None,+ not_installed=status,+ admission=admission,+ claim_owned=False,+ )+ assert admission is not None+ return await asyncio.shield(admission)++ async def recover_installation(self) -> EngineStatus:+ async with self._installation_lock:+ install_task = self._install_task+ if install_task is not None and not install_task.done():+ return await self.status()+ install_state = await asyncio.to_thread(self.supervisor.installer.install_state)+ if not install_state or install_state.get("state") != "installing":+ return await self.status()+ generation = uuid.uuid4().hex+ claimed = await asyncio.to_thread(+ self.supervisor.installer.transition_install_claim,+ InstallClaimTransition.RESUME,+ generation=generation,+ previous_generation=install_state.get("generation"),+ target=install_state["target"],+ )+ if not claimed:+ return await self.status()+ try:+ self._start_install_task_locked(+ generation=generation,+ expected_target=install_state["target"],+ not_installed=None,+ admission=None,+ claim_owned=True,+ )+ except Exception: # noqa: BLE001+ logger.exception("Failed to schedule Model Hub runtime install recovery")+ await self._abandon_install_claim(+ generation=generation,+ target=install_state["target"],+ reason=_INSTALL_RECOVERY_SCHEDULE_FAILED_REASON,+ )+ return await self.status()++ def _start_install_task_locked(+ self,+ *,+ generation: str,+ expected_target: Mapping[str, str] | None,+ not_installed: EngineStatus | None,+ admission: asyncio.Future[EngineStatus] | None,+ claim_owned: bool,+ ) -> None:+ task = asyncio.create_task(+ self._run_installation(+ generation=generation,+ expected_target=expected_target,+ not_installed=not_installed,+ admission=admission,+ claim_owned=claim_owned,+ ),+ name="model-hub-runtime-install",+ )+ self._install_task = task+ self._install_owner_active = True+ task.add_done_callback(self._installation_done)++ def _installation_done(self, task: asyncio.Task[None]) -> None:+ if self._install_task is task:+ self._install_task = None+ self._install_admission = None+ self._install_owner_active = False+ try:+ task.result()+ except asyncio.CancelledError:+ return+ except Exception: # noqa: BLE001+ logger.exception("Model Hub runtime install task failed")++ async def _run_installation(+ self,+ *,+ generation: str,+ expected_target: Mapping[str, str] | None,+ not_installed: EngineStatus | None,+ admission: asyncio.Future[EngineStatus] | None,+ claim_owned: bool,+ ) -> None:+ loop = asyncio.get_running_loop()+ recovery_deadline: float | None = None+ recovery_delay = _INSTALL_RECOVERY_INITIAL_DELAY_SECONDS+ claimed_target: dict[str, str] | None = (+ dict(expected_target) if expected_target is not None else None+ )++ def persist_claim(target: dict[str, str]) -> None:+ nonlocal claim_owned, claimed_target+ claimed_target = dict(target)+ if expected_target is not None:+ return+ claim_owned = self.supervisor.installer.transition_install_claim(+ InstallClaimTransition.CREATE,+ generation=generation,+ target=target,+ )+ if not claim_owned:+ raise RuntimeError("Model Hub runtime install claim moved during admission")+ assert not_installed is not None+ assert admission is not None+ installing = replace(+ not_installed,+ health=EngineHealth.INSTALLING,+ installed_version=None,+ verified=False,+ listen_port=None,+ error_key=None,+ )+ loop.call_soon_threadsafe(self._resolve_install_admission, admission, installing)++ try:+ while True:+ try:+ await self.ensure_installed(+ expected_target=expected_target,+ on_resolved=persist_claim,+ )+ break+ except EngineUnavailableError as exc:+ if (+ expected_target is None+ or exc.reason != _INSTALL_ALREADY_RUNNING_REASON+ ):+ raise+ if self._installation_stopping:+ await self._abandon_install_claim(+ generation=generation,+ target=claimed_target,+ )+ return+ now = loop.time()+ if recovery_deadline is None:+ recovery_deadline = now + _INSTALL_RECOVERY_WAIT_SECONDS+ logger.warning(+ "Model Hub runtime recovery waiting up to %.1fs for the shared install lock",+ _INSTALL_RECOVERY_WAIT_SECONDS,+ )+ remaining = recovery_deadline - now+ if remaining <= 0:+ logger.error(+ "Model Hub runtime recovery gave up waiting for the shared install lock"+ )+ raise EngineUnavailableError(+ "models.engine.install_failed",+ reason=_INSTALL_RECOVERY_TIMEOUT_REASON,+ )+ await asyncio.sleep(min(recovery_delay, remaining))+ recovery_delay = min(+ recovery_delay * 2,+ _INSTALL_RECOVERY_MAX_DELAY_SECONDS,+ )+ installed = await asyncio.to_thread(+ self.supervisor.installer.resolve_engine_path,+ )+ if installed is None:+ raise EngineUnavailableError("models.engine.install_failed")+ settled = await asyncio.to_thread(+ self.supervisor.installer.transition_install_claim,+ InstallClaimTransition.SETTLE_SUCCESS,+ generation=generation,+ target=claimed_target,+ )+ self._install_owner_active = False+ if settled:+ await asyncio.to_thread(self.supervisor.note_installation_settled)+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001+ self._install_owner_active = False+ reason = self._install_failure_reason(exc)+ if claim_owned:+ try:+ await asyncio.to_thread(+ self.supervisor.installer.transition_install_claim,+ InstallClaimTransition.SETTLE_FAILURE,+ generation=generation,+ target=claimed_target,+ reason=reason,+ )+ except Exception: # noqa: BLE001+ logger.exception("Failed to persist Model Hub runtime install failure")+ elif admission is not None and reason != _INSTALL_PLATFORM_UNSUPPORTED_REASON:+ try:+ await asyncio.to_thread(+ self.supervisor.installer.transition_install_claim,+ InstallClaimTransition.ADMISSION_FAILURE,+ generation=generation,+ reason=reason,+ )+ except Exception: # noqa: BLE001+ logger.exception("Failed to persist Model Hub runtime admission failure")+ if admission is not None:+ self._reject_install_admission(admission, exc)++ async def _abandon_install_claim(+ self,+ *,+ generation: str,+ target: Mapping[str, str] | None,+ reason: str = _INSTALL_RECOVERY_ABANDONED_REASON,+ ) -> None:+ self._install_owner_active = False+ try:+ await asyncio.to_thread(+ self.supervisor.installer.transition_install_claim,+ InstallClaimTransition.ABANDON,+ generation=generation,+ target=target,+ reason=reason,+ )+ except Exception: # noqa: BLE001+ logger.exception("Failed to abandon Model Hub runtime install claim")++ @staticmethod+ def _resolve_install_admission(+ admission: asyncio.Future[EngineStatus],+ status: EngineStatus,+ ) -> None:+ if not admission.done():+ admission.set_result(status)++ @staticmethod+ def _reject_install_admission(+ admission: asyncio.Future[EngineStatus],+ error: Exception,+ ) -> None:+ if not admission.done():+ admission.set_exception(error)++ @staticmethod+ def _install_failure_reason(error: Exception) -> str:+ if isinstance(error, RuntimePlatformUnsupportedError):+ return _INSTALL_PLATFORM_UNSUPPORTED_REASON+ if isinstance(error, EngineUnavailableError) and error.reason:+ return error.reason+ return "model_hub_engine_install_failed"++ @staticmethod+ def _install_failure(reason: str) -> Exception:+ if reason == _INSTALL_PLATFORM_UNSUPPORTED_REASON:+ return RuntimePlatformUnsupportedError()+ return EngineUnavailableError("models.engine.install_failed", reason=reason)++ async def ensure_installed(+ self,+ *,+ expected_target: Mapping[str, str] | None = None,+ on_resolved: Callable[[dict[str, str]], None] | None = None,+ ) -> EngineStatus:async with self._routing_lock:- install = await asyncio.to_thread(self.supervisor.installer.ensure)+ if expected_target is None and on_resolved is None:+ install = await asyncio.to_thread(self.supervisor.installer.ensure)+ else:+ install = await asyncio.to_thread(+ self.supervisor.installer.ensure,+ expected_target=expected_target,+ on_resolved=on_resolved,+ )if not install.get("ok"):reason = str(install.get("reason") or "engine_install_failed")- raise EngineUnavailableError("models.engine.install_failed", reason=reason)+ raise self._install_failure(reason)if install.get("changed"):await asyncio.to_thread(self.supervisor.restart_if_running)return await self.status()async def start(self) -> EngineStatus:- await asyncio.to_thread(self.supervisor.ensure_running)- return await self.status()+ async with self._installation_lock:+ status = await self.status()+ if status.health is EngineHealth.INSTALLING:+ return status+ await asyncio.to_thread(self.supervisor.ensure_running)+ return await self.status()async def stop(self) -> None:+ async with self._installation_lock:+ self._installation_stopping = True+ install_task = self._install_task+ if install_task is not None:+ try:+ await asyncio.shield(install_task)+ except asyncio.CancelledError:+ if not install_task.cancelled():+ raise+ except Exception: # noqa: BLE001+ passawait asyncio.to_thread(self.supervisor.stop)async def status(self) -> EngineStatus:raw = await asyncio.to_thread(self.supervisor.status)status = raw["status"]listening = status.get("listening") or {}- return EngineStatus(+ projected = EngineStatus(health=EngineHealth(status["health"]),installed_version=status.get("installed_version"),verified=bool(status.get("verified")),listen_host="127.0.0.1",listen_port=listening.get("port"),last_check_iso=status.get("last_check"),+ host_platform=raw.get("host_platform"),+ error_key=status.get("error_key"),)+ if self._install_owner_active:+ return replace(+ projected,+ health=EngineHealth.INSTALLING,+ installed_version=None,+ verified=False,+ listen_port=None,+ error_key=None,+ )+ return projectedasync def gateway_token(self) -> str:connection = await asyncio.to_thread(self.supervisor.ensure_running)diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.pyindex 4866af1ee..7f976c109 100644--- a/vibe/model_hub_runtime/installer.py+++ b/vibe/model_hub_runtime/installer.py@@ -1,8 +1,14 @@from __future__ import annotations+import json+import loggingimport osimport reimport subprocess+import threading+from collections.abc import Mapping+from dataclasses import dataclass+from enum import Enumfrom pathlib import Pathfrom typing import Any@@ -16,6 +22,7 @@ from core.managed_runtime import (env_flag_enabled,)from core.process_isolation import isolated_subprocess_kwargs+from storage.lock import MigrationFileLockfrom vibe.model_hub_runtime.environment import engine_subprocess_environment@@ -28,6 +35,21 @@ _ENGINE_PLATFORM_MAP = {"linux-arm64": "linux-arm64",}_ENGINE_ASSET_PLATFORMS = frozenset(_ENGINE_PLATFORM_MAP.values())+_INSTALL_STATE_SCHEMA_VERSION = 2+_INSTALL_STATE_SUPPORTED_SCHEMA_VERSIONS = frozenset({1, _INSTALL_STATE_SCHEMA_VERSION})+_INSTALL_FAILURE_KEY = "settings.models.install.fail.detail"+_INSTALL_CLAIM_INVALID_REASON = "model_hub_engine_install_claim_invalid"+_INSTALL_GENERATION_RE = re.compile(r"^[0-9a-f]{32}$")+_INSTALL_TARGET_FIELDS = frozenset(+ {+ "manifest_sha256",+ "runtime_version",+ "platform",+ "archive_sha256",+ "binary_sha256",+ }+)+_INSTALL_STATE_UNSET = object()_ENGINE_SPEC = ManagedRuntimeSpec(runtime_id="model_hub_engine",manifest_resource="model_hub_runtime/cliproxyapi_manifest.json",@@ -38,6 +60,30 @@ _ENGINE_SPEC = ManagedRuntimeSpec()+logger = logging.getLogger(__name__)+++class InstallClaimTransition(str, Enum):+ CREATE = "create"+ RESUME = "resume"+ ADMISSION_FAILURE = "admission_failure"+ SETTLE_SUCCESS = "settle_success"+ SETTLE_FAILURE = "settle_failure"+ ABANDON = "abandon"+++class ManifestResolution(str, Enum):+ RESOLVED = "resolved"+ UNRESOLVED = "unresolved"+ UNSUPPORTED = "unsupported"+++@dataclass(frozen=True)+class _InstallStateOverride:+ generation: str+ payload: dict[str, Any] | None++class EngineRuntimeManager(ManagedRuntimeManager):"""Install and verify the pinned CLIProxyAPI engine dependency."""@@ -59,6 +105,237 @@ class EngineRuntimeManager(ManagedRuntimeManager):offline=(env_flag_enabled("VIBE_MODEL_HUB_ENGINE_OFFLINE") if offline is None else offline),)self._verified_binary_cache: tuple[tuple[object, ...], Path] | None = None+ self._install_state_lock = threading.RLock()+ self._install_state_override: object | _InstallStateOverride = _INSTALL_STATE_UNSET++ @property+ def install_state_path(self) -> Path:+ return self.runtime_dir / "install-state.json"++ @property+ def install_state_lock_path(self) -> Path:+ return self.runtime_dir / ".install-state.lock"++ def host_platform(self) -> str:+ platform_tag = managed_runtime.runtime_platform_tag()+ return _ENGINE_PLATFORM_MAP.get(platform_tag, platform_tag)++ def install_failure_reasons(self) -> frozenset[str]:+ """Return every admission failure emitted by the shared installer."""++ return self._base_install_failure_reasons()++ def install_state(self) -> dict[str, Any] | None:+ with self._install_state_lock:+ durable = self._read_install_state_file()+ override = self._install_state_override+ if not isinstance(override, _InstallStateOverride):+ return durable+ durable_generation = self._installing_generation(durable)+ if durable is None or durable_generation == override.generation:+ return dict(override.payload) if override.payload is not None else None+ self._install_state_override = _INSTALL_STATE_UNSET+ return durable++ def transition_install_claim(+ self,+ transition: InstallClaimTransition,+ *,+ generation: str,+ target: Mapping[str, Any] | None = None,+ previous_generation: str | None = None,+ reason: str | None = None,+ ) -> bool:+ if not _INSTALL_GENERATION_RE.fullmatch(generation):+ raise ValueError("invalid Model Hub runtime install generation")+ resolved_target = self._validated_install_target(target)+ if transition in {InstallClaimTransition.CREATE, InstallClaimTransition.RESUME}:+ if resolved_target is None:+ raise ValueError("invalid Model Hub runtime install target")+ elif target is not None and resolved_target is None:+ raise ValueError("invalid Model Hub runtime install target")+ if transition in {+ InstallClaimTransition.ADMISSION_FAILURE,+ InstallClaimTransition.SETTLE_FAILURE,+ InstallClaimTransition.ABANDON,+ }:+ if not reason:+ raise ValueError("missing Model Hub runtime install failure reason")++ with self._install_state_lock:+ with MigrationFileLock(self.install_state_lock_path):+ current = self._read_install_state_file()+ current_generation = self._installing_generation(current)+ current_target = (+ self._validated_install_target(current.get("target"))+ if current is not None+ else None+ )++ if transition is InstallClaimTransition.CREATE:+ if current_generation is not None or (+ current is not None and current.get("state") == "installing"+ ):+ return False+ self._write_installing_claim(generation, resolved_target)+ return True++ if transition is InstallClaimTransition.RESUME:+ if (+ current is None+ or current.get("state") != "installing"+ or current_generation != previous_generation+ or current_target != resolved_target+ ):+ return False+ self._write_installing_claim(generation, resolved_target)+ return True++ if transition is InstallClaimTransition.ADMISSION_FAILURE:+ if current is not None and current.get("state") == "installing":+ return False+ assert reason is not None+ payload = self._failed_install_state(+ generation=generation,+ target=None,+ reason=reason,+ )+ self._write_owned_failure(generation, payload)+ return True++ if (+ current is None+ or current.get("state") != "installing"+ or current_generation != generation+ or (resolved_target is not None and current_target != resolved_target)+ ):+ return False++ if transition is InstallClaimTransition.SETTLE_SUCCESS:+ self._clear_owned_install_state(generation)+ return True++ assert reason is not None+ payload = self._failed_install_state(+ generation=generation,+ target=current_target,+ reason=reason,+ )+ self._write_owned_failure(generation, payload)+ return True++ def _read_install_state_file(self) -> dict[str, Any] | None:+ try:+ payload = json.loads(self.install_state_path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ return None+ except (OSError, ValueError, TypeError):+ logger.warning("Ignoring invalid Model Hub runtime install state")+ return None+ if (+ not isinstance(payload, dict)+ or payload.get("schema_version") not in _INSTALL_STATE_SUPPORTED_SCHEMA_VERSIONS+ ):+ logger.warning("Ignoring unsupported Model Hub runtime install state")+ return None+ state = payload.get("state")+ error_key = payload.get("error_key")+ if state not in {"installing", "not_installed"}:+ logger.warning("Ignoring invalid Model Hub runtime install state")+ return None+ if error_key not in {None, _INSTALL_FAILURE_KEY}:+ logger.warning("Ignoring invalid Model Hub runtime install state")+ return None+ if state == "installing" and error_key is not None:+ logger.warning("Ignoring contradictory Model Hub runtime install state")+ return None+ target = self._validated_install_target(payload.get("target"))+ generation = payload.get("generation")+ if generation is not None and (+ not isinstance(generation, str) or not _INSTALL_GENERATION_RE.fullmatch(generation)+ ):+ logger.warning("Ignoring invalid Model Hub runtime install generation")+ return None+ if state == "installing" and target is None:+ logger.warning("Rejecting Model Hub runtime install state without a valid target")+ return self._failed_install_state(+ generation=generation,+ target=None,+ reason=_INSTALL_CLAIM_INVALID_REASON,+ )+ payload["target"] = target+ payload["generation"] = generation+ return payload++ @staticmethod+ def _installing_generation(payload: Mapping[str, Any] | None) -> str | None:+ if payload is None or payload.get("state") != "installing":+ return None+ generation = payload.get("generation")+ return generation if isinstance(generation, str) else None++ def _write_installing_claim(self, generation: str, target: dict[str, str] | None) -> None:+ assert target is not None+ payload = {+ "schema_version": _INSTALL_STATE_SCHEMA_VERSION,+ "state": "installing",+ "generation": generation,+ "error_key": None,+ "target": target,+ }+ managed_runtime.write_json_atomic(self.install_state_path, payload)+ self._install_state_override = _INSTALL_STATE_UNSET++ def _write_owned_failure(self, generation: str, payload: dict[str, Any]) -> None:+ self._install_state_override = _InstallStateOverride(generation, payload)+ try:+ managed_runtime.write_json_atomic(self.install_state_path, payload)+ except Exception:+ try:+ self.install_state_path.unlink()+ except OSError:+ pass+ raise+ self._install_state_override = _INSTALL_STATE_UNSET++ def _clear_owned_install_state(self, generation: str) -> None:+ self._install_state_override = _InstallStateOverride(generation, None)+ try:+ self.install_state_path.unlink()+ except FileNotFoundError:+ self._install_state_override = _INSTALL_STATE_UNSET+ except Exception:+ raise+ else:+ self._install_state_override = _INSTALL_STATE_UNSET++ @staticmethod+ def _validated_install_target(value: object) -> dict[str, str] | None:+ if not isinstance(value, Mapping) or set(value) != _INSTALL_TARGET_FIELDS:+ return None+ target: dict[str, str] = {}+ for field in _INSTALL_TARGET_FIELDS:+ item = value.get(field)+ if not isinstance(item, str) or not item:+ return None+ target[field] = item+ return target++ @staticmethod+ def _failed_install_state(+ *,+ generation: str | None,+ target: dict[str, str] | None,+ reason: str,+ ) -> dict[str, Any]:+ return {+ "schema_version": _INSTALL_STATE_SCHEMA_VERSION,+ "state": "not_installed",+ "generation": generation,+ "error_key": _INSTALL_FAILURE_KEY,+ "target": target,+ "reason": reason,+ }def resolve_engine_path(self) -> Path | None:return self.resolve_binary()@@ -121,10 +398,22 @@ class EngineRuntimeManager(ManagedRuntimeManager):def contract_manifest(self) -> dict[str, Any]:manifest = self._load_manifest(allow_network=False)if manifest is None:- return {"name": "cliproxyapi", "version": "", "source_sha": "", "assets": []}+ return {+ "name": "cliproxyapi",+ "resolution": ManifestResolution.UNRESOLVED.value,+ "assets": [],+ }+ resolution, _archive = self._resolve_manifest_state(manifest)+ if resolution is ManifestResolution.UNRESOLVED:+ return {+ "name": "cliproxyapi",+ "resolution": resolution.value,+ "assets": [],+ }payload = manifest.payloadreturn {"name": str(payload.get("name") or ""),+ "resolution": resolution.value,"version": manifest.runtime_version,"source_sha": str(payload.get("source_sha") or ""),"assets": [@@ -140,13 +429,8 @@ class EngineRuntimeManager(ManagedRuntimeManager):}def _manifest_installable(self, manifest: ManagedRuntimeManifest) -> bool:- payload = manifest.payload- if not (- payload.get("name") == "cliproxyapi"- and payload.get("release_tag") == manifest.runtime_version- and payload.get("license") == "MIT"- and re.fullmatch(r"[0-9a-f]{40}", str(payload.get("source_sha") or ""))- ):+ resolution, _archive = self._resolve_manifest_state(manifest)+ if resolution is ManifestResolution.UNRESOLVED:self._install_reason = "model_hub_engine_manifest_invalid"return Falsereturn True@@ -155,11 +439,32 @@ class EngineRuntimeManager(ManagedRuntimeManager):self,manifest: ManagedRuntimeManifest,) -> ManagedRuntimeArchive | None:+ resolution, archive = self._resolve_manifest_state(manifest)+ if resolution is ManifestResolution.UNRESOLVED:+ self._install_reason = "model_hub_engine_manifest_invalid"+ return None+ if resolution is ManifestResolution.UNSUPPORTED:+ self._install_reason = "model_hub_engine_platform_unsupported"+ return None+ return archive++ def _resolve_manifest_state(+ self,+ manifest: ManagedRuntimeManifest,+ ) -> tuple[ManifestResolution, ManagedRuntimeArchive | None]:+ payload = manifest.payload+ if not (+ payload.get("name") == "cliproxyapi"+ and payload.get("release_tag") == manifest.runtime_version+ and payload.get("license") == "MIT"+ and re.fullmatch(r"[0-9a-f]{40}", str(payload.get("source_sha") or ""))+ ):+ return ManifestResolution.UNRESOLVED, Noneasset_platform = _ENGINE_PLATFORM_MAP.get(managed_runtime.runtime_platform_tag())archive = manifest.archives.get(asset_platform) if asset_platform is not None else Noneif archive is None:- self._install_reason = "model_hub_engine_platform_unsupported"- return archive+ return ManifestResolution.UNSUPPORTED, None+ return ManifestResolution.RESOLVED, archivedef _binary_version(self, binary: Path | None) -> str | None:if binary is None:diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.pyindex ab2df29aa..ab82d0033 100644--- a/vibe/model_hub_runtime/supervisor.py+++ b/vibe/model_hub_runtime/supervisor.py@@ -75,6 +75,12 @@ class EngineSupervisor:self._stop_locked()self._start_locked()+ def note_installation_settled(self) -> None:+ """Expose a newly verified binary as lazy-started, not previously down."""+ with self._lock:+ if not self._is_running_locked():+ self._start_attempted = False+def invalidate_configs(self) -> None:"""Remove secret-bearing configs and recreate one only for a live engine."""with self._lock:@@ -92,23 +98,47 @@ class EngineSupervisor:with self._lock:managed = self.installer.status()installed = bool(managed.get("installed"))+ install_state_reader = getattr(self.installer, "install_state", None)+ install_state = install_state_reader() if callable(install_state_reader) else Nonelistening = Noneif self._is_running_locked() and self._connection is not None:parsed_port = int(self._connection.base_url.rsplit(":", 1)[1])listening = {"host": "127.0.0.1", "port": parsed_port}health = "ok" if self._healthy_locked() else "degraded"+ elif install_state and install_state.get("state") == "installing":+ health = "installing"+ elif install_state and install_state.get("state") == "not_installed":+ health = "not_installed"elif installed:health = "down" if self._start_attempted else "not_started"else:- health = "down" if self._start_attempted else "not_installed"+ # A missing or unverifiable binary remains installable even+ # after an earlier start attempt exposed its absence.+ health = "not_installed"+ host_platform_reader = getattr(self.installer, "host_platform", None)+ host_platform = (+ host_platform_reader()+ if callable(host_platform_reader)+ else str(managed.get("platform") or "")+ )return {+ "host_platform": host_platform,"manifest": self.installer.contract_manifest(),"status": {- "installed_version": managed.get("version") if installed else None,- "verified": installed,+ "installed_version": (+ managed.get("version")+ if installed and health != "installing"+ else None+ ),+ "verified": installed and health != "installing","listening": listening,"health": health,"last_check": self._last_check,+ "error_key": (+ install_state.get("error_key")+ if health == "not_installed" and install_state+ else None+ ),},}@@ -124,15 +154,15 @@ class EngineSupervisor:def _start_locked(self) -> EngineConnection:self._start_attempted = True- install = self.installer.ensure()- if not install.get("ok"):- reason = str(install.get("reason") or "engine_install_failed")+ managed = self.installer.status()+ binary = self.installer.resolve_engine_path()+ if binary is None:+ reason = str(managed.get("reason") or "engine_not_installed")raise EngineUnavailableError("models.engine.install_failed", reason=reason)- binary = Path(str(install["path"]))- install_id = Path(str(install.get("install_dir") or binary.parent)).name+ install_id = Path(str(managed.get("install_dir") or binary.parent)).nameinstance_dir, runtime_secrets = self.state_store.prepare_instance(install_id,- rotate=bool(install.get("changed")),+ rotate=False,)port = self._port_allocator()config_path = instance_dir / "config.yaml"@@ -177,7 +207,10 @@ class EngineSupervisor:self._stop_locked()raise EngineUnavailableError("models.engine.unsafe_permissions") from excself._last_check = _utc_now()- logger.info("Model Hub engine started on 127.0.0.1 with managed version %s", install.get("version"))+ logger.info(+ "Model Hub engine started on 127.0.0.1 with managed version %s",+ managed.get("version"),+ )return connectiontime.sleep(0.05)self._stop_locked()diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 0622648d3..efb1a2b2d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4316,6 +4316,16 @@ async def model_hub_runtime_status():return _model_hub_error(exc)[email protected]("/api/models/runtime/install", methods=["POST"])+async def model_hub_runtime_install():+ from core.handlers.model_hub import ModelHubError++ try:+ return _model_hub_success(runtime=await _model_hub_service().runtime_install())+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/models/runtime/start", methods=["POST"])async def model_hub_runtime_start():from core.handlers.model_hub import ModelHubError