Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(show-runtime): prune stale managed installs (#852)

Call White2ee9a8168952
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 5cda60815..921993df8 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -41,6 +41,8 @@ _RUNTIME_SOURCE_ARCHIVE = "archive"
_RUNTIME_SOURCE_GITHUB = "github"
_RUNTIME_SOURCE_NPM = "npm"
_RUNTIME_MANIFEST_RESOURCE = "show_runtime_manifest.json"
+_PACKAGED_RUNTIME_MANIFEST_SOURCE = f"package:{_RUNTIME_MANIFEST_RESOURCE}"
+_MANAGED_RUNTIME_ROLLBACK_INSTALLS = 1
_FALSE_VALUES = {"0", "false", "no", "off"}
_PREWARM_IMPORT_RE = re.compile(r"""(?P<quote>["'])(?P<path>[^"']+)(?P=quote)""")
_PREWARM_MAX_ASSETS = 64
@@ -373,16 +375,41 @@ class ShowRuntimeManager:
return command
def _install_managed_runtime(self) -> list[str] | None:
+ command: 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:
- return self._install_github_runtime()
- if self.runtime_source == _RUNTIME_SOURCE_NPM:
- return self._install_npm_runtime()
- self._install_reason = "runtime_source_unsupported"
- return None
+ command = self._install_manifest_runtime()
+ elif self.runtime_source == _RUNTIME_SOURCE_ARCHIVE:
+ command = self._install_archive_runtime()
+ elif self.runtime_source == _RUNTIME_SOURCE_GITHUB:
+ command = self._install_github_runtime()
+ elif self.runtime_source == _RUNTIME_SOURCE_NPM:
+ command = self._install_npm_runtime()
+ else:
+ self._install_reason = "runtime_source_unsupported"
+ return None
+ if command:
+ self._clean_after_managed_install(command)
+ return command
+
+ def _clean_after_managed_install(self, command: list[str]) -> None:
+ if (
+ self.runtime_source != _RUNTIME_SOURCE_MANIFEST
+ or self.manifest_path is not None
+ or self.manifest_url is not None
+ ):
+ return
+ try:
+ protected_install_dirs = self._manifest_install_dirs_for_command(command)
+ removed = self._clean_manifest_install_dirs(
+ keep_previous=_MANAGED_RUNTIME_ROLLBACK_INSTALLS,
+ manifest_source=_PACKAGED_RUNTIME_MANIFEST_SOURCE,
+ protected_install_dirs=protected_install_dirs,
+ )
+ if removed:
+ logger.info("Removed %d stale managed Show Runtime install(s)", len(removed))
+ except Exception:
+ # Cache cleanup must never turn a usable runtime install into a failed prepare.
+ logger.warning("Failed to clean stale managed Show Runtime installs", exc_info=True)
def status(self) -> dict[str, Any]:
configured_command = _resolve_command(self.command) if self._command_explicit else None
@@ -434,42 +461,136 @@ class ShowRuntimeManager:
if path.is_dir():
shutil.rmtree(path, ignore_errors=True)
removed.append(str(path))
+ removed.extend(self._clean_manifest_install_dirs(keep_previous=keep_previous))
+ return {"ok": True, "removed": removed}
+
+ def _clean_manifest_install_dirs(
+ self,
+ *,
+ keep_previous: int,
+ manifest_source: str | None = None,
+ protected_install_dirs: set[Path] | None = None,
+ ) -> list[str]:
versions_dir = self.runtime_dir / "versions"
- if versions_dir.is_dir():
- current_install_dir: Path | None = None
- try:
- pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
- pointer_install_dir = Path(str(pointer.get("install_dir") or "")).resolve()
- if versions_dir.resolve() in pointer_install_dir.parents:
- current_install_dir = pointer_install_dir
- except Exception:
- current_install_dir = None
- install_dirs = {
- path.parent
- for pattern in ("*/*/.vibe-show-runtime.json", "*/*/*/.vibe-show-runtime.json")
- for path in versions_dir.glob(pattern)
- if path.parent.is_dir()
- }
- sorted_install_dirs = sorted(install_dirs, key=lambda path: path.stat().st_mtime, reverse=True)
- kept_previous = 0
- for path in sorted_install_dirs:
- path_resolved = path.resolve()
- if current_install_dir is not None and (
- path_resolved == current_install_dir or path_resolved in current_install_dir.parents
- ):
- continue
- if kept_previous < keep_previous:
- kept_previous += 1
+ if not versions_dir.is_dir():
+ return []
+ protected = set(protected_install_dirs or ())
+ current_install_dir = self._current_manifest_install_dir(versions_dir)
+ if current_install_dir is not None:
+ protected.add(current_install_dir)
+ install_dirs = self._manifest_install_dirs(versions_dir, manifest_source=manifest_source)
+ all_manifest_install_dirs = self._manifest_install_dirs(versions_dir)
+ sorted_install_dirs = sorted(install_dirs, key=lambda path: path.stat().st_mtime, reverse=True)
+ resolved_install_dirs = {path: path.resolve() for path in install_dirs}
+ all_resolved_install_dirs = {path: path.resolve() for path in all_manifest_install_dirs}
+ rollback_candidates = [
+ path
+ for path in sorted_install_dirs
+ if not any(
+ resolved_install_dirs[path] in other_resolved.parents
+ for other, other_resolved in resolved_install_dirs.items()
+ if other != path
+ )
+ ]
+ kept_previous = 0
+ for path in rollback_candidates:
+ path_resolved = resolved_install_dirs[path]
+ if self._install_dir_overlaps_protected(path_resolved, protected):
+ continue
+ if kept_previous < keep_previous:
+ kept_previous += 1
+ protected.add(path_resolved)
+ removed: list[str] = []
+ removable_install_dirs = [
+ path
+ for path, path_resolved in resolved_install_dirs.items()
+ if not self._install_dir_overlaps_protected(path_resolved, protected)
+ ]
+ removable_resolved_install_dirs = {resolved_install_dirs[path] for path in removable_install_dirs}
+ safe_removable_install_dirs = [
+ path
+ for path in removable_install_dirs
+ if not any(
+ resolved_install_dirs[path] in other_resolved.parents
+ and other_resolved not in removable_resolved_install_dirs
+ for other_resolved in all_resolved_install_dirs.values()
+ )
+ ]
+ for path in sorted(safe_removable_install_dirs, key=lambda item: len(resolved_install_dirs[item].parts), reverse=True):
+ if not path.is_dir():
+ continue
+ shutil.rmtree(path, ignore_errors=True)
+ removed.append(str(path))
+ self._prune_empty_manifest_version_dirs(versions_dir)
+ return removed
+
+ @staticmethod
+ def _install_dir_overlaps_protected(path_resolved: Path, protected: set[Path]) -> bool:
+ return any(
+ path_resolved == item or path_resolved in item.parents or item in path_resolved.parents
+ for item in protected
+ )
+
+ def _manifest_install_dirs(self, versions_dir: Path, *, manifest_source: str | None = None) -> set[Path]:
+ install_dirs: set[Path] = set()
+ for pattern in ("*/*/.vibe-show-runtime.json", "*/*/*/.vibe-show-runtime.json"):
+ for metadata_path in versions_dir.glob(pattern):
+ if not metadata_path.parent.is_dir():
continue
- shutil.rmtree(path, ignore_errors=True)
- removed.append(str(path))
- for path in sorted(versions_dir.glob("*/*"), reverse=True):
- if path.is_dir() and not any(path.iterdir()):
- path.rmdir()
- for path in sorted(versions_dir.iterdir(), reverse=True):
- if path.is_dir() and not any(path.iterdir()):
- path.rmdir()
- return {"ok": True, "removed": removed}
+ if manifest_source is not None:
+ try:
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ if (
+ metadata.get("provider") != _RUNTIME_SOURCE_MANIFEST
+ or metadata.get("manifest_source") != manifest_source
+ ):
+ continue
+ install_dirs.add(metadata_path.parent)
+ return install_dirs
+
+ def _current_manifest_install_dir(self, versions_dir: Path) -> Path | None:
+ try:
+ pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
+ pointer_install_dir = Path(str(pointer.get("install_dir") or "")).resolve()
+ if versions_dir.resolve() in pointer_install_dir.parents:
+ return pointer_install_dir
+ except Exception:
+ pass
+ return None
+
+ def _manifest_install_dirs_for_command(self, command: list[str]) -> set[Path]:
+ versions_dir = self.runtime_dir / "versions"
+ if not versions_dir.is_dir():
+ return set()
+ install_dirs = self._manifest_install_dirs(
+ versions_dir,
+ manifest_source=_PACKAGED_RUNTIME_MANIFEST_SOURCE,
+ )
+ matching_install_dirs: set[Path] = set()
+ for command_part in command:
+ try:
+ command_path = Path(command_part).resolve()
+ except (OSError, RuntimeError):
+ continue
+ for install_dir in install_dirs:
+ install_dir_resolved = install_dir.resolve()
+ if install_dir_resolved == command_path or install_dir_resolved in command_path.parents:
+ matching_install_dirs.add(install_dir_resolved)
+ return {
+ path
+ for path in matching_install_dirs
+ if not any(path in other.parents for other in matching_install_dirs if other != path)
+ }
+
+ def _prune_empty_manifest_version_dirs(self, versions_dir: Path) -> None:
+ for path in sorted(versions_dir.glob("*/*"), reverse=True):
+ if path.is_dir() and not any(path.iterdir()):
+ path.rmdir()
+ for path in sorted(versions_dir.iterdir(), reverse=True):
+ if path.is_dir() and not any(path.iterdir()):
+ path.rmdir()
def prepare(self, *, force: bool | None = None, offline: bool | None = None) -> dict[str, Any]:
previous_force = self.force_install
@@ -593,7 +714,7 @@ class ShowRuntimeManager:
self._install_reason = "runtime_manifest_missing"
return None
payload = resource.read_bytes()
- source = f"package:{_RUNTIME_MANIFEST_RESOURCE}"
+ source = _PACKAGED_RUNTIME_MANIFEST_SOURCE
digest = hashlib.sha256(payload).hexdigest()
try:
data = json.loads(payload.decode("utf-8"))
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 11456066d..2e00856f7 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -2,6 +2,7 @@ import asyncio
import hashlib
import io
import json
+import os
import tarfile
from pathlib import Path
from types import SimpleNamespace
@@ -181,6 +182,42 @@ def _write_runtime_manifest(tmp_path: Path, archive_path: Path, *, sha256: str |
return manifest_path
+def _write_cached_runtime_install(
+ runtime_dir: Path,
+ name: str,
+ *,
+ manifest_source: str = "package:show_runtime_manifest.json",
+ mtime: float,
+) -> tuple[Path, Path]:
+ install_dir = runtime_dir / "versions" / name / _runtime_platform_tag() / f"fingerprint-{name}"
+ return _write_cached_runtime_install_at(install_dir, name, manifest_source=manifest_source, mtime=mtime)
+
+
+def _write_cached_runtime_install_at(
+ install_dir: Path,
+ name: str,
+ *,
+ manifest_source: str = "package:show_runtime_manifest.json",
+ mtime: float,
+) -> tuple[Path, Path]:
+ cli_path = install_dir / "node_modules" / "@avibe" / "show-runtime" / "dist" / "cli.js"
+ cli_path.parent.mkdir(parents=True)
+ cli_path.write_text(f"{name}\n", encoding="utf-8")
+ (install_dir / ".vibe-show-runtime.json").write_text(
+ json.dumps(
+ {
+ "provider": "manifest-cache",
+ "manifest_source": manifest_source,
+ "runtime_version": name,
+ "platform": _runtime_platform_tag(),
+ }
+ ),
+ encoding="utf-8",
+ )
+ os.utime(install_dir, (mtime, mtime))
+ return install_dir, cli_path
+
+
def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -1750,6 +1787,236 @@ def test_show_runtime_clean_prunes_stale_manifest_fingerprints(monkeypatch, tmp_
assert new_install_dir.exists() is True
+def test_show_runtime_prepare_prunes_old_packaged_installs_and_keeps_rollback(monkeypatch, tmp_path):
+ runtime_dir = tmp_path / "runtime"
+ old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=100)
+ previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=200)
+ current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)
+ custom_install, _custom_cli = _write_cached_runtime_install(
+ runtime_dir,
+ "custom",
+ manifest_source=str(tmp_path / "development-manifest.json"),
+ mtime=50,
+ )
+ github_source = runtime_dir / "source" / "github" / "avibe-bot_vibe-show-runtime" / "main"
+ github_source.mkdir(parents=True)
+ (github_source / "README.md").write_text("development checkout\n", encoding="utf-8")
+ local_bin = runtime_dir / "package" / "node_modules" / ".bin" / "avibe-show-runtime"
+ local_bin.parent.mkdir(parents=True)
+ local_bin.write_text("#!/bin/sh\n", encoding="utf-8")
+
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ runtime_source="manifest-cache",
+ )
+ monkeypatch.setattr(manager, "_install_manifest_runtime", lambda: ["/bin/node", str(current_cli)])
+ monkeypatch.setattr(manager, "status", lambda: {})
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert current_install.exists() is True
+ assert previous_install.exists() is True
+ assert old_install.exists() is False
+ assert custom_install.exists() is True
+ assert github_source.exists() is True
+ assert local_bin.exists() is True
+
+
[email protected](("parent_mtime", "child_mtime"), ((100, 200), (200, 100)))
+def test_show_runtime_prepare_preserves_nested_retained_rollback(monkeypatch, tmp_path, parent_mtime, child_mtime):
+ runtime_dir = tmp_path / "runtime"
+ old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=10)
+ current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)
+ rollback_parent = runtime_dir / "versions" / "rollback" / _runtime_platform_tag()
+ _rollback_parent, rollback_parent_cli = _write_cached_runtime_install_at(
+ rollback_parent,
+ "rollback-legacy",
+ mtime=parent_mtime,
+ )
+ rollback_install, rollback_cli = _write_cached_runtime_install_at(
+ rollback_parent / "fingerprint",
+ "rollback",
+ mtime=child_mtime,
+ )
+ stale_sibling, _stale_cli = _write_cached_runtime_install_at(
+ rollback_parent / "stale-fingerprint",
+ "stale-rollback",
+ mtime=20,
+ )
+
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ runtime_source="manifest-cache",
+ )
+ monkeypatch.setattr(manager, "_install_manifest_runtime", lambda: ["/bin/node", str(current_cli)])
+ monkeypatch.setattr(manager, "status", lambda: {})
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert current_install.exists() is True
+ assert rollback_install.exists() is True
+ assert rollback_cli.exists() is True
+ assert rollback_parent.exists() is True
+ assert rollback_parent_cli.exists() is True
+ assert stale_sibling.exists() is False
+ assert old_install.exists() is False
+
+
+def test_show_runtime_prepare_prunes_siblings_under_current_legacy_parent(monkeypatch, tmp_path):
+ runtime_dir = tmp_path / "runtime"
+ old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=100)
+ previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)
+ current_parent = runtime_dir / "versions" / "current" / _runtime_platform_tag()
+ _parent_install, parent_cli = _write_cached_runtime_install_at(current_parent, "current-legacy", mtime=400)
+ current_install, current_cli = _write_cached_runtime_install_at(
+ current_parent / "current-fingerprint",
+ "current",
+ mtime=300,
+ )
+ stale_sibling, _stale_cli = _write_cached_runtime_install_at(
+ current_parent / "stale-fingerprint",
+ "stale-current",
+ mtime=200,
+ )
+
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ runtime_source="manifest-cache",
+ )
+ monkeypatch.setattr(manager, "_install_manifest_runtime", lambda: ["/bin/node", str(current_cli)])
+ monkeypatch.setattr(manager, "status", lambda: {})
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert current_install.exists() is True
+ assert current_cli.exists() is True
+ assert current_parent.exists() is True
+ assert parent_cli.exists() is True
+ assert previous_install.exists() is True
+ assert stale_sibling.exists() is False
+ assert old_install.exists() is False
+
+
+def test_show_runtime_prepare_preserves_descendants_of_current_legacy_parent(monkeypatch, tmp_path):
+ runtime_dir = tmp_path / "runtime"
+ old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=100)
+ previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)
+ current_parent = runtime_dir / "versions" / "current" / _runtime_platform_tag()
+ _parent_install, parent_cli = _write_cached_runtime_install_at(current_parent, "current-legacy", mtime=400)
+ current_child, current_child_cli = _write_cached_runtime_install_at(
+ current_parent / "current-fingerprint",
+ "current-child",
+ mtime=300,
+ )
+
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ runtime_source="manifest-cache",
+ )
+ monkeypatch.setattr(manager, "_install_manifest_runtime", lambda: ["/bin/node", str(parent_cli)])
+ monkeypatch.setattr(manager, "status", lambda: {})
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert current_parent.exists() is True
+ assert parent_cli.exists() is True
+ assert current_child.exists() is True
+ assert current_child_cli.exists() is True
+ assert previous_install.exists() is True
+ assert old_install.exists() is False
+
+
+def test_show_runtime_prepare_preserves_custom_child_under_stale_packaged_parent(monkeypatch, tmp_path):
+ runtime_dir = tmp_path / "runtime"
+ old_install, _old_cli = _write_cached_runtime_install(runtime_dir, "old", mtime=20)
+ previous_install, _previous_cli = _write_cached_runtime_install(runtime_dir, "previous", mtime=250)
+ current_install, current_cli = _write_cached_runtime_install(runtime_dir, "current", mtime=300)
+ stale_parent = runtime_dir / "versions" / "stale-parent" / _runtime_platform_tag()
+ _parent_install, parent_cli = _write_cached_runtime_install_at(stale_parent, "stale-parent", mtime=80)
+ custom_child, custom_cli = _write_cached_runtime_install_at(
+ stale_parent / "custom-fingerprint",
+ "custom-child",
+ manifest_source=str(tmp_path / "custom-manifest.json"),
+ mtime=70,
+ )
+ stale_child, _stale_child_cli = _write_cached_runtime_install_at(
+ stale_parent / "stale-fingerprint",
+ "stale-child",
+ mtime=60,
+ )
+
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ runtime_source="manifest-cache",
+ )
+ monkeypatch.setattr(manager, "_install_manifest_runtime", lambda: ["/bin/node", str(current_cli)])
+ monkeypatch.setattr(manager, "status", lambda: {})
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert current_install.exists() is True
+ assert previous_install.exists() is True
+ assert stale_parent.exists() is True
+ assert parent_cli.exists() is True
+ assert custom_child.exists() is True
+ assert custom_cli.exists() is True
+ assert stale_child.exists() is False
+ assert old_install.exists() is False
+
+
+def test_show_runtime_prepare_with_explicit_command_does_not_clean_managed_installs(monkeypatch, tmp_path):
+ runtime_dir = tmp_path / "runtime"
+ install_dirs = [
+ _write_cached_runtime_install(runtime_dir, name, mtime=mtime)[0]
+ for name, mtime in (("old", 100), ("previous", 200), ("current", 300))
+ ]
+ local_bin = tmp_path / "development" / "show-runtime"
+ local_bin.parent.mkdir()
+ local_bin.write_text("#!/bin/sh\n", encoding="utf-8")
+ manager = ShowRuntimeManager(
+ command=str(local_bin),
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ )
+ monkeypatch.setattr("core.show_runtime._resolve_command", lambda command: [command])
+
+ result = manager.prepare()
+
+ assert result["ok"] is True
+ assert all(path.exists() for path in install_dirs)
+ assert local_bin.exists() is True
+
+
+def test_show_runtime_failed_prepare_does_not_clean_managed_installs(monkeypatch, tmp_path):
+ runtime_dir = tmp_path / "runtime"
+ install_dirs = [
+ _write_cached_runtime_install(runtime_dir, name, mtime=mtime)[0]
+ for name, mtime in (("old", 100), ("previous", 200), ("current", 300))
+ ]
+ manager = ShowRuntimeManager(
+ workspace_root=tmp_path / "show",
+ runtime_dir=runtime_dir,
+ runtime_source="manifest-cache",
+ )
+ monkeypatch.setattr(manager, "_install_manifest_runtime", lambda: None)
+ monkeypatch.setattr(manager, "status", lambda: {})
+
+ result = manager.prepare()
+
+ assert result["ok"] is False
+ assert all(path.exists() for path in install_dirs)
+
+
def test_show_runtime_manager_reuses_legacy_manifest_install_offline(monkeypatch, tmp_path):
archive_path = _write_runtime_archive(tmp_path, text="legacy runtime\n")
manifest_path = _write_runtime_manifest(tmp_path, archive_path)