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
Show Runtime manifest cache install (#361)
Call White078265492ba6
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex b15e0819f..d3224723b 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -15,7 +15,26 @@ permissions:contents: readjobs:+ resolve-show-runtime-ref:+ runs-on: ubuntu-latest+ outputs:+ ref: ${{ steps.ref.outputs.ref }}+ steps:+ - name: Resolve Show Runtime ref+ id: ref+ env:+ GH_TOKEN: ${{ github.token }}+ shell: bash+ run: |+ REF=$(gh api repos/avibe-bot/vibe-show-runtime/commits/main --jq '.sha')+ if [ -z "$REF" ]; then+ echo "Failed to resolve avibe-bot/vibe-show-runtime main" >&2+ exit 1+ fi+ echo "ref=$REF" >> "$GITHUB_OUTPUT"+show-runtime-bundles:+ needs: resolve-show-runtime-refruns-on: ${{ matrix.os }}strategy:matrix:@@ -37,32 +56,58 @@ jobs:uses: actions/checkout@v5with:repository: avibe-bot/vibe-show-runtime- ref: main+ ref: ${{ needs.resolve-show-runtime-ref.outputs.ref }}+- name: Setup Node.jsuses: actions/setup-node@v5with:node-version: "22.14.0"cache: "npm"+- name: Build Show Runtime bundlerun: |npm cinpm run buildnpm run bundle:vibe-remote+ cp dist/vibe-show-runtime-node-*.tgz .+ git rev-parse HEAD > show-runtime-ref-${{ matrix.artifact }}.txt+- name: Upload Show Runtime bundleuses: actions/upload-artifact@v6with:name: show-runtime-${{ matrix.artifact }}- path: dist/vibe-show-runtime-node-*.tgz+ path: |+ vibe-show-runtime-node-*.tgz+ show-runtime-ref-${{ matrix.artifact }}.txtbuild:needs: show-runtime-bundlesruns-on: ubuntu-latest+ permissions:+ contents: writesteps:- name: Checkoutuses: actions/checkout@v5with:ref: ${{ github.event.inputs.tag || github.ref }}+ - name: Resolve tag+ id: tag+ shell: bash+ run: |+ if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then+ TAG="${{ github.event.inputs.tag }}"+ else+ TAG="${GITHUB_REF_NAME}"+ fi++ if [ -z "$TAG" ]; then+ echo "Tag is empty" >&2+ exit 1+ fi++ echo "tag=$TAG" >> "$GITHUB_OUTPUT"+- name: Setup Node.jsuses: actions/setup-node@v5with:@@ -80,20 +125,92 @@ jobs:uses: actions/download-artifact@v6with:pattern: show-runtime-*- path: vibe/show_runtime+ path: runtime-artifactsmerge-multiple: true+ - name: Generate Show Runtime manifest+ run: |+ python scripts/generate_show_runtime_manifest.py \+ --archive-dir runtime-artifacts \+ --tag "${{ steps.tag.outputs.tag }}" \+ --repo "${{ github.repository }}" \+ --runtime-ref-file 'runtime-artifacts/show-runtime-ref-*.txt' \+ --output vibe/show_runtime_manifest.json+ cp vibe/show_runtime_manifest.json runtime-artifacts/show-runtime-manifest.json+- name: Setup Pythonuses: actions/setup-python@v6with:python-version: "3.12"+ - name: Verify Show Runtime release assets+ run: |+ python - <<'PY'+ import hashlib+ import json+ from pathlib import Path++ manifest_path = Path("vibe/show_runtime_manifest.json")+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ archives = manifest.get("archives") or {}+ expected = {+ "darwin-arm64",+ "darwin-x64",+ "linux-arm64",+ "linux-x64",+ "win32-arm64",+ "win32-x64",+ }+ missing = expected - set(archives)+ if missing:+ raise SystemExit("Manifest is missing platforms: " + ", ".join(sorted(missing)))++ def sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as file:+ for chunk in iter(lambda: file.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()++ for platform, archive in sorted(archives.items()):+ path = Path("runtime-artifacts") / archive["name"]+ if not path.exists():+ raise SystemExit(f"Missing release archive for {platform}: {archive['name']}")+ if archive.get("size") is not None and path.stat().st_size != archive["size"]:+ raise SystemExit(f"Size mismatch for {archive['name']}")+ if sha256(path) != archive["sha256"]:+ raise SystemExit(f"Checksum mismatch for {archive['name']}")+ PY+- name: Install build and test dependenciesrun: pip install -e . build pytest- name: Build packagerun: python -m build+ - name: Verify package Show Runtime manifest+ run: |+ python - <<'PY'+ import zipfile+ from pathlib import Path++ wheels = sorted(Path("dist").glob("*.whl"))+ if len(wheels) != 1:+ raise SystemExit(f"Expected exactly one wheel, found {len(wheels)}")++ with zipfile.ZipFile(wheels[0]) as wheel:+ names = set(wheel.namelist())+ archives = {+ name for name in names+ if name.startswith("vibe/show_runtime/") and name.endswith(".tgz")+ }++ if archives:+ raise SystemExit("Wheel unexpectedly contains Show Runtime archives:\n" + "\n".join(sorted(archives)))+ if "vibe/show_runtime_manifest.json" not in names:+ raise SystemExit("Wheel is missing vibe/show_runtime_manifest.json")+ PY+- name: Run release install and upgrade regressionsrun: |docker info@@ -105,6 +222,34 @@ jobs:tests/e2e/test_upgrade_command.py \-v+ - name: Upload GitHub release assets+ env:+ GH_TOKEN: ${{ github.token }}+ shell: bash+ run: |+ TAG="${{ steps.tag.outputs.tag }}"+ PRERELEASE="false"+ if [[ "$TAG" == *-* ]]; then+ PRERELEASE="true"+ elif [[ "$TAG" =~ ^v[0-9]+(\.[0-9]+)*(([.-])?(a|b|rc|dev)[0-9]+)$ ]]; then+ PRERELEASE="true"+ fi++ if ! gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1; then+ ARGS=(release create "$TAG" --repo "${GITHUB_REPOSITORY}" --title "$TAG" --notes "Release assets for $TAG.")+ if [ "$PRERELEASE" = "true" ]; then+ ARGS+=(--prerelease)+ fi+ gh "${ARGS[@]}" || gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" >/dev/null+ fi++ gh release upload "$TAG" \+ --repo "${GITHUB_REPOSITORY}" \+ dist/* \+ runtime-artifacts/vibe-show-runtime-node-*.tgz \+ runtime-artifacts/show-runtime-manifest.json \+ --clobber+- name: Upload artifactsuses: actions/upload-artifact@v6with:diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.ymlindex e7a81be72..90fbc91f6 100644--- a/.github/workflows/release_ai.yml+++ b/.github/workflows/release_ai.yml@@ -27,7 +27,26 @@ permissions:pull-requests: readjobs:+ resolve-show-runtime-ref:+ runs-on: ubuntu-latest+ outputs:+ ref: ${{ steps.ref.outputs.ref }}+ steps:+ - name: Resolve Show Runtime ref+ id: ref+ env:+ GH_TOKEN: ${{ github.token }}+ shell: bash+ run: |+ REF=$(gh api repos/avibe-bot/vibe-show-runtime/commits/main --jq '.sha')+ if [ -z "$REF" ]; then+ echo "Failed to resolve avibe-bot/vibe-show-runtime main" >&2+ exit 1+ fi+ echo "ref=$REF" >> "$GITHUB_OUTPUT"+show-runtime-bundles:+ needs: resolve-show-runtime-refruns-on: ${{ matrix.os }}strategy:matrix:@@ -49,7 +68,7 @@ jobs:uses: actions/checkout@v5with:repository: avibe-bot/vibe-show-runtime- ref: main+ ref: ${{ needs.resolve-show-runtime-ref.outputs.ref }}- name: Setup Node.jsuses: actions/setup-node@v5with:@@ -60,11 +79,15 @@ jobs:npm cinpm run buildnpm run bundle:vibe-remote+ cp dist/vibe-show-runtime-node-*.tgz .+ git rev-parse HEAD > show-runtime-ref-${{ matrix.artifact }}.txt- name: Upload Show Runtime bundleuses: actions/upload-artifact@v6with:name: show-runtime-${{ matrix.artifact }}- path: dist/vibe-show-runtime-node-*.tgz+ path: |+ vibe-show-runtime-node-*.tgz+ show-runtime-ref-${{ matrix.artifact }}.txtbuild-assets:needs: show-runtime-bundles@@ -92,9 +115,18 @@ jobs:uses: actions/download-artifact@v6with:pattern: show-runtime-*- path: vibe/show_runtime+ path: runtime-artifactsmerge-multiple: true+ - name: Generate Show Runtime manifest+ run: |+ python scripts/generate_show_runtime_manifest.py \+ --archive-dir runtime-artifacts \+ --tag "${{ github.event.inputs.tag || github.ref_name }}" \+ --repo "${{ github.repository }}" \+ --runtime-ref-file 'runtime-artifacts/show-runtime-ref-*.txt' \+ --output vibe/show_runtime_manifest.json+- name: Setup Pythonuses: actions/setup-python@v6with:@@ -117,27 +149,31 @@ jobs:raise SystemExit(f"Expected exactly one wheel, found {len(wheels)}")with zipfile.ZipFile(wheels[0]) as wheel:+ names = set(wheel.namelist())archives = {- name for name in wheel.namelist()- if name.startswith("vibe/show_runtime/vibe-show-runtime-node-")- and name.endswith(".tgz")+ name for name in names+ if name.startswith("vibe/show_runtime/") and name.endswith(".tgz")}- expected = {- "vibe/show_runtime/vibe-show-runtime-node-darwin-arm64.tgz",- "vibe/show_runtime/vibe-show-runtime-node-darwin-x64.tgz",- "vibe/show_runtime/vibe-show-runtime-node-linux-arm64.tgz",- "vibe/show_runtime/vibe-show-runtime-node-linux-x64.tgz",- "vibe/show_runtime/vibe-show-runtime-node-win32-arm64.tgz",- "vibe/show_runtime/vibe-show-runtime-node-win32-x64.tgz",- }- missing = sorted(expected - archives)- if missing:- raise SystemExit("Wheel is missing bundled Show Runtime archives:\n" + "\n".join(missing))-- print("\n".join(sorted(archives)))+ if archives:+ raise SystemExit("Wheel unexpectedly contains Show Runtime archives:\n" + "\n".join(sorted(archives)))+ if "vibe/show_runtime_manifest.json" not in names:+ raise SystemExit("Wheel is missing vibe/show_runtime_manifest.json")++ print("vibe/show_runtime_manifest.json")PY+ - name: Add Show Runtime release assets+ shell: bash+ run: |+ TAG="${{ github.event.inputs.tag || github.ref_name }}"+ if [[ "$TAG" == gh-v* ]]; then+ cp runtime-artifacts/vibe-show-runtime-node-*.tgz dist/+ cp vibe/show_runtime_manifest.json dist/show-runtime-manifest.json+ else+ echo "Show Runtime release assets for $TAG are produced by the PyPI publish workflow."+ fi+- name: Upload release artifactsuses: actions/upload-artifact@v6with:@@ -427,7 +463,8 @@ jobs:name: release-distpath: dist/- - name: Create GitHub Release+ - name: Create GitHub-only Release+ if: startsWith(steps.tag.outputs.tag, 'gh-v')uses: softprops/action-gh-release@v3with:tag_name: ${{ steps.tag.outputs.tag }}@@ -438,3 +475,32 @@ jobs:draft: falseprerelease: ${{ steps.release_type.outputs.prerelease == 'true' }}make_latest: ${{ github.event_name == 'push' && steps.release_type.outputs.prerelease != 'true' }}++ - name: Update official release notes+ if: ${{ !startsWith(steps.tag.outputs.tag, 'gh-v') }}+ env:+ GH_TOKEN: ${{ github.token }}+ shell: bash+ run: |+ TAG="${{ steps.tag.outputs.tag }}"+ if ! gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" >/dev/null 2>&1; then+ ARGS=(release create "$TAG" --repo "${GITHUB_REPOSITORY}" --title "$TAG" --notes-file release.md)+ if [ "${{ steps.release_type.outputs.prerelease }}" = "true" ]; then+ ARGS+=(--prerelease)+ fi+ if [ "${{ github.event_name }}" = "push" ] && [ "${{ steps.release_type.outputs.prerelease }}" != "true" ]; then+ ARGS+=(--latest)+ fi+ gh "${ARGS[@]}" || gh release edit "$TAG" --repo "${GITHUB_REPOSITORY}" --notes-file release.md+ else+ EDIT_ARGS=(release edit "$TAG" --repo "${GITHUB_REPOSITORY}" --title "$TAG" --notes-file release.md)+ if [ "${{ steps.release_type.outputs.prerelease }}" = "true" ]; then+ EDIT_ARGS+=(--prerelease)+ else+ EDIT_ARGS+=(--prerelease=false)+ fi+ if [ "${{ github.event_name }}" = "push" ] && [ "${{ steps.release_type.outputs.prerelease }}" != "true" ]; then+ EDIT_ARGS+=(--latest)+ fi+ gh "${EDIT_ARGS[@]}"+ fidiff --git a/core/show_runtime.py b/core/show_runtime.pyindex 1d2777acc..999bd95f0 100644--- a/core/show_runtime.py+++ b/core/show_runtime.py@@ -8,12 +8,14 @@ import jsonimport loggingimport osimport platform+import reimport shleximport shutilimport signalimport subprocessimport tarfileimport tempfile+import urllib.parseimport urllib.requestfrom dataclasses import dataclassfrom pathlib import Path@@ -33,9 +35,11 @@ _RUNTIME_ARCHIVE_PREFIX = "vibe-show-runtime-node"_RUNTIME_ARCHIVE_RELEASE_BASE_URL = "https://github.com/avibe-bot/vibe-show-runtime/releases/latest/download"_RUNTIME_GITHUB_REPO = "https://github.com/avibe-bot/vibe-show-runtime.git"_RUNTIME_GITHUB_REF = "main"+_RUNTIME_SOURCE_MANIFEST = "manifest-cache"_RUNTIME_SOURCE_ARCHIVE = "archive"_RUNTIME_SOURCE_GITHUB = "github"_RUNTIME_SOURCE_NPM = "npm"+_RUNTIME_MANIFEST_RESOURCE = "show_runtime_manifest.json"_FALSE_VALUES = {"0", "false", "no", "off"}@@ -46,6 +50,25 @@ class ShowRuntimeResult:reason: str | None = None+@dataclass(frozen=True)+class ShowRuntimeArchive:+ platform: str+ name: str+ url: str+ sha256: str+ size: int | None = None+++@dataclass(frozen=True)+class ShowRuntimeManifest:+ schema_version: int+ runtime_version: str+ minimum_node: str | None+ archives: dict[str, ShowRuntimeArchive]+ digest: str+ source: str++class ShowRuntimeManager:def __init__(self,@@ -60,21 +83,43 @@ class ShowRuntimeManager:archive_url: str | None = None,github_repo: str | None = None,github_ref: str | None = None,+ manifest_path: Path | str | None = None,+ manifest_url: str | None = None,+ offline: bool | None = None,+ force_install: bool = False,) -> None:- self.command = command or os.environ.get("VIBE_SHOW_RUNTIME_BIN") or _RUNTIME_BIN+ configured_command = command or os.environ.get("VIBE_SHOW_RUNTIME_BIN")+ self.command = configured_command or _RUNTIME_BIN+ self._command_explicit = configured_command is not Noneself.workspace_root = workspace_root or paths.get_show_pages_dir()self.runtime_dir = runtime_dir or paths.get_runtime_dir() / "show-runtime"- self.auto_install = _auto_install_enabled() if auto_install is None else auto_install- self.package_spec = package_spec or os.environ.get("VIBE_SHOW_RUNTIME_PACKAGE_SPEC") or _RUNTIME_PACKAGE- self.runtime_source = _normalize_runtime_source(runtime_source or os.environ.get("VIBE_SHOW_RUNTIME_SOURCE"))archive_path_value = archive_path or os.environ.get("VIBE_SHOW_RUNTIME_ARCHIVE_PATH")self.archive_path = Path(archive_path_value).expanduser() if archive_path_value else None+ archive_url_env = os.environ.get("VIBE_SHOW_RUNTIME_ARCHIVE_URL")+ manifest_path_value = manifest_path or os.environ.get("VIBE_SHOW_RUNTIME_MANIFEST_PATH")+ self.manifest_path = Path(manifest_path_value).expanduser() if manifest_path_value else None+ self.manifest_url = manifest_url if manifest_url is not None else os.environ.get("VIBE_SHOW_RUNTIME_MANIFEST_URL")+ source_value = runtime_source or os.environ.get("VIBE_SHOW_RUNTIME_SOURCE")+ if source_value is None and (archive_path_value or archive_url is not None or archive_url_env):+ source_value = _RUNTIME_SOURCE_ARCHIVE+ if (+ source_value is None+ and not self.manifest_path+ and not self.manifest_url+ and not _packaged_runtime_manifest_exists()+ ):+ source_value = _RUNTIME_SOURCE_ARCHIVE+ self.auto_install = _auto_install_enabled() if auto_install is None else auto_install+ self.package_spec = package_spec or os.environ.get("VIBE_SHOW_RUNTIME_PACKAGE_SPEC") or _RUNTIME_PACKAGE+ self.runtime_source = _normalize_runtime_source(source_value)self.archive_url = archive_url if archive_url is not None else os.environ.get("VIBE_SHOW_RUNTIME_ARCHIVE_URL",_default_runtime_archive_url(),)self.github_repo = github_repo or os.environ.get("VIBE_SHOW_RUNTIME_GITHUB_REPO") or _RUNTIME_GITHUB_REPOself.github_ref = github_ref or os.environ.get("VIBE_SHOW_RUNTIME_GITHUB_REF") or _RUNTIME_GITHUB_REF+ self.offline = _env_flag_enabled("VIBE_SHOW_RUNTIME_OFFLINE", default=False) if offline is None else offline+ self.force_install = force_installself.stdout_path = self.runtime_dir / "stdout.log"self.stderr_path = self.runtime_dir / "stderr.log"self.install_log_path = self.runtime_dir / "install.log"@@ -92,7 +137,7 @@ class ShowRuntimeManager:if self._base_url and await self._healthy(self._base_url):return ShowRuntimeResult(True, self._base_url)self.stop()- command = _resolve_command(self.command)+ command = _resolve_command(self.command) if self._command_explicit else Noneif not command:command = await self._resolve_managed_command()if not command:@@ -181,9 +226,27 @@ class ShowRuntimeManager:signal_process_tree(process, KILL_SIGNAL, logger, "show runtime")async def _resolve_managed_command(self) -> list[str] | None:- if self.command != _RUNTIME_BIN:+ if self._command_explicit and self.command != _RUNTIME_BIN:self._install_reason = "runtime_command_missing"return None+ if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:+ command = None if self.force_install else self._installed_manifest_runtime_command()+ if command:+ self._managed_command = command+ return command+ if self.auto_install and not self._install_attempted:+ self._install_attempted = True+ command = await asyncio.to_thread(self._install_managed_runtime)+ if command:+ self._managed_command = command+ return command+ command = self._installed_manifest_runtime_command()+ if command:+ self._managed_command = command+ return command+ if self._managed_command:+ return self._managed_command+ return Noneif self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:if self.auto_install and not self._install_attempted:self._install_attempted = True@@ -221,6 +284,8 @@ class ShowRuntimeManager:return commanddef _install_managed_runtime(self) -> list[str] | None:+ if self.runtime_source == _RUNTIME_SOURCE_MANIFEST:+ return self._install_manifest_runtime()if self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:return self._install_archive_runtime()if self.runtime_source == _RUNTIME_SOURCE_GITHUB:@@ -230,6 +295,347 @@ class ShowRuntimeManager:self._install_reason = "runtime_source_unsupported"return None+ def status(self) -> dict[str, Any]:+ configured_command = _resolve_command(self.command) if self._command_explicit else None+ manifest = self._load_runtime_manifest() if self.runtime_source == _RUNTIME_SOURCE_MANIFEST else None+ platform_tag = _runtime_platform_tag()+ node = _resolve_node_command()+ node_version = _node_version(node) if node else None+ node_supported = _node_satisfies_requirement(node_version, manifest.minimum_node) if manifest else None+ installed_command: list[str] | None = configured_command+ installed_dir: Path | None = None+ archive: ShowRuntimeArchive | None = None+ installed_matches = False+ if not configured_command and manifest:+ archive = manifest.archives.get(platform_tag)+ if archive:+ installed_dir = self._manifest_install_dir(manifest, archive)+ installed_matches = self._manifest_install_matches(installed_dir, manifest, archive)+ if installed_matches and node and node_supported is not False:+ installed_command = self._manifest_runtime_command(installed_dir, node)+ elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:+ installed_dir = self._archive_install_dir()+ installed_command = self._archive_runtime_command(installed_dir, node or ["node"])+ elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_GITHUB:+ installed_dir = self._github_source_dir()+ installed_command = self._github_runtime_command(installed_dir, node or ["node"])+ elif not configured_command and self.runtime_source == _RUNTIME_SOURCE_NPM:+ managed = _resolve_executable_path(self._managed_bin_path())+ installed_command = [managed] if managed else None+ return {+ "provider": self.runtime_source,+ "platform": platform_tag,+ "explicit_command": self.command if self._command_explicit else None,+ "node_available": node is not None,+ "node_version": _format_semver(node_version),+ "node_supported": node_supported,+ "manifest": _manifest_status_payload(manifest),+ "archive": _archive_status_payload(archive),+ "installed": installed_command is not None,+ "installed_matches_manifest": installed_matches,+ "install_dir": str(installed_dir) if installed_dir else None,+ "command": installed_command,+ "reason": self._install_reason,+ }++ def clean(self, *, keep_previous: int = 1) -> dict[str, Any]:+ removed: list[str] = []+ for pattern in ("prebuilt-*", "manifest-*"):+ for path in self.runtime_dir.glob(pattern):+ if path.is_dir():+ shutil.rmtree(path, ignore_errors=True)+ removed.append(str(path))+ versions_dir = self.runtime_dir / "versions"+ if versions_dir.is_dir():+ current_version_dir: Path | None = None+ try:+ pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))+ current_install_dir = Path(str(pointer.get("install_dir") or "")).resolve()+ if versions_dir.resolve() in current_install_dir.parents:+ current_version_dir = current_install_dir.relative_to(versions_dir.resolve()).parts[0]+ current_version_dir = versions_dir / current_version_dir+ except Exception:+ current_version_dir = None+ version_dirs = sorted(+ (path for path in versions_dir.iterdir() if path.is_dir()),+ key=lambda path: path.stat().st_mtime,+ reverse=True,+ )+ kept_previous = 0+ for path in version_dirs:+ if current_version_dir is not None and path.resolve() == current_version_dir.resolve():+ continue+ if kept_previous < keep_previous:+ kept_previous += 1+ continue+ shutil.rmtree(path, ignore_errors=True)+ removed.append(str(path))+ return {"ok": True, "removed": removed}++ def prepare(self, *, force: bool | None = None, offline: bool | None = None) -> dict[str, Any]:+ previous_force = self.force_install+ previous_offline = self.offline+ if force is not None:+ self.force_install = force+ if offline is not None:+ self.offline = offline+ try:+ if self._command_explicit:+ command = _resolve_command(self.command)+ self._install_reason = None if command else "runtime_command_missing"+ else:+ command = self._install_managed_runtime()+ return {+ "ok": command is not None,+ "provider": self.runtime_source,+ "platform": _runtime_platform_tag(),+ "command": command,+ "reason": None if command else self._install_reason,+ "status": self.status(),+ }+ finally:+ self.force_install = previous_force+ self.offline = previous_offline++ def _installed_manifest_runtime_command(self) -> list[str] | None:+ node = _resolve_node_command()+ if not node:+ return None+ manifest = self._load_runtime_manifest()+ if not manifest:+ return None+ if not self._manifest_node_supported(node, manifest):+ return None+ archive = self._manifest_archive_for_platform(manifest)+ if not archive:+ return None+ install_dir = self._manifest_install_dir(manifest, archive)+ command = self._manifest_runtime_command(install_dir, node)+ if command and self._manifest_install_matches(install_dir, manifest, archive):+ return command+ return None++ def _install_manifest_runtime(self) -> list[str] | None:+ node = _resolve_node_command()+ if not node:+ self._install_reason = "runtime_node_missing"+ return None+ manifest = self._load_runtime_manifest()+ if not manifest:+ return None+ if not self._manifest_node_supported(node, manifest):+ return None+ archive = self._manifest_archive_for_platform(manifest)+ if not archive:+ return None+ install_dir = self._manifest_install_dir(manifest, archive)+ existing_command = self._manifest_runtime_command(install_dir, node)+ existing_matches = self._manifest_install_matches(install_dir, manifest, archive)+ verified_existing_command = existing_command if existing_matches else None+ if verified_existing_command and not self.force_install:+ self._install_reason = None+ return verified_existing_command+ archive_path = self._resolve_manifest_archive(archive)+ if not archive_path:+ return self._reuse_existing_archive_runtime(verified_existing_command)+ self.runtime_dir.mkdir(parents=True, exist_ok=True)+ tmp_dir = Path(tempfile.mkdtemp(prefix="manifest-", dir=self.runtime_dir))+ try:+ with tarfile.open(archive_path, "r:gz") as tar:+ _safe_extract_tar(tar, tmp_dir)+ command = self._manifest_runtime_command(tmp_dir, node)+ if not command:+ self._install_reason = "runtime_install_missing_bin"+ return self._reuse_existing_archive_runtime(verified_existing_command)+ if install_dir.exists():+ shutil.rmtree(install_dir)+ install_dir.parent.mkdir(parents=True, exist_ok=True)+ shutil.move(str(tmp_dir), str(install_dir))+ self._write_manifest_install_metadata(install_dir, manifest, archive)+ self._write_current_manifest_pointer(manifest, archive, install_dir)+ self._install_reason = None+ return self._manifest_runtime_command(install_dir, node)+ except Exception:+ logger.exception("Failed to install manifest Show Runtime")+ self._install_reason = "runtime_install_failed"+ return self._reuse_existing_archive_runtime(verified_existing_command)+ finally:+ if tmp_dir.exists():+ shutil.rmtree(tmp_dir, ignore_errors=True)++ def _load_runtime_manifest(self) -> ShowRuntimeManifest | None:+ payload: bytes | None = None+ source = ""+ if self.manifest_path:+ if not self.manifest_path.exists():+ self._install_reason = "runtime_manifest_missing"+ return None+ payload = self.manifest_path.read_bytes()+ source = str(self.manifest_path)+ elif self.manifest_url:+ if self.offline:+ self._install_reason = "runtime_manifest_unavailable_offline"+ return None+ try:+ with urllib.request.urlopen(self.manifest_url, timeout=30) as response:+ payload = response.read()+ source = self.manifest_url+ except Exception:+ logger.exception("Failed to download Show Runtime manifest from %s", self.manifest_url)+ self._install_reason = "runtime_manifest_download_failed"+ return None+ else:+ try:+ resource = package_resources.files("vibe").joinpath(_RUNTIME_MANIFEST_RESOURCE)+ except Exception:+ resource = None+ if resource is None or not resource.is_file():+ self._install_reason = "runtime_manifest_missing"+ return None+ payload = resource.read_bytes()+ source = f"package:{_RUNTIME_MANIFEST_RESOURCE}"+ digest = hashlib.sha256(payload).hexdigest()+ try:+ data = json.loads(payload.decode("utf-8"))+ archives = {+ platform_tag: ShowRuntimeArchive(+ platform=platform_tag,+ name=str(item["name"]),+ url=str(item["url"]),+ sha256=str(item["sha256"]),+ size=int(item["size"]) if item.get("size") is not None else None,+ )+ for platform_tag, item in (data.get("archives") or {}).items()+ if isinstance(item, dict)+ }+ manifest = ShowRuntimeManifest(+ schema_version=int(data.get("schema_version")),+ runtime_version=str(data.get("runtime_version") or ""),+ minimum_node=str(data.get("minimum_node") or "") or None,+ archives=archives,+ digest=digest,+ source=source,+ )+ except Exception:+ self._install_reason = "runtime_manifest_invalid"+ return None+ if manifest.schema_version != 1 or not manifest.runtime_version or not manifest.archives:+ self._install_reason = "runtime_manifest_invalid"+ return None+ return manifest++ def _manifest_node_supported(self, node: list[str], manifest: ShowRuntimeManifest) -> bool:+ if not manifest.minimum_node:+ return True+ version = _node_version(node)+ if _node_satisfies_requirement(version, manifest.minimum_node):+ return True+ self._install_reason = "runtime_node_unsupported"+ return False++ def _manifest_archive_for_platform(self, manifest: ShowRuntimeManifest) -> ShowRuntimeArchive | None:+ platform_tag = _runtime_platform_tag()+ archive = manifest.archives.get(platform_tag)+ if not archive:+ self._install_reason = "runtime_platform_unsupported"+ return None+ return archive++ def _resolve_manifest_archive(self, archive: ShowRuntimeArchive) -> Path | None:+ cached = self.runtime_dir / "downloads" / f"{archive.sha256}.tgz"+ if cached.exists() and self._downloaded_archive_matches(cached, archive):+ return cached+ if self.offline:+ self._install_reason = "runtime_archive_unavailable_offline"+ return None+ parsed = urllib.parse.urlparse(archive.url)+ if parsed.scheme not in {"https", "file"}:+ self._install_reason = "runtime_archive_url_unsupported"+ return None+ tmp_path = cached.with_suffix(".tmp")+ cached.parent.mkdir(parents=True, exist_ok=True)+ try:+ with urllib.request.urlopen(archive.url, timeout=60) as response, tmp_path.open("wb") as destination:+ shutil.copyfileobj(response, destination)+ if not self._downloaded_archive_matches(tmp_path, archive):+ tmp_path.unlink(missing_ok=True)+ return None+ tmp_path.replace(cached)+ return cached+ except Exception:+ logger.exception("Failed to download Show Runtime archive from %s", archive.url)+ tmp_path.unlink(missing_ok=True)+ self._install_reason = "runtime_archive_download_failed"+ return None++ def _downloaded_archive_matches(self, path: Path, archive: ShowRuntimeArchive) -> bool:+ if archive.size is not None and path.stat().st_size != archive.size:+ self._install_reason = "runtime_archive_size_mismatch"+ return False+ if _file_sha256(path) != archive.sha256:+ self._install_reason = "runtime_archive_checksum_mismatch"+ return False+ return True++ def _manifest_install_dir(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> Path:+ return self.runtime_dir / "versions" / _safe_path_part(manifest.runtime_version) / _safe_path_part(archive.platform)++ def _manifest_metadata_path(self, install_dir: Path) -> Path:+ return install_dir / ".vibe-show-runtime.json"++ def _manifest_install_matches(self, install_dir: Path, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> bool:+ try:+ payload = json.loads(self._manifest_metadata_path(install_dir).read_text(encoding="utf-8"))+ except Exception:+ return False+ return (+ payload.get("provider") == _RUNTIME_SOURCE_MANIFEST+ and payload.get("manifest_sha256") == manifest.digest+ and payload.get("runtime_version") == manifest.runtime_version+ and payload.get("platform") == archive.platform+ and payload.get("archive_sha256") == archive.sha256+ )++ def _write_manifest_install_metadata(self, install_dir: Path, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive) -> None:+ self._manifest_metadata_path(install_dir).write_text(+ json.dumps(+ {+ "provider": _RUNTIME_SOURCE_MANIFEST,+ "manifest_sha256": manifest.digest,+ "runtime_version": manifest.runtime_version,+ "platform": archive.platform,+ "archive_name": archive.name,+ "archive_sha256": archive.sha256,+ "manifest_source": manifest.source,+ },+ sort_keys=True,+ )+ + "\n",+ encoding="utf-8",+ )++ def _write_current_manifest_pointer(self, manifest: ShowRuntimeManifest, archive: ShowRuntimeArchive, install_dir: Path) -> None:+ pointer = self.runtime_dir / "current.json"+ pointer.parent.mkdir(parents=True, exist_ok=True)+ pointer.write_text(+ json.dumps(+ {+ "provider": _RUNTIME_SOURCE_MANIFEST,+ "runtime_version": manifest.runtime_version,+ "platform": archive.platform,+ "install_dir": str(install_dir),+ "manifest_sha256": manifest.digest,+ "archive_sha256": archive.sha256,+ },+ sort_keys=True,+ )+ + "\n",+ encoding="utf-8",+ )++ def _manifest_runtime_command(self, install_dir: Path, node: list[str]) -> list[str] | None:+ return self._archive_runtime_command(install_dir, node)+def _installed_archive_runtime_command(self) -> list[str] | None:node = _resolve_node_command()if not node:@@ -286,6 +692,9 @@ class ShowRuntimeManager:if not self.archive_url:self._install_reason = "runtime_archive_missing"return None+ if self.offline:+ self._install_reason = "runtime_archive_unavailable_offline"+ return Nonereturn self._download_runtime_archive(self.archive_url)def _copy_packaged_runtime_archive(self) -> Path | None:@@ -502,9 +911,58 @@ def _auto_install_enabled() -> bool:return value is None or value.strip().lower() not in _FALSE_VALUES+def _env_flag_enabled(name: str, *, default: bool) -> bool:+ value = os.environ.get(name)+ if value is None:+ return default+ return value.strip().lower() not in _FALSE_VALUES+++def _packaged_runtime_manifest_exists() -> bool:+ try:+ resource = package_resources.files("vibe").joinpath(_RUNTIME_MANIFEST_RESOURCE)+ except Exception:+ return False+ return resource.is_file()++def _normalize_runtime_source(value: str | None) -> str:- normalized = (value or _RUNTIME_SOURCE_ARCHIVE).strip().lower()- return normalized or _RUNTIME_SOURCE_ARCHIVE+ normalized = (value or _RUNTIME_SOURCE_MANIFEST).strip().lower()+ aliases = {+ "manifest": _RUNTIME_SOURCE_MANIFEST,+ "manifest-cache": _RUNTIME_SOURCE_MANIFEST,+ "archive": _RUNTIME_SOURCE_ARCHIVE,+ "prebuilt": _RUNTIME_SOURCE_ARCHIVE,+ "github": _RUNTIME_SOURCE_GITHUB,+ "github-source": _RUNTIME_SOURCE_GITHUB,+ "npm": _RUNTIME_SOURCE_NPM,+ }+ return aliases.get(normalized, normalized or _RUNTIME_SOURCE_MANIFEST)+++def _manifest_status_payload(manifest: ShowRuntimeManifest | None) -> dict[str, Any] | None:+ if manifest is None:+ return None+ return {+ "schema_version": manifest.schema_version,+ "runtime_version": manifest.runtime_version,+ "minimum_node": manifest.minimum_node,+ "sha256": manifest.digest,+ "source": manifest.source,+ "platforms": sorted(manifest.archives),+ }+++def _archive_status_payload(archive: ShowRuntimeArchive | None) -> dict[str, Any] | None:+ if archive is None:+ return None+ return {+ "platform": archive.platform,+ "name": archive.name,+ "url": archive.url,+ "sha256": archive.sha256,+ "size": archive.size,+ }def _runtime_archive_name() -> str:@@ -574,6 +1032,64 @@ def _safe_path_part(value: str) -> str:return cleaned or "main"+def _node_version(node: list[str]) -> tuple[int, int, int] | None:+ try:+ result = subprocess.run(+ [*node, "--version"],+ capture_output=True,+ text=True,+ timeout=5,+ check=False,+ **isolated_subprocess_kwargs(),+ )+ except Exception:+ return None+ if result.returncode != 0:+ return None+ return _parse_semver(result.stdout.strip())+++def _parse_semver(value: str) -> tuple[int, int, int] | None:+ match = re.search(r"v?(\d+)\.(\d+)\.(\d+)", value)+ if not match:+ return None+ return int(match.group(1)), int(match.group(2)), int(match.group(3))+++def _format_semver(version: tuple[int, int, int] | None) -> str | None:+ if version is None:+ return None+ return ".".join(str(part) for part in version)+++def _node_satisfies_requirement(version: tuple[int, int, int] | None, requirement: str | None) -> bool | None:+ if not requirement:+ return None+ if version is None:+ return False+ return any(_node_satisfies_clause(version, clause.strip()) for clause in requirement.split("||") if clause.strip())+++def _node_satisfies_clause(version: tuple[int, int, int], clause: str) -> bool:+ if clause.startswith(">="):+ minimum = _parse_semver(clause[2:].strip())+ return minimum is not None and version >= minimum+ if clause.startswith("^"):+ minimum = _parse_semver(clause[1:].strip())+ if minimum is None or version < minimum:+ return False+ major, minor, patch = minimum+ if major > 0:+ ceiling = (major + 1, 0, 0)+ elif minor > 0:+ ceiling = (major, minor + 1, 0)+ else:+ ceiling = (major, minor, patch + 1)+ return version < ceiling+ exact = _parse_semver(clause)+ return exact is not None and version == exact++def _resolve_command(command: str) -> list[str] | None:parts = shlex.split(command)if not parts:diff --git a/docs/plans/show-runtime-manifest-cache.md b/docs/plans/show-runtime-manifest-cache.mdnew file mode 100644index 000000000..0e771079f--- /dev/null+++ b/docs/plans/show-runtime-manifest-cache.md@@ -0,0 +1,367 @@+# Show Runtime Manifest Cache Plan++## Summary++Vibe Remote should stop embedding every platform's Show Runtime archive in the+Python wheel. The wheel should stay small and carry only the runtime selection+metadata. The actual Show Runtime should be prepared per machine:++- resolve the current platform+- download exactly one matching runtime archive+- verify it against a pinned manifest+- install it into a global cache+- atomically switch new Show Page sessions to the prepared runtime++Official install and upgrade flows should run this preparation step up front, so+normal users do not wait for the first Show Page request. If runtime preparation+fails, Vibe Remote itself must still install and start; only Show Page runtime+availability is degraded.++## Goals++- Shrink Vibe Remote wheel size by removing the six embedded runtime archives.+- Keep Show Page ready after normal official install or upgrade.+- Share one prepared runtime across all sessions on the machine.+- Verify every downloaded runtime archive by version, platform, and sha256.+- Make runtime upgrades deterministic when Vibe Remote releases.+- Preserve offline behavior when a verified cached runtime already exists.+- Keep runtime install failures isolated from core Vibe Remote installation.++## Non-Goals++- Do not require npm install in user session directories.+- Do not use one Node process or dev server per Show Page session.+- Do not expose live Show Runtime handlers on public `/p/<share-id>` links.+- Do not make the Python wheel platform-specific in the first iteration.+- Do not force-kill active runtime processes during normal upgrades.++## Current Problem++The current release workflow builds six platform archives from+`avibe-bot/vibe-show-runtime` and copies all of them into `vibe/show_runtime/`+before building the Vibe Remote wheel. This makes the `py3-none-any` wheel+roughly 100 MB even though each installed machine needs only one archive.++That approach is reliable for offline first launch, but it scales poorly:++- every platform pays for every other platform+- GitHub-only prereleases become large+- future UI/runtime dependency growth directly inflates the Python package+- PyPI publishing and local upgrades move more data than necessary++## Target Architecture++```text+Vibe Remote release+ -> small Python wheel+ - UI dist+ - runtime manifest lock+ - no platform runtime archive by default+ -> release assets+ - vibe-show-runtime-node-darwin-arm64.tgz+ - vibe-show-runtime-node-darwin-x64.tgz+ - vibe-show-runtime-node-linux-arm64.tgz+ - vibe-show-runtime-node-linux-x64.tgz+ - vibe-show-runtime-node-win32-arm64.tgz+ - vibe-show-runtime-node-win32-x64.tgz+ - show-runtime-manifest.json++Official installer / upgrade+ -> install Vibe Remote+ -> vibe runtime prepare+ - read pinned manifest from installed package+ - select current platform archive+ - download archive if cache miss+ - verify sha256 and size+ - safe extract into versioned cache+ - atomically update current pointer+```++Runtime state:++```text+~/.vibe_remote/runtime/show-runtime/+ downloads/+ <sha256>.tgz+ versions/+ <runtime-version>/+ darwin-arm64/+ package.json+ package-lock.json+ packages/+ node_modules/+ .vibe-show-runtime.json+ current.json+ install.log+ stdout.log+ stderr.log+```++The download cache key is the manifest archive digest, not only the version+string. Installed runtimes also record the manifest digest and archive digest;+an installed runtime is reused only when those values still match the active+manifest.++## Manifest Contract++The installed Vibe Remote package includes a pinned manifest lock, for example:++```json+{+ "schema_version": 1,+ "runtime_version": "0.0.12",+ "runtime_source": {+ "repo": "avibe-bot/vibe-show-runtime",+ "ref": "8ea539d104e3c9d9e1873924a2be302d35465fcf"+ },+ "minimum_node": "^20.19.0 || >=22.12.0",+ "archives": {+ "darwin-arm64": {+ "name": "vibe-show-runtime-node-darwin-arm64.tgz",+ "url": "https://github.com/cyhhao/vibe-remote/releases/download/gh-v2.3.7rc1/vibe-show-runtime-node-darwin-arm64.tgz",+ "sha256": "…",+ "size": 18300000+ }+ }+}+```++Required validation:++- `schema_version` is supported+- current platform exists in `archives`+- archive URL uses `https` or an explicit local `file` URL for development+- downloaded file size matches when present+- downloaded file sha256 exactly matches+- archive extraction passes the existing safe tar checks+- extracted archive exposes the expected runtime CLI+- extracted archive metadata records the same manifest digest++## Runtime Provider Model++Initial providers:++- `manifest-cache`: default for packaged Vibe Remote releases+- `local-bin`: explicit `VIBE_SHOW_RUNTIME_BIN` override for development+- `archive-path`: explicit local archive override for testing and emergency use+- `github-source`: development-only fallback for fast iteration+- `npm`: future stable-channel provider, not the first default++Resolution order:++1. `VIBE_SHOW_RUNTIME_BIN`+2. explicit local archive path+3. manifest cache+4. development provider override, if configured++The first implementation keeps the provider logic inside `ShowRuntimeManager`+instead of introducing a new class hierarchy. That keeps the change smaller+while preserving the provider boundary in the CLI and environment contract.+Show Page request-time install remains available as a recovery fallback, but+official install and `vibe upgrade` now run strict preparation first and treat+failure as a warning at the install/upgrade layer.++## Install And Upgrade Behavior++Official install script:++```text+install Vibe Remote+run vibe runtime prepare --strict+if prepare succeeds:+ print Show Runtime ready+else:+ print warning and keep Vibe Remote installed+```++Official upgrade flow:++```text+upgrade Vibe Remote+read newly installed runtime manifest+run vibe runtime prepare --strict+if same manifest digest already installed:+ reuse cache+else:+ download and verify current platform archive+ extract to new version directory+ atomically switch current+```++Direct `pip install` or `uv tool install`:++- should not depend on Python package postinstall hooks+- may leave runtime unprepared+- `vibe start` or first `vibe show` status can report a clear preparation+ warning+- first Show Page request can still attempt one controlled prepare if enabled++This split keeps official UX fast while preserving Python packaging norms.++## Runtime Update Semantics++Vibe Remote releases pin a specific runtime manifest. A Vibe Remote upgrade is+therefore the default runtime update trigger.++Rules:++- New Vibe Remote version sees a new manifest.+- If the current cache matches the manifest digest, no work is needed.+- If the manifest differs, prepare the new archive in a temporary directory.+- Only after verification succeeds, atomically update `current`.+- Existing sidecar processes keep running until idle TTL, explicit stop, or+ Vibe Remote restart.+- New sidecar starts use the new `current`.+- Keep the previous version for rollback until a cleanup policy removes it.++This avoids breaking active Show Pages mid-session while still making new+sessions pick up the updated runtime.++## CLI Surface++Add a small CLI group:++```bash+vibe runtime status+vibe runtime prepare+vibe runtime clean+```++`status` should show:++- provider+- current platform+- pinned runtime version+- installed runtime version+- archive digest+- cache path+- last prepare result+- whether Node satisfies the manifest engine++`prepare` options:++- `--force` redownload/reinstall even if the digest matches+- `--offline` use only verified cache, no network+- `--manifest <path>` or `--manifest-url <url>` for development and regression+ tests+- `--strict` returns non-zero when preparation fails++`clean` options:++- keep current+- keep previous N versions+- remove failed temporary directories and stale downloads++## Failure Policy++Runtime prepare failure must not fail core Vibe Remote install.++Failure modes:++- Node missing or unsupported+- network unavailable+- checksum mismatch+- unsupported platform+- unsafe archive member+- missing runtime CLI after extraction+- permission or disk-space error++Behavior:++- official install/upgrade prints a warning and exits successfully unless the+ user explicitly requested strict runtime preparation+- `vibe runtime prepare --strict` can return non-zero for CI+- Show Page recovery page should explain that the runtime package is missing or+ invalid and suggest `vibe runtime prepare`+- if a previously verified runtime exists, reuse it when safe+- do not reuse a stale installed runtime when the active manifest changed and+ the new archive fails integrity checks++## Release Workflow Changes++GitHub prerelease workflow:++1. Build six runtime archives.+2. Compute sha256 and size for each archive.+3. Generate `show-runtime-manifest.json` pinned to the runtime repo commit.+4. Attach the archives and manifest as GitHub release assets.+5. Copy only the manifest lock into the Vibe Remote package.+6. Verify the wheel does not contain `vibe/show_runtime/*.tgz`.+7. Verify the wheel does contain the manifest lock.++PyPI workflow:++- Generate the same manifest and verify the wheel contains the manifest but no+ runtime archives.+- Do not copy runtime archives into `dist/` for PyPI upload; PyPI should receive+ only Python package artifacts.+- The manifest URLs still point at GitHub release assets for the same tag, so+ the matching GitHub release assets must exist before users run+ `vibe runtime prepare` from a PyPI-installed package.++## Security And Integrity++- Use sha256 verification before extraction.+- Keep safe tar extraction checks for files, directories, symlinks, and hard+ links.+- Extract into a temporary directory under the runtime cache and rename after+ validation.+- Never execute code from a newly downloaded archive before integrity checks.+- Treat manifest URL overrides as advanced/development mode.+- Avoid forwarding user credentials or UI cookies to the runtime sidecar.++## Tests++Unit tests:++- platform tag selection+- manifest parsing and validation+- checksum mismatch handling+- offline cache hit and cache miss+- atomic install success path+- safe tar rejection still works+- old verified runtime fallback after failed new download++CLI tests:++- `vibe runtime status` with no runtime+- `vibe runtime prepare --offline` cache hit+- `vibe runtime prepare --offline` cache miss+- `vibe runtime prepare` is warning-only by default+- `vibe runtime prepare --strict` returns non-zero on failure+- `vibe runtime clean` keeps current++Release tests:++- wheel has no runtime archives+- wheel includes manifest lock+- manifest contains all six platforms+- manifest sha256 matches uploaded artifacts+- install/upgrade script treats prepare failure as warning by default++Regression:++- clean install through official script prepares runtime+- new Show Page opens without runtime download wait+- upgrade prepares newer runtime and preserves existing session behavior+- offline start reuses verified cache++## Implementation Steps++1. Add manifest schema and test fixtures.+2. Add manifest-cache support to `ShowRuntimeManager`.+3. Keep archive/github/npm as explicit provider overrides.+4. Add `vibe runtime status/prepare/clean`.+5. Update install and upgrade scripts to call `vibe runtime prepare --strict` with+ warning-only behavior by default.+6. Update release workflows to generate and attach runtime manifest/assets.+7. Remove `vibe/show_runtime/*.tgz` from wheel artifacts.+8. Run a full clean-install regression.++## Open Questions++- Should prerelease manifests point to the Vibe Remote release assets or to a+ dedicated `vibe-show-runtime` release?+- How many old runtime versions should `vibe runtime clean` retain by default?+- Should `vibe check-update` report runtime manifest drift separately from+ Vibe Remote package drift?diff --git a/docs/plans/show-service-runtime.md b/docs/plans/show-service-runtime.mdindex bdd94dd2b..7e9f6c8d0 100644--- a/docs/plans/show-service-runtime.md+++ b/docs/plans/show-service-runtime.md@@ -169,6 +169,12 @@ can use presets or override CSS variables without editing component source.Dependencies are owned by the runtime, not by each session.+The next distribution step is the manifest/cache model described in+`show-runtime-manifest-cache.md`: Vibe Remote wheels should carry a pinned+runtime manifest, while official install and upgrade flows prepare only the+current platform's runtime archive into the global cache. This replaces the+temporary bundled-six-archive wheel strategy once implemented.+Vibe Remote resolution order:1. `VIBE_SHOW_RUNTIME_BIN`, for local development or pinned custom runtime.diff --git a/install.ps1 b/install.ps1index e3df7c983..1ac50746a 100644--- a/install.ps1+++ b/install.ps1@@ -9,7 +9,7 @@ $ErrorActionPreference = "Stop"$REPO = "cyhhao/vibe-remote"$PACKAGE_NAME = "vibe-remote"$TSINGHUA_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple"-$NODE_VERSION_MAJOR = 20+$NODE_MINIMUM_REQUIREMENT = "20.19+ or 22.12+"function Write-Banner {Write-Host @"@@ -60,8 +60,19 @@ function Test-Node {}try {$version = (& node --version).Trim().TrimStart("v")- $major = [int]($version.Split(".")[0])- return $major -ge $NODE_VERSION_MAJOR+ $parts = $version.Split(".")+ $major = [int]$parts[0]+ $minor = [int]$parts[1]+ if ($major -eq 20) {+ return $minor -ge 19+ }+ if ($major -gt 22) {+ return $true+ }+ if ($major -eq 22) {+ return $minor -ge 12+ }+ return $false} catch {return $false}@@ -78,7 +89,7 @@ function Install-Node {return}- Write-Info "Installing Node.js for Show Pages runtime..."+ Write-Info "Installing Node.js $NODE_MINIMUM_REQUIREMENT for Show Pages runtime..."if (Test-Command "winget") {$result = Invoke-NativeCommand -FilePath "winget" -Arguments @("install",@@ -103,7 +114,7 @@ function Install-Node {}}- throw "Node.js 20+ is required for Show Pages runtime. Please install Node.js LTS from https://nodejs.org/ if needed."+ throw "Node.js $NODE_MINIMUM_REQUIREMENT is required for Show Pages runtime. Please install Node.js LTS from https://nodejs.org/ if needed."}function Install-NodeOptional {@@ -114,7 +125,7 @@ function Install-NodeOptional {if ($message) {Write-Warning $message}- Write-Warning "Node.js 20+ is not available, so managed Show Pages may install/start later when first used."+ Write-Warning "Node.js $NODE_MINIMUM_REQUIREMENT is not available, so managed Show Pages may install/start later when first used."Write-Warning "Continuing with Vibe Remote installation; install Node.js manually if Show Pages runtime reports it missing."}}@@ -318,6 +329,31 @@ function Test-Installation {Write-Error "Installation verification failed. vibe command not found."}+function Prepare-ShowRuntime {+ if ($env:VIBE_INSTALL_SKIP_SHOW_RUNTIME -eq "1") {+ Write-Warning "Skipping Show Runtime preparation because VIBE_INSTALL_SKIP_SHOW_RUNTIME=1"+ return+ }++ if (-not (Test-Command "vibe")) {+ Write-Warning "Show Runtime was not prepared because the vibe command is not available yet"+ return+ }++ Write-Info "Preparing Show Runtime for this platform..."+ $result = Invoke-NativeCommand -FilePath "vibe" -Arguments @("runtime", "prepare", "--strict")+ if ($result.Success) {+ Write-Success "Show Runtime is ready"+ return+ }++ Write-Warning "Show Runtime preparation failed; Vibe Remote installation is still complete"+ if ($result.Output) {+ Write-Warning $result.Output+ }+ Write-Warning "Run 'vibe runtime prepare' after fixing Node.js or network access"+}+function Write-NextSteps {Write-Host ""Write-Host "Installation complete!" -ForegroundColor Green@@ -360,6 +396,10 @@ function Main {# VerifyTest-Installation++ # Pre-download the current platform Show Runtime when possible. This is+ # intentionally warning-only so Node/network issues never break Vibe Remote.+ Prepare-ShowRuntime# DoneWrite-NextStepsdiff --git a/install.sh b/install.shindex 49219456b..3c95d3a10 100755--- a/install.sh+++ b/install.sh@@ -16,8 +16,7 @@ NC='\033[0m' # No Color# ConfigurationREPO="cyhhao/vibe-remote"PACKAGE_NAME="vibe-remote"-NODE_VERSION="22.16.0"-NODE_VERSION_MAJOR="20"+NODE_MINIMUM_REQUIREMENT="20.19+ or 22.12+"VIBE_BIN_PATH=""VIBE_TOOL_BIN_DIR=""ORIGINAL_PATH="$PATH"@@ -261,21 +260,36 @@ uv_is_native_for_host() {uv_binary_is_acceptable "$uv_path"}-node_major_version() {+node_version_parts() {local version=""version="$(node --version 2>/dev/null || true)"version="${version#v}"- version="${version%%.*}"- case "$version" in- ''|*[!0-9]*) return 1 ;;- *) printf '%s\n' "$version" ;;+ IFS='.' read -r major minor patch_extra <<EOF+$version+EOF+ local patch="${patch_extra%%[^0-9]*}"+ case "$major.$minor.$patch" in+ *[!0-9.]*|.*|*..*|*.) return 1 ;;+ *) printf '%s %s %s\n' "$major" "$minor" "$patch" ;;esac}node_is_acceptable() {- local major=""- major="$(node_major_version || true)"- [ -n "$major" ] && [ "$major" -ge 20 ]+ local major minor patch+ read -r major minor patch <<EOF+$(node_version_parts || true)+EOF+ [ -n "${major:-}" ] || return 1+ if [ "$major" -eq 20 ]; then+ [ "$minor" -ge 19 ]+ elif [ "$major" -ge 22 ]; then+ if [ "$major" -gt 22 ]; then+ return 0+ fi+ [ "$minor" -ge 12 ]+ else+ return 1+ fi}node_platform_arch() {@@ -320,13 +334,13 @@ install_node() {local osos="$(detect_os)"- info "Installing Node.js ${NODE_VERSION_MAJOR:-20}+ for Show Pages runtime..."+ info "Installing Node.js ${NODE_MINIMUM_REQUIREMENT} for Show Pages runtime..."case "$os" inmacos)if command_exists brew; thenbrew install node || return 1else- warn "Node.js 20+ is required for managed Show Pages. Install Homebrew or Node.js from https://nodejs.org/ if needed."+ warn "Node.js ${NODE_MINIMUM_REQUIREMENT} is required for managed Show Pages. Install Homebrew or Node.js from https://nodejs.org/ if needed."return 1fi;;@@ -341,12 +355,12 @@ install_node() {elif command_exists pacman; thenrun_as_root pacman -S --noconfirm nodejs npm || return 1else- warn "Node.js 20+ is required for managed Show Pages. Please install Node.js globally with your system package manager if needed."+ warn "Node.js ${NODE_MINIMUM_REQUIREMENT} is required for managed Show Pages. Please install Node.js globally with your system package manager if needed."return 1fi;;*)- warn "Node.js 20+ is required for managed Show Pages. Please install Node.js globally if needed."+ warn "Node.js ${NODE_MINIMUM_REQUIREMENT} is required for managed Show Pages. Please install Node.js globally if needed."return 1;;esac@@ -356,7 +370,7 @@ install_node() {return 0fi- warn "Node.js installation completed but node 20+ is not available in PATH"+ warn "Node.js installation completed but Node.js ${NODE_MINIMUM_REQUIREMENT} is not available in PATH"return 1}@@ -370,7 +384,7 @@ install_node_optional() {return 0fi- warn "Node.js 20+ is not available, so managed Show Pages may install/start later when first used."+ warn "Node.js ${NODE_MINIMUM_REQUIREMENT} is not available, so managed Show Pages may install/start later when first used."warn "Continuing with Vibe Remote installation; install Node.js manually if Show Pages runtime reports it missing."return 0}@@ -536,6 +550,30 @@ verify_installation() {error "Installation verification failed. vibe command not found."}+prepare_show_runtime() {+ if [ "${VIBE_INSTALL_SKIP_SHOW_RUNTIME:-}" = "1" ]; then+ warn "Skipping Show Runtime preparation because VIBE_INSTALL_SKIP_SHOW_RUNTIME=1"+ return 0+ fi++ local vibe_cmd="${VIBE_BIN_PATH:-}"+ if [ -z "$vibe_cmd" ] && command_exists vibe; then+ vibe_cmd="$(command -v vibe)"+ fi+ if [ -z "$vibe_cmd" ] || [ ! -x "$vibe_cmd" ]; then+ warn "Show Runtime was not prepared because the vibe command is not available yet"+ return 0+ fi++ info "Preparing Show Runtime for this platform..."+ if "$vibe_cmd" runtime prepare --strict; then+ success "Show Runtime is ready"+ else+ warn "Show Runtime preparation failed; Vibe Remote installation is still complete"+ warn "Run 'vibe runtime prepare' after fixing Node.js or network access"+ fi+}+# Print next stepsprint_next_steps() {local vibe_dir@@ -605,6 +643,10 @@ main() {# Verifyverify_installation++ # Pre-download the current platform Show Runtime when possible. This is+ # intentionally warning-only so Node/network issues never break Vibe Remote.+ prepare_show_runtime# Doneprint_next_stepsdiff --git a/pyproject.toml b/pyproject.tomlindex 5cc9f8590..2c3ae14e5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -85,7 +85,7 @@ version-file = "vibe/_version.py"[tool.hatch.build]# Include generated assets even though they are in .gitignore (build artifacts)-artifacts = ["ui/dist/**", "vibe/show_runtime/*.tgz"]+artifacts = ["ui/dist/**", "vibe/show_runtime_manifest.json"][tool.hatch.build.targets.wheel]packages = ["vibe", "config", "core", "modules", "storage"]@@ -104,7 +104,7 @@ include = ["storage/**","main.py","ui/dist/**",- "vibe/show_runtime/**",+ "vibe/show_runtime_manifest.json","README.md","LICENSE",]diff --git a/scripts/generate_show_runtime_manifest.py b/scripts/generate_show_runtime_manifest.pynew file mode 100644index 000000000..4a474b366--- /dev/null+++ b/scripts/generate_show_runtime_manifest.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+from __future__ import annotations++import argparse+import hashlib+import json+from pathlib import Path+++ARCHIVE_PREFIX = "vibe-show-runtime-node-"+ARCHIVE_SUFFIX = ".tgz"+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as file:+ for chunk in iter(lambda: file.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _platform_from_archive(path: Path) -> str:+ name = path.name+ if not name.startswith(ARCHIVE_PREFIX) or not name.endswith(ARCHIVE_SUFFIX):+ raise ValueError(f"Unexpected Show Runtime archive name: {name}")+ return name[len(ARCHIVE_PREFIX) : -len(ARCHIVE_SUFFIX)]+++def _read_runtime_ref(value: str | None, patterns: list[str]) -> str:+ refs: set[str] = set()+ if value:+ refs.add(value.strip())+ for pattern in patterns:+ for path in sorted(Path().glob(pattern)):+ text = path.read_text(encoding="utf-8").strip()+ if text:+ refs.add(text)+ refs.discard("")+ if len(refs) != 1:+ raise SystemExit("Expected exactly one Show Runtime ref, found: " + ", ".join(sorted(refs)))+ return next(iter(refs))+++def build_manifest(*, archive_dir: Path, tag: str, repo: str, runtime_ref: str, output: Path) -> dict:+ archives: dict[str, dict[str, object]] = {}+ base_url = f"https://github.com/{repo}/releases/download/{tag}"+ for archive in sorted(archive_dir.glob(f"{ARCHIVE_PREFIX}*{ARCHIVE_SUFFIX}")):+ platform = _platform_from_archive(archive)+ archives[platform] = {+ "name": archive.name,+ "url": f"{base_url}/{archive.name}",+ "sha256": _sha256(archive),+ "size": archive.stat().st_size,+ }++ expected = {+ "darwin-arm64",+ "darwin-x64",+ "linux-arm64",+ "linux-x64",+ "win32-arm64",+ "win32-x64",+ }+ missing = sorted(expected - set(archives))+ if missing:+ raise SystemExit("Missing Show Runtime archives: " + ", ".join(missing))++ manifest = {+ "schema_version": 1,+ "runtime_version": runtime_ref,+ "runtime_source": {+ "repo": "avibe-bot/vibe-show-runtime",+ "ref": runtime_ref,+ },+ "minimum_node": "^20.19.0 || >=22.12.0",+ "archives": archives,+ }+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ return manifest+++def main() -> int:+ parser = argparse.ArgumentParser(description="Generate a Vibe Show Runtime manifest from platform archives.")+ parser.add_argument("--archive-dir", required=True, type=Path)+ parser.add_argument("--tag", required=True)+ parser.add_argument("--repo", required=True)+ runtime_ref_group = parser.add_mutually_exclusive_group(required=True)+ runtime_ref_group.add_argument("--runtime-ref")+ runtime_ref_group.add_argument(+ "--runtime-ref-file",+ action="append",+ default=[],+ help="Glob pattern for files containing the Show Runtime commit used to build the archives.",+ )+ parser.add_argument("--output", required=True, type=Path)+ args = parser.parse_args()+ runtime_ref = _read_runtime_ref(args.runtime_ref, args.runtime_ref_file)+ manifest = build_manifest(+ archive_dir=args.archive_dir,+ tag=args.tag,+ repo=args.repo,+ runtime_ref=runtime_ref,+ output=args.output,+ )+ print(json.dumps({"ok": True, "platforms": sorted(manifest["archives"])}, indent=2))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/e2e/test_install_command.py b/tests/e2e/test_install_command.pyindex fe022914e..ba0c4e2b1 100644--- a/tests/e2e/test_install_command.py+++ b/tests/e2e/test_install_command.py@@ -60,7 +60,7 @@ def test_install_command_starts_vibe_in_fresh_container():command = ("apt-get update >/dev/null && ""apt-get install -y --no-install-recommends curl ca-certificates bash procps >/dev/null && "- f"cat /work/install.sh | env VIBE_INSTALL_PACKAGE_SPEC=/fixtures/{wheel_path.name} bash && "+ f"cat /work/install.sh | env VIBE_INSTALL_SKIP_SHOW_RUNTIME=1 VIBE_INSTALL_PACKAGE_SPEC=/fixtures/{wheel_path.name} bash && ""vibe version && ""vibe && sleep 2 && vibe status")diff --git a/tests/e2e/test_upgrade_command.py b/tests/e2e/test_upgrade_command.pyindex 7a69c677b..d3363af41 100644--- a/tests/e2e/test_upgrade_command.py+++ b/tests/e2e/test_upgrade_command.py@@ -73,9 +73,9 @@ def test_upgrade_command_uses_built_release_artifact():'export PATH="/usr/local/bin:/usr/bin:/bin"',"vibe version","VIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json "- f"VIBE_UPGRADE_PACKAGE_SPEC=/fixtures/{wheel_path.name} vibe check-update",+ f"VIBE_INSTALL_SKIP_SHOW_RUNTIME=1 VIBE_UPGRADE_PACKAGE_SPEC=/fixtures/{wheel_path.name} vibe check-update","VIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json "- f"VIBE_UPGRADE_PACKAGE_SPEC=/fixtures/{wheel_path.name} vibe upgrade",+ f"VIBE_INSTALL_SKIP_SHOW_RUNTIME=1 VIBE_UPGRADE_PACKAGE_SPEC=/fixtures/{wheel_path.name} vibe upgrade","hash -r",'printf "launcher=%s\n" "$(command -v vibe)"',"vibe version",diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex 54c384952..82ead06f4 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -49,6 +49,12 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:echo "usage: vibe"elif [ "${{1:-}}" = "version" ]; thenecho "vibe-remote 9.9.9"+ elif [ "${{1:-}}" = "runtime" ] && [ "${{2:-}}" = "prepare" ]; then+ if [ "${{VIBE_TEST_RUNTIME_PREPARE_FAIL:-}}" = "1" ]; then+ echo "node missing" >&2+ exit 9+ fi+ echo "Show Runtime ready."elseecho "started"fi@@ -197,11 +203,58 @@ def test_install_script_installs_node_when_missing(tmp_path):install_result = _install(env, cwd=tmp_path)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert "Installing Node.js 20+" in install_result.stdout+ assert "Installing Node.js 20.19+ or 22.12+" in install_result.stdoutassert "Node.js installed successfully" in install_result.stdoutassert (path_dir / "node").exists()+def test_install_script_replaces_node_below_show_runtime_floor(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"++ _write_fake_uv(path_dir / "uv", uv_log)+ _write_fake_node(path_dir / "node", version="v20.18.0")+ _write_fake_uname(path_dir / "uname", machine="arm64")+ _write_executable(+ path_dir / "brew",+ f"""\+ #!/usr/bin/env bash+ if [ "${{1:-}}" = "install" ] && [ "${{2:-}}" = "node" ]; then+ cat > "{path_dir / 'node'}" <<'EOF'+ #!/usr/bin/env bash+ if [ "${{1:-}}" = "--version" ]; then+ echo "v22.16.0"+ else+ echo "node"+ fi+ EOF+ chmod +x "{path_dir / 'node'}"+ exit 0+ fi+ exit 1+ """,+ )++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_INSTALL_SKIP_NODE"] = "0"++ install_result = _install(env, cwd=tmp_path)++ assert install_result.returncode == 0, install_result.stdout + install_result.stderr+ assert "Installing Node.js 20.19+ or 22.12+" in install_result.stdout+ assert subprocess.run(+ [str(path_dir / "node"), "--version"],+ capture_output=True,+ text=True,+ check=False,+ ).stdout.strip() == "v22.16.0"++def test_install_script_continues_when_node_install_fails(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()@@ -229,13 +282,36 @@ def test_install_script_continues_when_node_install_fails(tmp_path):version_result = _vibe_version(env)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert "Installing Node.js 20+" in install_result.stdout+ assert "Installing Node.js 20.19+ or 22.12+" in install_result.stdoutassert "Continuing with Vibe Remote installation" in install_result.stdoutassert "vibe-remote installed successfully" in install_result.stdoutassert version_result.returncode == 0, version_result.stdout + version_result.stderrassert "vibe-remote 9.9.9" in version_result.stdout+def test_install_script_continues_when_show_runtime_prepare_fails(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"++ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_TEST_RUNTIME_PREPARE_FAIL"] = "1"++ install_result = _install(env, cwd=tmp_path)+ version_result = _vibe_version(env)++ assert install_result.returncode == 0, install_result.stdout + install_result.stderr+ assert "Show Runtime preparation failed; Vibe Remote installation is still complete" in install_result.stdout+ assert version_result.returncode == 0, version_result.stdout + version_result.stderr+ assert "vibe-remote 9.9.9" in version_result.stdout++def test_install_script_prefers_new_bin_over_stale_local_bin(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 98c3254fd..6e170062f 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -36,11 +36,37 @@ def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_assert result["old_pid"] == 12345assert calls["command"][:2] == ["/bin/vibe", "__restart-supervisor"]assert calls["command"][calls["command"].index("--delay-seconds") + 1] == "60"+ assert "--prepare-show-runtime" not in calls["command"]assert calls["kwargs"]["start_new_session"] is Trueassert calls["kwargs"]["env"] == {"PATH": "/bin"}assert runtime.read_json(runtime.get_restart_status_path())["job_id"] == result["job_id"]+def test_schedule_restart_can_prepare_show_runtime_after_restart(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ calls = {}++ monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)++ def fake_popen(command, **kwargs):+ calls["command"] = command++ class Proc:+ pid = 45678++ return Proc()++ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)++ restart_supervisor.schedule_restart(delay_seconds=2, vibe_path="/bin/vibe", trigger="upgrade", prepare_show_runtime=True)++ assert "--prepare-show-runtime" in calls["command"]++def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()@@ -72,6 +98,46 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):assert status["new_pid"] == 222+def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ paths.get_runtime_pid_path().write_text("111", encoding="utf-8")+ calls = []++ monkeypatch.setattr(runtime, "stop_ui", lambda: calls.append("stop_ui") or True)+ monkeypatch.setattr(runtime, "stop_service", lambda: calls.append("stop_service") or True)+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])+ monkeypatch.setattr(restart_supervisor, "get_restart_command", lambda vibe_path=None: ["/bin/vibe"])+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)++ def fake_run(command, **kwargs):+ calls.append(("run", command))+ if command == ["/bin/vibe", "start"]:+ paths.get_runtime_pid_path().write_text("222", encoding="utf-8")+ return subprocess.CompletedProcess(command, 0)++ monkeypatch.setattr(restart_supervisor.subprocess, "run", fake_run)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)++ rc = restart_supervisor._run_restart_job(+ job_id="jobruntime",+ delay_seconds=0,+ vibe_path="/bin/vibe",+ trigger="upgrade",+ prepare_show_runtime=True,+ )++ assert rc == 0+ assert calls == [+ "stop_ui",+ "stop_service",+ ("run", ["/bin/vibe", "start"]),+ ("run", ["/bin/vibe", "runtime", "prepare", "--strict"]),+ ]+ assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"++def test_restart_job_aborts_when_stop_fails(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/tests/test_show_pages.py b/tests/test_show_pages.pyindex 3c763a6d1..921f888bf 100644--- a/tests/test_show_pages.py+++ b/tests/test_show_pages.py@@ -22,6 +22,64 @@ def test_show_without_subcommand_prints_help(capsys):assert "vibe show path --session-id sesk8m4q2p7x" in captured.out+def test_runtime_prepare_cli_reports_warning_only_failure(monkeypatch, capsys):+ parser = cli.build_parser()+ args = parser.parse_args(["runtime", "prepare", "--json"])++ class FakeRuntimeManager:+ def prepare(self, *, force=False, offline=None):+ assert force is False+ assert offline is None+ return {"ok": False, "reason": "runtime_node_missing"}++ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())++ assert cli.cmd_runtime(args) == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["ok"] is False+ assert payload["reason"] == "runtime_node_missing"+++def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):+ parser = cli.build_parser()+ args = parser.parse_args(["runtime", "prepare", "--json"])++ class FakeRuntimeManager:+ def prepare(self, *, force=False, offline=None):+ assert force is False+ assert offline is None+ return {"ok": True}++ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())++ assert cli.cmd_runtime(args) == 0+++def test_runtime_manager_from_args_preserves_offline_environment(monkeypatch, tmp_path):+ parser = cli.build_parser()+ args = parser.parse_args(["runtime", "status"])+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ monkeypatch.setenv("VIBE_SHOW_RUNTIME_OFFLINE", "1")++ manager = cli._show_runtime_manager_from_args(args)++ assert manager.offline is True+++def test_runtime_prepare_cli_strict_fails_when_prepare_fails(monkeypatch, capsys):+ parser = cli.build_parser()+ args = parser.parse_args(["runtime", "prepare", "--strict"])++ class FakeRuntimeManager:+ def prepare(self, *, force=False, offline=None):+ return {"ok": False, "reason": "runtime_archive_download_failed"}++ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())++ assert cli.cmd_runtime(args) == 1+ assert "runtime_archive_download_failed" in capsys.readouterr().err++def _save_config() -> V2Config:config = V2Config(mode="self_host",diff --git a/tests/test_show_runtime_manifest.py b/tests/test_show_runtime_manifest.pynew file mode 100644index 000000000..3f0f57e13--- /dev/null+++ b/tests/test_show_runtime_manifest.py@@ -0,0 +1,58 @@+import json+from pathlib import Path++import pytest++from scripts.generate_show_runtime_manifest import build_manifest+++PLATFORMS = (+ "darwin-arm64",+ "darwin-x64",+ "linux-arm64",+ "linux-x64",+ "win32-arm64",+ "win32-x64",+)+++def test_generate_show_runtime_manifest_records_all_platform_archives(tmp_path: Path) -> None:+ archive_dir = tmp_path / "archives"+ archive_dir.mkdir()+ for platform in PLATFORMS:+ (archive_dir / f"vibe-show-runtime-node-{platform}.tgz").write_bytes(f"runtime-{platform}".encode())++ output = tmp_path / "manifest.json"+ manifest = build_manifest(+ archive_dir=archive_dir,+ tag="gh-v2.4.0rc1",+ repo="cyhhao/vibe-remote",+ runtime_ref="runtime-sha",+ output=output,+ )++ assert set(manifest["archives"]) == set(PLATFORMS)+ assert output.exists()+ written = json.loads(output.read_text(encoding="utf-8"))+ assert written["runtime_version"] == "runtime-sha"+ assert written["archives"]["linux-x64"]["url"] == (+ "https://github.com/cyhhao/vibe-remote/releases/download/gh-v2.4.0rc1/"+ "vibe-show-runtime-node-linux-x64.tgz"+ )+ assert written["archives"]["linux-x64"]["size"] == len(b"runtime-linux-x64")+++def test_generate_show_runtime_manifest_fails_when_platform_archive_missing(tmp_path: Path) -> None:+ archive_dir = tmp_path / "archives"+ archive_dir.mkdir()+ for platform in PLATFORMS[:-1]:+ (archive_dir / f"vibe-show-runtime-node-{platform}.tgz").write_bytes(b"runtime")++ with pytest.raises(SystemExit, match="Missing Show Runtime archives"):+ build_manifest(+ archive_dir=archive_dir,+ tag="v2.4.0",+ repo="cyhhao/vibe-remote",+ runtime_ref="runtime-sha",+ output=tmp_path / "manifest.json",+ )diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex a39b0a5b9..193189dbd 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -1,5 +1,7 @@import asyncio+import hashlibimport io+import jsonimport tarfilefrom pathlib import Path@@ -51,6 +53,11 @@ class _FakeShowRuntimeManager:self.stopped = True[email protected](autouse=True)+def _show_runtime_node_version(monkeypatch):+ monkeypatch.setattr("core.show_runtime._node_version", lambda node: (22, 16, 0))++def _create_show_page(session_id: str, visibility: str) -> str | None:page_dir = ensure_show_page_dir(session_id)(page_dir / "index.html").write_text("<!doctype html><title>Show</title><h1>Show Page</h1>", encoding="utf-8")@@ -92,6 +99,49 @@ def _create_agent_session(session_id: str) -> None:)+def _write_runtime_archive(tmp_path: Path, *, text: str = "#!/usr/bin/env node\n") -> Path:+ archive_root = tmp_path / f"archive-root-{hashlib.sha256(text.encode()).hexdigest()[:8]}"+ cli_path = archive_root / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"+ cli_path.parent.mkdir(parents=True)+ cli_path.write_text(text, encoding="utf-8")+ archive_path = tmp_path / f"vibe-show-runtime-node-{hashlib.sha256(text.encode()).hexdigest()[:8]}.tgz"+ with tarfile.open(archive_path, "w:gz") as tar:+ tar.add(archive_root / "node_modules", arcname="node_modules")+ return archive_path+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as file:+ for chunk in iter(lambda: file.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _write_runtime_manifest(tmp_path: Path, archive_path: Path, *, sha256: str | None = None, size: int | None = None) -> Path:+ manifest_path = tmp_path / "show_runtime_manifest.json"+ manifest_path.parent.mkdir(parents=True, exist_ok=True)+ manifest_path.write_text(+ json.dumps(+ {+ "schema_version": 1,+ "runtime_version": "runtime-test-ref",+ "minimum_node": "^20.19.0 || >=22.12.0",+ "archives": {+ _runtime_platform_tag(): {+ "name": archive_path.name,+ "url": archive_path.resolve().as_uri(),+ "sha256": sha256 or _sha256(archive_path),+ "size": archive_path.stat().st_size if size is None else size,+ }+ },+ }+ ),+ encoding="utf-8",+ )+ return manifest_path++def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))_save_config(tmp_path)@@ -731,6 +781,7 @@ def test_show_runtime_manager_installs_from_prebuilt_archive(monkeypatch, tmp_pamanager = ShowRuntimeManager(workspace_root=tmp_path / "show",runtime_dir=tmp_path / "runtime",+ runtime_source="archive",archive_path=archive_path,)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)@@ -762,6 +813,7 @@ def test_show_runtime_manager_installs_prebuilt_archive_with_internal_symlinks(mmanager = ShowRuntimeManager(workspace_root=tmp_path / "show",runtime_dir=tmp_path / "runtime",+ runtime_source="archive",archive_path=archive_path,)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)@@ -814,6 +866,7 @@ def test_show_runtime_manager_reuses_installed_prebuilt_runtime_without_archive(manager = ShowRuntimeManager(workspace_root=tmp_path / "show",runtime_dir=tmp_path / "runtime",+ runtime_source="archive",archive_path=tmp_path / "missing.tgz",)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)@@ -822,6 +875,22 @@ def test_show_runtime_manager_reuses_installed_prebuilt_runtime_without_archive(assert manager._install_reason is None+def test_show_runtime_manager_archive_source_honors_offline_mode(monkeypatch, tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="archive",+ offline=True,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)+ monkeypatch.setattr(manager, "_download_runtime_archive", lambda archive_url: (_ for _ in ()).throw(AssertionError("network")))++ result = manager.prepare()++ assert result["ok"] is False+ assert result["reason"] == "runtime_archive_unavailable_offline"++def test_show_runtime_manager_refreshes_stale_prebuilt_archive(monkeypatch, tmp_path):runtime_dir = tmp_path / "runtime"installed_cli = runtime_dir / "prebuilt" / "current" / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"@@ -839,6 +908,7 @@ def test_show_runtime_manager_refreshes_stale_prebuilt_archive(monkeypatch, tmp_manager = ShowRuntimeManager(workspace_root=tmp_path / "show",runtime_dir=runtime_dir,+ runtime_source="archive",archive_path=archive_path,)monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)@@ -847,10 +917,147 @@ def test_show_runtime_manager_refreshes_stale_prebuilt_archive(monkeypatch, tmp_assert installed_cli.read_text(encoding="utf-8") == "new runtime\n"+def test_show_runtime_manager_installs_from_manifest_cache(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ runtime_dir = tmp_path / "runtime"+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ manifest_path=manifest_path,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)++ result = manager.prepare()+ installed_cli = (+ runtime_dir+ / "versions"+ / "runtime-test-ref"+ / _runtime_platform_tag()+ / "node_modules"+ / "@avibe"+ / "show-runtime"+ / "dist"+ / "cli.js"+ )++ assert result["ok"] is True+ assert result["command"] == ["/bin/node", str(installed_cli)]+ assert manager._install_reason is None+ assert (runtime_dir / "downloads" / f"{_sha256(archive_path)}.tgz").exists()+ metadata = json.loads((installed_cli.parents[4] / ".vibe-show-runtime.json").read_text(encoding="utf-8"))+ assert metadata["provider"] == "manifest-cache"+ assert metadata["archive_sha256"] == _sha256(archive_path)+ status = manager.status()+ assert status["installed"] is True+ assert status["installed_matches_manifest"] is True+++def test_show_runtime_manager_rejects_node_below_manifest_minimum(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)+ monkeypatch.setattr("core.show_runtime._node_version", lambda node: (20, 18, 0))++ result = manager.prepare()++ assert result["ok"] is False+ assert result["reason"] == "runtime_node_unsupported"+ assert result["status"]["node_supported"] is False+++def test_show_runtime_manager_rejects_manifest_archive_checksum_mismatch(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path, sha256="0" * 64)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ manifest_path=manifest_path,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)++ result = manager.prepare()++ assert result["ok"] is False+ assert result["reason"] == "runtime_archive_checksum_mismatch"+++def test_show_runtime_manager_does_not_reuse_stale_manifest_install_after_checksum_failure(monkeypatch, tmp_path):+ old_archive_path = _write_runtime_archive(tmp_path, text="old runtime\n")+ old_manifest_path = _write_runtime_manifest(tmp_path / "old", old_archive_path)+ runtime_dir = tmp_path / "runtime"+ old_manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ manifest_path=old_manifest_path,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)+ assert old_manager.prepare()["ok"] is True++ new_archive_path = _write_runtime_archive(tmp_path, text="new runtime\n")+ new_manifest_path = _write_runtime_manifest(tmp_path / "new", new_archive_path, sha256="f" * 64)+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ manifest_path=new_manifest_path,+ )++ result = manager.prepare()++ assert result["ok"] is False+ assert result["reason"] == "runtime_archive_checksum_mismatch"+++def test_show_runtime_manager_installs_manifest_archive_from_verified_offline_cache(monkeypatch, tmp_path):+ archive_path = _write_runtime_archive(tmp_path)+ manifest_path = _write_runtime_manifest(tmp_path, archive_path)+ digest = _sha256(archive_path)+ runtime_dir = tmp_path / "runtime"+ cached = runtime_dir / "downloads" / f"{digest}.tgz"+ cached.parent.mkdir(parents=True)+ cached.write_bytes(archive_path.read_bytes())+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ manifest["archives"][_runtime_platform_tag()]["url"] = "https://example.invalid/runtime.tgz"+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=runtime_dir,+ manifest_path=manifest_path,+ offline=True,+ )+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: ["/bin/node"] if command == "node" else None)++ result = manager.prepare()++ assert result["ok"] is True+ assert result["reason"] is None+++def test_show_runtime_manager_status_does_not_read_manifest_for_legacy_sources(tmp_path):+ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ runtime_source="npm",+ auto_install=False,+ )++ status = manager.status()++ assert status["provider"] == "npm"+ assert status["manifest"] is None+ assert status["reason"] is None++def test_show_runtime_manager_can_disable_auto_install(tmp_path):manager = ShowRuntimeManager(workspace_root=tmp_path / "show",runtime_dir=tmp_path / "runtime",+ runtime_source="npm",auto_install=False,)@@ -859,6 +1066,7 @@ def test_show_runtime_manager_can_disable_auto_install(tmp_path):def test_show_runtime_manager_installs_without_blocking_event_loop(monkeypatch, tmp_path):+ monkeypatch.setattr("core.show_runtime._packaged_runtime_manifest_exists", lambda: True)manager = ShowRuntimeManager(workspace_root=tmp_path / "show",runtime_dir=tmp_path / "runtime",@@ -884,6 +1092,28 @@ def test_show_runtime_manager_installs_without_blocking_event_loop(monkeypatch,assert calls == [fake_install]+def test_show_runtime_manager_defaults_to_archive_when_package_manifest_is_absent(monkeypatch, tmp_path):+ monkeypatch.setattr("core.show_runtime._packaged_runtime_manifest_exists", lambda: False)++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )++ assert manager.runtime_source == "archive"+++def test_show_runtime_manager_defaults_to_manifest_when_package_manifest_exists(monkeypatch, tmp_path):+ monkeypatch.setattr("core.show_runtime._packaged_runtime_manifest_exists", lambda: True)++ manager = ShowRuntimeManager(+ workspace_root=tmp_path / "show",+ runtime_dir=tmp_path / "runtime",+ )++ assert manager.runtime_source == "manifest-cache"++def test_show_runtime_manager_installs_from_github_source(monkeypatch, tmp_path):runtime_dir = tmp_path / "runtime"source_dir = runtime_dir / "source" / "github" / "avibe-bot_vibe-show-runtime" / "main"diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.pyindex cf8d88ece..eab24a520 100644--- a/tests/test_upgrade_flow.py+++ b/tests/test_upgrade_flow.py@@ -327,8 +327,11 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):monkeypatch.setattr(api, "schedule_restart", lambda **kwargs: calls.setdefault("restart_kwargs", kwargs))def fake_run(cmd, **kwargs):- calls["run_cmd"] = cmd- calls["run_kwargs"] = kwargs+ if cmd == plan.command:+ calls["run_cmd"] = cmd+ calls["run_kwargs"] = kwargs+ else:+ raise AssertionError(f"unexpected subprocess command: {cmd}")return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")monkeypatch.setattr(api.subprocess, "run", fake_run)@@ -343,7 +346,80 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):assert calls["run_kwargs"]["env"] == plan.envsafe_cwd = calls["run_kwargs"].get("cwd")assert safe_cwd and os.path.isabs(safe_cwd), f"subprocess.run cwd must be an absolute path, got {safe_cwd!r}"- assert calls["restart_kwargs"] == {"delay_seconds": 2.0, "vibe_path": "/custom/bin/vibe", "trigger": "upgrade"}+ assert calls["restart_kwargs"] == {+ "delay_seconds": 2.0,+ "vibe_path": "/custom/bin/vibe",+ "trigger": "upgrade",+ "prepare_show_runtime": True,+ }+++def test_do_upgrade_auto_restart_does_not_block_on_runtime_prepare(monkeypatch):+ plan = UpgradePlan(+ command=["/usr/local/bin/uv", "tool", "install", "vibe-remote", "--upgrade"],+ env=None,+ method="uv",+ )+ events: list[str] = []++ monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")+ monkeypatch.setattr(api, "schedule_restart", lambda **kwargs: events.append("restart") or {"job_id": "restart"})++ def fake_run(cmd, **kwargs):+ if cmd == plan.command:+ events.append("upgrade")+ else:+ raise AssertionError(f"unexpected subprocess command: {cmd}")+ return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")++ monkeypatch.setattr(api.subprocess, "run", fake_run)++ result = api.do_upgrade(auto_restart=True)++ assert result["ok"] is True+ assert events == ["upgrade", "restart"]+++def test_do_upgrade_without_auto_restart_prepares_runtime(monkeypatch):+ plan = UpgradePlan(+ command=["/usr/local/bin/uv", "tool", "install", "vibe-remote", "--upgrade"],+ env=None,+ method="uv",+ )+ calls: dict[str, Any] = {}++ monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")++ def fail_restart(**kwargs):+ raise AssertionError("schedule_restart should not run when auto_restart is disabled")++ monkeypatch.setattr(api, "schedule_restart", fail_restart)++ def fake_run(cmd, **kwargs):+ if cmd == plan.command:+ calls["upgrade_cmd"] = cmd+ calls["upgrade_kwargs"] = kwargs+ return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")+ if cmd == ["/custom/bin/vibe", "runtime", "prepare", "--strict"]:+ calls["runtime_prepare_cmd"] = cmd+ calls["runtime_prepare_kwargs"] = kwargs+ return subprocess.CompletedProcess(cmd, 0, stdout="runtime ready", stderr="")+ raise AssertionError(f"unexpected subprocess command: {cmd}")++ monkeypatch.setattr(api.subprocess, "run", fake_run)++ result = api.do_upgrade(auto_restart=False)++ assert result["ok"] is True+ assert result["restarting"] is False+ assert result["output"] == "done\n\nruntime ready"+ assert calls["runtime_prepare_cmd"] == ["/custom/bin/vibe", "runtime", "prepare", "--strict"]+ assert calls["runtime_prepare_kwargs"]["capture_output"] is True+ assert calls["runtime_prepare_kwargs"]["text"] is True+ assert calls["runtime_prepare_kwargs"]["timeout"] == 300+ assert calls["runtime_prepare_kwargs"]["cwd"] == calls["upgrade_kwargs"]["cwd"]def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):@@ -359,8 +435,14 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):monkeypatch.setattr(cli, "build_upgrade_plan", lambda **kwargs: plan)def fake_run(cmd, **kwargs):- calls["cmd"] = cmd- calls["kwargs"] = kwargs+ if cmd == plan.command:+ calls["cmd"] = cmd+ calls["kwargs"] = kwargs+ elif cmd == ["/custom/bin/vibe", "runtime", "prepare", "--strict"]:+ calls["runtime_prepare_cmd"] = cmd+ calls["runtime_prepare_kwargs"] = kwargs+ else:+ raise AssertionError(f"unexpected subprocess command: {cmd}")return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")monkeypatch.setattr(cli.subprocess, "run", fake_run)@@ -374,6 +456,10 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):assert calls["kwargs"]["env"] == plan.envassert "cwd" in calls["kwargs"], "subprocess.run must specify cwd to avoid stale venv cwd"assert os.path.isabs(calls["kwargs"]["cwd"]), f"cwd must be absolute, got {calls['kwargs']['cwd']!r}"+ assert calls["runtime_prepare_cmd"] == ["/custom/bin/vibe", "runtime", "prepare", "--strict"]+ assert calls["runtime_prepare_kwargs"]["capture_output"] is True+ assert calls["runtime_prepare_kwargs"]["text"] is True+ assert calls["runtime_prepare_kwargs"]["timeout"] == 300def test_cmd_upgrade_skips_install_when_already_latest(monkeypatch):diff --git a/vibe/api.py b/vibe/api.pyindex 9cc2fba9a..2a8c93653 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1634,14 +1634,22 @@ def do_upgrade(auto_restart: bool = True) -> dict:)if result.returncode == 0:restarting = False+ runtime_output = Noneif auto_restart:- schedule_restart(delay_seconds=2.0, vibe_path=current_vibe_path, trigger="upgrade")+ schedule_restart(+ delay_seconds=2.0,+ vibe_path=current_vibe_path,+ trigger="upgrade",+ prepare_show_runtime=True,+ )restarting = True+ else:+ runtime_output = _prepare_show_runtime_after_upgrade(current_vibe_path, safe_cwd)return {"ok": True,"message": "Upgrade successful." + (" Restarting..." if restarting else " Please restart vibe."),- "output": result.stdout,+ "output": _append_upgrade_output(result.stdout, runtime_output),"restarting": restarting,}else:@@ -1662,6 +1670,35 @@ def do_upgrade(auto_restart: bool = True) -> dict:return {"ok": False, "message": str(e), "output": None, "restarting": False}+def _append_upgrade_output(output: str | None, runtime_output: str | None) -> str | None:+ parts = [part for part in ((output or "").strip(), (runtime_output or "").strip()) if part]+ if not parts:+ return None+ return "\n\n".join(parts)+++def _prepare_show_runtime_after_upgrade(vibe_path: str | None, cwd: str) -> str | None:+ if os.environ.get("VIBE_INSTALL_SKIP_SHOW_RUNTIME", "").strip().lower() in {"1", "true", "yes", "on"}:+ return "Show Runtime preparation skipped because VIBE_INSTALL_SKIP_SHOW_RUNTIME is set."+ if not vibe_path:+ return "Show Runtime was not prepared because the vibe executable path was not available."+ try:+ result = subprocess.run(+ [vibe_path, "runtime", "prepare", "--strict"],+ capture_output=True,+ text=True,+ timeout=300,+ cwd=cwd,+ check=False,+ )+ except Exception as exc:+ return f"Show Runtime preparation skipped: {exc}"+ output = (result.stdout or result.stderr or "").strip()+ if result.returncode == 0:+ return output or "Show Runtime prepared."+ return "Show Runtime preparation failed; Vibe Remote upgrade is still installed." + (f"\n{output}" if output else "")++def setup_opencode_permission() -> dict:"""Set OpenCode permission to 'allow' in config file.diff --git a/vibe/cli.py b/vibe/cli.pyindex 4ed27cfed..1c57219c6 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -4451,6 +4451,7 @@ def cmd_upgrade():result = subprocess.run(plan.command, capture_output=True, text=True, env=plan.env, cwd=safe_cwd)if result.returncode == 0:print("\033[32mUpgrade successful!\033[0m")+ _prepare_show_runtime_after_install(current_vibe_path)print("Please restart vibe to use the new version:")print(" vibe restart")return 0@@ -4462,6 +4463,105 @@ def cmd_upgrade():return 1+def _show_runtime_manager_from_args(args):+ from core.show_runtime import ShowRuntimeManager++ offline = True if getattr(args, "offline", False) else None+ return ShowRuntimeManager(+ runtime_source=getattr(args, "source", None),+ manifest_path=getattr(args, "manifest", None),+ manifest_url=getattr(args, "manifest_url", None),+ offline=offline,+ force_install=bool(getattr(args, "force", False)),+ )+++def _print_runtime_status(payload: dict) -> None:+ print("Show Runtime:")+ print(f" Provider: {payload.get('provider')}")+ print(f" Platform: {payload.get('platform')}")+ print(f" Node: {'available' if payload.get('node_available') else 'missing'}")+ manifest = payload.get("manifest") or {}+ if manifest:+ print(f" Manifest runtime: {manifest.get('runtime_version')}")+ print(f" Manifest sha256: {manifest.get('sha256')}")+ print(f" Manifest source: {manifest.get('source')}")+ archive = payload.get("archive") or {}+ if archive:+ print(f" Archive: {archive.get('name')}")+ print(f" Archive sha256: {archive.get('sha256')}")+ print(f" Installed: {'yes' if payload.get('installed') else 'no'}")+ if payload.get("install_dir"):+ print(f" Install dir: {payload.get('install_dir')}")+ if payload.get("reason"):+ print(f" Reason: {payload.get('reason')}")+++def cmd_runtime(args) -> int:+ manager = _show_runtime_manager_from_args(args)+ command = getattr(args, "runtime_command", None)+ if command == "status":+ payload = manager.status()+ if getattr(args, "json", False):+ print(json.dumps(payload, indent=2))+ else:+ _print_runtime_status(payload)+ return 0+ if command == "prepare":+ offline = True if getattr(args, "offline", False) else None+ payload = manager.prepare(force=getattr(args, "force", False), offline=offline)+ if getattr(args, "json", False):+ print(json.dumps(payload, indent=2))+ elif payload.get("ok"):+ print("Show Runtime ready.")+ status = payload.get("status") or {}+ if status.get("install_dir"):+ print(f"Install dir: {status['install_dir']}")+ else:+ reason = payload.get("reason") or "unknown"+ print(f"Show Runtime prepare failed: {reason}", file=sys.stderr)+ return 1 if getattr(args, "strict", False) and not payload.get("ok") else 0+ if command == "clean":+ payload = manager.clean(keep_previous=getattr(args, "keep_previous", 1))+ if getattr(args, "json", False):+ print(json.dumps(payload, indent=2))+ else:+ removed = payload.get("removed") or []+ print(f"Removed {len(removed)} Show Runtime cache item(s).")+ return 0+ raise TaskCliError("runtime command is required", code="invalid_arguments", help_command="vibe runtime --help")+++def _prepare_show_runtime_after_install(vibe_path: str | None) -> None:+ if os.environ.get("VIBE_INSTALL_SKIP_SHOW_RUNTIME", "").strip().lower() in {"1", "true", "yes", "on"}:+ print("\033[33mSkipping Show Runtime preparation because VIBE_INSTALL_SKIP_SHOW_RUNTIME is set.\033[0m")+ return+ executable = vibe_path or shutil.which("vibe")+ if not executable:+ print("\033[33mShow Runtime was not prepared because the vibe executable was not found.\033[0m")+ return+ safe_cwd = get_safe_cwd()+ try:+ result = subprocess.run(+ [executable, "runtime", "prepare", "--strict"],+ capture_output=True,+ text=True,+ cwd=safe_cwd,+ timeout=300,+ check=False,+ )+ except Exception as exc:+ print(f"\033[33mShow Runtime preparation skipped: {exc}\033[0m")+ return+ if result.returncode == 0:+ print("Show Runtime prepared.")+ return+ detail = (result.stderr or result.stdout).strip()+ print("\033[33mShow Runtime preparation failed; Vibe Remote upgrade is still installed.\033[0m")+ if detail:+ print(detail)++def cmd_restart():"""Restart all services (stop + start)."""return _cmd_restart_with_delay(0.0)@@ -4519,11 +4619,50 @@ def build_parser():supervisor_parser.add_argument("--delay-seconds", type=_non_negative_float, default=0)supervisor_parser.add_argument("--trigger", default="cli")supervisor_parser.add_argument("--vibe-path")+ supervisor_parser.add_argument("--prepare-show-runtime", action="store_true")subparsers.add_parser("status", help="Show service status")subparsers.add_parser("doctor", help="Run diagnostics")subparsers.add_parser("version", help="Show version")subparsers.add_parser("check-update", help="Check for updates")subparsers.add_parser("upgrade", help="Upgrade to latest version")+ runtime_parser = subparsers.add_parser(+ "runtime",+ help="Inspect and prepare the managed Show Runtime",+ description="Inspect, prepare, and clean the global Show Runtime cache used by Show Pages.",+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe runtime --help",+ )+ runtime_subparsers = runtime_parser.add_subparsers(dest="runtime_command", metavar="{status,prepare,clean}")+ runtime_subparsers.required = True++ def add_runtime_provider_args(runtime_command_parser):+ runtime_command_parser.add_argument(+ "--source",+ choices=("manifest-cache", "manifest", "archive", "prebuilt", "github", "github-source", "npm"),+ help="Runtime provider override. Defaults to the packaged manifest cache.",+ )+ manifest_group = runtime_command_parser.add_mutually_exclusive_group()+ manifest_group.add_argument("--manifest", help="Read a development manifest from a local path.")+ manifest_group.add_argument("--manifest-url", help="Read a development manifest from a URL.")++ runtime_status_parser = runtime_subparsers.add_parser("status", help="Show managed Show Runtime status")+ add_runtime_provider_args(runtime_status_parser)+ runtime_status_parser.add_argument("--offline", action="store_true", help="Do not fetch a remote manifest.")+ runtime_status_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")++ runtime_prepare_parser = runtime_subparsers.add_parser(+ "prepare",+ help="Download, verify, and install the current platform runtime",+ )+ add_runtime_provider_args(runtime_prepare_parser)+ runtime_prepare_parser.add_argument("--force", action="store_true", help="Reinstall even when the cached runtime matches.")+ runtime_prepare_parser.add_argument("--offline", action="store_true", help="Use only the verified local cache.")+ runtime_prepare_parser.add_argument("--strict", action="store_true", help="Return a non-zero exit code when preparation fails.")+ runtime_prepare_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")++ runtime_clean_parser = runtime_subparsers.add_parser("clean", help="Clean stale Show Runtime cache entries")+ runtime_clean_parser.add_argument("--keep-previous", type=int, default=1, help="Number of previous runtime versions to keep.")+ runtime_clean_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")remote_parser = subparsers.add_parser("remote",help="Manage Avibe Cloud remote access",@@ -5352,6 +5491,7 @@ def main():str(args.delay_seconds),"--trigger",args.trigger,+ *(["--prepare-show-runtime"] if args.prepare_show_runtime else []),*(["--vibe-path", args.vibe_path] if args.vibe_path else []),])@@ -5374,6 +5514,12 @@ def main():sys.exit(cmd_check_update())if args.command == "upgrade":sys.exit(cmd_upgrade())+ if args.command == "runtime":+ try:+ sys.exit(cmd_runtime(args))+ except Exception as exc:+ _print_task_error(exc, help_command="vibe runtime --help")+ sys.exit(1)if args.command == "remote":if args.remote_command is None:sys.exit(cmd_remote_setup(args))diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 313f822cd..f603425f9 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -12,7 +12,7 @@ from pathlib import Pathfrom config import pathsfrom vibe import runtime-from vibe.upgrade import get_restart_environment, get_restart_invocation_command, get_safe_cwd+from vibe.upgrade import get_restart_command, get_restart_environment, get_restart_invocation_command, get_safe_cwdlogger = logging.getLogger(__name__)@@ -76,6 +76,7 @@ def _run_restart_job(delay_seconds: float,vibe_path: str | None,trigger: str,+ prepare_show_runtime: bool = False,) -> int:log_path = _restart_log_path(job_id)safe_cwd = get_safe_cwd()@@ -152,6 +153,35 @@ def _run_restart_job(payload.update(ok=True, state="succeeded", new_pid=new_pid, error=None)_write_status(payload)write(f"restart job succeeded new_pid={new_pid}")++ if prepare_show_runtime:+ prepare_command = [+ *get_restart_command(vibe_path=vibe_path),+ "runtime",+ "prepare",+ "--strict",+ ]+ write("preparing Show Runtime after service restart")+ try:+ prepare_result = subprocess.run(+ prepare_command,+ cwd=safe_cwd,+ env=env,+ stdout=log,+ stderr=subprocess.STDOUT,+ text=True,+ check=False,+ timeout=300,+ )+ if prepare_result.returncode != 0:+ write(f"Show Runtime preparation failed with exit code {prepare_result.returncode}")+ else:+ write("Show Runtime preparation succeeded")+ except subprocess.TimeoutExpired:+ write("Show Runtime preparation timed out after 300 seconds")+ except Exception as exc:+ write(f"Show Runtime preparation skipped: {exc}")+return 0@@ -160,6 +190,7 @@ def schedule_restart(delay_seconds: float = 0.0,vibe_path: str | None = None,trigger: str = "cli",+ prepare_show_runtime: bool = False,) -> dict:job_id = uuid.uuid4().hex[:12]invocation = get_restart_invocation_command(vibe_path=vibe_path)@@ -170,6 +201,8 @@ def schedule_restart(command.extend(["--job-id", job_id, "--delay-seconds", str(delay_seconds), "--trigger", trigger])if vibe_path:command.extend(["--vibe-path", vibe_path])+ if prepare_show_runtime:+ command.append("--prepare-show-runtime")env = get_restart_environment(vibe_path=vibe_path)log_path = _restart_log_path(job_id)log_path.parent.mkdir(parents=True, exist_ok=True)@@ -209,12 +242,14 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--delay-seconds", type=float, default=0.0)parser.add_argument("--trigger", default="cli")parser.add_argument("--vibe-path")+ parser.add_argument("--prepare-show-runtime", action="store_true")args = parser.parse_args(argv)return _run_restart_job(job_id=args.job_id,delay_seconds=max(0.0, args.delay_seconds),vibe_path=args.vibe_path,trigger=args.trigger,+ prepare_show_runtime=args.prepare_show_runtime,)