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(update): stop repeated auto-update success notices (#648)

Call White30bf5784d750
diff --git a/core/update_checker.py b/core/update_checker.py
index 0405ef10b..8206bfbda 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -26,7 +26,13 @@ from config.v2_config import UpdateConfig
from config.v2_settings import _infer_channel_platform, _infer_user_platform, _split_scoped_key
from modules.im import InlineButton, InlineKeyboard, MessageContext
from vibe.i18n import t as i18n_t
-from vibe.upgrade import PACKAGE_NAME, get_update_metadata_url, has_newer_version, select_latest_update_version
+from vibe.upgrade import (
+ PACKAGE_NAME,
+ get_running_vibe_path,
+ get_update_metadata_url,
+ has_newer_version,
+ select_latest_update_version,
+)
if TYPE_CHECKING:
from core.controller import Controller
@@ -52,6 +58,7 @@ UPDATE_NOTIFICATION_POLICY_MARKER_RE = re.compile(
r"<!--\s*(?:avibe|vibe-remote):update-notification\s*=\s*(?P<policy>none|default)\s*-->",
re.IGNORECASE,
)
+_STABLE_PACKAGE_VERSION_RE = re.compile(r"^\d+(?:\.\d+)*(?:[.-]?post\d+)?$")
def _fetch_pypi_version_sync() -> Dict[str, Any]:
@@ -140,6 +147,10 @@ class UpdateState:
notified_at: Optional[str] = None
last_check_at: Optional[str] = None
last_activity_at: Optional[float] = None
+ blocked_auto_update_version: Optional[str] = None
+ blocked_auto_update_reason: Optional[str] = None
+ blocked_auto_update_at: Optional[str] = None
+ blocked_auto_update_current_version: Optional[str] = None
@classmethod
def load(cls) -> "UpdateState":
@@ -153,6 +164,10 @@ class UpdateState:
notified_at=data.get("notified_at"),
last_check_at=data.get("last_check_at"),
last_activity_at=data.get("last_activity_at"),
+ blocked_auto_update_version=data.get("blocked_auto_update_version"),
+ 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"),
)
except Exception as e:
logger.warning(f"Failed to load update state: {e}")
@@ -168,6 +183,10 @@ class UpdateState:
"notified_at": self.notified_at,
"last_check_at": self.last_check_at,
"last_activity_at": self.last_activity_at,
+ "blocked_auto_update_version": self.blocked_auto_update_version,
+ "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,
}
# Atomic write: write to temp file, then rename
with tempfile.NamedTemporaryFile(
@@ -261,6 +280,64 @@ class UpdateChecker:
except Exception as e:
logger.warning(f"Failed to reload update config: {e}")
+ def _clear_blocked_auto_update(self) -> None:
+ if (
+ self.state.blocked_auto_update_version is None
+ and self.state.blocked_auto_update_reason is None
+ and self.state.blocked_auto_update_at is None
+ and self.state.blocked_auto_update_current_version is None
+ ):
+ return
+ self.state.blocked_auto_update_version = None
+ self.state.blocked_auto_update_reason = None
+ self.state.blocked_auto_update_at = None
+ self.state.blocked_auto_update_current_version = None
+ self.state.save()
+
+ def _clear_blocked_auto_update_if_resolved(self, latest: Optional[str], *, has_update: bool) -> None:
+ blocked = self.state.blocked_auto_update_version
+ if not blocked:
+ return
+ if has_update and latest == blocked:
+ return
+ logger.info("Clearing blocked auto-update state for %s", blocked)
+ self._clear_blocked_auto_update()
+
+ def _block_auto_update(self, target_version: str, reason: str, *, current_version: Optional[str] = None) -> None:
+ self.state.blocked_auto_update_version = target_version
+ self.state.blocked_auto_update_reason = reason
+ self.state.blocked_auto_update_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ self.state.blocked_auto_update_current_version = current_version
+ self.state.save()
+
+ def _blocked_auto_update_reason_for(self, target_version: str) -> Optional[str]:
+ if self.state.blocked_auto_update_version != target_version:
+ return None
+ return self.state.blocked_auto_update_reason or "unknown"
+
+ def _supports_unattended_self_update(self, current_version: str) -> tuple[bool, Optional[str]]:
+ from vibe import runtime
+
+ service_main_path = runtime.get_service_main_path()
+ if service_main_path.name == "main.py":
+ return False, f"service is running from source checkout at {service_main_path}"
+
+ normalized_version = str(current_version or "").strip()
+ if not _STABLE_PACKAGE_VERSION_RE.fullmatch(normalized_version):
+ return False, f"running version {normalized_version or 'unknown'} is not a packaged stable release"
+
+ if not get_running_vibe_path():
+ return False, "current vibe executable path is unavailable"
+
+ return True, None
+
+ def _running_version_satisfies_target(self, running_version: str, target_version: str) -> bool:
+ running = str(running_version or "").strip()
+ target = str(target_version or "").strip()
+ if not running or not target:
+ return False
+ return running == target or has_newer_version(running, target)
+
async def _check_loop(self) -> None:
"""Main loop for periodic update checking."""
# Initial delay to let the service fully start
@@ -309,6 +386,11 @@ class UpdateChecker:
logger.warning(f"Failed to check for updates: {version_info['error']}")
return
+ self._clear_blocked_auto_update_if_resolved(
+ version_info.get("latest") if version_info.get("has_update") else None,
+ has_update=bool(version_info.get("has_update")),
+ )
+
if not version_info.get("has_update"):
logger.debug(f"No update available (current={version_info['current']})")
return
@@ -317,6 +399,7 @@ class UpdateChecker:
current = version_info["current"]
logger.info(f"Update available: {current} -> {latest}")
release_notifications_enabled: Optional[bool] = None
+ unattended_supported, unattended_reason = self._supports_unattended_self_update(current)
# Notification flow — failure must not block auto-update
if self.config.notify_admins and self.state.notified_version != latest:
@@ -343,6 +426,17 @@ class UpdateChecker:
# Auto-update flow — respect a grace period after successful notification
# so the admin has time to read the notification before auto-update kicks in.
if self.config.auto_update and self._is_idle():
+ blocked_reason = self._blocked_auto_update_reason_for(latest)
+ if blocked_reason:
+ logger.warning(
+ "Skipping auto-update to %s; previous attempt is blocked: %s",
+ latest,
+ blocked_reason,
+ )
+ return
+ if not unattended_supported:
+ logger.warning("Skipping unattended self-update for %s: %s", latest, unattended_reason)
+ return
release_notifications = await self._should_send_release_notifications(
latest,
cached=release_notifications_enabled,
@@ -354,7 +448,23 @@ class UpdateChecker:
update_kwargs = {}
if not release_notifications:
update_kwargs["suppress_post_update_notification"] = True
- await self._perform_update(latest, **update_kwargs)
+ result = await self._perform_update(latest, **update_kwargs)
+ if not result.get("ok"):
+ logger.warning(
+ "Auto-update to %s failed and will be retried on a later check: %s",
+ latest,
+ result.get("message") or "unknown",
+ )
+ elif not result.get("restarting"):
+ await self._send_post_update_failure_notification(
+ target_version=str(latest),
+ running_version=str(current),
+ )
+ self._block_auto_update(
+ latest,
+ "restart_not_scheduled",
+ current_version=current,
+ )
except Exception as e:
logger.error(f"Update check failed: {e}", exc_info=True)
@@ -578,6 +688,73 @@ class UpdateChecker:
logger.warning("Update notification skipped: no admins and unsupported platform %s", platform)
return False
+ async def _send_post_update_failure_notification(
+ self,
+ *,
+ target_version: str,
+ running_version: str,
+ channel_id: Optional[str] = None,
+ message_id: Optional[str] = None,
+ platform: Optional[str] = None,
+ ) -> None:
+ """Notify admins that an installed update did not become the active runtime."""
+ resolved_platform = platform or getattr(self.controller.config, "platform", "slack")
+ if channel_id:
+ resolved_platform = platform or _infer_channel_platform(channel_id)
+
+ failure_text = self._t(
+ "update.postUpdateVersionMismatch",
+ target=target_version,
+ current=running_version or "unknown",
+ )
+
+ try:
+ im_client = self._get_im_client_for_platform(resolved_platform)
+ if channel_id and message_id and resolved_platform == "slack":
+ try:
+ await im_client.web_client.chat_update(channel=channel_id, ts=message_id, text=failure_text)
+ logger.info("Updated original message with post-update failure notification")
+ return
+ except Exception as e:
+ logger.error("Failed to update Slack post-update failure message: %s", e)
+ if channel_id and message_id:
+ try:
+ context = MessageContext(user_id="system", channel_id=channel_id, platform=resolved_platform)
+ await im_client.edit_message(context, message_id, text=failure_text)
+ logger.info("Updated %s message with post-update failure notification", resolved_platform)
+ return
+ except Exception as e:
+ logger.error("Failed to edit %s post-update failure message: %s", resolved_platform, e)
+
+ admin_ids = self._get_admin_user_ids()
+ if admin_ids:
+ for uid in admin_ids:
+ try:
+ admin_client, raw_user_id, _ = self._get_im_client_for_user(uid)
+ await admin_client.send_dm(raw_user_id, failure_text)
+ logger.info("Sent post-update failure notification to admin %s", uid)
+ except Exception as e:
+ logger.error("Failed to send post-update failure notification to admin %s: %s", uid, e)
+ elif resolved_platform == "slack":
+ owner_id = await self._get_workspace_owner_id()
+ if owner_id:
+ dm_channel = await self._open_dm_channel(owner_id)
+ if dm_channel:
+ await im_client.web_client.chat_postMessage(channel=dm_channel, text=failure_text)
+ logger.info("Sent post-update failure notification to %s", owner_id)
+ elif resolved_platform == "discord":
+ channel_id = self._get_default_notification_channel_id()
+ if channel_id:
+ context = MessageContext(user_id="system", channel_id=channel_id, platform="discord")
+ await self.controller.get_im_client_for_context(context).send_message(
+ context,
+ failure_text,
+ parse_mode="markdown",
+ )
+ logger.info("Sent Discord post-update failure notification to channel %s", channel_id)
+ except Exception as e:
+ logger.error("Failed to send post-update failure notification: %s", e)
+
async def _send_notification_to_admins(self, admin_ids: list, current: str, latest: str, platform: str) -> bool:
"""Send update notification DM to each admin user."""
delivered = False
@@ -816,14 +993,13 @@ class UpdateChecker:
# Write marker only if restart is scheduled
if suppress_post_update_notification:
logger.info("Post-update notification suppressed for %s", target_version)
- self._remove_update_marker()
- else:
- self._write_update_marker(
- target_version,
- channel_id=channel_id,
- message_id=message_id,
- platform=platform,
- )
+ self._write_update_marker(
+ target_version,
+ channel_id=channel_id,
+ message_id=message_id,
+ platform=platform,
+ suppress_success_notification=suppress_post_update_notification,
+ )
else:
logger.warning("Upgrade completed without restart; manual restart required")
return result
@@ -840,6 +1016,7 @@ class UpdateChecker:
channel_id: Optional[str] = None,
message_id: Optional[str] = None,
platform: Optional[str] = None,
+ suppress_success_notification: bool = False,
) -> None:
"""Write a marker file to trigger post-update notification."""
try:
@@ -849,6 +1026,8 @@ class UpdateChecker:
"version": version,
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
+ if suppress_success_notification:
+ data["suppress_success_notification"] = True
# Store message coordinates for updating the original message after restart
if channel_id and message_id:
data["channel_id"] = channel_id
@@ -881,15 +1060,42 @@ class UpdateChecker:
return
try:
+ from vibe import __version__
+
data = json.loads(marker_path.read_text(encoding="utf-8"))
channel_id = data.get("channel_id")
message_id = data.get("message_id")
# Use the target version from marker (more reliable than __version__ in edge cases)
target_version = data.get("version", "unknown")
+ running_version = str(__version__ or "").strip()
+ if not self._running_version_satisfies_target(running_version, str(target_version)):
+ logger.warning(
+ "Suppressing post-update success notification: expected %s but still running %s",
+ target_version,
+ running_version or "unknown",
+ )
+ self._block_auto_update(
+ str(target_version),
+ "post_update_version_mismatch",
+ current_version=running_version or None,
+ )
+ await self._send_post_update_failure_notification(
+ target_version=str(target_version),
+ running_version=running_version or "unknown",
+ channel_id=channel_id,
+ message_id=message_id,
+ platform=data.get("platform"),
+ )
+ return
platform = data.get("platform") or getattr(self.controller.config, "platform", "slack")
if channel_id:
platform = data.get("platform") or _infer_channel_platform(channel_id)
+ if self.state.blocked_auto_update_version == target_version:
+ self._clear_blocked_auto_update()
+ if data.get("suppress_success_notification"):
+ logger.info("Post-update success notification suppressed for %s", target_version)
+ return
im_client = self._get_im_client_for_platform(platform)
success_text = self._t("update.updated", version=target_version)
success_blocks = [
diff --git a/tests/test_update_checker_platforms.py b/tests/test_update_checker_platforms.py
index 12a6d3033..440167948 100644
--- a/tests/test_update_checker_platforms.py
+++ b/tests/test_update_checker_platforms.py
@@ -11,7 +11,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from config.v2_settings import SettingsStore, UserSettings
+from config.v2_settings import ChannelSettings, SettingsStore, UserSettings
from config.v2_config import UpdateConfig
from core import update_checker
from core.update_checker import UpdateChecker
@@ -35,12 +35,16 @@ class _StubController:
self.im_client = object()
self.im_clients = {}
+ def get_im_client_for_context(self, context):
+ return self.im_clients.get(context.platform) or self.im_client
+
class _FakeIMClient:
def __init__(self, message_id="msg-1"):
self.message_id = message_id
self.dm_calls = []
self.edit_calls = []
+ self.message_calls = []
async def send_dm(self, user_id: str, text: str, **kwargs):
self.dm_calls.append((user_id, text, kwargs))
@@ -50,6 +54,10 @@ class _FakeIMClient:
self.edit_calls.append((context, message_id, text, kwargs))
return True
+ async def send_message(self, context, text: str, **kwargs):
+ self.message_calls.append((context, text, kwargs))
+ return self.message_id
+
def test_get_admin_user_ids_includes_all_platforms(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -182,6 +190,8 @@ def test_failed_update_notification_does_not_defer_idle_auto_update(monkeypatch,
lambda version: {"version": version, "policy": "default", "error": None},
)
monkeypatch.setattr(checker, "_is_idle", lambda: True)
+ monkeypatch.setattr("vibe.runtime.get_service_main_path", lambda: Path("/pkg/service_main.py"))
+ monkeypatch.setattr(update_checker, "get_running_vibe_path", lambda: "/tmp/vibe")
performed = []
async def fake_perform_update(target_version, **kwargs):
@@ -220,6 +230,8 @@ def test_silent_release_metadata_skips_notifications_but_keeps_auto_update(monke
lambda version: {"version": version, "policy": "none", "error": None},
)
monkeypatch.setattr(checker, "_is_idle", lambda: True)
+ monkeypatch.setattr("vibe.runtime.get_service_main_path", lambda: Path("/pkg/service_main.py"))
+ monkeypatch.setattr(update_checker, "get_running_vibe_path", lambda: "/tmp/vibe")
notified = []
performed = []
@@ -289,7 +301,7 @@ def test_update_check_reconciles_askill_even_when_product_checks_disabled(monkey
assert reconciled == [True]
-def test_suppressed_post_update_notification_does_not_write_marker(monkeypatch, tmp_path):
+def test_suppressed_post_update_notification_writes_verification_marker(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
SettingsStore.reset_instance()
checker = UpdateChecker(_StubController(SettingsStore.get_instance()), UpdateConfig())
@@ -303,7 +315,9 @@ def test_suppressed_post_update_notification_does_not_write_marker(monkeypatch,
assert result["ok"] is True
marker = tmp_path / "state" / "pending_update_notification.json"
- assert not marker.exists()
+ data = json.loads(marker.read_text(encoding="utf-8"))
+ assert data["version"] == "1.0.1"
+ assert data["suppress_success_notification"] is True
def test_update_marker_records_platform_for_non_slack_callbacks(monkeypatch, tmp_path):
@@ -329,6 +343,7 @@ def test_post_update_notification_uses_unicode_emoji_for_non_slack(monkeypatch,
controller.im_clients = {"telegram": telegram_client}
checker = UpdateChecker(controller, UpdateConfig())
checker._write_update_marker("1.0.1", channel_id="123456", message_id="42", platform="telegram")
+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)
asyncio.run(checker.check_and_send_post_update_notification())
@@ -338,6 +353,293 @@ def test_post_update_notification_uses_unicode_emoji_for_non_slack(monkeypatch,
assert ":white_check_mark:" not in text
+def test_suppressed_post_update_marker_verifies_without_success_message(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ controller = _StubController(SettingsStore.get_instance())
+ telegram_client = _FakeIMClient()
+ controller.im_clients = {"telegram": telegram_client}
+ checker = UpdateChecker(controller, UpdateConfig())
+ checker._write_update_marker(
+ "1.0.1",
+ channel_id="123456",
+ message_id="42",
+ platform="telegram",
+ suppress_success_notification=True,
+ )
+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)
+
+ asyncio.run(checker.check_and_send_post_update_notification())
+
+ assert telegram_client.edit_calls == []
+ marker = tmp_path / "state" / "pending_update_notification.json"
+ assert not marker.exists()
+
+
+def test_auto_update_skips_unattended_source_checkout_install(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ checker = UpdateChecker(
+ _StubController(SettingsStore.get_instance()),
+ UpdateConfig(check_interval_minutes=1, notify_admins=False, auto_update=True),
+ )
+ checker.state.last_activity_at = time.time() - 3600
+ monkeypatch.setattr(
+ update_checker,
+ "_fetch_pypi_version_sync",
+ lambda: {"current": "3.0.4.dev10+g4d621ef0a", "latest": "3.0.4", "has_update": True, "error": None},
+ )
+ monkeypatch.setattr(checker, "_is_idle", lambda: True)
+ monkeypatch.setattr(update_checker, "get_running_vibe_path", lambda: "/tmp/dev-vibe")
+ monkeypatch.setattr("vibe.runtime.get_service_main_path", lambda: Path("/repo/main.py"))
+ performed = []
+
+ async def fake_perform_update(target_version, **kwargs):
+ performed.append((target_version, kwargs))
+ return {"ok": True, "restarting": True, "message": "ok"}
+
+ monkeypatch.setattr(checker, "_perform_update", fake_perform_update)
+
+ asyncio.run(checker._do_check())
+
+ assert performed == []
+ assert checker.state.blocked_auto_update_version is None
+
+
+def test_restartless_auto_update_blocks_same_version_retry_and_notifies(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"123456": UserSettings(display_name="Telegram", is_admin=True)})
+ store.save()
+ controller = _StubController(store)
+ telegram_client = _FakeIMClient()
+ controller.im_clients = {"telegram": telegram_client}
+ checker = UpdateChecker(
+ controller,
+ UpdateConfig(check_interval_minutes=1, notify_admins=False, auto_update=True),
+ )
+ checker.state.last_activity_at = time.time() - 3600
+ monkeypatch.setattr(
+ update_checker,
+ "_fetch_pypi_version_sync",
+ lambda: {"current": "3.0.3", "latest": "3.0.4", "has_update": True, "error": None},
+ )
+ monkeypatch.setattr(checker, "_is_idle", lambda: True)
+ monkeypatch.setattr("vibe.runtime.get_service_main_path", lambda: Path("/pkg/service_main.py"))
+ monkeypatch.setattr(update_checker, "get_running_vibe_path", lambda: "/tmp/vibe")
+ attempts = []
+
+ async def fake_perform_update(target_version, **kwargs):
+ attempts.append((target_version, kwargs))
+ return {"ok": True, "restarting": False, "message": "restart missing"}
+
+ monkeypatch.setattr(checker, "_perform_update", fake_perform_update)
+
+ asyncio.run(checker._do_check())
+ asyncio.run(checker._do_check())
+
+ assert attempts == [("3.0.4", {})]
+ assert telegram_client.dm_calls
+ _, text, _ = telegram_client.dm_calls[0]
+ assert "did not take effect" in text
+ assert "`3.0.4`" in text
+ assert "`3.0.3`" in text
+ assert checker.state.blocked_auto_update_version == "3.0.4"
+ assert checker.state.blocked_auto_update_reason == "restart_not_scheduled"
+
+
+def test_post_update_failure_notification_uses_discord_fallback_channel(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ store = SettingsStore.get_instance()
+ store.update_channel("123456789012345678", ChannelSettings(enabled=True), platform="discord")
+ controller = _StubController(store)
+ controller.config.platform = "discord"
+ discord_client = _FakeIMClient()
+ controller.im_clients = {"discord": discord_client}
+ controller.im_client = discord_client
+ checker = UpdateChecker(controller, UpdateConfig())
+
+ asyncio.run(
+ checker._send_post_update_failure_notification(
+ target_version="3.0.4",
+ running_version="3.0.3",
+ platform="discord",
+ )
+ )
+
+ assert discord_client.message_calls
+ context, text, kwargs = discord_client.message_calls[0]
+ assert context.platform == "discord"
+ assert context.channel_id == "123456789012345678"
+ assert "did not take effect" in text
+ assert kwargs["parse_mode"] == "markdown"
+
+
+def test_post_update_failure_notification_continues_after_admin_dm_failure(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bad": UserSettings(display_name="Bad", is_admin=True)})
+ store.set_users_for_platform("discord", {"good": UserSettings(display_name="Good", is_admin=True)})
+ store.save()
+ controller = _StubController(store)
+
+ class _FailingDMClient(_FakeIMClient):
+ async def send_dm(self, user_id: str, text: str, **kwargs):
+ raise RuntimeError("dm failed")
+
+ bad_client = _FailingDMClient()
+ good_client = _FakeIMClient()
+ controller.im_clients = {"telegram": bad_client, "discord": good_client}
+ checker = UpdateChecker(controller, UpdateConfig())
+
+ asyncio.run(
+ checker._send_post_update_failure_notification(
+ target_version="3.0.4",
+ running_version="3.0.3",
+ )
+ )
+
+ assert bad_client.dm_calls == []
+ assert good_client.dm_calls
+ user_id, text, _ = good_client.dm_calls[0]
+ assert user_id == "good"
+ assert "did not take effect" in text
+
+
+def test_post_update_failure_notification_falls_back_after_edit_failure(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"admin": UserSettings(display_name="Admin", is_admin=True)})
+ store.save()
+ controller = _StubController(store)
+
+ class _FailingEditClient(_FakeIMClient):
+ async def edit_message(self, context, message_id: str, text: str, **kwargs):
+ self.edit_calls.append((context, message_id, text, kwargs))
+ raise RuntimeError("edit failed")
+
+ telegram_client = _FailingEditClient()
+ controller.im_clients = {"telegram": telegram_client}
+ checker = UpdateChecker(controller, UpdateConfig())
+
+ asyncio.run(
+ checker._send_post_update_failure_notification(
+ target_version="3.0.4",
+ running_version="3.0.3",
+ channel_id="123456",
+ message_id="42",
+ platform="telegram",
+ )
+ )
+
+ assert telegram_client.edit_calls
+ assert telegram_client.dm_calls
+ user_id, text, _ = telegram_client.dm_calls[0]
+ assert user_id == "admin"
+ assert "did not take effect" in text
+
+
+def test_install_failure_auto_update_remains_retryable(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ checker = UpdateChecker(
+ _StubController(SettingsStore.get_instance()),
+ UpdateConfig(check_interval_minutes=1, notify_admins=False, auto_update=True),
+ )
+ checker.state.last_activity_at = time.time() - 3600
+ monkeypatch.setattr(
+ update_checker,
+ "_fetch_pypi_version_sync",
+ lambda: {"current": "3.0.3", "latest": "3.0.4", "has_update": True, "error": None},
+ )
+ monkeypatch.setattr(checker, "_is_idle", lambda: True)
+ monkeypatch.setattr("vibe.runtime.get_service_main_path", lambda: Path("/pkg/service_main.py"))
+ monkeypatch.setattr(update_checker, "get_running_vibe_path", lambda: "/tmp/vibe")
+ attempts = []
+
+ async def fake_perform_update(target_version, **kwargs):
+ attempts.append((target_version, kwargs))
+ return {"ok": False, "restarting": False, "message": "network down"}
+
+ monkeypatch.setattr(checker, "_perform_update", fake_perform_update)
+
+ asyncio.run(checker._do_check())
+ asyncio.run(checker._do_check())
+
+ assert attempts == [("3.0.4", {}), ("3.0.4", {})]
+ assert checker.state.blocked_auto_update_version is None
+ assert checker.state.blocked_auto_update_reason is None
+
+
+def test_update_check_error_preserves_blocked_auto_update(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ checker = UpdateChecker(
+ _StubController(SettingsStore.get_instance()),
+ UpdateConfig(check_interval_minutes=1, notify_admins=False, auto_update=True),
+ )
+ checker._block_auto_update("3.0.4", "post_update_version_mismatch", current_version="3.0.3")
+ monkeypatch.setattr(
+ update_checker,
+ "_fetch_pypi_version_sync",
+ lambda: {"current": "3.0.3", "latest": None, "has_update": False, "error": "network down"},
+ )
+
+ asyncio.run(checker._do_check())
+
+ assert checker.state.blocked_auto_update_version == "3.0.4"
+ assert checker.state.blocked_auto_update_reason == "post_update_version_mismatch"
+ assert checker.state.blocked_auto_update_current_version == "3.0.3"
+
+
+def test_post_update_notification_accepts_newer_running_version(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ controller = _StubController(SettingsStore.get_instance())
+ telegram_client = _FakeIMClient()
+ controller.im_clients = {"telegram": telegram_client}
+ checker = UpdateChecker(controller, UpdateConfig())
+ checker._write_update_marker("3.0.4", channel_id="123456", message_id="42", platform="telegram")
+ monkeypatch.setattr("vibe.__version__", "3.0.5", raising=False)
+
+ asyncio.run(checker.check_and_send_post_update_notification())
+
+ assert telegram_client.edit_calls
+ _, _, text, _ = telegram_client.edit_calls[0]
+ assert text == "✅ Avibe has been updated to `3.0.4`"
+ assert checker.state.blocked_auto_update_version is None
+ marker = tmp_path / "state" / "pending_update_notification.json"
+ assert not marker.exists()
+
+
+def test_post_update_notification_skips_success_when_running_version_mismatches(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ SettingsStore.reset_instance()
+ controller = _StubController(SettingsStore.get_instance())
+ telegram_client = _FakeIMClient()
+ controller.im_clients = {"telegram": telegram_client}
+ checker = UpdateChecker(controller, UpdateConfig())
+ checker._write_update_marker("3.0.4", channel_id="123456", message_id="42", platform="telegram")
+ monkeypatch.setattr("vibe.__version__", "3.0.3", raising=False)
+
+ asyncio.run(checker.check_and_send_post_update_notification())
+
+ assert telegram_client.edit_calls
+ _, _, text, _ = telegram_client.edit_calls[0]
+ assert "did not take effect" in text
+ assert "`3.0.4`" in text
+ assert "`3.0.3`" in text
+ assert checker.state.blocked_auto_update_version == "3.0.4"
+ assert checker.state.blocked_auto_update_reason == "post_update_version_mismatch"
+ assert checker.state.blocked_auto_update_current_version == "3.0.3"
+ marker = tmp_path / "state" / "pending_update_notification.json"
+ assert not marker.exists()
+
+
def test_stop_returns_cancellable_task(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
SettingsStore.reset_instance()
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 4465da406..a9ad6a3be 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -117,6 +117,7 @@
"restartRequired": "Upgrade complete. Please restart Avibe.",
"restartRequiredShort": "Upgrade completed - restart required",
"restartRequiredSlack": "✅ *Upgrade complete*\n\nPlease restart Avibe to apply the update.",
+ "postUpdateVersionMismatch": "❌ Avibe update did not take effect. Tried to update to `{target}`, but the service is still running `{current}`. Automatic retries for this version have been paused; please check the install path and restart logs.",
"updated": "✅ Avibe has been updated to `{version}`",
"updatedSlack": "✅ *Avibe Updated Successfully*\n\nNow running version `{version}`",
"availablePlain": "Avibe update available: {current} → {latest} ({releaseUrl})",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 22c38daa0..b2233c8a2 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -117,6 +117,7 @@
"restartRequired": "升级完成,请重启 Avibe。",
"restartRequiredShort": "升级完成 - 需要重启",
"restartRequiredSlack": "✅ *升级完成*\n\n请重启 Avibe 以应用更新。",
+ "postUpdateVersionMismatch": "❌ Avibe 更新没有生效。尝试更新到 `{target}`,但服务仍在运行 `{current}`。已暂停这个版本的自动重试,请检查安装路径和重启日志。",
"updated": "✅ Avibe 已更新到 `{version}`",
"updatedSlack": "✅ *Avibe 更新成功*\n\n当前运行版本 `{version}`",
"availablePlain": "Avibe 有可用更新:{current} → {latest} ({releaseUrl})",