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(backend): skip no-op agent refresh (#2095)

Call Whitebc636b656fac
diff --git a/docs/plans/backend-rolling-restart.md b/docs/plans/backend-rolling-restart.md
index f921ca3d0..fb2f0eaf6 100644
--- a/docs/plans/backend-rolling-restart.md
+++ b/docs/plans/backend-rolling-restart.md
@@ -38,6 +38,17 @@ Codex and Claude may later prepare a new generation during DRAINING, but only if
their adapters can prove isolated ownership. That optimization does not change
the Session protocol.
+Agent CLI install/upgrade jobs measure the CLI selected by the persisted
+`agents.<backend>.cli_path` before and after installation. Only an unchanged
+configured path, resolved target, and known reported version can skip the
+refresh. A changed configured path requires reconciliation even when it resolves
+to the same executable. Missing configuration, paths, or versions conservatively
+retain the existing refresh path. Measurements bypass the UI version cache.
+
+The install worker produces this decision and the existing controller restart
+coordinator remains the sole owner of any required cutover. This optimization
+does not relax the barrier for real upgrades or change manual/auth refreshes.
+
## Timeout
Draining is bounded. At the deadline, the coordinator:
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index 7410ec359..c86ff7b75 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -150,8 +150,11 @@ def test_install_job_applies_persisted_path_before_admitting_connection(monkeypa
config.model_hub.agents[name].mode = "direct"
getattr(config.agents, backend).cli_path = "/old/missing-cli"
config.save()
+ # Resolve lazy config imports before substituting the process constructor.
+ assert not V2Config.load().load_warnings
installed_path = str(tmp_path / "安装 后端/bin" / backend)
monkeypatch.setattr(api, "resolve_cli_path", lambda _: installed_path)
+ monkeypatch.setattr(api, "_probe_cli_version", lambda _: "1.0.0")
monkeypatch.setattr(api.subprocess, "Popen", lambda *a, **kw: SimpleNamespace(
communicate=lambda **_: ("fixture installed", ""), returncode=0,
))
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index 3c9644623..06cb8e822 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -2,6 +2,9 @@ from __future__ import annotations
import threading
import time
+from unittest.mock import Mock
+
+import pytest
from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, UiConfig, V2Config
from vibe import api
@@ -225,6 +228,7 @@ def test_dependency_install_route_preserves_structured_memory_package_rejection(
def test_install_job_fails_when_runtime_refresh_fails(monkeypatch):
monkeypatch.setattr(api, "is_agent_backend", lambda name: name == "codex")
monkeypatch.setattr(api, "supports_runtime_refresh", lambda name: name == "codex")
+ monkeypatch.setattr(api, "_agent_runtime_fingerprint", lambda name: None)
monkeypatch.setattr(
api,
"install_agent",
@@ -250,6 +254,145 @@ def test_install_job_fails_when_runtime_refresh_fails(monkeypatch):
assert result["restart"] == {"ok": False, "message": "refresh timeout"}
+def test_agent_runtime_fingerprint_fails_closed_when_config_probe_fails(monkeypatch):
+ monkeypatch.setattr(api.V2Config, "load", Mock(side_effect=RuntimeError("fixture config failure")))
+
+ assert api._agent_runtime_fingerprint("claude") is None
+
+
+def _wait_for_install_job(job_id):
+ deadline = time.monotonic() + 3.0
+ while time.monotonic() < deadline:
+ result = api.get_agent_install_job(job_id)
+ if result["status"] != "running":
+ return result
+ time.sleep(0.001)
+ pytest.fail("install worker did not finish")
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+ "change",
+ [
+ "unchanged",
+ "version",
+ "custom-cli",
+ "same-target-alias",
+ "symlink-target",
+ "unknown-before",
+ "unknown-after",
+ "fresh-install",
+ ],
+)
+def test_install_job_measures_configured_runtime(monkeypatch, tmp_path, backend, change):
+ """BRR-009: actual install bookkeeping feeds the refresh decision."""
+ standard = tmp_path / "标准 CLI" / backend
+ custom = tmp_path / "自定义 CLI" / backend
+ replacement = tmp_path / "新 CLI" / backend
+ for binary in (standard, custom, replacement):
+ binary.parent.mkdir()
+ binary.touch()
+ if change == "same-target-alias":
+ custom.unlink()
+ custom.symlink_to(standard)
+ configured = custom if change in {"custom-cli", "same-target-alias"} else standard
+ config = V2Config.default()
+ getattr(config.agents, backend).cli_path = str(configured)
+ config.save()
+ # Load config before replacing subprocess constructors used by lazy imports.
+ assert not V2Config.load().load_warnings
+ installed = False
+ resolved = []
+ probed = []
+
+ def resolve(binary):
+ resolved.append(binary)
+ if change == "fresh-install" and not installed:
+ return None
+ return str(standard) if binary == backend else binary
+
+ def probe(binary):
+ probed.append(binary)
+ if change == ("unknown-after" if installed else "unknown-before"):
+ return None
+ return "1.0.1" if installed and change == "version" else "1.0.0"
+
+ class InstallProcess:
+ returncode = 0
+
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def communicate(self, **kwargs):
+ nonlocal installed
+ installed = True
+ if change == "symlink-target":
+ standard.unlink()
+ standard.symlink_to(replacement)
+ return "fixture installed", ""
+
+ monkeypatch.setattr(api, "resolve_cli_path", resolve)
+ monkeypatch.setattr(api, "_probe_cli_version", probe)
+ monkeypatch.setattr(api, "_cached_version", Mock(side_effect=AssertionError("must measure, not use cached versions")))
+ monkeypatch.setattr(api.subprocess, "Popen", InstallProcess)
+ monkeypatch.setattr(
+ api, "install_agent",
+ lambda name: api._run_install_command(name, ["fixture-installer"], lambda value: value),
+ )
+ refresh = Mock(return_value={"ok": True})
+ monkeypatch.setattr(api, "restart_backend", refresh)
+ monkeypatch.setattr(api, "_AGENT_INSTALL_JOBS", {})
+ monkeypatch.setattr(api, "_AGENT_INSTALL_LATEST_BY_BACKEND", {})
+
+ started = api.start_agent_install_job(backend)
+ result = _wait_for_install_job(started["job_id"])
+ assert result["status"] == "succeeded"
+ assert result["ok"] is True
+ assert getattr(V2Config.load().agents, backend).cli_path == str(standard)
+ assert resolved == [str(configured), backend, str(standard)]
+ assert probed == ([str(standard)] if change == "fresh-install" else [str(configured), str(standard)])
+ if change == "unchanged":
+ refresh.assert_not_called()
+ assert result["restart"] == {"ok": True, "skipped": True}
+ else:
+ refresh.assert_called_once_with(
+ backend, metadata={"reason": "agent_install_job", "source": "ui_api"},
+ )
+ assert result["restart"] == {"ok": True}
+
+
+def test_install_job_does_not_refresh_when_install_fails(monkeypatch):
+ monkeypatch.setattr(api, "is_agent_backend", lambda name: name == "claude")
+ monkeypatch.setattr(api, "supports_runtime_refresh", lambda name: name == "claude")
+ monkeypatch.setattr(
+ api,
+ "_agent_runtime_fingerprint",
+ lambda name: ("/fixture/claude", "/fixture/claude", "1.0.0"),
+ )
+ monkeypatch.setattr(
+ api,
+ "install_agent",
+ lambda name: {"ok": False, "message": "Upgrade failed", "output": "error", "path": None},
+ )
+ monkeypatch.setattr(api, "restart_backend", lambda *args, **kwargs: pytest.fail("refresh should not run"))
+ with api._AGENT_INSTALL_JOB_LOCK:
+ api._AGENT_INSTALL_JOBS.clear()
+ api._AGENT_INSTALL_LATEST_BY_BACKEND.clear()
+
+ started = api.start_agent_install_job("claude")
+ deadline = time.time() + 2.0
+ result = {}
+ while time.time() < deadline:
+ result = api.get_agent_install_job(started["job_id"], backend="claude")
+ if result.get("status") != "running":
+ break
+ time.sleep(0.01)
+
+ assert result["status"] == "failed"
+ assert result["ok"] is False
+ assert "restart" not in result
+
+
def test_vibe_agent_routes_return_structured_client_errors(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path / ".vibe_remote"))
client = app.test_client()
@@ -325,6 +468,7 @@ def test_install_job_dedupes_running_backend(monkeypatch):
second = api.start_agent_install_job("codex")
release.set()
+ _wait_for_install_job(first["job_id"])
assert second["job_id"] == first["job_id"]
assert second["status"] == "running"
diff --git a/vibe/api.py b/vibe/api.py
index ff1f0b361..c55fa0ce1 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -7197,6 +7197,30 @@ def _agent_install_job_succeeded(result: dict, name: str) -> bool:
return isinstance(restart, dict) and bool(restart.get("ok"))
+def _agent_runtime_fingerprint(name: str) -> tuple[str, str, str] | None:
+ """Measure the configured CLI, not another installation found by name.
+
+ Include the persisted launch path as well as its resolved target: changing
+ an alias still requires the controller to load the new configuration.
+ Unknown configuration, paths, or versions cannot prove a no-op.
+ """
+ try:
+ config = V2Config.load()
+ if config.load_warnings:
+ return None
+ configured_path = getattr(config.agents, name).cli_path or name
+ resolved_path = resolve_cli_path(configured_path)
+ if not resolved_path:
+ return None
+ version = _probe_cli_version(resolved_path)
+ if not version:
+ return None
+ return configured_path, os.path.realpath(resolved_path), version
+ except Exception as exc: # noqa: BLE001
+ logger.debug("Agent runtime fingerprint probe failed for %s: %s", name, exc)
+ return None
+
+
def start_agent_install_job(name: str) -> dict:
"""Start backend CLI install/upgrade in a background job.
@@ -7233,13 +7257,26 @@ def start_agent_install_job(name: str) -> dict:
def _worker() -> None:
try:
+ refresh_supported = supports_runtime_refresh(name)
+ runtime_before = _agent_runtime_fingerprint(name) if refresh_supported else None
result = install_agent(name)
- if result.get("ok") and supports_runtime_refresh(name):
+ if result.get("ok") and refresh_supported:
try:
- result["restart"] = restart_backend(
- name,
- metadata={"reason": "agent_install_job", "source": "ui_api"},
- )
+ runtime_after = _agent_runtime_fingerprint(name)
+ if runtime_before is None or runtime_before != runtime_after:
+ result["restart"] = restart_backend(
+ name,
+ metadata={"reason": "agent_install_job", "source": "ui_api"},
+ )
+ else:
+ logger.info(
+ "Skipping %s backend refresh after install: effective CLI runtime unchanged",
+ name,
+ )
+ result["restart"] = {
+ "ok": True,
+ "skipped": True,
+ }
except Exception as exc: # noqa: BLE001
logger.warning(
"Backend refresh after %s install job failed: %s",