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(models): report idle engine health honestly (#1126)
Call White6c631d99f49e
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 33ec195ed..a737142e4 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -1,4 +1,8 @@-"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.4 (2026-07-30 15:36 +08:00).+"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.5 (2026-07-31).++v1.5 changelog (honest lazy-start health):+- ``EngineHealth.NOT_STARTED`` distinguishes an installed runtime that has not+ been demanded in this service lifetime from one that started and went down.v1.4 changelog (ref-keyed cleanup convergence):- ``cleanup_orphaned_oauth_material`` treats an absent credential ref as an@@ -65,6 +69,7 @@ class EngineHealth(str, Enum):OK = "ok"DEGRADED = "degraded"DOWN = "down"+ NOT_STARTED = "not_started"NOT_INSTALLED = "not_installed"diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 3bd2b1303..41b66f4ad 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -79,4 +79,6 @@ 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_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 8c1b7e9be..6b7ca3115 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -6,7 +6,7 @@ import asyncioimport loggingimport timeimport uuid-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezonefrom typing import Any, Callable, Literal, Mapping, Optional, Protocol, castfrom urllib.parse import parse_qsl, urlsplit@@ -370,6 +370,7 @@ def _runtime_payload(status: EngineStatus) -> dict:from vibe.model_hub_runtime.installer import EngineRuntimeManagerreturn {+ "contract_version": 4,"manifest": EngineRuntimeManager().contract_manifest(),"status": {"installed_version": status.installed_version,@@ -425,6 +426,7 @@ class ModelHubService:)self._mutation_lock = asyncio.Lock()self._engine_synced = False+ self._engine_preparation_failed = False@staticmethoddef _source(config: ModelHubConfig, source_id: str) -> ModelHubSourceConfig:@@ -517,8 +519,10 @@ class ModelHubService:source.supply_channel == "hub" for source in config.sources)if not bindings and not force_empty and not has_hub_sources:+ self._engine_preparation_failed = Falsereturnawait self._engine_call(self.adapter.sync_sources(bindings))+ self._engine_preparation_failed = Falseasync def _commit_synced(self, previous: ModelHubConfig, updated: ModelHubConfig) -> None:"""Persist the authoritative config before updating its engine projection."""@@ -591,6 +595,25 @@ class ModelHubService:except OSError:pass+ async def _prepare_engine_for_demand(self, *, already_synced: bool = False) -> None:+ try:+ if already_synced:+ self._engine_preparation_failed = False+ return+ await self._ensure_engine_synced()+ except Exception:+ self._engine_preparation_failed = True+ raise+ self._engine_preparation_failed = False++ def _runtime_status_after_demand(self, status: EngineStatus) -> EngineStatus:+ if self._engine_preparation_failed and status.health in {+ EngineHealth.NOT_INSTALLED,+ EngineHealth.NOT_STARTED,+ }:+ return replace(status, health=EngineHealth.DOWN)+ return status+@staticmethoddef _credential_was_already_revoked(error: Exception) -> bool:# The frozen adapter surface has no typed not-found result. Match the@@ -2562,7 +2585,7 @@ class ModelHubService:),}- await self._ensure_engine_synced()+ await self._prepare_engine_for_demand()started_at = time.monotonic()handle = await self._engine_call(self.adapter.invoke(@@ -3050,6 +3073,11 @@ class ModelHubService:async def runtime_status(self) -> dict:status = await self._engine_call(self.adapter.status())+ return _runtime_payload(self._runtime_status_after_demand(status))++ async def runtime_start(self) -> dict:+ await self._prepare_engine_for_demand()+ status = await self._engine_call(self.adapter.start())return _runtime_payload(status)def migration_scan(self) -> dict:@@ -3283,8 +3311,8 @@ class ModelHubService:None,supply_channel="native_cli",)- if not engine_prepared:- await self._ensure_engine_synced()+ await self._prepare_engine_for_demand(already_synced=engine_prepared)+ engine_prepared = Trueif attempt_observer is not None:attempt_observer(source.id,diff --git a/docs/CLI.md b/docs/CLI.mdindex dea0e1d4c..b9a40eff0 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -466,6 +466,8 @@ vibe doctorvibe restart --delay-seconds 60```+The Model Hub engine process is named `cli-proxy-api` (hyphenated); `pgrep cliproxyapi` therefore always returns no match.+## Web UI ControlsThe web UI (`http://127.0.0.1:5123`) provides the same controls:diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 812fc228e..40feb7bc0 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -126,6 +126,14 @@ order after any mutation; clients never compute partial reorders.discriminator into both producers, and audits every remaining contract file.It is evidence-pinned, delivered into the implementing lane rather than bychat, and remains owner-vetoable.+- **Targeted v4 process instance trail — entry 5 (engine health honesty).** The+ 2026-07-31 restart incident proved that `runtime-dependency.status.health`+ collapsed an installed runtime that had never been demanded into `down`. The+ orchestrator authorized this owner-vetoable amendment: the nested runtime+ object now carries `contract_version: 4`, adds `not_started`, and exposes a+ CSRF-guarded explicit start route without making the status read mutate state.+ Existing v3 clients with exhaustive health switches fall through their+ unknown-value/default branch until upgraded; no boot-time eager start is added.- Contract tests (implementation plan §5) validate both directions againstthese schemas.diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 33ec195ed..a737142e4 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -1,4 +1,8 @@-"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.4 (2026-07-30 15:36 +08:00).+"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.5 (2026-07-31).++v1.5 changelog (honest lazy-start health):+- ``EngineHealth.NOT_STARTED`` distinguishes an installed runtime that has not+ been demanded in this service lifetime from one that started and went down.v1.4 changelog (ref-keyed cleanup convergence):- ``cleanup_orphaned_oauth_material`` treats an absent credential ref as an@@ -65,6 +69,7 @@ class EngineHealth(str, Enum):OK = "ok"DEGRADED = "degraded"DOWN = "down"+ NOT_STARTED = "not_started"NOT_INSTALLED = "not_installed"diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 41fda4ba2..ddaa71b4d 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -42,7 +42,8 @@ responses without changing the envelope version.| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources}` | Imported sources auto-join eligible follow orders; custom orders stay frozen. || GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |-| GET `/api/models/runtime` | → `RuntimeDependency` status | Managed engine status. |+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object is contract v4; `not_started` is installed lazy-start idleness, not an alarm. |+| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Explicitly starts the managed engine. Uses the existing mutation authentication and CSRF guards; status reads never start it. |The removed global route `PUT /api/models/priority` has no v3 replacement.Ordering is backend-owned through the sources routes.diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex 471cfaaa2..ad92140a5 100644--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json@@ -2,11 +2,12 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/runtime-dependency.schema.json","title": "RuntimeDependency",- "description": "Managed engine dependency manifest + status (spec §8; S3 verdict: generalize the Show Runtime managed-archive installer, effort M; process/health/config stay per-runtime). Pinned values below are the S1 survey result and are normative until the next explicit re-pin. Platform set expanded 2026-07-25 (orchestrator decision after F1 smoke proved linux-arm64 fail-closed blocks regression verification). Avibe-owned mirror remains the L7 pre-GA gate; URLs stay upstream until then.",+ "description": "v4 (2026-07-31 targeted amendment): managed engine dependency manifest + status. The installed lazy-start state is not a failure: not_started means no start has been demanded in this service lifetime; down means a demanded runtime failed or stopped. Pinned manifest values remain normative until the next explicit re-pin.","type": "object",- "required": ["manifest", "status"],+ "required": ["contract_version", "manifest", "status"],"additionalProperties": false,"properties": {+ "contract_version": { "const": 4 },"manifest": {"type": "object","required": ["name", "version", "source_sha", "assets"],@@ -47,13 +48,17 @@"port": { "type": "integer" }}},- "health": { "enum": ["ok", "degraded", "down", "not_installed"] },+ "health": {+ "enum": ["ok", "degraded", "down", "not_started", "not_installed"],+ "description": "not_started is installed and intentionally idle until first demand; down is a runtime that was demanded and is no longer available."+ },"last_check": { "type": ["string", "null"], "format": "date-time" }}}},"examples": [{+ "contract_version": 4,"manifest": {"name": "cliproxyapi","version": "v7.2.95",diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 75e378926..3dbccad25 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -20,6 +20,7 @@ capabilities:- tests/test_model_hub_api.py- tests/test_model_hub_config.py- tests/test_model_hub_resolution.py+ - tests/test_model_hub_runtime.py- id: harness_failure_recoveryname: Harness per-Session failure recoverystatus: activediff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex f2346efcf..008b3aff5 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -7,6 +7,7 @@ capability:- tests/test_model_hub_config.py- tests/test_model_hub_resolution.py- tests/test_model_hub_injection.py+ - tests/test_model_hub_runtime.py- tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py- tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pystatus_legend:@@ -14,6 +15,12 @@ status_legend:partial: unit or contract coverage exists but the cross-lane loop is incompletegap: owned by a later lane or integration passscenarios:+ - id: MH-RUNTIME-001+ name: Service restart reports an installed engine as idle until first demand+ status: partial+ kind: recovery+ layer: unit+ test: tests/test_model_hub_runtime.py::test_mh_runtime_001_service_restart_reports_installed_engine_as_not_started- id: MH-RES-LIVE-001name: Live turn retries an eligible backup before streaming startsstatus: covereddiff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 3be26ad73..de5b4d422 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -33,9 +33,10 @@ from core.handlers.model_hub.service import (ModelHubService,create_default_service,)-from vibe.model_hub_client import ModelHubRemoteService, _decode+from tests.test_ui_remote_access_auth import _remote_peer, _save_configfrom tests.ui_server_test_helpers import csrf_headersfrom vibe import ui_server+from vibe.model_hub_client import ModelHubRemoteService, _decodefrom vibe.ui_server import appCONTRACTS = Path("docs/plans/model-hub-contracts")@@ -105,11 +106,13 @@ class FakeAdapter:self.orphan_cleanup_calls = []self.orphan_cleanup_succeeds = Falseself.cancel_disposition = RetainedMaterialDisposition.NONE+ self.start_calls = 0async def ensure_installed(self):return await self.status()async def start(self):+ self.start_calls += 1return await self.status()async def stop(self):@@ -328,6 +331,204 @@ def test_runtime_status_reports_packaged_engine_manifest(tmp_path):]+def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):+ service, _store, adapter = _service(tmp_path)++ runtime = asyncio.run(service.runtime_start())++ assert adapter.start_calls == 1+ assert runtime["contract_version"] == 4+ assert runtime["status"]["health"] == "ok"+ _assert_valid("runtime-dependency.schema.json", runtime)+++def test_runtime_start_syncs_sources_before_starting_once(tmp_path):+ class OrderedAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.calls = []++ async def sync_sources(self, bindings):+ self.calls.append("sync")+ await super().sync_sources(bindings)++ async def start(self):+ self.calls.append("start")+ return await super().start()++ store = MemoryStore()+ store.config.sources.append(+ ModelHubSourceConfig(+ id="src_runtime01",+ kind="api_key",+ vendor="openai",+ display_name="Runtime source",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="gpt-5", provenance="manual")],+ credential_ref="cred_runtime01",+ )+ )+ adapter = OrderedAdapter()+ service = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ async def start_then_enter_normal_gateway_path():+ runtime = await service.runtime_start()+ await service._ensure_engine_synced()+ return runtime++ runtime = asyncio.run(start_then_enter_normal_gateway_path())++ assert runtime["status"]["health"] == "ok"+ assert adapter.calls == ["sync", "start"]+ assert [binding.source_id for binding in adapter.synced[0]] == ["src_runtime01"]+++ ("idle_health", "installed_version", "verified", "recovered_health"),+ [+ (EngineHealth.NOT_STARTED, "v7.2.95", True, "not_started"),+ (EngineHealth.NOT_INSTALLED, None, False, "not_installed"),+ ],+)+def test_runtime_start_sync_failure_is_reported_as_down(+ tmp_path,+ idle_health,+ installed_version,+ verified,+ recovered_health,+):+ class IdleAdapter(FakeAdapter):+ async def status(self):+ return EngineStatus(+ health=idle_health,+ installed_version=installed_version,+ verified=verified,+ listen_host="127.0.0.1",+ listen_port=None,+ last_check_iso=None,+ )++ store = MemoryStore()+ store.config.sources.append(+ ModelHubSourceConfig(+ id="src_runtime01",+ kind="api_key",+ vendor="openai",+ display_name="Runtime source",+ protocol="openai_responses",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="gpt-5", provenance="manual")],+ credential_ref="cred_runtime01",+ )+ )+ adapter = IdleAdapter()+ adapter.fail_sync = True+ service = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ with pytest.raises(ModelHubError, match="engine_down"):+ asyncio.run(service.runtime_start())+ runtime = asyncio.run(service.runtime_status())++ assert adapter.start_calls == 0+ assert runtime["status"]["health"] == "down"++ adapter.fail_sync = False+ config = store.load()+ asyncio.run(service._commit_synced(config, service._clone_config(config)))++ recovered = asyncio.run(service.runtime_status())+ assert recovered["status"]["health"] == recovered_health+++def test_runtime_start_in_progress_remains_not_started(tmp_path):+ class IdleAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.started = False++ async def start(self):+ self.started = True+ return await super().start()++ async def status(self):+ return EngineStatus(+ health=(EngineHealth.OK if self.started else EngineHealth.NOT_STARTED),+ installed_version="v7.2.95",+ verified=True,+ listen_host="127.0.0.1",+ listen_port=15220 if self.started else None,+ last_check_iso=None,+ )++ service = ModelHubService(+ store=MemoryStore(),+ adapter=IdleAdapter(),+ events=BoundedEventLog(tmp_path / "events.json"),+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ )++ async def status_while_start_waits_for_sync():+ await service._mutation_lock.acquire()+ start = asyncio.create_task(service.runtime_start())+ await asyncio.sleep(0)+ assert not start.done()+ pending = await service.runtime_status()+ service._mutation_lock.release()+ started = await start+ return pending, started++ pending, started = asyncio.run(status_while_start_waits_for_sync())++ assert pending["status"]["health"] == "not_started"+ assert started["status"]["health"] == "ok"+++def test_runtime_start_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": 4, "status": {"health": "ok"}}++ monkeypatch.setattr(model_hub_client, "_rpc", rpc)++ runtime = asyncio.run(ModelHubRemoteService().runtime_start())++ assert runtime["status"]["health"] == "ok"+ assert calls == [("runtime_start", None)]+++def test_runtime_start_is_allowlisted_by_controller_rpc(tmp_path):+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc++ service, _store, adapter = _service(tmp_path)++ runtime = asyncio.run(dispatch_model_hub_rpc(service, "runtime_start", {}))++ assert runtime["status"]["health"] == "ok"+ assert adapter.start_calls == 1++def test_runtime_status_reports_observed_not_installed_state(tmp_path):class NotInstalledAdapter(FakeAdapter):async def start(self):@@ -542,6 +743,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/start"),],)def test_disabled_model_hub_rest_surface_returns_feature_disabled_without_runtime_work(@@ -3081,6 +3283,44 @@ def test_model_hub_mutations_use_existing_origin_and_csrf_guards(monkeypatch, tmassert model_response.get_json() == config_response.get_json()+def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, tmp_path):+ service, _, adapter = _service(tmp_path)+ 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/start", base_url=base_url)++ assert rejected.status_code == 403+ assert adapter.start_calls == 0++ accepted = client.post(+ "/api/models/runtime/start",+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert accepted.status_code == 200+ runtime = accepted.get_json()["runtime"]+ assert adapter.start_calls == 1+ assert runtime["contract_version"] == 4+ _assert_valid("runtime-dependency.schema.json", runtime)+++def test_runtime_start_route_requires_remote_session(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)++ response = app.test_client().post(+ "/api/models/runtime/start",+ base_url="https://alex.avibe.bot",+ environ_base=_remote_peer(),+ )++ assert response.status_code == 401+ assert response.get_json()["error"] == "remote_access_login_required"++def test_native_source_configuration_does_not_require_l1_engine(tmp_path):store = MemoryStore()native = FakeAdapter()diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 7eaa72fc7..ffcb7c082 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -31,7 +31,7 @@ from core.handlers.model_hub.classification import classify_outcomefrom core.handlers.model_hub.request import ModelHubRequestfrom vibe.model_hub_runtime import client as client_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter-from vibe.model_hub_runtime.client import EngineClient, EngineClientError+from vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnectionfrom vibe.model_hub_runtime.config import write_engine_configfrom vibe.model_hub_runtime.installer import EngineRuntimeManagerfrom vibe.model_hub_runtime.environment import engine_subprocess_environment@@ -432,6 +432,34 @@ def test_engine_installer_is_idempotent_and_rejects_tampered_archive(tmp_path: Passert rejected["reason"] == "model_hub_engine_archive_checksum_mismatch"+def test_engine_status_rehashes_binary_only_after_file_identity_changes(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ archive, binary = _write_fixture_archive(tmp_path / "fixture")+ manifest = _write_fixture_manifest(tmp_path / "fixture", archive, binary)+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)+ installed = manager.ensure()+ binary_path = Path(installed["path"])+ original_file_sha256 = managed_runtime.file_sha256+ hashed_paths: list[Path] = []++ def tracked_file_sha256(path: Path) -> str:+ hashed_paths.append(path)+ return original_file_sha256(path)++ monkeypatch.setattr(managed_runtime, "file_sha256", tracked_file_sha256)++ assert manager.status()["installed"] is True+ assert manager.status()["installed"] is True+ assert hashed_paths == [binary_path]++ binary_path.write_bytes(binary_path.read_bytes() + b"\n# tampered\n")++ assert manager.status()["installed"] is False+ assert hashed_paths == [binary_path, binary_path]++def test_engine_version_check_uses_minimal_environment(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -941,6 +969,60 @@ def _fixture_supervisor()+ ("installed", "start_attempted", "running", "healthy", "expected"),+ [+ (False, False, False, False, "not_installed"),+ (False, True, False, False, "down"),+ (True, False, False, False, "not_started"),+ (True, True, False, False, "down"),+ (True, True, True, False, "degraded"),+ (True, True, True, True, "ok"),+ ],+)+def test_supervisor_status_distinguishes_all_runtime_health_states(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ installed: bool,+ start_attempted: bool,+ running: bool,+ healthy: bool,+ expected: str,+) -> None:+ installer = SimpleNamespace(+ status=lambda: {"installed": installed, "version": "v7.2.95" if installed else None},+ contract_manifest=lambda: {"name": "cliproxyapi", "version": "v7.2.95", "assets": []},+ )+ supervisor = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / expected),+ )+ supervisor._start_attempted = start_attempted+ if running:+ supervisor._process = SimpleNamespace(poll=lambda: None)+ supervisor._connection = EngineConnection("http://127.0.0.1:15220", "management", "gateway")+ monkeypatch.setattr(supervisor, "_healthy_locked", lambda: healthy)++ assert supervisor.status()["status"]["health"] == expected+++def test_supervisor_failed_first_install_reports_down(tmp_path: Path) -> None:+ installer = SimpleNamespace(+ ensure=lambda: {"ok": False, "reason": "fixture_install_failed"},+ status=lambda: {"installed": False, "version": None},+ contract_manifest=lambda: {"name": "cliproxyapi", "version": "v7.2.95", "assets": []},+ )+ supervisor = EngineSupervisor(+ installer=installer,+ state_store=EngineStateStore(tmp_path / "failed-install"),+ )++ with pytest.raises(EngineUnavailableError, match="models.engine.install_failed"):+ supervisor.ensure_running()++ assert supervisor.status()["status"]["health"] == "down"++def test_supervisor_starts_checks_health_and_stops_mock_engine(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -959,6 +1041,7 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(monkeypatch.setenv("PATH", "/usr/bin:/bin")supervisor, store = _fixture_supervisor(tmp_path, process_factory=spawn)+ assert supervisor.status()["status"]["health"] == "not_started"first = supervisor.ensure_running()assert first.base_url.startswith("http://127.0.0.1:")assert "MANAGEMENT_PASSWORD" not in captured_env@@ -980,6 +1063,27 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(supervisor.stop()+def test_mh_runtime_001_service_restart_reports_installed_engine_as_not_started(+ tmp_path: Path,+) -> None:+ """MH-RUNTIME-001: a service restart restores lazy-start idleness, never down."""++ before_restart, store = _fixture_supervisor(tmp_path)+ before_restart.ensure_running()+ observed_health = [before_restart.status()["status"]["health"]]+ before_restart.stop()++ after_restart = EngineSupervisor(+ installer=before_restart.installer,+ state_store=store,+ startup_timeout=5,+ )+ observed_health.append(after_restart.status()["status"]["health"])++ assert observed_health == ["ok", "not_started"]+ assert "down" not in observed_health++def test_adapter_enforces_origin_and_returns_raw_outcomes(tmp_path: Path) -> None:async def run() -> None:supervisor, store = _fixture_supervisor(tmp_path)diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsxindex 6db844805..280e7af75 100644--- a/ui/src/components/settings/models/AgentCard.tsx+++ b/ui/src/components/settings/models/AgentCard.tsx@@ -35,6 +35,7 @@ import {modelChainKey,modelHasOffOrderSupplier,modelNeedsAttention,+ runtimeHealthNeedsAttention,type ModelChainIndex,type ModelChainRead,} from './modelRows';@@ -291,7 +292,8 @@ const ModelRow: React.FC<{const selected = agent.selected_model_id === modelId;const head = runnableHead(read);const headIndex = read?.kind === 'ready' && head ? read.chain.chain.indexOf(head) : -1;- const runtimeBlocked = head?.channel === 'hub' && Boolean(runtime && runtime.status.health !== 'ok');+ const runtimeBlocked = head?.channel === 'hub'+ && Boolean(runtime && runtimeHealthNeedsAttention(runtime.status.health));const needsAttention = modelNeedsAttention(agent, modelId, read, runtime);const recoversAutomatically = read?.kind === 'ready' && read.chain.supply_state === 'waiting';const needsAction = needsAttention && !recoversAutomatically;diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxnew file mode 100644index 000000000..50c1859af--- /dev/null+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -0,0 +1,242 @@+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import { createInstance } from 'i18next';+import { renderToStaticMarkup } from 'react-dom/server';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { describe, expect, it, vi } from 'vitest';++import zh from '../../../i18n/zh.json';+import {+ ModelsPageActions,+ pollRuntimeStatus,+ RuntimeNotStartedAction,+ startRuntimeWithStatusRefresh,+} from './SettingsModelsPage';+import type { RuntimeDependency } from './types';++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'zh',+ resources: { zh: { translation: zh } },+ interpolation: { escapeValue: false },+});++const render = (starting = false): string => renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <RuntimeNotStartedAction starting={starting} onStart={vi.fn()} />+ </I18nextProvider>,+);++const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({+ contract_version: 4,+ manifest: { name: 'cliproxyapi', version: '1', source_sha: 'sha', assets: [] },+ status: { installed_version: '1', verified: true, listening: null, health, last_check: null },+});++describe('installed but not-started Model Hub runtime', () => {+ it('renders neutral lazy-start copy with a quiet explicit start affordance', () => {+ const html = render();++ expect(html).toContain(zh.settings.models.runtime.notStarted);+ expect(html).toContain(zh.settings.models.runtime.startNow);+ expect(html).toContain('text-muted');+ expect(html).not.toContain(zh.settings.models.modelStatus.runtime);+ });++ it('shows a disabled pending state while the explicit start request runs', () => {+ const html = render(true);++ expect(html).toContain(zh.settings.models.runtime.starting);+ expect(html).toContain('disabled=""');+ });++ it('refreshes authoritative health after an explicit start fails', async () => {+ const api = {+ startRuntime: vi.fn().mockRejectedValue(new Error('start failed')),+ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('down')),+ };++ const result = await startRuntimeWithStatusRefresh(api);++ expect(result).toEqual({ runtime: runtime('down'), failed: true });+ expect(api.startRuntime).toHaveBeenCalledOnce();+ expect(api.getRuntimeStatus).toHaveBeenCalledOnce();+ });++ it('drops the stale idle snapshot when post-failure health cannot be read', async () => {+ const api = {+ startRuntime: vi.fn().mockRejectedValue(new Error('start failed')),+ getRuntimeStatus: vi.fn().mockRejectedValue(new Error('status failed')),+ };++ await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({ runtime: null, failed: true });+ });++ it('accepts an authoritative healthy read after the start response is lost', async () => {+ const api = {+ startRuntime: vi.fn().mockRejectedValue(new Error('response lost')),+ getRuntimeStatus: vi.fn().mockResolvedValue(runtime('ok')),+ };++ await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({+ runtime: runtime('ok'),+ failed: false,+ });+ });++ it('treats an unhealthy successful start response as failed', async () => {+ const api = {+ startRuntime: vi.fn().mockResolvedValue(runtime('degraded')),+ getRuntimeStatus: vi.fn(),+ };++ await expect(startRuntimeWithStatusRefresh(api)).resolves.toEqual({+ runtime: runtime('degraded'),+ failed: true,+ });+ expect(api.getRuntimeStatus).not.toHaveBeenCalled();+ });++ it('surfaces an automatic runtime transition on the next idle poll', async () => {+ vi.useFakeTimers();+ try {+ const nextRuntime = runtime('ok');+ const api = { getRuntimeStatus: vi.fn().mockResolvedValue(nextRuntime) };+ const onRuntime = vi.fn();+ const stop = pollRuntimeStatus(api, onRuntime, 100);++ await vi.advanceTimersByTimeAsync(100);++ expect(onRuntime).toHaveBeenCalledOnce();+ expect(onRuntime).toHaveBeenCalledWith(nextRuntime);+ stop();+ } finally {+ vi.useRealTimers();+ }+ });++ it('polls read-only health while idle and cancels stale async writes', async () => {+ vi.useFakeTimers();+ try {+ let resolveStatus: ((value: RuntimeDependency) => void) | undefined;+ const api = {+ getRuntimeStatus: vi.fn().mockImplementation(() => new Promise<RuntimeDependency>((resolve) => {+ resolveStatus = resolve;+ })),+ };+ const onRuntime = vi.fn();+ const stop = pollRuntimeStatus(api, onRuntime, 100);++ await vi.advanceTimersByTimeAsync(100);+ expect(api.getRuntimeStatus).toHaveBeenCalledOnce();++ await vi.advanceTimersByTimeAsync(500);+ expect(api.getRuntimeStatus).toHaveBeenCalledOnce();++ stop();+ resolveStatus?.(runtime('ok'));+ await Promise.resolve();+ expect(onRuntime).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(100);+ expect(api.getRuntimeStatus).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps real configuration issues visible beside lazy-start status', () => {+ const html = renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ModelsPageActions+ runtimeHealth="not_started"+ startingRuntime={false}+ issueCount={2}+ issuesOnly={false}+ onStartRuntime={vi.fn()}+ onFocusIssues={vi.fn()}+ />+ </I18nextProvider>,+ );++ expect(html).toContain(zh.settings.models.runtime.notStarted);+ expect(html).toContain(i18n.t('settings.models.status.needsAction', { count: 2 }));+ });++ it('offers installation and transition polling for a pristine missing runtime', () => {+ const html = renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ModelsPageActions+ runtimeHealth="not_installed"+ startingRuntime={false}+ issueCount={2}+ issuesOnly={false}+ onStartRuntime={vi.fn()}+ onFocusIssues={vi.fn()}+ />+ </I18nextProvider>,+ );+ const here = dirname(fileURLToPath(import.meta.url));+ const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');++ expect(html).toContain(zh.settings.models.runtime.startNow);+ expect(html).toContain(i18n.t('settings.models.status.needsAction', { count: 2 }));+ expect(html).not.toContain(zh.settings.models.runtime.notStarted);+ expect(page).toMatch(/runtimeCanRecover[\s\S]+runtimeHealth === 'not_installed'/);+ });++ it('keeps the explicit start action after an unhealthy attempt', () => {+ for (const health of ['down', 'degraded'] as const) {+ const html = renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ModelsPageActions+ runtimeHealth={health}+ startingRuntime={false}+ issueCount={2}+ issuesOnly={false}+ onStartRuntime={vi.fn()}+ onFocusIssues={vi.fn()}+ />+ </I18nextProvider>,+ );++ expect(html).toContain(zh.settings.models.runtime.startNow);+ expect(html).toContain(i18n.t('settings.models.status.needsAction', { count: 2 }));+ expect(html).not.toContain(zh.settings.models.runtime.notStarted);+ }+ });++ it('keeps retry and recovery wiring when both start requests fail', () => {+ const html = renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ModelsPageActions+ runtimeHealth={null}+ runtimeRecoveryPending+ startingRuntime={false}+ issueCount={0}+ issuesOnly={false}+ onStartRuntime={vi.fn()}+ onFocusIssues={vi.fn()}+ />+ </I18nextProvider>,+ );+ const here = dirname(fileURLToPath(import.meta.url));+ const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');++ expect(html).toContain(zh.settings.models.runtime.startNow);+ expect(html).not.toContain(zh.settings.models.status.allHealthy);+ expect(page).toMatch(/runtimeRecoveryPending\n\s+\|\| runtimeHealth === 'not_started'/);+ });++ it('wires recoverable runtime states to the POST-backed start action', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const page = readFileSync(join(here, 'SettingsModelsPage.tsx'), 'utf8');+ const api = readFileSync(join(here, 'modelsApi.ts'), 'utf8');++ expect(page).toMatch(/runtimeNotStarted\n\s+\|\| runtimeHealth === 'not_installed'/);+ expect(page).toMatch(/startRuntimeWithStatusRefresh\(modelsApi\)/);+ expect(api).toMatch(/'\/api\/models\/runtime\/start', jsonInit\('POST'\)/);+ });+});diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 951a824ca..f587a152d 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -1,7 +1,7 @@// Model-centric settings surface. The page reads model chains from the server,// hosts shared source repair journeys, and serializes Agent writes by backend.import * as React from 'react';-import { CheckCircle2, ListFilter, TriangleAlert } from 'lucide-react';+import { CheckCircle2, ListFilter, LoaderCircle, Play, TriangleAlert } from 'lucide-react';import { useTranslation } from 'react-i18next';import { Button } from '@/components/ui/button';@@ -32,7 +32,7 @@ import {} from './eventFeed';import { AddCustomModelDialog } from './menus/AddCustomModelDialog';import { OpenCodeMenuDrawer } from './menus/OpenCodeMenuDrawer';-import { modelsApi } from './modelsApi';+import { modelsApi, type ModelsApi } from './modelsApi';import { connectOutcome, isSupplyWarning } from './sufficiency';import {manualModelSources,@@ -67,6 +67,108 @@ const ModelStatusButton: React.FC<{ issueCount: number; active: boolean; onClick);};+export const RuntimeNotStartedAction: React.FC<{+ starting: boolean;+ showIdleCopy?: boolean;+ onStart: () => void;+}> = ({+ starting,+ showIdleCopy = true,+ onStart,+}) => {+ const { t } = useTranslation();+ return (+ <div className="flex max-w-[calc(100vw-2rem)] flex-wrap items-center justify-end gap-2 text-[13px] text-muted sm:max-w-none">+ {showIdleCopy && <span>{t('settings.models.runtime.notStarted')}</span>}+ <Button variant="secondary" size="xs" onClick={onStart} disabled={starting}>+ {starting ? <LoaderCircle className="animate-spin" /> : <Play />}+ {t(starting ? 'settings.models.runtime.starting' : 'settings.models.runtime.startNow')}+ </Button>+ </div>+ );+};++export const ModelsPageActions: React.FC<{+ runtimeHealth: RuntimeDependency['status']['health'] | null;+ runtimeRecoveryPending?: boolean;+ startingRuntime: boolean;+ issueCount: number;+ issuesOnly: boolean;+ onStartRuntime: () => void;+ onFocusIssues: () => void;+}> = ({+ runtimeHealth,+ runtimeRecoveryPending = false,+ startingRuntime,+ issueCount,+ issuesOnly,+ onStartRuntime,+ onFocusIssues,+}) => {+ const runtimeNotStarted = runtimeHealth === 'not_started';+ const runtimeStartable = runtimeRecoveryPending+ || runtimeNotStarted+ || runtimeHealth === 'not_installed'+ || runtimeHealth === 'down'+ || runtimeHealth === 'degraded';+ if (!runtimeStartable) {+ return <ModelStatusButton issueCount={issueCount} active={issuesOnly} onClick={onFocusIssues} />;+ }+ return (+ <div className="flex max-w-[calc(100vw-2rem)] flex-wrap items-center justify-end gap-2 sm:max-w-none">+ {issueCount > 0 && (+ <ModelStatusButton issueCount={issueCount} active={issuesOnly} onClick={onFocusIssues} />+ )}+ <RuntimeNotStartedAction+ starting={startingRuntime}+ showIdleCopy={runtimeNotStarted}+ onStart={onStartRuntime}+ />+ </div>+ );+};++export async function startRuntimeWithStatusRefresh(+ api: Pick<ModelsApi, 'startRuntime' | 'getRuntimeStatus'>,+): Promise<{ runtime: RuntimeDependency | null; failed: boolean }> {+ try {+ const runtime = await api.startRuntime();+ return { runtime, failed: runtime.status.health !== 'ok' };+ } catch {+ // A failed start changes supervisor health. Read that authoritative state+ // back so the persistent page does not keep presenting lazy-start idleness.+ const runtime = await api.getRuntimeStatus().catch(() => null);+ return { runtime, failed: runtime?.status.health !== 'ok' };+ }+}++export function pollRuntimeStatus(+ api: Pick<ModelsApi, 'getRuntimeStatus'>,+ onRuntime: (runtime: RuntimeDependency) => void,+ intervalMs = 5_000,+): () => void {+ let active = true;+ let timeout: ReturnType<typeof globalThis.setTimeout> | undefined;+ const schedule = () => {+ timeout = globalThis.setTimeout(() => void refresh(), intervalMs);+ };+ const refresh = async () => {+ try {+ const runtime = await api.getRuntimeStatus();+ if (active) onRuntime(runtime);+ } catch {+ // Keep the last authoritative snapshot and try again on the next tick.+ } finally {+ if (active) schedule();+ }+ };+ schedule();+ return () => {+ active = false;+ if (timeout !== undefined) globalThis.clearTimeout(timeout);+ };+}+const CHAIN_READ_CONCURRENCY = 6;const readModelChains = async (agents: AgentSupply[]): Promise<ModelChainIndex> => {@@ -117,6 +219,8 @@ export const SettingsModelsPage: React.FC = () => {const [feed, setFeed] = React.useState<EventFeed>(emptyFeed);const [loadingEvents, setLoadingEvents] = React.useState(false);const [runtime, setRuntime] = React.useState<RuntimeDependency | null>(null);+ const [startingRuntime, setStartingRuntime] = React.useState(false);+ const [runtimeRecoveryPending, setRuntimeRecoveryPending] = React.useState(false);const [loading, setLoading] = React.useState(true);const [loadError, setLoadError] = React.useState<string | null>(null);const [connecting, setConnecting] = React.useState<string | null>(null);@@ -169,6 +273,21 @@ export const SettingsModelsPage: React.FC = () => {};}, []);+ const runtimeHealth = runtime?.status.health ?? null;+ React.useEffect(() => {+ const runtimeCanRecover = runtimeRecoveryPending+ || runtimeHealth === 'not_started'+ || runtimeHealth === 'not_installed'+ || runtimeHealth === 'down'+ || runtimeHealth === 'degraded';+ if (!runtimeCanRecover || startingRuntime) return undefined;+ return pollRuntimeStatus(modelsApi, (nextRuntime) => {+ if (!aliveRef.current) return;+ setRuntime(nextRuntime);+ setRuntimeRecoveryPending(false);+ });+ }, [runtimeHealth, runtimeRecoveryPending, startingRuntime]);+// 最近切换 is re-read here with the rows, because the writes this refresh exists// for are the writes that FILE events: a failing 试跑 cools its head down through// `_cooldown`, which records the `cooldown` row that explains the state change@@ -411,6 +530,20 @@ export const SettingsModelsPage: React.FC = () => {requestAnimationFrame(() => agentSectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }));};+ const startRuntime = async () => {+ setStartingRuntime(true);+ setRuntimeRecoveryPending(false);+ try {+ const result = await startRuntimeWithStatusRefresh(modelsApi);+ if (!aliveRef.current) return;+ setRuntime(result.runtime);+ setRuntimeRecoveryPending(result.runtime === null);+ if (result.failed) showToast(t('settings.models.errors.startFailed') as string, 'error');+ } finally {+ if (aliveRef.current) setStartingRuntime(false);+ }+ };+return (<SettingsPageShellactiveTab="models"@@ -418,7 +551,15 @@ export const SettingsModelsPage: React.FC = () => {subtitle={t('settings.models.subtitle')}actions={!loading && !loadError ? (- <ModelStatusButton issueCount={issueCount} active={issuesOnly} onClick={focusIssues} />+ <ModelsPageActions+ runtimeHealth={runtimeHealth}+ runtimeRecoveryPending={runtimeRecoveryPending}+ startingRuntime={startingRuntime}+ issueCount={issueCount}+ issuesOnly={issuesOnly}+ onStartRuntime={() => void startRuntime()}+ onFocusIssues={focusIssues}+ />) : undefined}>diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex f5c40cee3..4bff3fd7d 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -357,6 +357,7 @@ function olderHistory(count: number): ResolutionEvent[] {export function buildMockRuntime(): RuntimeDependency {return {+ contract_version: 4,manifest: {name: 'cliproxyapi',version: 'v7.2.95',diff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.tsindex 9625f3db1..7a4c3825b 100644--- a/ui/src/components/settings/models/modelRows.test.ts+++ b/ui/src/components/settings/models/modelRows.test.ts@@ -55,6 +55,7 @@ const read = (over: Partial<Extract<ModelChainRead, { kind: 'ready' }>['chain']>});const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({+ contract_version: 4,manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a', assets: [] },status: { health, verified: health === 'ok' },});@@ -170,6 +171,7 @@ describe('model row projection', () => {it('attributes runtime failure only to a model whose current head uses the managed channel', () => {expect(modelNeedsAttention(agent(), 'builtin-model', read(), runtime('down'))).toBe(true);+ expect(modelNeedsAttention(agent(), 'builtin-model', read(), runtime('not_started'))).toBe(false);const native = read({ chain: [{source_id: 'src_native',channel: 'native_cli',diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsindex 42aab441e..68e8f8df3 100644--- a/ui/src/components/settings/models/modelRows.ts+++ b/ui/src/components/settings/models/modelRows.ts@@ -16,6 +16,10 @@ export type ModelChainRequest = {export const modelChainKey = (backend: AgentBackend, modelId: string): string =>`${backend}\u0000${modelId}`;+/** Lazy-start idleness is runnable-on-demand; only actual failures block Hub rows. */+export const runtimeHealthNeedsAttention = (health: RuntimeDependency['status']['health']): boolean =>+ health !== 'ok' && health !== 'not_started';+/** Manual inventory is a credential-backed capability; subscriptions are read-only. */export function manualModelSources(sources: Source[]): Source[] {return sources.filter((source) => source.kind === 'api_key');@@ -104,7 +108,7 @@ export function modelNeedsAttention(if (read?.kind === 'error') return true;if (read?.kind === 'ready') {const head = read.chain.chain.find((link) => link.runnable);- if (head?.channel === 'hub' && runtime && runtime.status.health !== 'ok') return true;+ if (head?.channel === 'hub' && runtime && runtimeHealthNeedsAttention(runtime.status.health)) return true;return read.chain.supply_state !== 'ok';}return agent.model_supply?.find((model) => model.model_id === modelId)?.chain_length === 0;diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex 591abfaf0..cbfef6b9e 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -138,6 +138,7 @@ export type ModelsApi = {/** `before` is an event id cursor (「查看全部」 pagination). */listEvents(limit?: number, before?: string): Promise<ResolutionEvent[]>;getRuntimeStatus(): Promise<RuntimeDependency>;+ startRuntime(): Promise<RuntimeDependency>;/** `experimentalConsent` MUST be true for a consent-gated hub-held* subscription connect, or the server returns consent_required. */startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean): Promise<OAuthFlow>;@@ -393,6 +394,7 @@ const liveApi: ModelsApi = {`/api/models/events?limit=${limit}${before ? `&before=${encodeURIComponent(before)}` : ''}`,).then((r) => r.events),getRuntimeStatus: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/status').then((r) => (r.runtime ?? r) as RuntimeDependency),+ startRuntime: () => call<{ runtime?: RuntimeDependency } & RuntimeDependency>('/api/models/runtime/start', jsonInit('POST')).then((r) => (r.runtime ?? r) as RuntimeDependency),startOAuth: (vendor, channel, experimentalConsent) =>call<{ flow?: OAuthFlow } & OAuthFlow>('/api/models/oauth/start',@@ -985,6 +987,12 @@ class MockStore {return delay(structuredClone(this.runtime));}+ startRuntime() {+ this.runtime.status.health = 'ok';+ this.runtime.status.listening = { host: '127.0.0.1', port: 15220 };+ return delay(structuredClone(this.runtime));+ }+startOAuth(vendor: string, channel: SupplyChannel, experimentalConsent?: boolean) {// Mirror the server: a hub-held subscription connect requires recorded consent.if (channel === 'hub' && !experimentalConsent) throw new ApiCallError('consent_required');@@ -1225,6 +1233,7 @@ const mockApi: ModelsApi = {applyMigration: (itemIds) => mockStore.applyMigration(itemIds),listEvents: (limit, before) => mockStore.listEvents(limit, before),getRuntimeStatus: () => mockStore.getRuntimeStatus(),+ startRuntime: () => mockStore.startRuntime(),startOAuth: (vendor, channel, experimentalConsent) => mockStore.startOAuth(vendor, channel, experimentalConsent),getOAuthStatus: (flowId) => mockStore.getOAuthStatus(flowId),submitOAuth: (flowId, value) => mockStore.submitOAuth(flowId, value),diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 9496500e4..99f96ec91 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -462,9 +462,10 @@ export type OAuthFlow = {};// ── runtime-dependency.schema.json ──────────────────────────────────────-export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_installed';+export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_started' | 'not_installed';export type RuntimeDependency = {+ contract_version: 4;manifest: {name: 'cliproxyapi';version: string;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex d19f42ba0..fb885ce0f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -688,7 +688,13 @@"direct": "Direct"},"errors": {- "engineDown": "Model engine is not ready yet; try again shortly"+ "engineDown": "Model engine is not ready yet; try again shortly",+ "startFailed": "Model engine could not be started"+ },+ "runtime": {+ "notStarted": "Not started · starts automatically on first use",+ "startNow": "Start now",+ "starting": "Starting"},"experimental": "Experimental","agents": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex cba8d5777..dc8fec7b6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -688,7 +688,13 @@"direct": "直连 Direct"},"errors": {- "engineDown": "模型引擎未就绪,请稍后重试"+ "engineDown": "模型引擎未就绪,请稍后重试",+ "startFailed": "模型引擎启动失败"+ },+ "runtime": {+ "notStarted": "未启动 · 首次使用时自动启动",+ "startNow": "立即启动",+ "starting": "正在启动"},"experimental": "实验","agents": {diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex c4b9d392c..07bb5ae4a 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -179,3 +179,6 @@ class ModelHubRemoteService:async def runtime_status(self) -> dict:return await _rpc("runtime_status")++ async def runtime_start(self) -> dict:+ return await _rpc("runtime_start")diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.pyindex 6535a8012..4866af1ee 100644--- a/vibe/model_hub_runtime/installer.py+++ b/vibe/model_hub_runtime/installer.py@@ -58,10 +58,66 @@ 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 = Nonedef resolve_engine_path(self) -> Path | None:return self.resolve_binary()+ def _verified_manifest_binary(+ self,+ install_dir: Path,+ manifest: ManagedRuntimeManifest,+ archive: ManagedRuntimeArchive,+ ) -> Path | None:+ binary = install_dir / archive.bin_path+ metadata = install_dir / self.spec.metadata_filename+ cache_key = self._verification_cache_key(binary, metadata, manifest, archive)+ cached = self._verified_binary_cache+ if cache_key is not None and cached is not None and cached[0] == cache_key:+ return cached[1]++ verified = super()._verified_manifest_binary(install_dir, manifest, archive)+ if verified is None:+ self._verified_binary_cache = None+ return None++ cache_key = self._verification_cache_key(verified, metadata, manifest, archive)+ self._verified_binary_cache = (cache_key, verified) if cache_key is not None else None+ return verified++ @staticmethod+ def _verification_cache_key(+ binary: Path,+ metadata: Path,+ manifest: ManagedRuntimeManifest,+ archive: ManagedRuntimeArchive,+ ) -> tuple[object, ...] | None:+ try:+ binary_stat = binary.stat()+ metadata_stat = metadata.stat()+ except OSError:+ return None++ return (+ manifest.digest,+ manifest.runtime_version,+ archive.platform,+ archive.sha256,+ archive.binary_sha256,+ archive.bin_path,+ binary_stat.st_dev,+ binary_stat.st_ino,+ binary_stat.st_mode,+ binary_stat.st_size,+ binary_stat.st_mtime_ns,+ binary_stat.st_ctime_ns,+ metadata_stat.st_dev,+ metadata_stat.st_ino,+ metadata_stat.st_size,+ metadata_stat.st_mtime_ns,+ metadata_stat.st_ctime_ns,+ )+def contract_manifest(self) -> dict[str, Any]:manifest = self._load_manifest(allow_network=False)if manifest is None:diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.pyindex 4738a0926..ab2df29aa 100644--- a/vibe/model_hub_runtime/supervisor.py+++ b/vibe/model_hub_runtime/supervisor.py@@ -54,6 +54,7 @@ class EngineSupervisor:self._process: subprocess.Popen[bytes] | None = Noneself._connection: EngineConnection | None = Noneself._last_check: str | None = None+ self._start_attempted = Falsedef ensure_running(self) -> EngineConnection:with self._lock:@@ -97,9 +98,9 @@ class EngineSupervisor:listening = {"host": "127.0.0.1", "port": parsed_port}health = "ok" if self._healthy_locked() else "degraded"elif installed:- health = "down"+ health = "down" if self._start_attempted else "not_started"else:- health = "not_installed"+ health = "down" if self._start_attempted else "not_installed"return {"manifest": self.installer.contract_manifest(),"status": {@@ -122,6 +123,7 @@ class EngineSupervisor:return EngineClient(self._connection)def _start_locked(self) -> EngineConnection:+ self._start_attempted = Trueinstall = self.installer.ensure()if not install.get("ok"):reason = str(install.get("reason") or "engine_install_failed")diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 856e487bf..b74337bab 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3484,6 +3484,16 @@ async def model_hub_runtime_status():return _model_hub_error(exc)[email protected]("/api/models/runtime/start", methods=["POST"])+async def model_hub_runtime_start():+ from core.handlers.model_hub import ModelHubError++ try:+ return _model_hub_success(runtime=await _model_hub_service().runtime_start())+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/platforms", methods=["GET"])def platforms_get():from vibe import api