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(release): harden install and upgrade regressions

cyhd990421747e9
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index cc870fc19..ff4d10a00 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -18,3 +18,38 @@ jobs:
run: |
pip install pre-commit
pre-commit run --all-files
+
+ install-upgrade-regression:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "20"
+ cache: "npm"
+ cache-dependency-path: ui/package-lock.json
+
+ - name: Build UI assets
+ working-directory: ui
+ run: |
+ npm ci
+ npm run build
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+
+ - name: Install test dependencies
+ run: |
+ pip install -e . pytest
+
+ - name: Run install and upgrade regressions
+ run: |
+ docker info
+ pytest \
+ tests/test_upgrade_flow.py \
+ tests/test_install_script.py \
+ tests/e2e/test_install_command.py \
+ tests/e2e/test_upgrade_command.py \
+ -v
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 9e6684e6e..d9537b6b6 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -41,6 +41,19 @@ jobs:
with:
python-version: "3.12"
+ - name: Install test dependencies
+ run: pip install -e . pytest
+
+ - name: Run release install and upgrade regressions
+ run: |
+ docker info
+ pytest \
+ tests/test_upgrade_flow.py \
+ tests/test_install_script.py \
+ tests/e2e/test_install_command.py \
+ tests/e2e/test_upgrade_command.py \
+ -v
+
- name: Install build tools
run: pip install build
diff --git a/install.sh b/install.sh
index d98b9a657..8bcc03899 100755
--- a/install.sh
+++ b/install.sh
@@ -17,6 +17,8 @@ NC='\033[0m' # No Color
REPO="cyhhao/vibe-remote"
PACKAGE_NAME="vibe-remote"
VIBE_BIN_PATH=""
+VIBE_TOOL_BIN_DIR=""
+ORIGINAL_PATH="$PATH"
print_banner() {
echo -e "${BLUE}"
@@ -60,11 +62,73 @@ detect_os() {
echo "$OS"
}
+path_contains_dir() {
+ local path_value="$1"
+ local target_dir="$2"
+
+ case ":$path_value:" in
+ *":$target_dir:"*) return 0 ;;
+ *) return 1 ;;
+ esac
+}
+
+ensure_writable_dir() {
+ local dir="$1"
+
+ if [ -z "$dir" ]; then
+ return 1
+ fi
+
+ if [ ! -d "$dir" ]; then
+ mkdir -p "$dir" 2>/dev/null || return 1
+ fi
+
+ [ -d "$dir" ] && [ -w "$dir" ]
+}
+
+choose_tool_bin_dir() {
+ local preferred_dirs=(
+ "$HOME/.local/bin"
+ "$HOME/bin"
+ "/usr/local/bin"
+ "/opt/homebrew/bin"
+ )
+ local dir
+
+ for dir in "${preferred_dirs[@]}"; do
+ if path_contains_dir "$ORIGINAL_PATH" "$dir" && ensure_writable_dir "$dir"; then
+ echo "$dir"
+ return 0
+ fi
+ done
+
+ local old_ifs="$IFS"
+ IFS=":"
+ for dir in $ORIGINAL_PATH; do
+ if [ -n "$dir" ] && ensure_writable_dir "$dir"; then
+ IFS="$old_ifs"
+ echo "$dir"
+ return 0
+ fi
+ done
+ IFS="$old_ifs"
+
+ return 1
+}
+
# Check if command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
+uv_tool_install() {
+ if [ -n "$VIBE_TOOL_BIN_DIR" ]; then
+ UV_TOOL_BIN_DIR="$VIBE_TOOL_BIN_DIR" uv tool install "$@"
+ else
+ uv tool install "$@"
+ fi
+}
+
# Install uv if not present
install_uv() {
if command_exists uv; then
@@ -110,16 +174,23 @@ install_uv() {
# Install vibe-remote using uv (uv auto-downloads Python if needed)
install_vibe() {
info "Installing vibe-remote (Python will be downloaded automatically if needed)..."
+
+ VIBE_TOOL_BIN_DIR="$(choose_tool_bin_dir || true)"
+ if [ -n "$VIBE_TOOL_BIN_DIR" ]; then
+ info "Installing vibe command into $VIBE_TOOL_BIN_DIR"
+ else
+ warn "Could not find a writable directory in PATH; you may need a new shell before 'vibe' is available"
+ fi
# uv tool install will auto-download Python if not available
# --force: reinstall even if already installed
# --refresh: refresh package cache to get latest version
# Try in order: PyPI -> China mirror (tsinghua) -> GitHub
- if uv tool install "$PACKAGE_NAME" --force --refresh 2>/dev/null; then
+ if uv_tool_install "$PACKAGE_NAME" --force --refresh 2>/dev/null; then
success "vibe-remote installed successfully (from PyPI)"
- elif uv tool install "$PACKAGE_NAME" --force --refresh --index-url https://pypi.tuna.tsinghua.edu.cn/simple 2>/dev/null; then
+ elif uv_tool_install "$PACKAGE_NAME" --force --refresh --index-url https://pypi.tuna.tsinghua.edu.cn/simple 2>/dev/null; then
success "vibe-remote installed successfully (from Tsinghua mirror)"
- elif uv tool install "git+https://github.com/${REPO}.git" --force 2>/dev/null; then
+ elif uv_tool_install "git+https://github.com/${REPO}.git" --force 2>/dev/null; then
success "vibe-remote installed successfully (from GitHub)"
else
error "Failed to install vibe-remote from all sources"
@@ -131,6 +202,9 @@ verify_installation() {
info "Verifying installation..."
# Refresh PATH
+ if [ -n "$VIBE_TOOL_BIN_DIR" ]; then
+ export PATH="$VIBE_TOOL_BIN_DIR:$PATH"
+ fi
export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
if command_exists vibe; then
@@ -171,10 +245,16 @@ print_next_steps() {
echo -e "${GREEN}Installation complete!${NC}"
echo ""
echo -e "${BLUE}Next steps:${NC}"
- echo " 1. Run 'source ${vibe_dir}/env' (or restart your shell)"
- echo " 2. Run 'vibe' to start the setup wizard"
- echo " 3. Configure your Slack app tokens in the web UI"
- echo " 4. Enable channels and start chatting with AI agents"
+ if command_exists vibe; then
+ echo " 1. Run 'vibe' to start the setup wizard"
+ echo " 2. Configure your Slack app tokens in the web UI"
+ echo " 3. Enable channels and start chatting with AI agents"
+ else
+ echo " 1. Run 'source ${vibe_dir}/env' (or restart your shell)"
+ echo " 2. Run 'vibe' to start the setup wizard"
+ echo " 3. Configure your Slack app tokens in the web UI"
+ echo " 4. Enable channels and start chatting with AI agents"
+ fi
echo ""
echo -e "${BLUE}Quick commands:${NC}"
echo " vibe - Start Vibe Remote (service + web UI)"
diff --git a/tests/e2e/test_install_command.py b/tests/e2e/test_install_command.py
new file mode 100644
index 000000000..1e47e0721
--- /dev/null
+++ b/tests/e2e/test_install_command.py
@@ -0,0 +1,66 @@
+"""Docker smoke test for the README one-command install flow."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_SCRIPT = REPO_ROOT / "install.sh"
+BASE_IMAGE = os.environ.get("VIBE_INSTALL_TEST_IMAGE", "debian:trixie-slim")
+
+
+def _docker_available() -> bool:
+ if not shutil.which("docker"):
+ return False
+ try:
+ result = subprocess.run(["docker", "info"], capture_output=True, timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return result.returncode == 0
+
+
+def test_install_command_starts_vibe_in_fresh_container():
+ if not _docker_available():
+ pytest.skip("Docker is not available")
+
+ container_name = f"vibe-install-smoke-{os.getpid()}"
+ command = (
+ "apt-get update >/dev/null && "
+ "apt-get install -y --no-install-recommends curl ca-certificates bash procps >/dev/null && "
+ "cat /work/install.sh | bash && "
+ "vibe && sleep 2 && vibe status"
+ )
+
+ result = subprocess.run(
+ [
+ "docker",
+ "run",
+ "--name",
+ container_name,
+ "--rm",
+ "-v",
+ f"{REPO_ROOT}:/work",
+ "-w",
+ "/work",
+ BASE_IMAGE,
+ "bash",
+ "-lc",
+ command,
+ ],
+ capture_output=True,
+ text=True,
+ timeout=600,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "Installing vibe command into" in result.stdout
+ assert "Web UI:" in result.stdout
+ assert '"running": true' in result.stdout
+ assert '"service_pid":' in result.stdout
diff --git a/tests/e2e/test_upgrade_command.py b/tests/e2e/test_upgrade_command.py
new file mode 100644
index 000000000..5fd84d30d
--- /dev/null
+++ b/tests/e2e/test_upgrade_command.py
@@ -0,0 +1,116 @@
+"""Docker smoke test for release-style upgrade flow using a built wheel."""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+BASE_IMAGE = os.environ.get("VIBE_UPGRADE_TEST_IMAGE", "debian:trixie-slim")
+INITIAL_RELEASE_VERSION = "9998.0.0"
+TEST_RELEASE_VERSION = "9999.0.0"
+
+
+def _docker_available() -> bool:
+ if not shutil.which("docker"):
+ return False
+ try:
+ result = subprocess.run(["docker", "info"], capture_output=True, timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return result.returncode == 0
+
+
+def _build_test_wheel(fixtures_dir: Path, version: str) -> Path:
+ env = os.environ.copy()
+ env["SETUPTOOLS_SCM_PRETEND_VERSION"] = version
+
+ result = subprocess.run(
+ [sys.executable, "-m", "pip", "wheel", ".", "--no-deps", "--wheel-dir", str(fixtures_dir)],
+ cwd=REPO_ROOT,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=600,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ wheel_path = fixtures_dir / f"vibe_remote-{version}-py3-none-any.whl"
+ assert wheel_path.exists(), f"Expected built wheel at {wheel_path}"
+ return wheel_path
+
+
+def test_upgrade_command_uses_built_release_artifact():
+ if not _docker_available():
+ pytest.skip("Docker is not available")
+
+ with tempfile.TemporaryDirectory(prefix="vibe-upgrade-fixtures-") as tmpdir:
+ fixtures_dir = Path(tmpdir)
+ initial_wheel_path = _build_test_wheel(fixtures_dir, INITIAL_RELEASE_VERSION)
+ wheel_path = _build_test_wheel(fixtures_dir, TEST_RELEASE_VERSION)
+
+ metadata_path = fixtures_dir / "metadata.json"
+ metadata_path.write_text(json.dumps({"info": {"version": TEST_RELEASE_VERSION}}), encoding="utf-8")
+
+ container_name = f"vibe-upgrade-smoke-{os.getpid()}"
+ command = " && ".join(
+ [
+ "apt-get update >/dev/null",
+ "apt-get install -y --no-install-recommends curl ca-certificates bash procps >/dev/null",
+ "curl -LsSf https://astral.sh/uv/install.sh | env UV_UNMANAGED_INSTALL=/usr/local/bin sh",
+ f"UV_TOOL_BIN_DIR=/usr/local/bin uv tool install /fixtures/{initial_wheel_path.name} --force",
+ "vibe version",
+ "VIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json "
+ f"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",
+ "vibe version",
+ "VIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json vibe check-update",
+ "vibe",
+ "sleep 2",
+ "vibe status",
+ ]
+ )
+
+ try:
+ result = subprocess.run(
+ [
+ "docker",
+ "run",
+ "--name",
+ container_name,
+ "--rm",
+ "-v",
+ f"{REPO_ROOT}:/work",
+ "-v",
+ f"{fixtures_dir}:/fixtures",
+ "-w",
+ "/work",
+ BASE_IMAGE,
+ "bash",
+ "-lc",
+ command,
+ ],
+ capture_output=True,
+ text=True,
+ timeout=1200,
+ )
+ finally:
+ subprocess.run(["docker", "rm", "-f", container_name], capture_output=True)
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert f"vibe-remote {INITIAL_RELEASE_VERSION}" in result.stdout
+ assert "New version available: 9999.0.0" in result.stdout
+ assert "Upgrade successful!" in result.stdout
+ assert f"vibe-remote {TEST_RELEASE_VERSION}" in result.stdout
+ assert "You are using the latest version." in result.stdout
+ assert '"running": true' in result.stdout
diff --git a/tests/test_install_script.py b/tests/test_install_script.py
new file mode 100644
index 000000000..35401b2df
--- /dev/null
+++ b/tests/test_install_script.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+import os
+import stat
+import subprocess
+import textwrap
+from pathlib import Path
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+INSTALL_SCRIPT = REPO_ROOT / "install.sh"
+
+
+def _write_executable(path: Path, content: str) -> None:
+ path.write_text(textwrap.dedent(content), encoding="utf-8")
+ path.chmod(path.stat().st_mode | stat.S_IEXEC)
+
+
+def test_install_script_keeps_vibe_available_on_current_path(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_executable(
+ path_dir / "uv",
+ f"""\
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ printf '%s' "${{UV_TOOL_BIN_DIR:-}}" > "{uv_log}"
+
+ if [ "$1" != "tool" ] || [ "$2" != "install" ]; then
+ exit 1
+ fi
+
+ bin_dir="${{UV_TOOL_BIN_DIR:-$HOME/.local/bin}}"
+ mkdir -p "$bin_dir"
+ cat > "$bin_dir/vibe" <<'EOF'
+ #!/usr/bin/env bash
+ set -euo pipefail
+ if [ "${{1:-}}" = "--help" ]; then
+ echo "usage: vibe"
+ elif [ "${{1:-}}" = "version" ]; then
+ echo "vibe-remote 9.9.9"
+ else
+ echo "started"
+ fi
+ EOF
+ chmod +x "$bin_dir/vibe"
+ """,
+ )
+
+ env = os.environ.copy()
+ env["HOME"] = str(home_dir)
+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])
+
+ result = subprocess.run(
+ ["bash", "-lc", f'bash "{INSTALL_SCRIPT}" && vibe version'],
+ cwd=REPO_ROOT,
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "vibe-remote 9.9.9" in result.stdout
+ assert uv_log.read_text(encoding="utf-8")
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
new file mode 100644
index 000000000..995a4a3ba
--- /dev/null
+++ b/tests/test_upgrade_flow.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from vibe import api, cli
+from vibe.upgrade import UpgradePlan, build_upgrade_plan, get_latest_version_info
+
+
+def test_build_upgrade_plan_uses_uv_and_preserves_tool_bin_dir():
+ plan = build_upgrade_plan(
+ python_executable="/tmp/.local/share/uv/tools/vibe-remote/bin/python",
+ uv_path="/usr/local/bin/uv",
+ vibe_path="/custom/bin/vibe",
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert plan.method == "uv"
+ assert plan.command == ["/usr/local/bin/uv", "tool", "install", "vibe-remote", "--upgrade"]
+ assert plan.env is not None
+ assert plan.env["UV_TOOL_BIN_DIR"] == "/custom/bin"
+ assert plan.env["PATH"] == "/usr/bin"
+
+
+def test_build_upgrade_plan_uses_pip_for_non_uv_install():
+ plan = build_upgrade_plan(
+ python_executable="/usr/bin/python3",
+ uv_path="/usr/local/bin/uv",
+ vibe_path="/custom/bin/vibe",
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert plan.method == "pip"
+ assert plan.command == ["/usr/bin/python3", "-m", "pip", "install", "--upgrade", "vibe-remote"]
+ assert plan.env == {"PATH": "/usr/bin"}
+
+
+def test_build_upgrade_plan_uses_env_package_spec(monkeypatch):
+ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "/tmp/vibe_remote-9999.0.0-py3-none-any.whl")
+
+ plan = build_upgrade_plan(
+ python_executable="/tmp/.local/share/uv/tools/vibe-remote/bin/python",
+ uv_path="/usr/local/bin/uv",
+ vibe_path="/custom/bin/vibe",
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert plan.command == [
+ "/usr/local/bin/uv",
+ "tool",
+ "install",
+ "/tmp/vibe_remote-9999.0.0-py3-none-any.whl",
+ "--upgrade",
+ ]
+
+
+def test_get_latest_version_info_uses_override_metadata_url(monkeypatch, tmp_path):
+ metadata_path = tmp_path / "metadata.json"
+ metadata_path.write_text('{"info": {"version": "9999.0.0"}}', encoding="utf-8")
+ monkeypatch.setenv("VIBE_UPDATE_METADATA_URL", metadata_path.as_uri())
+
+ info = get_latest_version_info("2.2.0")
+
+ assert info == {"current": "2.2.0", "latest": "9999.0.0", "has_update": True, "error": None}
+
+
+def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):
+ plan = UpgradePlan(
+ command=["/usr/local/bin/uv", "tool", "install", "vibe-remote", "--upgrade"],
+ env={"UV_TOOL_BIN_DIR": "/custom/bin"},
+ method="uv",
+ )
+ calls: dict[str, Any] = {}
+
+ monkeypatch.setattr(api, "build_upgrade_plan", lambda: plan)
+
+ def fake_run(cmd, **kwargs):
+ calls["run_cmd"] = cmd
+ calls["run_kwargs"] = kwargs
+ return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")
+
+ def fake_popen(cmd, **kwargs):
+ calls["popen_cmd"] = cmd
+ calls["popen_kwargs"] = kwargs
+
+ class _Proc:
+ pass
+
+ return _Proc()
+
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api.subprocess, "Popen", fake_popen)
+ monkeypatch.setattr(api.shutil, "which", lambda name: "/custom/bin/vibe" if name == "vibe" else None)
+
+ result = api.do_upgrade(auto_restart=True)
+
+ assert result["ok"] is True
+ assert result["restarting"] is True
+ assert calls["run_cmd"] == plan.command
+ assert calls["run_kwargs"] == {
+ "capture_output": True,
+ "text": True,
+ "timeout": 120,
+ "env": plan.env,
+ }
+ assert calls["popen_cmd"] == "sleep 2 && /custom/bin/vibe"
+ assert calls["popen_kwargs"]["shell"] is True
+ assert calls["popen_kwargs"]["start_new_session"] is True
+
+
+def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):
+ plan = UpgradePlan(
+ command=["/usr/local/bin/uv", "tool", "install", "vibe-remote", "--upgrade"],
+ env={"UV_TOOL_BIN_DIR": "/custom/bin"},
+ method="uv",
+ )
+ calls: dict[str, Any] = {}
+
+ monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})
+ monkeypatch.setattr(cli, "build_upgrade_plan", lambda: plan)
+
+ def fake_run(cmd, **kwargs):
+ calls["cmd"] = cmd
+ calls["kwargs"] = kwargs
+ return subprocess.CompletedProcess(cmd, 0, stdout="done", stderr="")
+
+ monkeypatch.setattr(cli.subprocess, "run", fake_run)
+
+ result = cli.cmd_upgrade()
+
+ assert result == 0
+ assert calls["cmd"] == plan.command
+ assert calls["kwargs"] == {"capture_output": True, "text": True, "env": plan.env}
+
+
+def test_cmd_upgrade_skips_install_when_already_latest(monkeypatch):
+ monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": False, "latest": "2.2.0"})
+
+ def fail_run(*args, **kwargs):
+ raise AssertionError("subprocess.run should not be called when already latest")
+
+ monkeypatch.setattr(cli.subprocess, "run", fail_run)
+
+ assert cli.cmd_upgrade() == 0
diff --git a/vibe/api.py b/vibe/api.py
index 1d3ba66dd..654c293bd 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -5,6 +5,7 @@ import os
import shutil
import subprocess
import time
+import urllib.request
from pathlib import Path
from typing import Dict, List, Optional
@@ -20,6 +21,7 @@ from config.v2_settings import (
_routing_to_dict,
)
from config.v2_sessions import SessionsStore
+from vibe.upgrade import build_upgrade_plan, get_latest_version_info
logger = logging.getLogger(__name__)
@@ -627,32 +629,9 @@ def get_version_info() -> dict:
"error": str | None
}
"""
- import urllib.request
from vibe import __version__
- current = __version__
- result = {"current": current, "latest": None, "has_update": False, "error": None}
-
- try:
- url = "https://pypi.org/pypi/vibe-remote/json"
- req = urllib.request.Request(url, headers={"User-Agent": "vibe-remote"})
- with urllib.request.urlopen(req, timeout=10) as resp:
- data = json.loads(resp.read().decode("utf-8"))
- latest = data.get("info", {}).get("version", "")
- result["latest"] = latest
-
- # Simple version comparison (works for semver)
- if latest and latest != current:
- try:
- current_parts = [int(x) for x in current.split(".")[:3] if x.isdigit()]
- latest_parts = [int(x) for x in latest.split(".")[:3] if x.isdigit()]
- result["has_update"] = latest_parts > current_parts
- except (ValueError, AttributeError):
- result["has_update"] = latest != current
- except Exception as e:
- result["error"] = str(e)
-
- return result
+ return get_latest_version_info(__version__)
def do_upgrade(auto_restart: bool = True) -> dict:
@@ -664,24 +643,16 @@ def do_upgrade(auto_restart: bool = True) -> dict:
Returns:
{"ok": bool, "message": str, "output": str | None, "restarting": bool}
"""
- import sys
-
- # Determine upgrade method based on how vibe was installed
- # Check if running from uv tool environment
- exe_path = sys.executable
- is_uv_tool = ".local/share/uv/tools/" in exe_path or "/uv/tools/" in exe_path
-
- uv_path = shutil.which("uv")
-
- if is_uv_tool and uv_path:
- # Installed via uv tool, upgrade with uv
- cmd = [uv_path, "tool", "install", "vibe-remote", "--upgrade"]
- else:
- # Installed via pip or other method, use current Python's pip
- cmd = [sys.executable, "-m", "pip", "install", "--upgrade", "vibe-remote"]
+ plan = build_upgrade_plan()
try:
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
+ result = subprocess.run(
+ plan.command,
+ capture_output=True,
+ text=True,
+ timeout=120,
+ env=plan.env,
+ )
if result.returncode == 0:
restarting = False
if auto_restart:
diff --git a/vibe/cli.py b/vibe/cli.py
index b548f8bad..c6f70982e 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -7,7 +7,6 @@ import signal
import subprocess
import sys
import time
-import urllib.request
from pathlib import Path
from config import paths
@@ -21,6 +20,7 @@ from config.v2_config import (
V2Config,
)
from vibe import __version__, api, runtime
+from vibe.upgrade import build_upgrade_plan, get_latest_version_info
logger = logging.getLogger(__name__)
@@ -607,31 +607,7 @@ def get_latest_version() -> dict:
Returns:
{"current": str, "latest": str, "has_update": bool, "error": str|None}
"""
- current = __version__
- result = {"current": current, "latest": None, "has_update": False, "error": None}
-
- try:
- url = "https://pypi.org/pypi/vibe-remote/json"
- req = urllib.request.Request(url, headers={"User-Agent": "vibe-remote"})
- with urllib.request.urlopen(req, timeout=10) as resp:
- data = json.loads(resp.read().decode("utf-8"))
- latest = data.get("info", {}).get("version", "")
- result["latest"] = latest
-
- # Simple version comparison (works for semver)
- if latest and latest != current:
- # Compare version tuples
- try:
- current_parts = [int(x) for x in current.split(".")[:3] if x.isdigit()]
- latest_parts = [int(x) for x in latest.split(".")[:3] if x.isdigit()]
- result["has_update"] = latest_parts > current_parts
- except (ValueError, AttributeError):
- # If version format is unusual, just check if different
- result["has_update"] = latest != current
- except Exception as e:
- result["error"] = str(e)
-
- return result
+ return get_latest_version_info(__version__)
def cmd_check_update():
@@ -672,24 +648,11 @@ def cmd_upgrade():
print("\nUpgrading...")
- # Determine upgrade method based on how vibe was installed
- # Check if running from uv tool environment
- exe_path = sys.executable
- is_uv_tool = ".local/share/uv/tools/" in exe_path or "/uv/tools/" in exe_path
-
- uv_path = shutil.which("uv")
-
- if is_uv_tool and uv_path:
- # Installed via uv tool, upgrade with uv
- cmd = [uv_path, "tool", "install", "vibe-remote", "--upgrade"]
- print(f"Using uv: {' '.join(cmd)}")
- else:
- # Installed via pip or other method, use current Python's pip
- cmd = [sys.executable, "-m", "pip", "install", "--upgrade", "vibe-remote"]
- print(f"Using pip: {' '.join(cmd)}")
+ plan = build_upgrade_plan()
+ print(f"Using {plan.method}: {' '.join(plan.command)}")
try:
- result = subprocess.run(cmd, capture_output=True, text=True)
+ result = subprocess.run(plan.command, capture_output=True, text=True, env=plan.env)
if result.returncode == 0:
print("\033[32mUpgrade successful!\033[0m")
print("Please restart vibe to use the new version:")
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
new file mode 100644
index 000000000..cf439ea67
--- /dev/null
+++ b/vibe/upgrade.py
@@ -0,0 +1,94 @@
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import sys
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+
+
+PACKAGE_NAME = "vibe-remote"
+DEFAULT_UPDATE_METADATA_URL = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
+
+
+@dataclass(frozen=True)
+class UpgradePlan:
+ command: list[str]
+ env: dict[str, str] | None
+ method: str
+
+
+def get_update_metadata_url() -> str:
+ return os.environ.get("VIBE_UPDATE_METADATA_URL", DEFAULT_UPDATE_METADATA_URL)
+
+
+def get_upgrade_package_spec() -> str:
+ return os.environ.get("VIBE_UPGRADE_PACKAGE_SPEC", PACKAGE_NAME)
+
+
+def get_latest_version_info(current_version: str) -> dict:
+ result = {"current": current_version, "latest": None, "has_update": False, "error": None}
+
+ try:
+ url = get_update_metadata_url()
+ req = urllib.request.Request(url, headers={"User-Agent": PACKAGE_NAME})
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ data = json.loads(resp.read().decode("utf-8"))
+
+ latest = data.get("info", {}).get("version", "")
+ result["latest"] = latest
+
+ if latest and latest != current_version:
+ try:
+ current_parts = [int(x) for x in current_version.split(".")[:3] if x.isdigit()]
+ latest_parts = [int(x) for x in latest.split(".")[:3] if x.isdigit()]
+ result["has_update"] = latest_parts > current_parts
+ except (ValueError, AttributeError):
+ result["has_update"] = latest != current_version
+ except Exception as e:
+ result["error"] = str(e)
+
+ return result
+
+
+def is_uv_tool_install(python_executable: str | None = None) -> bool:
+ executable = (python_executable or sys.executable or "").replace("\\", "/")
+ return "/uv/tools/" in executable
+
+
+def get_current_vibe_bin_dir(vibe_path: str | None = None) -> str | None:
+ current_vibe = vibe_path if vibe_path is not None else shutil.which("vibe")
+ if not current_vibe:
+ return None
+ return str(Path(current_vibe).expanduser().parent)
+
+
+def build_upgrade_plan(
+ *,
+ python_executable: str | None = None,
+ uv_path: str | None = None,
+ vibe_path: str | None = None,
+ base_env: dict[str, str] | None = None,
+) -> UpgradePlan:
+ executable = python_executable or sys.executable
+ uv_binary = uv_path if uv_path is not None else shutil.which("uv")
+ package_spec = get_upgrade_package_spec()
+
+ if is_uv_tool_install(executable) and uv_binary:
+ env = dict(base_env or os.environ)
+ vibe_bin_dir = get_current_vibe_bin_dir(vibe_path)
+ if vibe_bin_dir:
+ env["UV_TOOL_BIN_DIR"] = vibe_bin_dir
+ return UpgradePlan(
+ command=[uv_binary, "tool", "install", package_spec, "--upgrade"],
+ env=env,
+ method="uv",
+ )
+
+ return UpgradePlan(
+ command=[executable, "-m", "pip", "install", "--upgrade", package_spec],
+ env=dict(base_env or os.environ),
+ method="pip",
+ )