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(upgrade): recover rollback target from legacy service (#1615)

Call White95ebbe24ad51
diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.py
index 5e96e40b1..21f39b37e 100644
--- a/tests/test_restart_supervisor.py
+++ b/tests/test_restart_supervisor.py
@@ -109,6 +109,178 @@ def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_
assert runtime.read_json(runtime.get_restart_status_path())["job_id"] == result["job_id"]
+def test_legacy_upgrade_target_reads_the_running_release_and_launcher(monkeypatch, tmp_path):
+ """A pre-rollback release can still hand the new supervisor its target."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ paths.ensure_data_dirs()
+ tool_root = tmp_path / "uv" / "tools" / "avibe-os"
+ python_path = tool_root / "bin" / "python"
+ vibe_path = tool_root / "bin" / "vibe"
+ service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"
+ python_path.parent.mkdir(parents=True)
+ service_main.parent.mkdir(parents=True)
+ python_path.write_text("#!/bin/sh\n", encoding="utf-8")
+ vibe_path.write_text(f"#!{python_path}\n", encoding="utf-8")
+ service_main.write_text("# old release\n", encoding="utf-8")
+ metadata_dir = service_main.parent.parent / "avibe_os-3.0.12.dist-info"
+ metadata_dir.mkdir()
+ (metadata_dir / "METADATA").write_text("Name: avibe-os\nVersion: 3.0.12\n", encoding="utf-8")
+
+ monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 123)
+ monkeypatch.setattr(restart_supervisor, "_running_ui_version", lambda: None)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: f"{python_path} {service_main}",
+ )
+
+ target = restart_supervisor._discover_legacy_upgrade_target(
+ trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")
+ )
+
+ assert target == RollbackTarget(
+ version="3.0.12",
+ package="avibe-os",
+ launcher=runtime.ServiceLauncher(python=str(python_path), main=str(service_main)),
+ )
+
+
+def test_legacy_upgrade_target_prefers_running_version_over_stale_metadata(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ paths.ensure_data_dirs()
+ tool_root = tmp_path / "venv"
+ python_path = tool_root / "bin" / "python"
+ service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"
+ python_path.parent.mkdir(parents=True)
+ service_main.parent.mkdir(parents=True)
+ python_path.write_text("#!/bin/sh\n", encoding="utf-8")
+ service_main.write_text("# replaced release\n", encoding="utf-8")
+ metadata_root = service_main.parent.parent
+ for name, version in (("avibe_os", "3.0.13"), ("vibe_remote", "2.9.4")):
+ metadata_dir = metadata_root / f"{name}-{version}.dist-info"
+ metadata_dir.mkdir()
+ package_name = "avibe-os" if name == "avibe_os" else "vibe-remote"
+ (metadata_dir / "METADATA").write_text(
+ f"Name: {package_name}\nVersion: {version}\n", encoding="utf-8"
+ )
+
+ monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 123)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: f"{python_path} {service_main}",
+ )
+ monkeypatch.setattr(restart_supervisor, "_running_ui_version", lambda: "3.0.12")
+
+ target = restart_supervisor._discover_legacy_upgrade_target(
+ trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")
+ )
+
+ assert target == RollbackTarget(
+ version="3.0.12",
+ package="avibe-os",
+ launcher=runtime.ServiceLauncher(python=str(python_path), main=str(service_main)),
+ )
+
+
+def test_legacy_upgrade_target_recovers_from_ui_only_process(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ paths.ensure_data_dirs()
+ tool_root = tmp_path / "uv" / "tools" / "vibe-remote"
+ python_path = tool_root / "bin" / "python"
+ service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"
+ python_path.parent.mkdir(parents=True)
+ service_main.parent.mkdir(parents=True)
+ python_path.write_text("#!/bin/sh\n", encoding="utf-8")
+ service_main.write_text("# old release\n", encoding="utf-8")
+ metadata_dir = service_main.parent.parent / "vibe_remote-2.9.4.dist-info"
+ metadata_dir.mkdir()
+ (metadata_dir / "METADATA").write_text("Name: vibe-remote\nVersion: 2.9.4\n", encoding="utf-8")
+
+ monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 999)
+ monkeypatch.setattr(restart_supervisor, "_read_recorded_ui_pid", lambda: 456)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: None if pid == 999 else f'{python_path} -c "from vibe.ui_server import run_ui_server; run_ui_server()"',
+ )
+ monkeypatch.setattr(restart_supervisor, "_running_ui_version", lambda: "2.9.4")
+
+ target = restart_supervisor._discover_legacy_upgrade_target(
+ trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")
+ )
+
+ assert target == RollbackTarget(
+ version="2.9.4",
+ package="vibe-remote",
+ launcher=runtime.ServiceLauncher(python=str(python_path), main=str(service_main)),
+ )
+
+
+def test_service_launcher_from_process_strips_windows_quotes(monkeypatch, tmp_path):
+ python_path = tmp_path / "Program Files" / "uv" / "tools" / "avibe-os" / "Scripts" / "python.exe"
+ service_main = tmp_path / "Program Files" / "uv" / "tools" / "avibe-os" / "Lib" / "site-packages" / "vibe" / "service_main.py"
+ service_main.parent.mkdir(parents=True)
+ service_main.write_text("# old release\n", encoding="utf-8")
+ command = f'"{python_path}" "{service_main}"'
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: command)
+
+ target = restart_supervisor._service_launcher_from_process(123)
+
+ assert target == runtime.ServiceLauncher(python=str(python_path), main=str(service_main))
+
+
+def test_legacy_upgrade_without_target_leaves_packaged_runtime_running(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ monkeypatch.setattr(restart_supervisor, "get_build_identity", lambda: SimpleNamespace(kind="package"))
+ monkeypatch.setattr(restart_supervisor, "_discover_legacy_upgrade_target", lambda **kwargs: None)
+ monkeypatch.setattr(
+ restart_supervisor,
+ "_stop_runtime_for_restart",
+ lambda **kwargs: pytest.fail("a legacy upgrade without a target must not stop the runtime"),
+ )
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="job-legacy-no-target",
+ delay_seconds=0,
+ vibe_path="/bin/vibe",
+ trigger="upgrade",
+ )
+
+ assert rc == 2
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["state"] == "failed"
+ assert "existing runtime was left running" in status["error"]
+
+
+def test_failed_legacy_upgrade_uses_discovered_target_for_rollback(monkeypatch, tmp_path):
+ """The v3.0.12 path is recoverable even though it passed no rollback argv."""
+
+ armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)
+ monkeypatch.setattr(
+ restart_supervisor,
+ "_discover_legacy_upgrade_target",
+ lambda **kwargs: _rollback_target(),
+ )
+
+ rc = restart_supervisor._run_restart_job(
+ job_id="joblegacy",
+ delay_seconds=0,
+ vibe_path="/bin/vibe",
+ trigger="upgrade",
+ rollback_to=None,
+ )
+
+ assert rc == 1
+ status = runtime.read_json(runtime.get_restart_status_path())
+ assert status["rollback_to"] == "3.0.10"
+ assert status["rollback_target_source"] == "running_service"
+ assert status["rollback"]["state"] == "succeeded"
+ assert armed.observed_by_the_rolled_back_version == [["before the upgrade"]]
+
+
def test_schedule_restart_can_prepare_show_runtime_after_restart(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
paths.ensure_data_dirs()
@@ -380,6 +552,8 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_
monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))
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)
+ monkeypatch.setattr(restart_supervisor, "_discover_legacy_upgrade_target", lambda **kwargs: None)
+ monkeypatch.setattr(restart_supervisor, "get_build_identity", lambda: SimpleNamespace(kind="source"))
def fake_run(command, **kwargs):
calls.append(("run", command))
diff --git a/tests/test_version_identity.py b/tests/test_version_identity.py
index 519672f73..a43d294dd 100644
--- a/tests/test_version_identity.py
+++ b/tests/test_version_identity.py
@@ -70,6 +70,13 @@ def test_packaged_install_keeps_semantic_update_behavior(monkeypatch) -> None:
assert api.get_version_info() == {**expected, "build": {"kind": "package"}}
+def test_local_version_info_never_queries_package_index(monkeypatch) -> None:
+ monkeypatch.setattr("vibe.__version__", "3.0.12", raising=False)
+ monkeypatch.setattr(api, "get_build_identity", lambda: type("Build", (), {"as_dict": lambda self: {"kind": "package"}})())
+
+ assert api.get_local_version_info() == {"current": "3.0.12", "build": {"kind": "package"}}
+
+
def test_configured_missing_metadata_stays_a_source_build(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("VIBE_BUILD_METADATA_PATH", str(tmp_path / "not-written-yet.json"))
monkeypatch.setattr("vibe.__version__", "3.0.6rc5", raising=False)
diff --git a/vibe/api.py b/vibe/api.py
index 840ee65aa..c1612ebe4 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -5970,6 +5970,20 @@ def get_version_info() -> dict:
return result
+def get_local_version_info() -> dict:
+ """Return only the version already loaded by this process.
+
+ Upgrade recovery must be able to identify the release that is still
+ running even when the package index is unavailable. Keep this endpoint
+ separate from :func:`get_version_info`, whose update check is intentionally
+ allowed to perform network I/O for the user-facing version screen.
+ """
+
+ from vibe import __version__
+
+ return {"current": __version__, "build": get_build_identity().as_dict()}
+
+
def do_upgrade(auto_restart: bool = True) -> dict:
"""Perform upgrade to latest version.
diff --git a/vibe/authorization.py b/vibe/authorization.py
index ec39d93aa..c600d6487 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -371,7 +371,7 @@ _VIEWER_HTTP_RULES = tuple(
r"^/api/session$",
r"^/api/csrf-token$",
r"^/api/config$",
- r"^/api/version$",
+ r"^/api/version(?:/local)?$",
r"^/api/platforms$",
r"^/api/projects(?:/[^/]+)?$",
r"^/api/workbench/prefs$",
diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.py
index 615e8f76c..7e42c5055 100644
--- a/vibe/restart_supervisor.py
+++ b/vibe/restart_supervisor.py
@@ -1,11 +1,15 @@
from __future__ import annotations
import argparse
+import email.parser
import json
import logging
import os
+import shlex
import subprocess
import time
+import urllib.error
+import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
@@ -21,13 +25,18 @@ from config import paths
# is pure stdlib, so paying for it on every restart costs nothing.
from storage.backups import find_restorable_backup, next_backup_sequence, restore_sqlite_backup
from vibe import runtime
+from vibe.build_identity import get_build_identity
from vibe.upgrade import (
+ LEGACY_PACKAGE_NAME,
+ PACKAGE_NAME,
RollbackTarget,
+ _names_a_published_release,
build_upgrade_plan,
get_restart_command,
get_restart_environment,
get_restart_invocation_command,
get_safe_cwd,
+ installed_package_name,
)
@@ -87,6 +96,195 @@ def _ui_is_serving(started: StartedRuntime) -> bool:
return runtime.wait_for_ui_server(host, port, timeout=_ROLLBACK_UI_READY_TIMEOUT_SECONDS)
+def _running_ui_version() -> str | None:
+ """Read the version that is still serving while an upgrade is being staged.
+
+ Releases before the rollback protocol cannot pass a target into the detached
+ supervisor. The old service is still alive when that supervisor starts, so
+ its own version endpoint is the last authoritative answer before the old
+ install is stopped and replaced.
+ """
+
+ from core.services import settings as settings_service
+
+ config = settings_service.load_config(default_factory=settings_service.default_config)
+ host = runtime.effective_ui_bind_host(config)
+ if host in {"0.0.0.0", ""}:
+ host = "127.0.0.1"
+ elif host in {"::", "::0"}:
+ host = "::1"
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ base_url = f"http://{host}:{config.ui.setup_port}"
+ for endpoint in ("/api/version/local", "/api/version"):
+ try:
+ with urllib.request.urlopen(f"{base_url}{endpoint}", timeout=2.0) as response:
+ payload = json.loads(response.read().decode("utf-8"))
+ except urllib.error.HTTPError as exc:
+ if exc.code == 404:
+ continue
+ return None
+ except (OSError, ValueError, TypeError, urllib.error.URLError):
+ return None
+ version = payload.get("current") if isinstance(payload, dict) else None
+ if isinstance(version, str) and _names_a_published_release(version):
+ return version
+ return None
+
+
+def _launcher_from_python(python: str) -> runtime.ServiceLauncher | None:
+ """Pair an interpreter with the service entry point in its install."""
+
+ python_path = Path(python)
+ package_root = python_path.parent.parent / "lib"
+ main_candidates = sorted(package_root.glob("python*/site-packages/vibe/service_main.py"))
+ if not main_candidates:
+ package_root = python_path.parent.parent / "Lib" / "site-packages"
+ main_candidates = sorted(package_root.glob("vibe/service_main.py"))
+ if not main_candidates:
+ return None
+ return runtime.ServiceLauncher(python=python, main=str(main_candidates[0]))
+
+
+def _service_launcher_from_process(pid: int | None) -> runtime.ServiceLauncher | None:
+ """Read the old launcher from a still-running service or UI command line."""
+
+ if not pid:
+ return None
+ command = runtime.get_process_command(pid)
+ if not command:
+ return None
+ try:
+ argv = [arg.strip("\"'") for arg in shlex.split(command, posix=(os.name != "nt"))]
+ if Path(argv[0]).name.lower() == "systemd-run" and "--" in argv:
+ argv = argv[argv.index("--") + 1 :]
+ if not argv or not Path(argv[0]).name.lower().startswith("python"):
+ return None
+ entry = next(
+ (arg for arg in argv[1:] if not arg.startswith("-") and Path(arg).name in {"main.py", "service_main.py"}),
+ None,
+ )
+ if entry is not None:
+ return runtime.ServiceLauncher(python=argv[0], main=entry)
+ # The UI is launched with ``python -c`` rather than service_main.py.
+ # Its interpreter still identifies the install that owns the old code.
+ return _launcher_from_python(argv[0])
+ except (IndexError, ValueError):
+ return None
+
+
+def _legacy_service_launcher(
+ vibe_path: str | None, *, service_pid: int | None = None, ui_pid: int | None = None
+) -> runtime.ServiceLauncher:
+ """Recover the launcher that existed before the package-manager replace.
+
+ The service command is authoritative: the normal ``~/.local/bin/vibe``
+ symlink may already point at the replacement by the time this process starts.
+ """
+
+ for pid in (service_pid, ui_pid):
+ process_launcher = _service_launcher_from_process(pid)
+ if process_launcher is not None:
+ return process_launcher
+
+ fallback = runtime.current_service_launcher()
+ if not vibe_path:
+ return fallback
+
+ try:
+ script = Path(vibe_path).resolve()
+ shebang = script.read_text(encoding="utf-8", errors="replace").splitlines()[0]
+ python = shebang[2:].strip().split()[0] if shebang.startswith("#!") else ""
+ python_path = Path(python)
+ if not python or not python_path.is_file():
+ return fallback
+ return _launcher_from_python(str(python_path)) or fallback
+ except (OSError, IndexError, ValueError):
+ return fallback
+
+
+def _launcher_dist_metadata(launcher: runtime.ServiceLauncher) -> list[tuple[str, str]]:
+ """Read all supported distributions from the launcher's site-packages."""
+
+ site_packages = Path(launcher.main).resolve().parent.parent
+ entries: list[tuple[str, str]] = []
+ try:
+ for metadata_path in sorted(site_packages.glob("*.dist-info/METADATA")):
+ payload = email.parser.Parser().parsestr(metadata_path.read_text(encoding="utf-8"))
+ name = str(payload.get("Name") or "").strip()
+ version = str(payload.get("Version") or "").strip()
+ if name in {PACKAGE_NAME, LEGACY_PACKAGE_NAME} and version:
+ entries.append((name, version))
+ except (OSError, UnicodeError, ValueError):
+ return []
+ return entries
+
+
+def _launcher_package_name(launcher: runtime.ServiceLauncher, *, version: str | None = None) -> str:
+ """Infer the distribution name that owns a launcher when metadata is stale."""
+
+ metadata = _launcher_dist_metadata(launcher)
+ if version:
+ exact = [name for name, candidate in metadata if candidate == version]
+ if exact:
+ return exact[0]
+
+ executable = launcher.python.replace("\\", "/")
+ for package in (PACKAGE_NAME, LEGACY_PACKAGE_NAME):
+ if f"/uv/tools/{package}/" in executable:
+ return package
+ names = {name for name, _version in metadata}
+ if PACKAGE_NAME in names:
+ return PACKAGE_NAME
+ if LEGACY_PACKAGE_NAME in names:
+ return LEGACY_PACKAGE_NAME
+ return installed_package_name(python_executable=launcher.python) or PACKAGE_NAME
+
+
+def _legacy_install_metadata(
+ launcher: runtime.ServiceLauncher, *, package_name: str
+) -> tuple[str, str] | None:
+ """Read the old release metadata from the launcher-owned site-packages.
+
+ A renamed distribution can leave an older ``vibe-remote`` dist-info beside
+ the current ``avibe-os`` install. The launcher identifies which side was
+ running, so unrelated metadata must never win by directory order.
+ """
+
+ try:
+ from vibe import __version__ as replacement_version
+
+ for name, version in _launcher_dist_metadata(launcher):
+ if (
+ name == package_name
+ and version
+ and version != replacement_version
+ and _names_a_published_release(version)
+ ):
+ return version, name
+ except (OSError, UnicodeError, ValueError):
+ return None
+ return None
+
+
+def _discover_legacy_upgrade_target(*, trigger: str, vibe_path: str | None) -> RollbackTarget | None:
+ """Build a rollback target for an upgrade initiated by an older release."""
+
+ if trigger != "upgrade":
+ return None
+ service_pid = _read_recorded_pid()
+ ui_pid = _read_recorded_ui_pid()
+ launcher = _legacy_service_launcher(vibe_path, service_pid=service_pid, ui_pid=ui_pid)
+ version = _running_ui_version()
+ package = _launcher_package_name(launcher, version=version)
+ if version is None:
+ metadata = _legacy_install_metadata(launcher, package_name=package)
+ if metadata is None:
+ return None
+ version, package = metadata
+ return RollbackTarget(version=version, package=package, launcher=launcher)
+
+
def _now_iso() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
@@ -586,6 +784,20 @@ def _run_restart_job(
safe_cwd = get_safe_cwd()
_prune_restart_logs()
+ rollback_target_source = "explicit" if rollback_to else None
+ rollback_discovery_error: str | None = None
+ legacy_target_required = trigger == "upgrade" and get_build_identity().kind == "package"
+ if rollback_to is None and trigger == "upgrade":
+ try:
+ rollback_to = _discover_legacy_upgrade_target(trigger=trigger, vibe_path=vibe_path)
+ if rollback_to is not None:
+ rollback_target_source = "running_service"
+ except Exception as exc:
+ # Older releases do not know how to carry a target. Discovery is a
+ # compatibility aid; if it cannot identify one, the job fails closed
+ # before stopping the old runtime rather than creating a dark one.
+ rollback_discovery_error = str(exc)
+
with log_path.open("a", encoding="utf-8") as log:
def write(message: str) -> None:
log.write(f"{_now_iso()} {message}\n")
@@ -669,6 +881,8 @@ def _run_restart_job(
"rollback_to": rollback_to.version if rollback_to else None,
"rollback_package": rollback_to.package if rollback_to else None,
"rollback_launcher": rollback_to.launcher._asdict() if rollback_to else None,
+ "rollback_target_source": rollback_target_source,
+ "rollback_discovery_error": rollback_discovery_error,
"old_pid": old_pid,
"new_pid": None,
"log_path": str(log_path),
@@ -689,6 +903,13 @@ def _run_restart_job(
write("restart job started after delay")
restart_started_at = time.monotonic()
+ if legacy_target_required and rollback_to is None:
+ return fail(
+ "legacy upgrade rollback target unavailable; existing runtime was left running",
+ 2,
+ started_at=restart_started_at,
+ )
+
write("stopping UI and service" if restart_ui else "stopping service (Web UI kept running)")
stop_runtime_started_at = time.monotonic()
try:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index c09326636..84a484df5 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6384,6 +6384,13 @@ def version():
return jsonify(api.get_version_info())
[email protected]("/api/version/local")
+def local_version():
+ from vibe import api
+
+ return jsonify(api.get_local_version_info())
+
+
# =============================================================================
# POST Endpoints
# =============================================================================