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.

feat(backends): auto-update idle backend CLIs (#2292)

Call White3d53e67d7495
diff --git a/config/v2_config.py b/config/v2_config.py
index 202bea067..88bf6457c 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -938,6 +938,10 @@ _RUNTIME_RETENTION_FIELDS = frozenset(
}
)
+# A backend's unattended-upgrade switch recovers alone and off, keeping the
+# backend's CLI path, credentials, and enablement.
+_BACKEND_AUTO_UPDATE_FIELD = "auto_update"
+
# The switch that decides whether an optional feature runs at all. Named once
# because recovery has to tell it apart from every other switch in a section:
# the rest describe how a feature behaves, this one decides whether it happens.
@@ -1009,6 +1013,10 @@ def _recovery_field_for_error(section: Optional[str], error: BaseException) -> O
return None
field_name = path[len(prefix) :].split(".", 1)[0]
return field_name if field_name in _RUNTIME_RETENTION_FIELDS or field_name == "skill_observability_enabled" else None
+ if section is not None and section.startswith("agents."):
+ match = re.search(r"Config '([^']+)'", str(error))
+ auto_update = f"{section}.{_BACKEND_AUTO_UPDATE_FIELD}"
+ return _BACKEND_AUTO_UPDATE_FIELD if match and match.group(1) == auto_update else None
if section not in _FIELD_SCOPED_RECOVERY_SECTIONS:
return None
match = re.search(r"Config '([^']+)'", str(error))
@@ -1175,6 +1183,9 @@ def _reset_recoverable_config_section(
agents_payload = payload.get("agents")
if not isinstance(agents_payload, dict):
return False
+ if field_name == _BACKEND_AUTO_UPDATE_FIELD and isinstance(agents_payload.get(agent_name), dict):
+ agents_payload[agent_name][field_name] = False
+ return True
if agent_name == "codex":
# Codex is opt-in in the canonical first-run/recovery config.
agents_payload[agent_name] = dict(V2Config.default().agents.codex.__dict__)
@@ -1908,6 +1919,10 @@ class RuntimeConfig:
class OpenCodeConfig:
enabled: bool = True
cli_path: str = "opencode"
+ # Install a newer release of this backend CLI once no turn is using it.
+ # Runs on the Avibe update checker, so ``update.check_interval_minutes = 0``
+ # also stops it.
+ auto_update: bool = True
default_agent: Optional[str] = None
default_reasoning_effort: Optional[str] = None
error_retry_limit: int = DEFAULT_OPENCODE_ERROR_RETRY_LIMIT # Max retries on LLM stream errors (0 = no retry)
@@ -1930,6 +1945,7 @@ class OpenCodeConfig:
class ClaudeConfig:
enabled: bool = True
cli_path: str = "claude"
+ auto_update: bool = True # See ``OpenCodeConfig.auto_update``.
idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
# Auth model: "oauth" relies on Claude Code's own credential storage;
# "api_key" injects ANTHROPIC_API_KEY (and optionally ANTHROPIC_BASE_URL)
@@ -1954,6 +1970,7 @@ class ClaudeConfig:
class CodexConfig:
enabled: bool = True
cli_path: str = "codex"
+ auto_update: bool = True # See ``OpenCodeConfig.auto_update``.
idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
# Auth model: "oauth" defers to whatever ~/.codex/config.toml already
# has (typically `auth.method = "ChatGPT"`); "api_key" writes the
@@ -3573,7 +3590,7 @@ class V2Config:
# Diff each reset on its own: ``from_payload`` normalizes a few
# stored values in place, and those are not recovery's rewrites.
for path in {
- tuple(recovered.split(".", 1)),
+ tuple(recovered.split(".")[:_RECOVERY_REGION_DEPTH]),
*_changed_config_paths(before_reset, candidate),
}:
rewritten.setdefault(path, set()).add(recovered)
@@ -3716,6 +3733,11 @@ class V2Config:
opencode = OpenCodeConfig(**_filter_dataclass_fields(OpenCodeConfig, opencode_payload))
claude = ClaudeConfig(**_filter_dataclass_fields(ClaudeConfig, claude_payload))
codex = CodexConfig(**_filter_dataclass_fields(CodexConfig, codex_payload))
+ for backend_name, backend_config in (("opencode", opencode), ("claude", claude), ("codex", codex)):
+ # Unattended upgrades run on this switch, so ``"false"`` must read as off.
+ backend_config.auto_update = _named_bool(
+ f"agents.{backend_name}.auto_update", backend_config.auto_update
+ )
avault = AVaultConfig(**_filter_dataclass_fields(AVaultConfig, avault_payload))
agents = AgentsConfig(
diff --git a/core/backend_restart.py b/core/backend_restart.py
index 30ff62d98..1eccd5653 100644
--- a/core/backend_restart.py
+++ b/core/backend_restart.py
@@ -12,13 +12,14 @@ import stat
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
from contextlib import AsyncExitStack, asynccontextmanager
from pathlib import Path
-from typing import Any
+from typing import Any, TypeVar
logger = logging.getLogger(__name__)
DEFAULT_DRAIN_TIMEOUT_SECONDS = 300.0
_POLL_INTERVAL_SECONDS = 0.1
_NATIVE_BACKENDS = frozenset({"claude", "codex", "opencode"})
+_T = TypeVar("_T")
class NativeMigrationBlockedError(RuntimeError):
@@ -391,7 +392,7 @@ class BackendRestartCoordinator:
self._refresh = refresh
self._drain_timeout = _configured_drain_timeout() if drain_timeout is None else max(0.0, drain_timeout)
self._poll_interval = max(0.001, poll_interval)
- self._tasks: dict[str, asyncio.Task[None]] = {}
+ self._tasks: dict[str, asyncio.Task[Any]] = {}
self._request_locks: dict[str, asyncio.Lock] = {}
self._outcomes: dict[str, dict[str, str]] = {}
self._migration_backends: set[str] = set()
@@ -611,7 +612,83 @@ class BackendRestartCoordinator:
return "restarted"
return "draining"
- def _on_done(self, backend: str, task: asyncio.Task[None]) -> None:
+ async def run_when_idle(self, backend: str, operation: Callable[[], Awaitable[_T]]) -> _T | None:
+ """Run ``operation`` while ``backend`` admits no turn, then refresh it.
+
+ Unattended maintenance can simply try again later, so unlike a restart
+ this never waits out or cancels work: it returns ``None`` without running
+ ``operation`` when a turn, cutover, migration, or native login already
+ holds the backend. Messages that arrive meanwhile are deferred to the
+ refreshed runtime, which also applies a restart requested during it.
+ """
+ lock = self._request_locks.setdefault(backend, asyncio.Lock())
+ async with lock:
+ if backend in self._migration_backends or backend in self._blocked_backends():
+ return None
+ existing = self._tasks.get(backend)
+ if existing is not None:
+ if not existing.done():
+ return None
+ self._on_done(backend, existing)
+ try:
+ self._assert_no_native_login((backend,))
+ # A login in either process holds this lease for its whole flow,
+ # so owning it until the refresh keeps one off a replaced CLI.
+ lease = NativeCredentialLease((backend,), state_dir=self._native_state_dir()).acquire()
+ except NativeMigrationBlockedError:
+ return None
+
+ task: asyncio.Task[_T] | None = None
+ try:
+ agent_service = self.controller.agent_service
+ session_turns = self.controller.session_turns
+ agent_service.begin_backend_drain(backend)
+ session_turns.begin_backend_drain(backend)
+ busy = True
+ try:
+ await agent_service.prepare_backend_restart(backend)
+ busy = await self._has_active_turns(backend)
+ finally:
+ # Nothing changed, so deferred messages resume on the same runtime.
+ if busy and backend not in self._blocked_backends():
+ agent_service.end_backend_drain(backend)
+ await session_turns.end_backend_drain(backend)
+ if not busy:
+ task = asyncio.create_task(
+ self._maintain(backend, operation, lease), name=f"backend-maintenance:{backend}"
+ )
+ self._tasks[backend] = task
+ task.add_done_callback(lambda completed, name=backend: self._on_done(name, completed))
+ finally:
+ if task is None:
+ lease.release()
+ if task is None:
+ return None
+
+ # A cancelled requester, such as the update checker at shutdown, still
+ # waits for the install and the refresh that picks it up.
+ return await finish_native_operation(task)
+
+ async def _maintain(
+ self, backend: str, operation: Callable[[], Awaitable[_T]], lease: NativeCredentialLease
+ ) -> _T:
+ refreshed = False
+ try:
+ try:
+ return await operation()
+ finally:
+ # Even a failed operation may have replaced the CLI.
+ await self._refresh(backend, False)
+ refreshed = True
+ finally:
+ try:
+ if backend not in self._blocked_backends():
+ self.controller.agent_service.end_backend_drain(backend)
+ await self.controller.session_turns.end_backend_drain(backend, resume_deferred=refreshed)
+ finally:
+ lease.release()
+
+ def _on_done(self, backend: str, task: asyncio.Task[Any]) -> None:
current = self._tasks.get(backend) is task
if current:
self._tasks.pop(backend, None)
diff --git a/core/update_checker.py b/core/update_checker.py
index de872ac2b..6ae3691e7 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -16,7 +16,7 @@ import re
import time
import urllib.parse
import urllib.request
-from dataclasses import dataclass, fields
+from dataclasses import dataclass, field, fields
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Optional
@@ -156,6 +156,9 @@ class UpdateState:
blocked_auto_update_reason: Optional[str] = None
blocked_auto_update_at: Optional[str] = None
blocked_auto_update_current_version: Optional[str] = None
+ # Backend name -> the release its unattended upgrade last ran for, so a
+ # release that fails to install is not retried on every check.
+ backend_auto_update_attempts: Dict[str, str] = field(default_factory=dict)
@classmethod
def load(cls) -> "UpdateState":
@@ -164,6 +167,7 @@ class UpdateState:
return cls()
try:
data = json.loads(path.read_text(encoding="utf-8"))
+ attempts = data.get("backend_auto_update_attempts")
return cls(
notified_version=data.get("notified_version"),
notified_at=data.get("notified_at"),
@@ -173,6 +177,11 @@ class UpdateState:
blocked_auto_update_reason=data.get("blocked_auto_update_reason"),
blocked_auto_update_at=data.get("blocked_auto_update_at"),
blocked_auto_update_current_version=data.get("blocked_auto_update_current_version"),
+ backend_auto_update_attempts=(
+ {str(name): str(version) for name, version in attempts.items()}
+ if isinstance(attempts, dict)
+ else {}
+ ),
)
except Exception as e:
logger.warning(f"Failed to load update state: {e}")
@@ -191,6 +200,7 @@ class UpdateState:
"blocked_auto_update_reason": self.blocked_auto_update_reason,
"blocked_auto_update_at": self.blocked_auto_update_at,
"blocked_auto_update_current_version": self.blocked_auto_update_current_version,
+ "backend_auto_update_attempts": self.backend_auto_update_attempts,
}
write_atomic(path, json.dumps(data, indent=2))
except Exception as e:
@@ -385,6 +395,8 @@ class UpdateChecker:
if self.config.check_interval_minutes <= 0:
return
+ await self._reconcile_backend_auto_updates()
+
# Fetch version info in a thread to avoid blocking the event loop
version_info = await asyncio.to_thread(_fetch_pypi_version_sync)
@@ -507,6 +519,62 @@ class UpdateChecker:
except Exception as exc: # noqa: BLE001
logger.warning("askill managed dependency reconcile raised: %s", exc, exc_info=True)
+ async def _reconcile_backend_auto_updates(self) -> None:
+ """Upgrade opted-in backend CLIs, each only while no turn is using it."""
+ coordinator = getattr(self.controller, "backend_restart_coordinator", None)
+ if coordinator is None:
+ return
+
+ from modules.agents.catalog import AGENT_BACKENDS, supports_install
+ from vibe import api
+
+ for backend in AGENT_BACKENDS:
+ if not supports_install(backend):
+ continue
+ try:
+ runtime = await asyncio.to_thread(api.get_backend_runtime, backend)
+ latest = runtime.get("latest_version")
+ if not (
+ runtime.get("ok")
+ and runtime.get("enabled")
+ and runtime.get("auto_update")
+ and runtime.get("installed")
+ and runtime.get("has_update")
+ and latest
+ ) or self.state.backend_auto_update_attempts.get(backend) == latest:
+ continue
+ # Checked per backend: a message may arrive during an earlier install.
+ if not self._quiet_for_idle_window():
+ return
+
+ async def install(name: str = backend, release: str = latest) -> dict:
+ try:
+ result = await asyncio.to_thread(api.install_agent, name)
+ except Exception as exc: # noqa: BLE001
+ result = {"ok": False, "message": str(exc) or type(exc).__name__}
+ # A failed release is not retried unattended. It is recorded
+ # before the refresh, whose own failure must not undo that.
+ # A success needs no record: the next check sees whether it
+ # actually reached the release, and tries again if not.
+ if not result.get("ok") and result.get("code") != "install_locked":
+ self.state.backend_auto_update_attempts[name] = release
+ self.state.save()
+ return result
+
+ result = await coordinator.run_when_idle(backend, install)
+ if result is None:
+ logger.info("Backend %s auto-update to %s deferred: backend is busy", backend, latest)
+ elif result.get("code") == "install_locked":
+ logger.info("Backend %s auto-update to %s deferred: another install is running", backend, latest)
+ elif not result.get("ok"):
+ logger.warning("Backend %s auto-update to %s failed: %s", backend, latest, result.get("message"))
+ elif (await asyncio.to_thread(api.get_backend_runtime, backend)).get("has_update"):
+ logger.info("Backend %s installer left it behind %s; retrying on a later check", backend, latest)
+ else:
+ logger.info("Backend %s auto-updated to %s", backend, latest)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Backend %s auto-update failed: %s", backend, exc, exc_info=True)
+
async def _get_version_info_async(self) -> Dict[str, Any]:
"""Get version info asynchronously."""
return await asyncio.to_thread(_fetch_pypi_version_sync)
@@ -538,7 +606,10 @@ class UpdateChecker:
logger.debug("Not idle: has active sessions")
return False
- # Check for recent activity
+ return self._quiet_for_idle_window()
+
+ def _quiet_for_idle_window(self) -> bool:
+ """Check that no message has arrived within ``idle_minutes``."""
# If no activity recorded yet, consider it NOT idle (just started)
if not self.state.last_activity_at:
logger.debug("Not idle: no activity recorded yet (service just started)")
diff --git a/skills/use-avibe/references/global-config.md b/skills/use-avibe/references/global-config.md
index 821c640cb..fd663967b 100644
--- a/skills/use-avibe/references/global-config.md
+++ b/skills/use-avibe/references/global-config.md
@@ -77,6 +77,7 @@ Important config payload shape:
"opencode": {
"enabled": true,
"cli_path": "opencode",
+ "auto_update": true,
"default_agent": null,
"default_reasoning_effort": null,
"error_retry_limit": 1
@@ -84,11 +85,13 @@ Important config payload shape:
"claude": {
"enabled": true,
"cli_path": "claude",
+ "auto_update": true,
"idle_timeout_seconds": 600
},
"codex": {
"enabled": true,
"cli_path": "codex",
+ "auto_update": true,
"idle_timeout_seconds": 600
}
},
@@ -164,6 +167,7 @@ Per-platform fields worth knowing about:
- `telegram.allowed_chat_ids` / `allowed_user_ids` restrict which chats and users Telegram will respond to.
- `wechat.cdn_base_url` controls the CDN host used for fetching WeChat media; the default `novac2c.cdn.weixin.qq.com` is the official c2c CDN.
- `update.auto_update`, `check_interval_minutes`, and `idle_minutes` control unattended upgrades; `notify_admins` posts the upgrade announcement to bound admins.
+- `agents.<backend>.auto_update` (default `true`) installs a newer backend CLI release on the same check once `idle_minutes` have passed without a message and no turn is using that backend; messages that arrive during the install run afterwards. Each release is tried once unattended, and `check_interval_minutes = 0` stops it as well.
- `ui.setup_host`, `setup_port`, and `open_browser` configure the local Web UI server; changing host or port requires `POST /ui/reload`.
Secret-bearing config fields that you should not print:
diff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.py
index a87d82c6e..c38f40dd4 100644
--- a/tests/test_backend_restart.py
+++ b/tests/test_backend_restart.py
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, Mock
import pytest
-from core.backend_restart import BackendRestartCoordinator
+from core.backend_restart import BackendRestartCoordinator, NativeCredentialLease, NativeMigrationBlockedError
from core.controller import Controller
@@ -271,3 +271,146 @@ def test_cancelled_application_remains_failed_after_task_is_removed():
assert not service.draining
asyncio.run(run())
+
+
+def test_idle_maintenance_runs_behind_closed_admission_then_refreshes():
+ async def run():
+ service = _AgentService()
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+
+ async def install():
+ # Nothing may start a turn on the CLI while it is being replaced.
+ assert service.draining is True
+ controller.session_turns.begin_backend_drain.assert_called_once_with("opencode")
+ refresh.assert_not_awaited()
+ return {"ok": True}
+
+ assert await coordinator.run_when_idle("opencode", install) == {"ok": True}
+
+ refresh.assert_awaited_once_with("opencode", False)
+ controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode", resume_deferred=True)
+ assert service.draining is False
+
+ asyncio.run(run())
+
+
[email protected]("holder", ["active_turn", "restart_draining"])
+def test_maintenance_yields_to_a_busy_backend_without_touching_its_work(holder):
+ async def run():
+ service = _AgentService()
+ service.active = True
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, drain_timeout=1, poll_interval=0.001)
+ if holder == "restart_draining":
+ assert await coordinator.request_restart("opencode") == "draining"
+ controller.session_turns.end_backend_drain.reset_mock()
+ operation = AsyncMock()
+
+ assert await coordinator.run_when_idle("opencode", operation) is None
+
+ operation.assert_not_awaited()
+ refresh.assert_not_awaited()
+ controller.session_turns.release_for_backend_refresh.assert_not_awaited()
+ if holder == "active_turn":
+ # The turn keeps running; messages held meanwhile resume unchanged.
+ controller.session_turns.end_backend_drain.assert_awaited_once_with("opencode")
+ assert service.draining is False
+ else:
+ controller.session_turns.end_backend_drain.assert_not_awaited()
+ assert service.draining is True
+ service.active = False
+ await coordinator.wait("opencode")
+ refresh.assert_awaited_once_with("opencode", False)
+
+ asyncio.run(run())
+
+
+def test_maintenance_and_a_native_login_exclude_each_other():
+ async def run():
+ service = _AgentService()
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ operation = AsyncMock()
+
+ # A login in the Web process holds the backend's lease for its whole flow.
+ login = NativeCredentialLease(("opencode",)).acquire()
+ try:
+ assert await coordinator.run_when_idle("opencode", operation) is None
+ finally:
+ login.release()
+ operation.assert_not_awaited()
+ controller.session_turns.begin_backend_drain.assert_not_called()
+
+ async def install():
+ with pytest.raises(NativeMigrationBlockedError) as blocked:
+ NativeCredentialLease(("opencode",)).acquire()
+ assert blocked.value.reason == "native_auth_in_progress"
+ return {"ok": True}
+
+ assert await coordinator.run_when_idle("opencode", install) == {"ok": True}
+ NativeCredentialLease(("opencode",)).acquire().release()
+
+ asyncio.run(run())
+
+
+def test_cancelled_requester_waits_for_maintenance_and_its_refresh():
+ async def run():
+ service = _AgentService()
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ installing = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def install():
+ installing.set()
+ await finish.wait()
+ return {"ok": True}
+
+ requester = asyncio.create_task(coordinator.run_when_idle("opencode", install))
+ await installing.wait()
+ requester.cancel()
+ await asyncio.sleep(0.01)
+ # Shutdown cancels the update checker; the CLI swap must not be abandoned.
+ assert not requester.done()
+
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await requester
+ refresh.assert_awaited_once_with("opencode", False)
+ assert service.draining is False
+
+ asyncio.run(run())
+
+
+def test_restart_requested_during_maintenance_is_applied_by_its_refresh():
+ async def run():
+ service = _AgentService()
+ service.agents = {"opencode": object()}
+ controller = _controller(service)
+ refresh = AsyncMock()
+ coordinator = BackendRestartCoordinator(controller, refresh, poll_interval=0.001)
+ installing = asyncio.Event()
+ finish = asyncio.Event()
+
+ async def install():
+ installing.set()
+ await finish.wait()
+ return {"ok": True}
+
+ maintenance = asyncio.create_task(coordinator.run_when_idle("opencode", install))
+ await installing.wait()
+ assert coordinator.snapshot("opencode") == {"state": "draining"}
+ assert await coordinator.request_restart("opencode") == "draining"
+ controller.session_turns.begin_backend_drain.assert_called_once_with("opencode")
+
+ finish.set()
+ assert await maintenance == {"ok": True}
+ refresh.assert_awaited_once_with("opencode", False)
+ assert coordinator.snapshot("opencode") == {"state": "applied"}
+
+ asyncio.run(run())
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index 9beeb0f09..d8af7e3b8 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -2633,6 +2633,36 @@ def test_config_reload_recovers_invalid_codex_agent_with_disabled_default(monkey
assert config_path.read_text(encoding="utf-8") == original
+ ("stored", "recovered"),
+ [
+ pytest.param("false", (), id="spelled-off"),
+ pytest.param("garbage", ("agents.codex.auto_update",), id="unreadable"),
+ ],
+)
+def test_config_reload_reads_backend_auto_update_off_without_losing_the_backend(
+ monkeypatch, tmp_path, stored, recovered
+):
+ """Unattended backend upgrades run only on a stored value that reads as on."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["agents"]["codex"].update({"enabled": True, "cli_path": "/preserved/codex", "auto_update": stored})
+ config_path = tmp_path / "config.json"
+ original = json.dumps(payload)
+ config_path.write_text(original, encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.agents.codex.auto_update is False
+ assert loaded.agents.codex.enabled is True
+ assert loaded.agents.codex.cli_path == "/preserved/codex"
+ assert loaded.agents.claude.auto_update is True
+ assert loaded.recovered_sections == recovered
+ assert loaded.whole_config_recovery is False
+ assert config_path.read_text(encoding="utf-8") == original
+
+
def test_config_load_degrades_codex_relay_marker_shapes(monkeypatch, tmp_path):
"""Persisted-shape rule for the new ``oauth_relay_marker`` field:
a config written before the field existed loads with ``None``
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index f1d3d8292..483792b76 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1,7 +1,9 @@
import asyncio
import json
import subprocess
+import threading
import time
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
@@ -2555,6 +2557,44 @@ def test_install_agent_returns_resolved_path(monkeypatch):
assert result["path"] == "/Users/test/.opencode/bin/opencode"
+def test_install_agent_refuses_a_second_concurrent_install_of_one_backend(monkeypatch):
+ # Settings installs in the UI process and auto-update in the controller;
+ # both reach the CLI only through ``install_agent``.
+ started = threading.Event()
+ release = threading.Event()
+ commands: list[list[str]] = []
+
+ def fake_run(command, **_kwargs):
+ commands.append(command)
+ started.set()
+ assert release.wait(5)
+ return subprocess.CompletedProcess(command, 0, "installed", "")
+
+ monkeypatch.setattr(
+ api.shutil,
+ "which",
+ lambda binary: f"/usr/bin/{binary}" if binary in {"curl", "bash"} else None,
+ )
+ monkeypatch.setattr(api.subprocess, "run", fake_run)
+ monkeypatch.setattr(api.subprocess, "Popen", _PopenFromRun)
+ monkeypatch.setattr(api, "resolve_cli_path", lambda binary: "/Users/test/.opencode/bin/opencode")
+
+ with ThreadPoolExecutor(max_workers=1) as pool:
+ first = pool.submit(api.install_agent, "opencode")
+ assert started.wait(5)
+ ran_before = len(commands)
+ second = api.install_agent("opencode")
+ ran_after = len(commands)
+ release.set()
+ assert first.result(timeout=5)["ok"] is True
+
+ assert second["ok"] is False
+ assert second["code"] == "install_locked"
+ assert ran_after == ran_before
+ # The finished install leaves the backend installable again.
+ assert api.install_agent("opencode")["ok"] is True
+
+
def test_install_codex_fresh_install_uses_resolved_npm(monkeypatch, tmp_path):
# Fresh-install path: codex is not yet on disk, but npm is resolvable.
# install_agent must shell out to `npm install -g @openai/codex` and
diff --git a/tests/test_update_checker_platforms.py b/tests/test_update_checker_platforms.py
index 4f198c4cd..6c15ed74e 100644
--- a/tests/test_update_checker_platforms.py
+++ b/tests/test_update_checker_platforms.py
@@ -1056,3 +1056,141 @@ def test_fetch_pypi_version_sync_ignores_prerelease_for_stable_current(monkeypat
assert req.full_url == "https://pypi.org/pypi/avibe-os/json"
assert req.headers["User-agent"] == "avibe-os"
assert info == {"current": "2.2.7", "latest": "2.2.7", "has_update": False, "error": None}
+
+
+def _backend_auto_update_checker(monkeypatch, tmp_path, sqlite_schema_db_factory, coordinator, runtimes, install):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")
+ SettingsStore.reset_instance()
+ controller = _StubController(SettingsStore.get_instance())
+ controller.backend_restart_coordinator = coordinator
+ monkeypatch.setattr(
+ "vibe.api.get_backend_runtime",
+ lambda name: {"ok": True, "enabled": True, "installed": True, **runtimes[name]},
+ )
+ monkeypatch.setattr("vibe.api.install_agent", install)
+ monkeypatch.setattr("vibe.api.reconcile_askill_auto_update", lambda: {"ok": True, "skipped": True})
+ monkeypatch.setattr(
+ update_checker,
+ "_fetch_pypi_version_sync",
+ lambda: {"current": "1.0.0", "latest": "1.0.0", "has_update": False, "error": None},
+ )
+ checker = UpdateChecker(controller, UpdateConfig(check_interval_minutes=60, idle_minutes=30))
+ checker.state.last_activity_at = time.time() - 3600
+ return checker
+
+
+def test_backend_auto_update_retries_a_release_until_it_lands_or_its_install_fails(
+ monkeypatch, tmp_path, sqlite_schema_db_factory
+):
+ admissions = []
+ coordinator_state = {"busy": True, "refresh_fails": False}
+
+ class _Coordinator:
+ async def run_when_idle(self, backend, operation):
+ admissions.append(backend)
+ if coordinator_state["busy"]:
+ return None
+ result = await operation()
+ if coordinator_state["refresh_fails"]:
+ raise RuntimeError("refresh failed")
+ return result
+
+ runtimes = {
+ "codex": {"auto_update": True, "has_update": True, "latest_version": "1.1.0"},
+ "claude": {"auto_update": False, "has_update": True, "latest_version": "2.0.0"},
+ "opencode": {"auto_update": True, "has_update": False, "latest_version": "1.0.0"},
+ }
+ install_results = [
+ {"ok": False, "code": "install_locked", "message": "Another Codex installation is already running."},
+ {"ok": True},
+ {"ok": False, "code": "install_failed", "message": "Could not upgrade Codex."},
+ {"ok": True},
+ ]
+ installs = []
+
+ def install(name):
+ installs.append(name)
+ return install_results.pop(0)
+
+ checker = _backend_auto_update_checker(
+ monkeypatch, tmp_path, sqlite_schema_db_factory, _Coordinator(), runtimes, install
+ )
+
+ # A message inside the quiet window defers every backend, like Avibe's own update.
+ checker.state.last_activity_at = time.time() - 60
+ asyncio.run(checker._do_check())
+ assert admissions == []
+
+ checker.state.last_activity_at = time.time() - 3600
+ asyncio.run(checker._do_check()) # codex has a turn running
+ coordinator_state["busy"] = False
+ asyncio.run(checker._do_check()) # a manual install holds the CLI
+ asyncio.run(checker._do_check()) # the installer succeeds without reaching the release
+ coordinator_state["refresh_fails"] = True
+ asyncio.run(checker._do_check()) # the install fails, then so does the refresh
+ coordinator_state["refresh_fails"] = False
+ asyncio.run(checker._do_check()) # the failed release is not retried
+
+ assert admissions == ["codex"] * 4
+ assert installs == ["codex"] * 3
+ assert update_checker.UpdateState.load().backend_auto_update_attempts == {"codex": "1.1.0"}
+
+ runtimes["codex"]["latest_version"] = "1.2.0"
+ asyncio.run(checker._do_check()) # a newer release is tried again
+
+ assert installs == ["codex"] * 4
+
+
+def test_backend_auto_update_stops_admitting_backends_once_a_message_arrives(
+ monkeypatch, tmp_path, sqlite_schema_db_factory
+):
+ admissions = []
+
+ class _Coordinator:
+ async def run_when_idle(self, backend, operation):
+ admissions.append(backend)
+ return await operation()
+
+ def install(name):
+ # The first backend's install outlasts the quiet window.
+ checker.record_activity()
+ return {"ok": True}
+
+ runtimes = {
+ name: {"auto_update": True, "has_update": True, "latest_version": "9.0.0"}
+ for name in ("codex", "claude", "opencode")
+ }
+ checker = _backend_auto_update_checker(
+ monkeypatch, tmp_path, sqlite_schema_db_factory, _Coordinator(), runtimes, install
+ )
+
+ asyncio.run(checker._do_check())
+
+ assert len(admissions) == 1
+
+
[email protected]("attempts", [None, ["codex"]])
+def test_update_state_without_backend_attempts_loads_released_fields(monkeypatch, tmp_path, attempts):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ released = {
+ "notified_version": "3.0.3",
+ "notified_at": "2026-09-01T00:00:00Z",
+ "last_check_at": "2026-09-01T00:00:00Z",
+ "last_activity_at": 1767225600.0,
+ "blocked_auto_update_version": None,
+ "blocked_auto_update_reason": None,
+ "blocked_auto_update_at": None,
+ "blocked_auto_update_current_version": None,
+ }
+ if attempts is not None:
+ released["backend_auto_update_attempts"] = attempts
+ path = tmp_path / "state" / "update_state.json"
+ path.parent.mkdir(parents=True)
+ path.write_text(json.dumps(released), encoding="utf-8")
+
+ state = update_checker.UpdateState.load()
+
+ assert state.notified_version == "3.0.3"
+ assert state.last_activity_at == 1767225600.0
+ assert state.backend_auto_update_attempts == {}
diff --git a/ui/src/components/settings/BackendLifecycleChip.test.tsx b/ui/src/components/settings/BackendLifecycleChip.test.tsx
index bb1c3b09b..8c5954126 100644
--- a/ui/src/components/settings/BackendLifecycleChip.test.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.test.tsx
@@ -10,6 +10,7 @@ import { BackendLifecycleChip } from './BackendLifecycleChip';
const api = vi.hoisted(() => ({
getBackendRuntime: vi.fn(),
installAgent: vi.fn(),
+ mutateConfig: vi.fn(),
restartBackend: vi.fn(),
}));
const showToast = vi.hoisted(() => vi.fn());
@@ -82,6 +83,24 @@ afterEach(() => {
});
describe('BackendLifecycleChip', () => {
+ it('saves the backend auto-update switch to its own agent config', async () => {
+ api.getBackendRuntime.mockResolvedValue({ ...updateAvailable, auto_update: true });
+ api.mutateConfig.mockResolvedValue({ ok: true });
+ const user = userEvent.setup();
+
+ render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={codexPath} />);
+ await user.click(await screen.findByRole('button', { name: 'backendLifecycle.statusUpdateAvailable' }));
+ const toggle = await screen.findByRole('switch', { name: 'backendLifecycle.autoUpdate' });
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+
+ await user.click(toggle);
+
+ expect(api.mutateConfig).toHaveBeenCalledWith([
+ { kind: 'set', path: ['agents', 'codex', 'auto_update'], value: false },
+ ]);
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('false'));
+ });
+
it('keeps an active upgrade visible across popover dismissal and stale runtime refreshes', async () => {
const install = deferred<{ ok: boolean; message: string; output: null }>();
api.installAgent.mockReturnValue(install.promise);
diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsx
index baed04c46..feac7c21f 100644
--- a/ui/src/components/settings/BackendLifecycleChip.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.tsx
@@ -6,12 +6,14 @@ import { useApi, type BackendRuntimeInfo } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { InstallOutcome, type InstallOutcomeResult } from '../shared/InstallOutcome';
import { Button } from '../ui/button';
+import { ToggleSwitch } from './SettingsPrimitives';
import {
badgeVariants,
interactiveBadgeTriggerClassName,
mobileHeaderPopoverClassName,
} from '../ui/badge-variants';
import { getBackendUiMeta } from '@/lib/agentBackends';
+import { setConfigField } from '@/lib/configMutations';
import { cn } from '@/lib/utils';
type CliStatus = 'unknown' | 'ok' | 'missing';
@@ -143,6 +145,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
const [runtime, setRuntime] = React.useState<BackendRuntimeInfo | null>(null);
const [runtimeLoading, setRuntimeLoading] = React.useState(false);
const [operation, setOperation] = React.useState<Operation>('idle');
+ const [savingAutoUpdate, setSavingAutoUpdate] = React.useState(false);
// The last upgrade's failure stays in the popover until the next attempt, so
// the reason outlives the toast that announced it. It is tied to what it
// describes: the executable it ran against, and the host's refresh generation,
@@ -267,6 +270,18 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
}
};
+ const handleAutoUpdateToggle = async (autoUpdate: boolean) => {
+ setSavingAutoUpdate(true);
+ try {
+ await api.mutateConfig([setConfigField(['agents', name, 'auto_update'], autoUpdate)]);
+ if (isMountedRef.current) setRuntime((prev) => (prev ? { ...prev, auto_update: autoUpdate } : prev));
+ } catch (e) {
+ showToast(String(e), 'error');
+ } finally {
+ if (isMountedRef.current) setSavingAutoUpdate(false);
+ }
+ };
+
const handleRestart = async () => {
setOperation('restarting');
onOperationChange?.(true);
@@ -362,6 +377,20 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
failed={!!shownFailure}
/>
{shownFailure && <InstallOutcome result={shownFailure} className="text-xs" />}
+ {visual !== 'disabled' && typeof runtime?.auto_update === 'boolean' && (
+ <div className="flex items-center justify-between gap-3 border-t border-border pt-3">
+ <div className="min-w-0">
+ <div className="text-sm text-foreground">{t('backendLifecycle.autoUpdate')}</div>
+ <div className="text-xs text-muted">{t('backendLifecycle.autoUpdateHint')}</div>
+ </div>
+ <ToggleSwitch
+ enabled={runtime.auto_update}
+ onClick={() => void handleAutoUpdateToggle(!runtime.auto_update)}
+ disabled={savingAutoUpdate}
+ label={t('backendLifecycle.autoUpdate')}
+ />
+ </div>
+ )}
</div>
{visual !== 'disabled' && visual !== 'updating' && (
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 16a021bc3..cf2370295 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1947,6 +1947,7 @@ export type BackendRuntimeInfo = {
ok: boolean;
name?: string;
enabled?: boolean;
+ auto_update?: boolean;
cli_path?: string;
resolved_path?: string | null;
installed?: boolean;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 886f391f3..c8b814581 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3434,7 +3434,9 @@
"reinstall": "Reinstall",
"restart": "Restart",
"restartSuccess": "Restart requested",
- "restartFailed": "Restart failed"
+ "restartFailed": "Restart failed",
+ "autoUpdate": "Auto Update",
+ "autoUpdateHint": "Install new releases once this backend is idle"
},
"channelList": {
"eyebrow": "Groups",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index a41f3f6c4..1e184ebfc 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3434,7 +3434,9 @@
"reinstall": "重新安装",
"restart": "重启",
"restartSuccess": "已请求重启",
- "restartFailed": "重启失败"
+ "restartFailed": "重启失败",
+ "autoUpdate": "自动更新",
+ "autoUpdateHint": "该后端空闲时自动安装新版本"
},
"channelList": {
"eyebrow": "群组",
diff --git a/vibe/api.py b/vibe/api.py
index 63eb62aa7..399ed2480 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -126,6 +126,7 @@ from core.vibe_agents import (
validate_agent_backend,
)
from core.process_isolation import isolated_subprocess_kwargs, signal_process_tree, KILL_SIGNAL
+from storage.lock import MigrationFileLock, MigrationLockTimeout
from core.dependency_network import DependencyNetworkError, dependency_error_message, fetch_bytes
@@ -7185,6 +7186,29 @@ def _run_desktop_backend_install(name: str, truncate_output) -> dict:
def install_agent(name: str) -> dict:
+ """Install (or upgrade) an agent CLI tool, one install per backend at a time.
+
+ Settings runs this in the UI process and backend auto-update in the
+ controller, so only a file lock keeps two installers off one CLI.
+ """
+ lock = MigrationFileLock(paths.get_state_dir() / "agent_install" / f"{name}.lock", timeout_seconds=0)
+ try:
+ lock.acquire()
+ except MigrationLockTimeout:
+ return {
+ "ok": False,
+ "code": "install_locked",
+ "message": _desktop_backend_install_message(name, "install_locked"),
+ "output": None,
+ "path": None,
+ }
+ try:
+ return _install_agent(name)
+ finally:
+ lock.release()
+
+
+def _install_agent(name: str) -> dict:
"""Install (or upgrade) an agent CLI tool.
Upgrade path (binary already on disk): keep the user's install method
@@ -10125,6 +10149,7 @@ def get_backend_runtime(name: str) -> dict:
"ok": True,
"name": name,
"enabled": enabled,
+ "auto_update": bool(getattr(backend_cfg, "auto_update", True)),
"cli_path": configured_path,
"resolved_path": resolved_path,
"installed": installed,