Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

test(model-hub): seed offline engine archives (#1826)

Max969fdc739ec3
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index a87f8edaa..a76f57f15 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -18,6 +18,7 @@ Out of scope (documented, not dropped silently):
- Runtime: hermetic `AVIBE_HOME` under the test dir; `VIBE_MODEL_HUB_ENABLED=1`. Docker `tests/e2e` service with `command: ["full"]` (controller + UI in one process pair) or an equivalent local hermetic run; whichever the implementing lane proves stable first.
- Engine binary: no GitHub egress in CI. Use `VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH` / `VIBE_MODEL_HUB_ENGINE_OFFLINE` (`vibe/model_hub_runtime/installer.py:105-109`) with the pinned cliproxyapi v7.2.95 assets vendored per platform (linux-amd64/arm64, darwin-arm64/x64).
+- Offline archive seeding: when the selected manifest asset uses `file://`, the harness verifies its declared size and SHA-256, then copies it into the hermetic `$AVIBE_HOME/runtime/model-hub/engine/downloads/` cache before spawning child processes. `VIBE_MODEL_HUB_ENGINE_OFFLINE=1` remains set, and non-file assets are never fetched.
- **Mock upstream provider** (new test fixture, `tests/e2e/drivers/mock_llm_upstream.py`): implements, per protocol — `POST /v1/messages`, `POST /v1/responses`, `POST /v1/chat/completions`, `GET /v1/models` — with:
- configurable model inventory (ids only, plus Anthropic-style `display_name` and relay-style `context_length` extensions to prove they are dropped, B-list);
- auth modes: accept / 401 / 403(banned-pattern) / 402 / 429 / quota-message / 5xx;
diff --git a/tests/e2e/drivers/model_hub_app.py b/tests/e2e/drivers/model_hub_app.py
index 1c560c9f2..c49ec55fd 100644
--- a/tests/e2e/drivers/model_hub_app.py
+++ b/tests/e2e/drivers/model_hub_app.py
@@ -3,9 +3,11 @@
from __future__ import annotations
import http.cookiejar
+import hashlib
import json
import logging
import os
+import shutil
import signal
import socket
import subprocess
@@ -16,11 +18,13 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping
from urllib.error import HTTPError, URLError
+from urllib.parse import urlparse
from urllib.request import (
HTTPCookieProcessor,
ProxyHandler,
Request,
build_opener,
+ url2pathname,
)
import psutil
@@ -28,6 +32,7 @@ import psutil
_MISSING = object()
_MUTATION_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
+_ENGINE_MANIFEST_PATH_ENV = "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH"
_SAFE_INHERITED_ENV = (
"LANG",
"LC_ALL",
@@ -35,6 +40,7 @@ _SAFE_INHERITED_ENV = (
"SSL_CERT_DIR",
"SSL_CERT_FILE",
"TZ",
+ _ENGINE_MANIFEST_PATH_ENV,
)
_UI_PORT_START_ATTEMPTS = 3
_OWNED_PROCESS_GRACE_SECONDS = 3.0
@@ -249,6 +255,136 @@ class ModelHubTestApp:
env.update(extra_env)
return env
+ def _seed_local_engine_archive(self) -> None:
+ """Put a verified local engine asset in the isolated offline cache."""
+
+ raw_manifest_path = self.env.get(_ENGINE_MANIFEST_PATH_ENV, "").strip()
+ if not raw_manifest_path:
+ return
+ manifest_path = Path(raw_manifest_path).expanduser()
+ if not manifest_path.is_absolute():
+ manifest_path = self.repo_root / manifest_path
+
+ from vibe.model_hub_runtime.installer import EngineRuntimeManager
+
+ runtime_dir = (
+ self.avibe_home / "runtime" / "model-hub" / "engine"
+ )
+ manager = EngineRuntimeManager(
+ runtime_dir=runtime_dir,
+ manifest_path=manifest_path,
+ offline=True,
+ )
+ contract = manager.contract_manifest()
+ if contract.get("resolution") != "resolved":
+ return
+ selected = next(
+ (
+ asset
+ for asset in contract.get("assets", ())
+ if isinstance(asset, Mapping)
+ and asset.get("platform") == manager.host_platform()
+ ),
+ None,
+ )
+ if selected is None:
+ return
+ archive_url = selected.get("url")
+ if not isinstance(archive_url, str):
+ return
+ parsed_url = urlparse(archive_url)
+ if parsed_url.scheme != "file":
+ return
+ if (
+ parsed_url.netloc not in {"", "localhost"}
+ or parsed_url.query
+ or parsed_url.fragment
+ ):
+ raise RuntimeError(
+ "local Model Hub engine archive must use a plain local file URL"
+ )
+ source = Path(url2pathname(parsed_url.path))
+ if not source.is_absolute():
+ raise RuntimeError(
+ "local Model Hub engine archive URL must be absolute"
+ )
+
+ expected_size = selected.get("size_bytes")
+ expected_sha256 = selected.get("sha256")
+ if (
+ not isinstance(expected_size, int)
+ or isinstance(expected_size, bool)
+ or not isinstance(expected_sha256, str)
+ ):
+ raise RuntimeError(
+ "local Model Hub engine archive requires size and sha256"
+ )
+ self._verify_local_engine_archive(
+ source,
+ expected_size=expected_size,
+ expected_sha256=expected_sha256,
+ )
+
+ archive_status = manager.status().get("archive")
+ if not isinstance(archive_status, Mapping):
+ return
+ archive_name = archive_status.get("name")
+ if (
+ not isinstance(archive_name, str)
+ or not archive_name
+ or Path(archive_name).name != archive_name
+ ):
+ raise RuntimeError("local Model Hub engine archive name is unsafe")
+
+ downloads = runtime_dir / "downloads"
+ downloads.mkdir(parents=True, exist_ok=True)
+ cached = downloads / archive_name
+ temporary = downloads / f".{archive_name}.seed.tmp"
+ try:
+ shutil.copyfile(source, temporary)
+ self._verify_local_engine_archive(
+ temporary,
+ expected_size=expected_size,
+ expected_sha256=expected_sha256,
+ )
+ temporary.replace(cached)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ @staticmethod
+ def _verify_local_engine_archive(
+ path: Path,
+ *,
+ expected_size: int,
+ expected_sha256: str,
+ ) -> None:
+ try:
+ actual_size = path.stat().st_size
+ except OSError as exc:
+ raise RuntimeError(
+ f"local Model Hub engine archive is unavailable: {path}"
+ ) from exc
+ if actual_size != expected_size:
+ raise RuntimeError(
+ "local Model Hub engine archive size mismatch: "
+ f"expected {expected_size}, got {actual_size}"
+ )
+ digest = hashlib.sha256()
+ try:
+ with path.open("rb") as archive:
+ for chunk in iter(lambda: archive.read(1024 * 1024), b""):
+ digest.update(chunk)
+ except OSError as exc:
+ raise RuntimeError(
+ f"local Model Hub engine archive is unavailable: {path}"
+ ) from exc
+ actual_sha256 = digest.hexdigest()
+ if actual_sha256 != expected_sha256.lower():
+ raise RuntimeError(
+ "local Model Hub engine archive sha256 mismatch: "
+ f"expected {expected_sha256.lower()}, got {actual_sha256}"
+ )
+
def start(self) -> "ModelHubTestApp":
try:
self.home.mkdir(parents=True, exist_ok=True)
@@ -257,6 +393,7 @@ class ModelHubTestApp:
(self.runtime_root / "tmp").mkdir(
parents=True, exist_ok=True
)
+ self._seed_local_engine_archive()
self._initialize_config()
self._start_controller()
self._start_ui_with_port_retry()
diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.py
index fdc56b487..69635deae 100644
--- a/tests/e2e/test_model_hub_routing.py
+++ b/tests/e2e/test_model_hub_routing.py
@@ -196,10 +196,16 @@ def test_d2_healthy_hop_is_served_by_the_real_engine_probe(
if item["path"] == "/v1/messages"
]
assert captured
+ # The engine forwards Anthropic credentials as Bearer; x-api-key is
+ # used only by Avibe's direct discovery probe path.
assert all(
- _request_credential(item) == SYNTHETIC_API_KEY
+ item["headers"].get("authorization")
+ == f"Bearer {SYNTHETIC_API_KEY}"
for item in captured
)
+ assert all(
+ item["headers"].get("anthropic-version") for item in captured
+ )
def test_replaced_shared_key_keeps_source_identity_and_reaches_upstream_once(
diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.py
index d38e551b1..02e8dd75e 100644
--- a/tests/e2e/test_model_hub_runtime.py
+++ b/tests/e2e/test_model_hub_runtime.py
@@ -2,16 +2,15 @@
from __future__ import annotations
+import hashlib
import json
import os
-import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
-import urllib.parse
from pathlib import Path
from types import SimpleNamespace
@@ -19,7 +18,6 @@ import psutil
import pytest
import yaml
-from core.managed_runtime import runtime_platform_tag
from tests.e2e.drivers.model_hub_app import (
HTTPResult,
ModelHubTestApp,
@@ -29,11 +27,6 @@ from tests.e2e.drivers.model_hub_app import (
pytestmark = pytest.mark.e2e_model_hub
-_ENGINE_MANIFEST_PLATFORMS = {
- "linux-x64": "linux-amd64",
-}
-
-
def _local_engine_manifest() -> str:
raw = os.environ.get("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", "").strip()
if not raw:
@@ -51,51 +44,8 @@ def _local_engine_manifest() -> str:
def _engine_app(model_hub_app_factory):
manifest = _local_engine_manifest()
-
- def seed_archive(app: ModelHubTestApp) -> None:
- payload = json.loads(Path(manifest).read_text(encoding="utf-8"))
- host_platform = runtime_platform_tag()
- platform = _ENGINE_MANIFEST_PLATFORMS.get(
- host_platform,
- host_platform,
- )
- archive = next(
- (
- item
- for item in payload["assets"]
- if item["platform"] == platform
- ),
- None,
- )
- if archive is None:
- return
- parsed = urllib.parse.urlparse(archive["url"])
- if parsed.scheme != "file" or parsed.netloc not in {"", "localhost"}:
- pytest.skip(
- "managed Model Hub E2E requires a local file archive "
- "in its offline manifest"
- )
- source = Path(urllib.parse.unquote(parsed.path))
- if not source.is_file():
- pytest.skip(
- f"managed Model Hub engine archive does not exist: {source}"
- )
- downloads = (
- app.avibe_home
- / "runtime"
- / "model-hub"
- / "engine"
- / "downloads"
- )
- downloads.mkdir(parents=True, exist_ok=True)
- shutil.copyfile(source, downloads / source.name)
-
return model_hub_app_factory(
- extra_env={
- "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH": manifest,
- "VIBE_MODEL_HUB_ENGINE_OFFLINE": "1",
- },
- before_start=seed_archive,
+ extra_env={"VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH": manifest}
)
@@ -193,6 +143,210 @@ def test_harness_scrubs_inherited_backend_credentials(
assert app.env["CODEX_HOME"] == str(tmp_path / "home" / ".codex")
+def _write_harness_engine_manifest(
+ path: Path,
+ *,
+ archive_url: str,
+ size_bytes: int,
+ sha256: str,
+) -> Path:
+ manifest = path / "manifest.json"
+ manifest.parent.mkdir(parents=True, exist_ok=True)
+ manifest.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source": "router-for-me/CLIProxyAPI",
+ "source_url": "https://example.test/source",
+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",
+ "release_tag": "v7.2.95",
+ "license": "MIT",
+ "assets": [
+ {
+ "platform": platform,
+ "url": archive_url,
+ "size_bytes": size_bytes,
+ "sha256": sha256,
+ "binary_sha256": "b" * 64,
+ "bin_path": "cli-proxy-api",
+ }
+ for platform in (
+ "darwin-arm64",
+ "darwin-x64",
+ "linux-amd64",
+ "linux-arm64",
+ )
+ ],
+ }
+ ),
+ encoding="utf-8",
+ )
+ return manifest
+
+
+def test_harness_inherits_only_the_engine_manifest_path(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Harness contract: the outer manifest path is the only engine control."""
+
+ manifest_path = tmp_path / "outer-manifest.json"
+ monkeypatch.setenv(
+ "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", str(manifest_path)
+ )
+ monkeypatch.setenv(
+ "VIBE_MODEL_HUB_ENGINE_MANIFEST_URL",
+ "https://inherited.example/manifest.json",
+ )
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENGINE_OFFLINE", "0")
+
+ app = ModelHubTestApp(Path.cwd(), tmp_path / "runtime")
+
+ assert app.env["VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH"] == str(
+ manifest_path
+ )
+ assert "VIBE_MODEL_HUB_ENGINE_MANIFEST_URL" not in app.env
+ assert app.env["VIBE_MODEL_HUB_ENGINE_OFFLINE"] == "1"
+
+
+def test_engine_app_passes_the_normalized_manifest_path(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Harness contract: child paths retain the validated parent meaning."""
+
+ manifest = tmp_path / "fixture" / "manifest.json"
+ manifest.parent.mkdir()
+ manifest.write_text("{}", encoding="utf-8")
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv(
+ "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH",
+ str(manifest.relative_to(tmp_path)),
+ )
+ captured: dict = {}
+ launched = object()
+
+ def factory(**kwargs):
+ captured.update(kwargs)
+ return launched
+
+ assert _engine_app(factory) is launched
+ assert captured == {
+ "extra_env": {
+ "VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH": str(manifest.resolve())
+ }
+ }
+
+
+def test_harness_seeds_a_verified_file_archive_before_child_start(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Harness contract: local assets enter the offline cache before spawn."""
+
+ archive = tmp_path / "fixture" / "CLIProxyAPI_fixture.tar.gz"
+ archive.parent.mkdir(parents=True)
+ archive.write_bytes(b"verified local engine archive")
+ manifest = _write_harness_engine_manifest(
+ tmp_path / "fixture",
+ archive_url=archive.as_uri(),
+ size_bytes=archive.stat().st_size,
+ sha256=hashlib.sha256(archive.read_bytes()).hexdigest(),
+ )
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", str(manifest))
+ app = ModelHubTestApp(Path.cwd(), tmp_path / "runtime")
+ cached = (
+ app.avibe_home
+ / "runtime"
+ / "model-hub"
+ / "engine"
+ / "downloads"
+ / archive.name
+ )
+ calls: list[str] = []
+
+ def initialize_config() -> None:
+ calls.append("config")
+
+ def start_controller() -> None:
+ assert cached.read_bytes() == archive.read_bytes()
+ calls.append("controller")
+
+ monkeypatch.setattr(app, "_initialize_config", initialize_config)
+ monkeypatch.setattr(app, "_start_controller", start_controller)
+ monkeypatch.setattr(
+ app,
+ "_start_ui_with_port_retry",
+ lambda: calls.append("ui"),
+ )
+
+ app.start()
+
+ assert calls == ["config", "controller", "ui"]
+ assert app.env["VIBE_MODEL_HUB_ENGINE_OFFLINE"] == "1"
+
+
+ ("size_delta", "sha256", "error"),
+ [
+ (1, None, "archive size mismatch"),
+ (0, "0" * 64, "archive sha256 mismatch"),
+ ],
+)
+def test_harness_rejects_unverified_local_engine_archives(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ size_delta: int,
+ sha256: str | None,
+ error: str,
+) -> None:
+ """Harness contract: neither size nor digest mismatches enter the cache."""
+
+ archive = tmp_path / "fixture" / "CLIProxyAPI_fixture.tar.gz"
+ archive.parent.mkdir(parents=True)
+ archive.write_bytes(b"local engine archive")
+ manifest = _write_harness_engine_manifest(
+ tmp_path / "fixture",
+ archive_url=archive.as_uri(),
+ size_bytes=archive.stat().st_size + size_delta,
+ sha256=sha256
+ or hashlib.sha256(archive.read_bytes()).hexdigest(),
+ )
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", str(manifest))
+ app = ModelHubTestApp(Path.cwd(), tmp_path / "runtime")
+
+ with pytest.raises(RuntimeError, match=error):
+ app._seed_local_engine_archive()
+
+ assert not (
+ app.avibe_home / "runtime" / "model-hub" / "engine" / "downloads"
+ ).exists()
+
+
+def test_harness_does_not_fetch_non_file_engine_assets(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Harness contract: offline seeding never turns into network egress."""
+
+ manifest = _write_harness_engine_manifest(
+ tmp_path / "fixture",
+ archive_url="https://network.invalid/CLIProxyAPI_fixture.tar.gz",
+ size_bytes=1,
+ sha256="0" * 64,
+ )
+ monkeypatch.setenv("VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH", str(manifest))
+ app = ModelHubTestApp(Path.cwd(), tmp_path / "runtime")
+
+ app._seed_local_engine_archive()
+
+ assert not (
+ app.avibe_home / "runtime" / "model-hub" / "engine" / "downloads"
+ ).exists()
+
+
def test_harness_cleans_controller_when_ui_start_fails(
monkeypatch,
tmp_path: Path,