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): restart stale installed runtime

cyh9d398d63f2ac
diff --git a/tests/test_runtime_service_lock.py b/tests/test_runtime_service_lock.py
index 1b89f932f..e708331b4 100644
--- a/tests/test_runtime_service_lock.py
+++ b/tests/test_runtime_service_lock.py
@@ -1,3 +1,4 @@
+import os
import sys
import tempfile
import unittest
@@ -60,6 +61,62 @@ class RuntimeServiceLockTests(unittest.TestCase):
self.assertEqual(pid, 12345)
spawn_background.assert_not_called()
+ def test_runtime_processes_stale_when_service_predates_installed_package(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ root = Path(tmpdir)
+ pid_path = root / "service.pid"
+ ui_pid_path = root / "ui.pid"
+ package_root = root / "site-packages" / "vibe"
+ project_root = root / "site-packages"
+ package_root.mkdir(parents=True)
+ init_path = package_root / "__init__.py"
+ service_main = package_root / "service_main.py"
+ ui_server = package_root / "ui_server.py"
+ for marker in (init_path, service_main, ui_server):
+ marker.write_text("", encoding="utf-8")
+ os.utime(marker, (2000, 2000))
+ pid_path.write_text("12345", encoding="utf-8")
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.paths.get_runtime_ui_pid_path", return_value=ui_pid_path):
+ with patch("vibe.runtime.get_project_root", return_value=project_root):
+ with patch("vibe.runtime.get_package_root", return_value=package_root):
+ with patch("vibe.runtime.get_service_main_path", return_value=service_main):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch(
+ "vibe.runtime.get_process_command",
+ return_value=f"{sys.executable} {service_main}",
+ ):
+ with patch("vibe.runtime.get_process_start_time", return_value=1000.0):
+ self.assertTrue(runtime.runtime_processes_stale_after_package_update())
+
+ def test_runtime_process_stale_check_is_disabled_in_source_checkout(self):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ root = Path(tmpdir)
+ pid_path = root / "service.pid"
+ ui_pid_path = root / "ui.pid"
+ project_root = root / "checkout"
+ package_root = project_root / "vibe"
+ package_root.mkdir(parents=True)
+ (project_root / "main.py").write_text("", encoding="utf-8")
+ service_main = project_root / "main.py"
+ (package_root / "__init__.py").write_text("", encoding="utf-8")
+ (package_root / "ui_server.py").write_text("", encoding="utf-8")
+ pid_path.write_text("12345", encoding="utf-8")
+
+ with patch("vibe.runtime.paths.get_runtime_pid_path", return_value=pid_path):
+ with patch("vibe.runtime.paths.get_runtime_ui_pid_path", return_value=ui_pid_path):
+ with patch("vibe.runtime.get_project_root", return_value=project_root):
+ with patch("vibe.runtime.get_package_root", return_value=package_root):
+ with patch("vibe.runtime.get_service_main_path", return_value=service_main):
+ with patch("vibe.runtime.pid_alive", return_value=True):
+ with patch(
+ "vibe.runtime.get_process_command",
+ return_value=f"{sys.executable} {service_main}",
+ ):
+ with patch("vibe.runtime.get_process_start_time", return_value=1000.0):
+ self.assertFalse(runtime.runtime_processes_stale_after_package_update())
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index b88897b5c..d85606554 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -176,44 +176,21 @@ def test_cmd_restart_runs_synchronously_by_default(monkeypatch):
assert calls == ["stop", ("sleep", 3), "start"]
-def test_cmd_vibe_treats_legacy_delayed_helper_as_restart(monkeypatch):
+def test_cmd_vibe_restarts_stale_runtime_processes(monkeypatch):
calls = []
config = SimpleNamespace(
has_configured_platform_credentials=lambda: True,
ui=SimpleNamespace(setup_host="127.0.0.1", setup_port=5123, open_browser=False),
)
- monkeypatch.delenv(cli.LEGACY_DELAYED_RESTART_HANDLED_ENV, raising=False)
monkeypatch.setattr(cli.paths, "ensure_data_dirs", lambda: None)
monkeypatch.setattr(cli, "_ensure_config", lambda: config)
- monkeypatch.setattr(cli, "_write_status", lambda *args, **kwargs: calls.append(("status", args)))
- monkeypatch.setattr(cli, "cmd_stop", lambda: calls.append("stop") or 0)
- monkeypatch.setattr(cli.time, "sleep", lambda seconds: calls.append(("sleep", seconds)))
- monkeypatch.setattr(cli.runtime, "start_service", lambda: calls.append("start_service") or 1234)
- monkeypatch.setattr(cli.runtime, "effective_ui_bind_host", lambda cfg: "127.0.0.1")
- monkeypatch.setattr(cli.runtime, "start_ui", lambda host, port: calls.append(("start_ui", host, port)) or 5678)
- monkeypatch.setattr(cli.runtime, "write_status", lambda *args: calls.append(("runtime_status", args)))
- monkeypatch.setattr(cli, "_open_browser", lambda url: calls.append(("open", url)) or True)
- monkeypatch.setattr(
- cli.runtime,
- "get_process_command",
- lambda pid: "python -c \"import subprocess, time; time.sleep(2); subprocess.Popen(['vibe'], "
- "stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\"",
- )
+ monkeypatch.setattr(cli.runtime, "runtime_processes_stale_after_package_update", lambda: True)
+ monkeypatch.setattr(cli, "_cmd_restart_with_delay", lambda delay: calls.append(("restart", delay)) or 0)
assert cli.cmd_vibe() == 0
- assert calls[:2] == ["stop", ("sleep", 3)]
- assert "start_service" in calls
- assert ("start_ui", "127.0.0.1", 5123) in calls
- assert os.environ[cli.LEGACY_DELAYED_RESTART_HANDLED_ENV] == "1"
-
-
-def test_legacy_delayed_helper_detection_ignores_normal_parent(monkeypatch):
- monkeypatch.delenv(cli.LEGACY_DELAYED_RESTART_HANDLED_ENV, raising=False)
- monkeypatch.setattr(cli.runtime, "get_process_command", lambda pid: "zsh")
-
- assert cli._launched_by_legacy_delayed_restart_helper() is False
+ assert calls == [("restart", 0.0)]
def test_restart_parser_accepts_delay_seconds():
diff --git a/vibe/cli.py b/vibe/cli.py
index 41df316a0..6fa13bc69 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -52,7 +52,6 @@ logger = logging.getLogger(__name__)
WATCH_STARTUP_STABLE_RUNNING_SECONDS = 1.5
WATCH_STARTUP_JITTER_BUFFER_SECONDS = 1.0
-LEGACY_DELAYED_RESTART_HANDLED_ENV = "VIBE_LEGACY_DELAYED_RESTART_HANDLED"
class VibeArgumentParser(argparse.ArgumentParser):
@@ -1814,9 +1813,8 @@ def cmd_vibe():
paths.ensure_data_dirs()
config = _ensure_config()
- if _launched_by_legacy_delayed_restart_helper():
- os.environ[LEGACY_DELAYED_RESTART_HANDLED_ENV] = "1"
- logger.info("Bare vibe command launched by legacy delayed restart helper; running explicit restart")
+ if runtime.runtime_processes_stale_after_package_update():
+ logger.info("Running Vibe processes predate the installed package; running explicit restart")
return _cmd_restart_with_delay(0.0)
has_configured_platform_credentials = getattr(config, "has_configured_platform_credentials", None)
@@ -1856,20 +1854,6 @@ def cmd_vibe():
return 0
-def _launched_by_legacy_delayed_restart_helper() -> bool:
- if os.environ.get(LEGACY_DELAYED_RESTART_HANDLED_ENV):
- return False
- parent_command = runtime.get_process_command(os.getppid())
- if not parent_command:
- return False
- return (
- "subprocess.Popen" in parent_command
- and "time.sleep(" in parent_command
- and "stdout=subprocess.DEVNULL" in parent_command
- and "stderr=subprocess.DEVNULL" in parent_command
- )
-
-
def _stop_opencode_server():
"""Terminate the OpenCode server if running."""
pid_file = paths.get_logs_dir() / "opencode_server.json"
diff --git a/vibe/runtime.py b/vibe/runtime.py
index d2dc9acc0..05b42ad71 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -10,6 +10,7 @@ import threading
import time
import urllib.error
import urllib.request
+from datetime import datetime
from pathlib import Path
from config import paths
@@ -461,6 +462,128 @@ def _pid_mismatches_service(pid: int) -> bool:
return not _command_references_path(command, get_service_main_path())
+def _pid_matches_service_process(pid: int) -> bool:
+ command = get_process_command(pid)
+ return bool(command and _command_references_path(command, get_service_main_path()))
+
+
+def _linux_process_start_time(pid: int) -> float | None:
+ proc_stat = Path(f"/proc/{pid}/stat")
+ system_stat = Path("/proc/stat")
+ if not proc_stat.exists() or not system_stat.exists():
+ return None
+ try:
+ boot_time = None
+ for line in system_stat.read_text(encoding="utf-8").splitlines():
+ if line.startswith("btime "):
+ boot_time = int(line.split()[1])
+ break
+ if boot_time is None:
+ return None
+ stat_text = proc_stat.read_text(encoding="utf-8")
+ after_command = stat_text.rsplit(")", 1)[1].strip().split()
+ start_ticks = int(after_command[19])
+ ticks_per_second = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
+ return boot_time + (start_ticks / ticks_per_second)
+ except (OSError, IndexError, KeyError, ValueError):
+ logger.debug("Failed to read Linux process start time for pid=%s", pid, exc_info=True)
+ return None
+
+
+def _ps_process_start_time(pid: int) -> float | None:
+ try:
+ result = subprocess.run(
+ ["ps", "-p", str(pid), "-o", "lstart="],
+ capture_output=True,
+ text=True,
+ timeout=2,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ logger.debug("Failed to invoke ps for process start time pid=%s", pid, exc_info=True)
+ return None
+ if result.returncode != 0:
+ return None
+ started_text = result.stdout.strip()
+ if not started_text:
+ return None
+ try:
+ return datetime.strptime(started_text, "%a %b %d %H:%M:%S %Y").timestamp()
+ except ValueError:
+ logger.debug("Failed to parse ps start time for pid=%s: %s", pid, started_text)
+ return None
+
+
+def get_process_start_time(pid: int) -> float | None:
+ if not isinstance(pid, int) or pid <= 0:
+ return None
+ if os.name == "posix":
+ return _linux_process_start_time(pid) or _ps_process_start_time(pid)
+ return None
+
+
+def _current_package_mtime() -> float | None:
+ # Only use this in installed-package mode. In a source checkout, editing
+ # files while a dev service is running should not make bare `vibe` restart.
+ if (get_project_root() / "main.py").exists():
+ return None
+
+ markers = [
+ get_package_root() / "__init__.py",
+ get_service_main_path(),
+ get_package_root() / "ui_server.py",
+ ]
+ mtimes: list[float] = []
+ for marker in markers:
+ try:
+ mtimes.append(marker.stat().st_mtime)
+ except OSError:
+ continue
+ if not mtimes:
+ return None
+ return max(mtimes)
+
+
+def _process_predates_current_package(pid: int) -> bool:
+ package_mtime = _current_package_mtime()
+ process_start_time = get_process_start_time(pid)
+ if package_mtime is None or process_start_time is None:
+ return False
+ return process_start_time + 1.0 < package_mtime
+
+
+def runtime_processes_stale_after_package_update() -> bool:
+ service_pid_path = paths.get_runtime_pid_path()
+ if service_pid_path.exists():
+ try:
+ service_pid = int(service_pid_path.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ service_pid = 0
+ if (
+ service_pid
+ and pid_alive(service_pid)
+ and _pid_matches_service_process(service_pid)
+ and _process_predates_current_package(service_pid)
+ ):
+ return True
+
+ ui_pid_path = paths.get_runtime_ui_pid_path()
+ if ui_pid_path.exists():
+ try:
+ ui_pid = int(ui_pid_path.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ ui_pid = 0
+ if (
+ ui_pid
+ and pid_alive(ui_pid)
+ and _pid_matches_ui_server(ui_pid)
+ and _process_predates_current_package(ui_pid)
+ ):
+ return True
+
+ return False
+
+
def render_status():
status = read_status()
pid_path = paths.get_runtime_pid_path()