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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(im): isolate Discord connection failures (#914)
Call White425307c5519b
diff --git a/core/controller.py b/core/controller.pyindex 171491688..3783fda7f 100644--- a/core/controller.py+++ b/core/controller.py@@ -705,7 +705,8 @@ class Controller:self.settings_handler.handle_routing_modal_update),on_resume_session=self._dispatch_to_controller_loop(self.session_handler.handle_resume_session_submission),- on_ready=self._dispatch_to_controller_loop(self._on_im_ready),+ on_ready=self._dispatch_to_controller_loop(self._on_runtime_ready),+ on_transport_ready=self._dispatch_to_controller_loop(self._on_im_ready),)def _dispatch_to_controller_loop(self, callback):@@ -823,24 +824,47 @@ class Controller:if loop and loop.is_running():loop.call_soon_threadsafe(loop.stop)- async def _on_im_ready(self):- """Called when IM client is connected and ready.-- Used to restore active poll loops that were interrupted by restart.- """- logger.info("IM client ready, checking for active polls to restore...")+ async def _restore_active_polls(self, platforms: set[str]) -> None:opencode_agent = self.agent_service.agents.get("opencode")if opencode_agent and hasattr(opencode_agent, "restore_active_polls"):try:- restored = await opencode_agent.restore_active_polls() # type: ignore[attr-defined]+ restored = await opencode_agent.restore_active_polls(platforms) # type: ignore[attr-defined]if restored > 0:logger.info(f"Restored {restored} active OpenCode poll(s)")except Exception as e:logger.error(f"Failed to restore active polls: {e}", exc_info=True)- # Start update checker and send any pending post-update notification+ async def _on_im_ready(self, *, platform: str) -> None:+ """Restore transport-owned state only after that transport can deliver."""+ logger.info("IM transport ready, restoring state for %s", platform)+ self.scheduled_task_service.notify_transport_ready(platform)+ notify_update_checker = getattr(self.update_checker, "notify_transport_ready", None)+ if callable(notify_update_checker):+ notify_update_checker(platform)+ platforms = {platform}+ if platform == self.primary_platform:+ platforms.add("")+ await self._restore_active_polls(platforms)+ try:+ await self.update_checker.check_and_send_post_update_notification(ready_platform=platform)+ except Exception as e:+ logger.error(f"Failed to send post-update notification: {e}", exc_info=True)++ def is_im_transport_ready(self, platform: str) -> bool:+ return self.im_client.is_transport_ready(platform)++ async def _on_runtime_ready(self) -> None:+ """Start aggregate services without waiting for external connectivity."""+ logger.info("IM runtime ready, starting core services")+ workbench_platforms = {"avibe"}+ if self.primary_platform == "avibe":+ workbench_platforms.add("")+ await self._restore_active_polls(workbench_platforms)+ try:+ await self.update_checker.check_and_send_post_update_notification(ready_platform="avibe")+ except Exception as e:+ logger.error(f"Failed to send post-update notification: {e}", exc_info=True)try:- await self.update_checker.check_and_send_post_update_notification()self.update_checker.start()except Exception as e:logger.error(f"Failed to start update checker: {e}", exc_info=True)diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 521f5fc0c..e00f990e8 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -1955,7 +1955,18 @@ class ScheduledTaskService:task = self.store.get_task(task_id)if not task or not task.enabled:return+ if any(+ request.request_type == "scheduled"+ and request.source_kind == "scheduler"+ and request.task_id == task.id+ for request in self.request_store.list_pending()+ ):+ self._drain_dirty = True+ returnqueued = self.request_store.enqueue_task_run(task.id, source_kind="scheduler", task=task)+ if not self._transport_ready_for_request(queued):+ self._drain_dirty = True+ returnrequest = self.request_store.claim(queued.id)if request is None:return@@ -1987,6 +1998,8 @@ class ScheduledTaskService:breakif pending.id in self._inflight_executions:continue+ if not self._transport_ready_for_request(pending):+ continuelock_key = self._execution_lock_key(pending)if lock_key is not None and lock_key in self._inflight_sessions:# A turn for this conversation is already running; keep this@@ -2256,6 +2269,52 @@ class ScheduledTaskService:return f"task:{task_id}"return None+ def _request_target_platform(self, request: TaskExecutionRequest) -> Optional[str]:+ session_key = request.session_key+ session_id = request.session_id+ deliver_key = request.deliver_key+ metadata = request.metadata or {}+ if request.request_type in {"task_run", "scheduled"} and request.task_id:+ task = self.store.get_task(request.task_id)+ if task is not None:+ session_key = task.session_key or session_key+ session_id = task.session_id or session_id+ deliver_key = task.deliver_key or deliver_key+ metadata = task.metadata or metadata++ if session_id:+ return resolve_session_id_target(session_id).session_key.platform+ if session_key:+ try:+ return parse_session_key(session_key).platform+ except ValueError:+ return parse_scope_id(session_key).platform++ scope_id = str(metadata.get("session_scope_id") or "").strip()+ if scope_id:+ return parse_scope_id(scope_id).platform+ if deliver_key:+ try:+ return parse_session_key(deliver_key).platform+ except ValueError:+ return parse_scope_id(deliver_key).platform+ return None++ def _transport_ready_for_request(self, request: TaskExecutionRequest) -> bool:+ try:+ platform = self._request_target_platform(request)+ except Exception:+ logger.debug("Could not resolve Run %s platform for readiness gating", request.id, exc_info=True)+ return True+ if not platform:+ return True+ is_ready = getattr(self.controller, "is_im_transport_ready", None)+ return bool(is_ready(platform)) if callable(is_ready) else True++ def notify_transport_ready(self, platform: str) -> None:+ logger.info("Transport %s ready; scheduled Run queue will be drained", platform)+ self._drain_dirty = True+def _canonical_session_lock(self, session_id: str, session_key: Optional[str]) -> str:cached = self._session_lock_cache.get(session_id)if cached is not None:diff --git a/core/update_checker.py b/core/update_checker.pyindex af02700b5..f82aecded 100644--- a/core/update_checker.py+++ b/core/update_checker.py@@ -213,6 +213,8 @@ class UpdateChecker:self._check_task: Optional[asyncio.Task] = Noneself._running = Falseself._upgrade_lock = asyncio.Lock() # Prevent concurrent upgrades+ self._post_update_lock = asyncio.Lock()+ self._transport_ready_event = asyncio.Event()self._cached_owner_dm_channel: Optional[str] = None # Cache DM channel ID (legacy fallback)def _lang(self) -> str:@@ -265,6 +267,11 @@ class UpdateChecker:self.state.last_activity_at = time.time()self.state.save() # save() has its own try/except, won't raise+ def notify_transport_ready(self, _platform: str) -> None:+ """Wake a deferred check when an IM transport becomes available."""+ if self._running:+ self._transport_ready_event.set()+def _reload_config(self) -> None:"""Reload UpdateConfig from config file (for hot-reload support)."""try:@@ -344,6 +351,7 @@ class UpdateChecker:await asyncio.sleep(30)while self._running:+ self._transport_ready_event.clear()try:await self._do_check()except asyncio.CancelledError:@@ -363,7 +371,10 @@ class UpdateChecker:# Even when product self-update checks are disabled, the loop stays# alive for managed local dependencies such as askill. Clamp to the# minimum so hot-reload can re-enable product checks too.- await asyncio.sleep(interval * 60)+ try:+ await asyncio.wait_for(self._transport_ready_event.wait(), timeout=interval * 60)+ except asyncio.TimeoutError:+ passasync def _do_check(self) -> None:"""Perform a single update check."""@@ -408,6 +419,21 @@ class UpdateChecker:cached=release_notifications_enabled,)if release_notifications_enabled:+ configured_admin_ids = self._get_admin_user_ids()+ admin_ids = self._active_admin_ids(configured_admin_ids)+ platform = getattr(self.controller.config, "platform", "slack")+ if admin_ids:+ waiting_for_transport = self._notification_targets_waiting_for_transport(admin_ids, platform)+ elif configured_admin_ids:+ waiting_for_transport = False+ else:+ waiting_for_transport = self._notification_targets_waiting_for_transport([], platform)+ if waiting_for_transport:+ logger.info(+ "Deferring update notification and auto-update for %s until an admin transport is ready",+ latest,+ )+ returndelivered = Falsetry:delivered = await self._send_update_notification(current, latest)@@ -595,6 +621,45 @@ class UpdateChecker:platform = scoped_platform or _infer_user_platform(raw_user_id)return self._get_im_client_for_platform(platform), raw_user_id, platform+ @staticmethod+ def _user_platform(user_id: str) -> str:+ scoped_platform, raw_user_id = _split_scoped_key(str(user_id))+ return scoped_platform or _infer_user_platform(raw_user_id)++ def _is_transport_ready(self, platform: str) -> bool:+ checker = getattr(self.controller, "is_im_transport_ready", None)+ if not callable(checker):+ return True+ try:+ return bool(checker(platform))+ except Exception as e:+ logger.warning("Failed to read %s transport readiness: %s", platform, e)+ return False++ def _admin_ids_for_platform(self, admin_ids: list, platform: str) -> list:+ return [uid for uid in admin_ids if self._user_platform(uid) == platform]++ def _active_admin_ids(self, admin_ids: Optional[list] = None) -> list:+ admin_ids = self._get_admin_user_ids() if admin_ids is None else admin_ids+ im_clients = getattr(self.controller, "im_clients", None)+ if isinstance(im_clients, dict) and im_clients:+ enabled_platforms = set(im_clients)+ else:+ enabled = getattr(getattr(self.controller, "config", None), "enabled_platforms", None)+ enabled_platforms = set(enabled()) if callable(enabled) else set()+ if not enabled_platforms:+ return admin_ids+ return [uid for uid in admin_ids if self._user_platform(uid) in enabled_platforms]++ def _notification_targets_waiting_for_transport(self, admin_ids: list, platform: str) -> bool:+ if admin_ids:+ return any(not self._is_transport_ready(self._user_platform(uid)) for uid in admin_ids)+ if platform == "discord" and not self._get_default_notification_channel_id("discord"):+ return False+ if platform in {"slack", "discord"}:+ return not self._is_transport_ready(platform)+ return False+async def _get_workspace_owner_id(self) -> Optional[str]:"""Get the Slack workspace primary owner's user ID.@@ -673,13 +738,18 @@ class UpdateChecker:async def _send_update_notification(self, current: str, latest: str) -> bool:"""Send update notification to admin users, with platform-specific fallbacks."""platform = getattr(self.controller.config, "platform", "slack")- admin_ids = self._get_admin_user_ids()+ configured_admin_ids = self._get_admin_user_ids()+ admin_ids = self._active_admin_ids(configured_admin_ids)- if admin_ids:+ if configured_admin_ids:# Send DM to each admin via the platform-agnostic send_dm method+ if not admin_ids or self._notification_targets_waiting_for_transport(admin_ids, platform):+ return Falsereturn await self._send_notification_to_admins(admin_ids, current, latest, platform)else:# Legacy fallback: no admins configured+ if self._notification_targets_waiting_for_transport([], platform):+ return Falseif platform == "slack":return await self._send_slack_notification_legacy(current, latest)elif platform == "discord":@@ -696,7 +766,8 @@ class UpdateChecker:channel_id: Optional[str] = None,message_id: Optional[str] = None,platform: Optional[str] = None,- ) -> None:+ admin_platform: Optional[str] = None,+ ) -> bool:"""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:@@ -711,30 +782,79 @@ class UpdateChecker:try:im_client = self._get_im_client_for_platform(resolved_platform)if channel_id and message_id and resolved_platform == "slack":- 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+ result = await im_client.web_client.chat_update(channel=channel_id, ts=message_id, text=failure_text)+ if self._delivery_succeeded(result):+ logger.info("Updated original message with post-update failure notification")+ return True+ return Falseif channel_id and message_id: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+ result = await im_client.edit_message(context, message_id, text=failure_text)+ if self._delivery_succeeded(result):+ logger.info("Updated %s message with post-update failure notification", resolved_platform)+ return True+ return False- admin_ids = self._get_admin_user_ids()+ configured_admin_ids = self._get_admin_user_ids()+ active_admin_ids = self._active_admin_ids(configured_admin_ids)+ admin_ids = (+ self._admin_ids_for_platform(active_admin_ids, admin_platform)+ if admin_platform+ else active_admin_ids+ )+ delivered = Falseif admin_ids:- for uid in admin_ids:- 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)- elif resolved_platform == "slack":+ delivered = bool(+ await self._send_admin_text(+ admin_ids,+ failure_text,+ log_label="post-update failure notification",+ )+ )+ elif not configured_admin_ids and 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)+ result = await im_client.web_client.chat_postMessage(channel=dm_channel, text=failure_text)+ delivered = self._delivery_succeeded(result)+ if delivered:+ logger.info("Sent post-update failure notification to %s", owner_id)+ elif not configured_admin_ids and resolved_platform == "discord":+ channel_id = self._get_default_notification_channel_id("discord")+ if channel_id:+ context = MessageContext(user_id="system", channel_id=channel_id, platform="discord")+ result = await im_client.send_message(context, failure_text)+ delivered = self._delivery_succeeded(result)+ if delivered:+ logger.info("Sent post-update failure notification to Discord channel %s", channel_id)+ return deliveredexcept Exception as e:logger.error("Failed to send post-update failure notification: %s", e)+ return False++ async def _send_admin_text(self, admin_ids: list, text: str, *, log_label: str) -> set[str]:+ delivered_platforms: set[str] = set()+ for uid in admin_ids:+ try:+ admin_client, raw_user_id, user_platform = self._get_im_client_for_user(uid)+ result = await admin_client.send_dm(raw_user_id, text)+ if self._delivery_succeeded(result):+ delivered_platforms.add(user_platform)+ logger.info("Sent %s to admin %s", log_label, uid)+ except Exception as e:+ logger.error("Failed to send %s to admin %s: %s", log_label, uid, e)+ return delivered_platforms++ @staticmethod+ def _delivery_succeeded(result: Any) -> bool:+ if result is None:+ return False+ if isinstance(result, bool):+ return result+ if isinstance(result, dict) and "ok" in result:+ return bool(result["ok"])+ return Trueasync def _send_notification_to_admins(self, admin_ids: list, current: str, latest: str, platform: str) -> bool:"""Send update notification DM to each admin user."""@@ -884,13 +1004,13 @@ class UpdateChecker:logger.error(f"Failed to send Discord update notification: {e}")return False- def _get_default_notification_channel_id(self) -> Optional[str]:+ def _get_default_notification_channel_id(self, platform: Optional[str] = None) -> Optional[str]:if not hasattr(self.controller, "settings_manager"):return Nonestore = self.controller.settings_manager.get_store()if store is None:return None- platform = getattr(self.controller.config, "platform", "slack")+ platform = platform or getattr(self.controller.config, "platform", "slack")for channel_id, settings in store.get_channels_for_platform(platform).items():if getattr(settings, "enabled", False):if platform == "discord" and not str(channel_id).isdigit():@@ -1001,8 +1121,6 @@ class UpdateChecker:) -> None:"""Write a marker file to trigger post-update notification."""try:- marker_path = paths.get_state_dir() / "pending_update_notification.json"- marker_path.parent.mkdir(parents=True, exist_ok=True)data = {"version": version,"updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),@@ -1015,17 +1133,43 @@ class UpdateChecker:data["message_id"] = message_idif platform:data["platform"] = platform-- # Atomic write- with tempfile.NamedTemporaryFile(- mode="w", dir=marker_path.parent, suffix=".tmp", delete=False, encoding="utf-8"- ) as f:- json.dump(data, f)- temp_path = Path(f.name)- temp_path.replace(marker_path)+ self._write_update_marker_payload(data)except Exception as e:logger.error(f"Failed to write update marker: {e}")+ @staticmethod+ def _write_update_marker_payload(data: dict[str, Any]) -> None:+ marker_path = paths.get_state_dir() / "pending_update_notification.json"+ marker_path.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.NamedTemporaryFile(+ mode="w", dir=marker_path.parent, suffix=".tmp", delete=False, encoding="utf-8"+ ) as f:+ json.dump(data, f)+ temp_path = Path(f.name)+ temp_path.replace(marker_path)++ def _record_post_update_admin_progress(+ self,+ *,+ marker_path: Path,+ data: dict[str, Any],+ active_platforms: set[str],+ handled_platforms: set[str],+ delivered_platforms: set[str],+ ) -> bool:+ handled_platforms.update(delivered_platforms)+ if active_platforms.issubset(handled_platforms):+ marker_path.unlink(missing_ok=True)+ return True+ if delivered_platforms:+ data["handled_admin_platforms"] = sorted(handled_platforms)+ self._write_update_marker_payload(data)+ logger.info(+ "Post-update notification is waiting for admin transport(s): %s",+ ", ".join(sorted(active_platforms - handled_platforms)),+ )+ return False+def _remove_update_marker(self) -> None:"""Remove the update marker file."""try:@@ -1034,11 +1178,15 @@ class UpdateChecker:except Exception as e:logger.warning(f"Failed to remove update marker: {e}")- async def check_and_send_post_update_notification(self) -> None:+ async def check_and_send_post_update_notification(self, *, ready_platform: Optional[str] = None) -> bool:"""Check for pending update notification and send it (called on startup)."""+ async with self._post_update_lock:+ return await self._check_and_send_post_update_notification(ready_platform=ready_platform)++ async def _check_and_send_post_update_notification(self, *, ready_platform: Optional[str] = None) -> bool:marker_path = paths.get_state_dir() / "pending_update_notification.json"if not marker_path.exists():- return+ return Falsetry:from vibe import __version__@@ -1046,6 +1194,44 @@ class UpdateChecker:data = json.loads(marker_path.read_text(encoding="utf-8"))channel_id = data.get("channel_id")message_id = data.get("message_id")+ platform = data.get("platform") or getattr(self.controller.config, "platform", "slack")+ if channel_id:+ platform = data.get("platform") or _infer_channel_platform(channel_id)+ elif ready_platform is not None:+ platform = ready_platform+ if channel_id and ready_platform is not None and ready_platform != platform:+ return False+ configured_admin_ids: list = []+ active_admin_ids: list = []+ active_admin_platforms: set[str] = set()+ handled_admin_platforms: set[str] = set()+ attempt_admin_ids: list = []+ if not channel_id:+ configured_admin_ids = self._get_admin_user_ids()+ active_admin_ids = self._active_admin_ids(configured_admin_ids)+ active_admin_platforms = {self._user_platform(uid) for uid in active_admin_ids}+ stored_handled_platforms = data.get("handled_admin_platforms", [])+ if not isinstance(stored_handled_platforms, list):+ stored_handled_platforms = []+ handled_admin_platforms = {+ str(value)+ for value in stored_handled_platforms+ if isinstance(value, str)+ } & active_admin_platforms+ pending_platforms = active_admin_platforms - handled_admin_platforms+ if ready_platform is not None:+ pending_platforms &= {ready_platform}+ else:+ pending_platforms = {+ candidate for candidate in pending_platforms if self._is_transport_ready(candidate)+ }+ attempt_admin_ids = [+ uid for uid in active_admin_ids if self._user_platform(uid) in pending_platforms+ ]+ if not configured_admin_ids:+ platform = data.get("platform") or getattr(self.controller.config, "platform", "slack")+ if ready_platform is not None and ready_platform != platform:+ return False# 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()@@ -1060,23 +1246,50 @@ class UpdateChecker:"post_update_version_mismatch",current_version=running_version or None,)- await self._send_post_update_failure_notification(+ if not channel_id and configured_admin_ids:+ failure_text = self._t(+ "update.postUpdateVersionMismatch",+ target=str(target_version),+ current=running_version or "unknown",+ )+ delivered_platforms = await self._send_admin_text(+ attempt_admin_ids,+ failure_text,+ log_label="post-update failure notification",+ )+ return self._record_post_update_admin_progress(+ marker_path=marker_path,+ data=data,+ active_platforms=active_admin_platforms,+ handled_platforms=handled_admin_platforms,+ delivered_platforms=delivered_platforms,+ )+ delivered = 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"),+ platform=platform,+ admin_platform=ready_platform if not channel_id else None,)- return+ if delivered:+ marker_path.unlink(missing_ok=True)+ elif not channel_id and not configured_admin_ids:+ no_target = platform not in {"slack", "discord"} or (+ platform == "discord" and not self._get_default_notification_channel_id("discord")+ )+ if no_target:+ logger.info("Discarding post-update marker with no viable %s notification target", platform)+ marker_path.unlink(missing_ok=True)+ return True+ return delivered- 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+ marker_path.unlink(missing_ok=True)+ return Trueim_client = self._get_im_client_for_platform(platform)success_text = self._t("update.updated", version=target_version)success_blocks = [@@ -1090,48 +1303,77 @@ class UpdateChecker:]# If we have original message coordinates, update that message+ delivered = Falseif channel_id and message_id and platform == "slack":- await im_client.web_client.chat_update(+ result = await im_client.web_client.chat_update(channel=channel_id,ts=message_id,text=success_text,blocks=success_blocks,)- logger.info("Updated original message with post-update notification")+ delivered = self._delivery_succeeded(result)+ if delivered:+ logger.info("Updated original message with post-update notification")elif channel_id and message_id:try:context = MessageContext(user_id="system", channel_id=channel_id, platform=platform)- await im_client.edit_message(context, message_id, text=success_text)- logger.info("Updated %s message with post-update notification", platform)+ result = await im_client.edit_message(context, message_id, text=success_text)+ delivered = self._delivery_succeeded(result)+ if delivered:+ logger.info("Updated %s message with post-update notification", platform)except Exception as e:logger.error("Failed to edit %s update message: %s", platform, e)+ elif configured_admin_ids:+ delivered_platforms = await self._send_admin_text(+ attempt_admin_ids,+ success_text,+ log_label="post-update notification",+ )+ return self._record_post_update_admin_progress(+ marker_path=marker_path,+ data=data,+ active_platforms=active_admin_platforms,+ handled_platforms=handled_admin_platforms,+ delivered_platforms=delivered_platforms,+ )else:- # Fallback: send a new message to admins, or workspace owner- 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, success_text)- logger.info(f"Sent post-update notification to admin {uid}")- except Exception as e:- logger.error(f"Failed to send post-update notification to admin {uid}: {e}")- elif platform == "slack":- # Legacy fallback: try workspace owner+ # Legacy fallback: try workspace owner+ if 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(+ result = await im_client.web_client.chat_postMessage(channel=dm_channel,text=success_text,blocks=success_blocks,)- logger.info(f"Sent post-update notification to {owner_id}")+ delivered = self._delivery_succeeded(result)+ if delivered:+ logger.info(f"Sent post-update notification to {owner_id}")+ elif platform == "discord":+ channel_id = self._get_default_notification_channel_id("discord")+ if not channel_id:+ logger.info("Discarding post-update marker with no viable Discord notification target")+ marker_path.unlink(missing_ok=True)+ return True+ context = MessageContext(user_id="system", channel_id=channel_id, platform="discord")+ result = await im_client.send_message(context, success_text)+ delivered = self._delivery_succeeded(result)+ if delivered:+ logger.info("Sent post-update notification to Discord channel %s", channel_id)+ else:+ logger.info("Discarding post-update marker with no viable %s notification target", platform)+ marker_path.unlink(missing_ok=True)+ return True+ if delivered:+ marker_path.unlink(missing_ok=True)+ else:+ logger.warning("Post-update notification for %s was not delivered; retaining marker", target_version)+ return deliveredexcept Exception as e:logger.error(f"Failed to send post-update notification: {e}")- finally:- marker_path.unlink(missing_ok=True)+ return Falseasync def handle_update_button_click(controller: "Controller", payload: Dict[str, Any]) -> None:diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 9b28a5794..999d1b30d 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -24,7 +24,7 @@ from modules.agents.base import AgentRequest, BaseAgentfrom .caller_context import bind_session as bind_caller_context_sessionfrom .client_manager import OpenCodeClientManagerfrom .message_processor import OpenCodeMessageProcessorMixin-from .poll_loop import OpenCodePollLoop, restored_session_key_from_poll_info+from .poll_loop import OpenCodePollLoop, restored_platform_from_poll_info, restored_session_key_from_poll_infofrom .server import OpenCodeServerManagerfrom .session import OpenCodeResumeUnavailableError, OpenCodeSessionManagerfrom .utils import resolve_opencode_model_id, resolve_opencode_reasoning_effort@@ -591,12 +591,12 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):not carry ``agent_session_id``, so we recover it from ``base_session_id``for avibe polls only — IM polls return ``None`` and get no status dot."""- if (poll_info.platform or "") != "avibe":+ if restored_platform_from_poll_info(poll_info) != "avibe":return Nonebase_session_id = poll_info.base_session_id or ""return base_session_id or None- async def restore_active_polls(self) -> int:+ async def restore_active_polls(self, platforms: set[str] | None = None) -> int:"""Restore active poll loops that were interrupted by vibe-remote restart."""active_polls = self.sessions.get_all_active_polls()@@ -608,6 +608,12 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):stale_poll_ids = []for session_id, poll_info in active_polls.items():+ poll_platform = restored_platform_from_poll_info(poll_info)+ if platforms is not None and poll_platform not in platforms:+ continue+ existing_task = self._active_requests.get(poll_info.base_session_id)+ if existing_task is not None and not existing_task.done():+ continuetry:server = await self._get_server()messages = await server.list_messages(diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 2784a7f1e..8edc3ef41 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -21,9 +21,18 @@ from .server import OpenCodeServerManagerlogger = logging.getLogger(__name__)-def restored_context_from_poll_info(poll_info) -> MessageContext:+def restored_platform_from_poll_info(poll_info) -> str:snapshot = poll_info.processing_indicator if isinstance(poll_info.processing_indicator, dict) else {}platform = str(snapshot.get("platform") or poll_info.platform or "")+ if platform:+ return platform+ session_key = str(getattr(poll_info, "session_key", "") or "").strip()+ return session_key.split("::", 1)[0] if "::" in session_key else ""+++def restored_context_from_poll_info(poll_info) -> MessageContext:+ snapshot = poll_info.processing_indicator if isinstance(poll_info.processing_indicator, dict) else {}+ platform = restored_platform_from_poll_info(poll_info)user_id = str(snapshot.get("user_id") or poll_info.user_id or "")channel_id = str(snapshot.get("channel_id") or poll_info.channel_id or "")context_token = str(snapshot.get("context_token") or getattr(poll_info, "context_token", "") or "")diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 69e9fa73c..179a432ec 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -3,6 +3,7 @@ import ioimport jsonimport loggingimport os+import threadingimport timefrom typing import Dict, Any, Optional, Callable, List@@ -37,6 +38,9 @@ from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASESlogger = logging.getLogger(__name__)+_RUNTIME_RETRY_INITIAL_SECONDS = 1.0+_RUNTIME_RETRY_MAX_SECONDS = 30.0+def _prioritize_claude_model_choices(models: List[str], current_model: Optional[str]) -> List[str]:"""Order Claude model ids so the active selection and the canonical bare@@ -70,7 +74,8 @@ class DiscordBot(BaseIMClient):intents.dm_messages = Trueintents.reactions = True- self.client = discord.Client(intents=intents)+ self._intents = intents+ self.client = self._new_client()self.formatter = DiscordFormatter()self.settings_manager = None@@ -81,9 +86,13 @@ class DiscordBot(BaseIMClient):self._recent_interaction_ids: Dict[str, float] = {}self._recent_callback_keys: Dict[str, float] = {}self._callback_dedupe_ttl_seconds = 3.0+ self._stop_event = threading.Event()- self.client.on_ready = self._on_ready_event- self.client.on_message = self._on_message_event+ def _new_client(self) -> discord.Client:+ client = discord.Client(intents=self._intents)+ client.on_ready = self._on_ready_event+ client.on_message = self._on_message_event+ return clientdef set_settings_manager(self, settings_manager):self.settings_manager = settings_manager@@ -326,38 +335,79 @@ class DiscordBot(BaseIMClient):async def _run():self._loop = asyncio.get_running_loop()- # Inject proxy connector inside the event loop (required by- # aiohttp). Must happen before login() creates the session.- from vibe.proxy import redact_proxy_url, resolve_proxy+ try:+ if self._stop_event.is_set():+ return- proxy_url = resolve_proxy(self.config.proxy_url)- if proxy_url:- try:- from aiohttp_socks import ProxyConnector+ # Inject proxy connector inside the event loop (required by+ # aiohttp). Must happen before login() creates the session.+ from vibe.proxy import redact_proxy_url, resolve_proxy- self.client.http.connector = ProxyConnector.from_url(proxy_url, rdns=True)- logger.info("Discord using proxy: %s", redact_proxy_url(proxy_url))- except ImportError:- logger.warning("Proxy configured but aiohttp_socks not installed")+ proxy_url = resolve_proxy(self.config.proxy_url)+ if proxy_url:+ try:+ from aiohttp_socks import ProxyConnector- async with self.client:- await self.client.start(self.config.bot_token)+ self.client.http.connector = ProxyConnector.from_url(proxy_url, rdns=True)+ logger.info("Discord using proxy: %s", redact_proxy_url(proxy_url))+ except ImportError:+ logger.warning("Proxy configured but aiohttp_socks not installed")- try:- asyncio.run(_run())- except KeyboardInterrupt:- return+ async with self.client:+ # stop() may race with startup before _loop is installed.+ if self._stop_event.is_set():+ return+ await self.client.start(self.config.bot_token)+ finally:+ callback = getattr(self, "on_transport_unready_callback", None)+ if callback is not None:+ try:+ await callback()+ except Exception:+ logger.exception("Discord transport-unready callback failed")+ self._loop = None++ retry_delay = _RUNTIME_RETRY_INITIAL_SECONDS+ while not self._stop_event.is_set():+ try:+ asyncio.run(_run())+ except KeyboardInterrupt:+ return+ except Exception:+ if self._stop_event.is_set():+ return+ logger.exception(+ "Discord runtime failed; retrying in %.1f seconds",+ retry_delay,+ )+ else:+ if self._stop_event.is_set():+ return+ logger.warning(+ "Discord runtime exited unexpectedly; retrying in %.1f seconds",+ retry_delay,+ )++ if self._stop_event.wait(retry_delay):+ return+ if self._stop_event.is_set():+ return+ self.client = self._new_client()+ retry_delay = min(retry_delay * 2, _RUNTIME_RETRY_MAX_SECONDS)def stop(self) -> None:+ self._stop_event.set()loop = getattr(self, "_loop", None)if loop is None or loop.is_closed():return+ client = self.clienttry:- loop.call_soon_threadsafe(lambda: loop.create_task(self.client.close()))+ loop.call_soon_threadsafe(lambda: loop.create_task(client.close()))except Exception:logger.exception("Failed to stop Discord client")async def shutdown(self) -> None:+ self._stop_event.set()loop = getattr(self, "_loop", None)current_loop = asyncio.get_running_loop()if loop is None or loop is current_loop:diff --git a/modules/im/multi.py b/modules/im/multi.pyindex 455fbc510..651702278 100644--- a/modules/im/multi.py+++ b/modules/im/multi.py@@ -14,6 +14,9 @@ from .base import BaseIMClient, InlineKeyboard, MessageContextlogger = logging.getLogger(__name__)+_RUNTIME_RETRY_INITIAL_SECONDS = 1.0+_RUNTIME_RETRY_MAX_SECONDS = 30.0+class IMClientRemovalError(RuntimeError):"""Raised when a hot-remove cannot stop a platform runtime cleanly."""@@ -34,7 +37,6 @@ class MultiIMClient(BaseIMClient):self._auxiliary_clients = auxiliary_clients or {}self.primary_platform = primary_platformself._threads: Dict[str, threading.Thread] = {}- self._run_exceptions: Dict[str, BaseException] = {}self._run_started = threading.Event()# Guards mutations of ``clients`` / ``_threads`` so the run() monitor# loop (IM worker thread) and runtime add/remove_client calls (the@@ -76,6 +78,12 @@ class MultiIMClient(BaseIMClient):with self._clients_lock:self._auxiliary_clients[platform] = client+ def is_transport_ready(self, platform: str) -> bool:+ if platform == "avibe":+ return self._run_started.is_set() and not self._stop_requested.is_set()+ with self._ready_lock:+ return platform in self._ready_platforms+def _primary_client(self) -> BaseIMClient:with self._clients_lock:client = self.clients.get(self.primary_platform)@@ -182,8 +190,13 @@ class MultiIMClient(BaseIMClient):if self._registered_callbacks is None:returnon_message, on_command, on_callback_query, kwargs = self._registered_callbacks- wrapped_kwargs = {key: self._wrap_additional_callback(platform, value) for key, value in kwargs.items()}- wrapped_kwargs["on_ready"] = self._wrap_on_ready(platform, kwargs.get("on_ready"))+ wrapped_kwargs = {+ key: self._wrap_additional_callback(platform, value)+ for key, value in kwargs.items()+ if key not in {"on_ready", "on_transport_ready", "on_transport_unready"}+ }+ wrapped_kwargs["on_ready"] = self._wrap_on_ready(platform, kwargs.get("on_transport_ready"))+ wrapped_kwargs["on_transport_unready"] = self._wrap_on_unready(platform, kwargs.get("on_transport_unready"))wrapped_commands: Optional[Dict[str, Callable]] = Noneif on_command is not None:wrapped_commands = {}@@ -237,38 +250,34 @@ class MultiIMClient(BaseIMClient):return _wrapped- def _wrap_on_ready(self, platform: str, callback: Optional[Callable]) -> Optional[Callable]:- if callback is None:- return None-+ def _wrap_on_ready(self, platform: str, callback: Optional[Callable]) -> Callable:async def _wrapped(*args: Any, **kwargs: Any):with self._ready_lock:+ should_emit = platform not in self._ready_platformsself._ready_platforms.add(platform)- if self._mark_ready_if_complete():- await callback(*args, **kwargs)+ logger.info("IM transport ready: %s", platform)+ if should_emit and callback is not None:+ await callback(platform=platform)return _wrapped- def _mark_ready_if_complete(self) -> bool:- """Return True once when all currently registered clients are ready."""+ def _mark_transport_unready(self, platform: str) -> bool:with self._ready_lock:- client_count = len(self._client_snapshot())- logger.info(- "IM runtime ready progress (%d/%d)",- len(self._ready_platforms),- client_count,- )- if client_count > 0 and not self._ready_emitted and len(self._ready_platforms) >= client_count:- self._ready_emitted = True- return True- return False+ was_ready = platform in self._ready_platforms+ self._ready_platforms.discard(platform)+ if was_ready:+ logger.info("IM transport unavailable: %s", platform)+ return was_ready- def _aggregate_ready_callback(self) -> Optional[Callable]:- if self._registered_callbacks is None:- return None- return self._registered_callbacks[3].get("on_ready")+ def _wrap_on_unready(self, platform: str, callback: Optional[Callable]) -> Callable:+ async def _wrapped(*args: Any, **kwargs: Any):+ was_ready = self._mark_transport_unready(platform)+ if was_ready and callback is not None:+ await callback(platform=platform)- def _fire_aggregate_ready_from_thread(self, callback: Callable) -> None:+ return _wrapped++ def _fire_runtime_ready_from_thread(self, callback: Callable) -> None:async def _call_ready() -> None:result = callback()if inspect.isawaitable(result):@@ -277,26 +286,17 @@ class MultiIMClient(BaseIMClient):try:asyncio.run(_call_ready())except Exception:- logger.exception("MultiIMClient aggregate on_ready callback failed")+ logger.exception("MultiIMClient runtime on_ready callback failed")- def _emit_empty_ready_once(self) -> None:+ def _emit_runtime_ready_once(self) -> None:callback = getattr(self, "on_ready_callback", None)if callback is None:returnwith self._ready_lock:- if self._ready_emitted or self.clients:+ if self._ready_emitted:returnself._ready_emitted = True-- async def _call_ready() -> None:- result = callback()- if inspect.isawaitable(result):- await result-- try:- asyncio.run(_call_ready())- except Exception:- logger.exception("MultiIMClient empty-runtime on_ready callback failed")+ self._fire_runtime_ready_from_thread(callback)@staticmethoddef _annotate_context(platform: str, context: MessageContext) -> None:@@ -443,64 +443,69 @@ class MultiIMClient(BaseIMClient):self._stop_requested.clear()with self._clients_lock:self._threads = {}- self._run_exceptions = {}for platform, client in self.clients.items():thread = threading.Thread(target=self._run_client, args=(platform, client), daemon=True)thread.start()self._threads[platform] = thread- if not self.clients:- self._emit_empty_ready_once()+ # Core services belong to the aggregate Avibe runtime, not to the+ # connectivity state of every external transport. Individual clients+ # may still be connecting or retrying after this callback fires.+ self._emit_runtime_ready_once()try:- # Idle-loop until an explicit stop. The runtime stays alive even when- # no platform threads remain — that is a valid state now: hot- # reconcile can disable every IM platform (workbench-only) or be- # mid-rebuild, and the runtime must keep running so a platform can be- # added back without restarting the service. (Previously this broke- # out when ``_threads`` emptied, which — via Controller._run_im_runtime- # calling loop.stop() — would tear the whole service down.)- while not self._stop_requested.is_set():- should_exit = False- crash_exception: BaseException | None = None+ # Platform runtimes are failure-isolated from the service lifecycle.+ # Keep the aggregate runtime alive until an explicit stop so the+ # workbench remains available and hot reconcile can replace a failed+ # or disabled platform without restarting Avibe.+ while not self._stop_requested.wait(0.5):with self._clients_lock:for platform, thread in list(self._threads.items()):if thread.is_alive():continueif platform in self._removing_platforms:continue- logger.warning("IM runtime for %s exited", platform)+ logger.warning("IM runtime for %s exited; Avibe remains available", platform)self._threads.pop(platform, None)- active_platforms = [platform for platform in self.clients if platform not in self._removing_platforms]- live_active_threads = [- platform- for platform in active_platforms- if (thread := self._threads.get(platform)) is not None and thread.is_alive()- ]- if active_platforms and not live_active_threads:- logger.error("All enabled IM runtime threads exited")- crash_exception = next(- (self._run_exceptions[platform] for platform in active_platforms if platform in self._run_exceptions),- None,- )- should_exit = True- if crash_exception is not None:- raise crash_exception- if should_exit:- break- time.sleep(0.5)finally:self.stop()for thread in list(self._threads.values()):thread.join(timeout=1.0)self._run_started.clear()+ def _client_should_run(self, platform: str, client: BaseIMClient) -> bool:+ if self._stop_requested.is_set():+ return False+ with self._clients_lock:+ return self.clients.get(platform) is client and platform not in self._removing_platforms++ def _wait_for_client_retry(self, platform: str, client: BaseIMClient, delay: float) -> bool:+ deadline = time.monotonic() + delay+ while self._client_should_run(platform, client):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return True+ if self._stop_requested.wait(min(remaining, 0.1)):+ return False+ return False+def _run_client(self, platform: str, client: BaseIMClient) -> None:- try:- client.run()- except Exception as exc:- with self._clients_lock:- self._run_exceptions[platform] = exc- logger.exception("IM runtime for %s crashed", platform)+ retry_delay = _RUNTIME_RETRY_INITIAL_SECONDS+ while self._client_should_run(platform, client):+ try:+ client.run()+ except Exception:+ logger.exception("IM runtime for %s crashed; retrying in %.1f seconds", platform, retry_delay)+ else:+ if self._client_should_run(platform, client):+ logger.warning("IM runtime for %s exited unexpectedly; retrying in %.1f seconds", platform, retry_delay)+ finally:+ self._mark_transport_unready(platform)++ if not self._client_should_run(platform, client):+ return+ if not self._wait_for_client_retry(platform, client, retry_delay):+ return+ retry_delay = min(retry_delay * 2, _RUNTIME_RETRY_MAX_SECONDS)def add_client(self, platform: str, client: BaseIMClient) -> None:"""Start one platform's client (+ its runtime thread) at runtime.@@ -514,7 +519,6 @@ class MultiIMClient(BaseIMClient):logger.warning("add_client: platform %s already present; skipping", platform)returnself._removing_platforms.discard(platform)- self._run_exceptions.pop(platform, None)self._register_client_callbacks(platform, client)self.clients[platform] = clientif self.primary_platform not in self.clients:@@ -563,12 +567,9 @@ class MultiIMClient(BaseIMClient):logger.error("%s; hot-remove failed", message)raise IMClientRemovalError(message)- ready_callback = None- emit_empty_ready = Falsewith self._clients_lock:self.clients.pop(platform, None)self._threads.pop(platform, None)- self._run_exceptions.pop(platform, None)self._removing_platforms.discard(platform)if self.clients:if self.primary_platform not in self.clients:@@ -578,19 +579,12 @@ class MultiIMClient(BaseIMClient):self.formatter = next_client.formatterelse:self._use_workbench_fallback_runtime()- emit_empty_ready = Trueexcept Exception:with self._clients_lock:self._removing_platforms.discard(platform)raisewith self._ready_lock:self._ready_platforms.discard(platform)- if emit_empty_ready:- self._emit_empty_ready_once()- elif self._mark_ready_if_complete():- ready_callback = self._aggregate_ready_callback()- if ready_callback is not None:- self._fire_aggregate_ready_from_thread(ready_callback)logger.info("Hot-removed IM platform %s", platform)return clientdiff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.pynew file mode 100644index 000000000..5db167245--- /dev/null+++ b/tests/test_controller_im_ready.py@@ -0,0 +1,62 @@+from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++from core.controller import Controller+++def test_runtime_services_start_when_post_update_notification_fails() -> None:+ controller = Controller.__new__(Controller)+ opencode_agent = SimpleNamespace(restore_active_polls=AsyncMock(return_value=0))+ controller.agent_service = SimpleNamespace(agents={"opencode": opencode_agent})+ controller.primary_platform = "discord"+ controller.update_checker = SimpleNamespace(+ check_and_send_post_update_notification=AsyncMock(side_effect=ConnectionError("transport unavailable")),+ start=Mock(),+ )+ controller.scheduled_task_service = SimpleNamespace(start=Mock(), notify_transport_ready=Mock())+ controller.watch_service = SimpleNamespace(start=Mock())+ controller.runtime_command_watcher = SimpleNamespace(start=AsyncMock())+ controller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))+ controller.cleanup_task = None++ asyncio.run(controller._on_runtime_ready())++ opencode_agent.restore_active_polls.assert_awaited_once_with({"avibe"})+ controller.update_checker.check_and_send_post_update_notification.assert_awaited_once_with(+ ready_platform="avibe"+ )+ controller.update_checker.start.assert_called_once_with()+ controller.scheduled_task_service.start.assert_called_once_with()+ controller.watch_service.start.assert_called_once_with()+ controller.runtime_command_watcher.start.assert_awaited_once_with()+++def test_transport_ready_restores_only_its_state() -> None:+ controller = Controller.__new__(Controller)+ opencode_agent = SimpleNamespace(restore_active_polls=AsyncMock(return_value=1))+ controller.agent_service = SimpleNamespace(agents={"opencode": opencode_agent})+ controller.primary_platform = "discord"+ controller.update_checker = SimpleNamespace(+ check_and_send_post_update_notification=AsyncMock(return_value=True),+ notify_transport_ready=Mock(),+ start=Mock(),+ )+ controller.scheduled_task_service = SimpleNamespace(start=Mock(), notify_transport_ready=Mock())+ controller.watch_service = SimpleNamespace(start=Mock())+ controller.runtime_command_watcher = SimpleNamespace(start=AsyncMock())++ asyncio.run(controller._on_im_ready(platform="discord"))++ opencode_agent.restore_active_polls.assert_awaited_once_with({"discord", ""})+ controller.scheduled_task_service.notify_transport_ready.assert_called_once_with("discord")+ controller.update_checker.notify_transport_ready.assert_called_once_with("discord")+ controller.update_checker.check_and_send_post_update_notification.assert_awaited_once_with(+ ready_platform="discord"+ )+ controller.update_checker.start.assert_not_called()+ controller.scheduled_task_service.start.assert_not_called()+ controller.watch_service.start.assert_not_called()+ controller.runtime_command_watcher.start.assert_not_awaited()diff --git a/tests/test_discord_runtime.py b/tests/test_discord_runtime.pynew file mode 100644index 000000000..1bf18c08c--- /dev/null+++ b/tests/test_discord_runtime.py@@ -0,0 +1,202 @@+from __future__ import annotations++import sys+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from config.v2_config import DiscordConfig+from modules.im.discord import DiscordBot+++def test_discord_runtime_retries_startup_failure_with_backoff(monkeypatch) -> None:+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))+ waits: list[float] = []+ attempts: list[FakeDiscordClient] = []+ clients: list[FakeDiscordClient] = []++ class FakeDiscordClient:+ def __init__(self) -> None:+ self.http = SimpleNamespace(connector=None)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc) -> None:+ return None++ async def start(self, _token: str) -> None:+ attempts.append(self)+ if len(attempts) < 3:+ raise ConnectionResetError("discord unavailable")+ bot._stop_event.set()++ def new_client() -> FakeDiscordClient:+ client = FakeDiscordClient()+ clients.append(client)+ return client++ monkeypatch.setattr(bot, "_new_client", new_client)+ bot.client = new_client()++ monkeypatch.setattr("vibe.proxy.resolve_proxy", lambda _configured: None)+ monkeypatch.setattr(bot._stop_event, "wait", lambda delay: waits.append(delay) or False)++ bot.run()++ assert len(attempts) == 3+ assert attempts == clients+ assert waits == [1.0, 2.0]+++def test_discord_runtime_stop_interrupts_retry_wait(monkeypatch) -> None:+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))+ new_client = Mock()++ def fake_asyncio_run(coro) -> None:+ coro.close()+ raise ConnectionResetError("discord unavailable")++ def stop_during_wait(_delay: float) -> bool:+ bot.stop()+ return bot._stop_event.is_set()++ monkeypatch.setattr("modules.im.discord.asyncio.run", fake_asyncio_run)+ monkeypatch.setattr(bot._stop_event, "wait", stop_during_wait)+ monkeypatch.setattr(bot, "_new_client", new_client)++ bot.run()++ new_client.assert_not_called()+++def test_discord_runtime_preserves_stop_requested_before_thread_start(monkeypatch) -> None:+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))+ asyncio_run = Mock(side_effect=AssertionError("stopped runtime must not start"))+ monkeypatch.setattr("modules.im.discord.asyncio.run", asyncio_run)++ bot.stop()+ bot.run()++ asyncio_run.assert_not_called()+++def test_discord_runtime_replaces_client_after_proxy_setup_failure(monkeypatch) -> None:+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))+ clients: list[FakeDiscordClient] = []+ starts: list[FakeDiscordClient] = []+ proxy_urls = iter(["socks5://bad proxy", None])++ class FakeDiscordClient:+ def __init__(self) -> None:+ self.http = SimpleNamespace(connector=None)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc) -> None:+ return None++ async def start(self, _token: str) -> None:+ starts.append(self)+ bot._stop_event.set()++ def new_client() -> FakeDiscordClient:+ client = FakeDiscordClient()+ clients.append(client)+ return client++ monkeypatch.setattr(bot, "_new_client", new_client)+ bot.client = new_client()+ monkeypatch.setattr("vibe.proxy.resolve_proxy", lambda _configured: next(proxy_urls))+ monkeypatch.setattr(+ "aiohttp_socks.ProxyConnector.from_url",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(ValueError("invalid proxy URL")),+ )+ monkeypatch.setattr(bot._stop_event, "wait", lambda _delay: False)++ bot.run()++ assert len(clients) == 2+ assert starts == [clients[1]]+++def test_discord_runtime_rechecks_stop_before_client_start(monkeypatch) -> None:+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))+ starts: list[bool] = []++ class FakeDiscordClient:+ def __init__(self) -> None:+ self.http = SimpleNamespace(connector=None)++ async def __aenter__(self):+ bot.stop()+ return self++ async def __aexit__(self, *_exc) -> None:+ return None++ async def start(self, _token: str) -> None:+ starts.append(True)++ async def close(self) -> None:+ return None++ bot.client = FakeDiscordClient()+ monkeypatch.setattr("vibe.proxy.resolve_proxy", lambda _configured: None)++ bot.run()++ assert starts == []+++def test_discord_runtime_reports_unready_before_replacing_client(monkeypatch) -> None:+ bot = DiscordBot(DiscordConfig(bot_token="test-token"))+ events: list[str] = []+ attempts = 0++ class FakeDiscordClient:+ def __init__(self, name: str) -> None:+ self.name = name+ self.http = SimpleNamespace(connector=None)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_exc) -> None:+ return None++ async def start(self, _token: str) -> None:+ nonlocal attempts+ attempts += 1+ events.append(f"start:{self.name}")+ if attempts == 1:+ raise ConnectionResetError("discord unavailable")+ bot._stop_event.set()++ async def on_transport_unready() -> None:+ events.append("unready")++ def new_client() -> FakeDiscordClient:+ client = FakeDiscordClient(f"client-{attempts + 1}")+ events.append(f"new:{client.name}")+ return client++ bot.register_callbacks(on_transport_unready=on_transport_unready)+ monkeypatch.setattr(bot, "_new_client", new_client)+ bot.client = new_client()+ monkeypatch.setattr("vibe.proxy.resolve_proxy", lambda _configured: None)+ monkeypatch.setattr(bot._stop_event, "wait", lambda _delay: False)++ bot.run()++ assert events == [+ "new:client-1",+ "start:client-1",+ "unready",+ "new:client-2",+ "start:client-2",+ "unready",+ ]diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex cf8f29e0d..b1784f84a 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -145,6 +145,24 @@ class _CrashingClient(_StubClient):raise self.exc+class _RestartOnceClient(_StubClient):+ def __init__(self, name: str, *, crash_first: bool):+ super().__init__(name, run_until_stopped=True)+ self.crash_first = crash_first+ self.run_calls = 0+ self.restarted = threading.Event()++ def run(self):+ self.run_calls += 1+ self.started.set()+ if self.run_calls == 1:+ if self.crash_first:+ raise RuntimeError(f"{self.name} failed")+ return+ self.restarted.set()+ self._stop_event.wait()++def test_multi_settings_manager_routes_scoped_keys(tmp_path):manager = MultiSettingsManager(["slack", "wechat"], settings_file=str(tmp_path / "settings.json"), primary_platform="slack"@@ -247,7 +265,7 @@ def test_multi_im_client_remove_last_client_restores_workbench_formatter():assert "Warning" in client.formatter.format_warning("heads up")-def test_multi_im_client_remove_pending_platform_completes_ready():+def test_multi_im_client_connected_transport_does_not_emit_runtime_ready():slack = _StubClient("slack")discord = _StubClient("discord")client = MultiIMClient({"slack": slack, "discord": discord}, primary_platform="slack")@@ -261,14 +279,38 @@ def test_multi_im_client_remove_pending_platform_completes_ready():assert slack.on_ready_callback is not Noneasyncio.run(slack.on_ready_callback())assert ready_calls == []+ assert client._ready_platforms == {"slack"}+ assert client.is_transport_ready("slack") is True+ assert client.is_transport_ready("discord") is Falseremoved = client.remove_client("discord")assert removed is discord- assert ready_calls == [True]+ assert ready_calls == []+++def test_multi_im_client_clears_transport_readiness_on_disconnect():+ discord = _StubClient("discord")+ client = MultiIMClient({"discord": discord}, primary_platform="discord")+ unavailable_calls: list[str] = []+ async def on_transport_unready(*, platform: str):+ unavailable_calls.append(platform)-def test_multi_im_client_remove_last_pending_platform_completes_empty_ready():+ client.register_callbacks(on_transport_unready=on_transport_unready)++ asyncio.run(discord.on_ready_callback())+ assert client.is_transport_ready("discord") is True++ asyncio.run(discord.on_transport_unready_callback())+ assert client.is_transport_ready("discord") is False+ assert unavailable_calls == ["discord"]++ asyncio.run(discord.on_transport_unready_callback())+ assert unavailable_calls == ["discord"]+++def test_multi_im_client_remove_before_runtime_start_does_not_emit_ready():slack = _StubClient("slack")client = MultiIMClient({"slack": slack}, primary_platform="slack")ready_calls: list[bool] = []@@ -281,10 +323,34 @@ def test_multi_im_client_remove_last_pending_platform_completes_empty_ready():removed = client.remove_client("slack")assert removed is slack+ assert ready_calls == []+++def test_multi_im_client_run_emits_ready_while_transports_are_unavailable():+ slack = _StubClient("slack", run_until_stopped=True)+ discord = _StubClient("discord", run_until_stopped=True)+ client = MultiIMClient({"slack": slack, "discord": discord}, primary_platform="slack")+ ready = threading.Event()+ ready_calls: list[bool] = []++ async def on_ready():+ ready_calls.append(True)+ ready.set()++ client.register_callbacks(on_ready=on_ready)+ thread = threading.Thread(target=client.run, daemon=True)+ thread.start()++ assert ready.wait(timeout=2)+ assert client._ready_platforms == set()assert ready_calls == [True]+ client.stop()+ thread.join(timeout=2)+ assert thread.is_alive() is False+-def test_multi_im_client_run_returns_when_all_enabled_threads_exit():+def test_multi_im_client_run_stays_alive_when_all_enabled_threads_exit():client = MultiIMClient({"slack": _StubClient("slack")}, primary_platform="slack")returned: list[bool] = []@@ -295,37 +361,90 @@ def test_multi_im_client_run_returns_when_all_enabled_threads_exit():thread = threading.Thread(target=_run, daemon=True)thread.start()+ assert client._run_started.wait(timeout=2)+ time.sleep(0.6)+ assert thread.is_alive() is True+ assert returned == []++ client.stop()thread.join(timeout=2)assert thread.is_alive() is Falseassert returned == [True]-def test_multi_im_client_run_raises_single_platform_runtime_crash():+def test_multi_im_client_isolates_single_platform_runtime_crash():boom = RuntimeError("slack failed")- client = MultiIMClient({"slack": _CrashingClient("slack", boom)}, primary_platform="slack")+ crashing = _CrashingClient("slack", boom)+ client = MultiIMClient({"slack": crashing}, primary_platform="slack")+ returned: list[bool] = []- try:+ def _run() -> None:client.run()- except RuntimeError as exc:- assert exc is boom- else:- raise AssertionError("MultiIMClient.run should raise the platform runtime crash")+ returned.append(True)+ thread = threading.Thread(target=_run, daemon=True)+ thread.start()++ assert crashing.started.wait(timeout=2)+ time.sleep(0.6)+ assert thread.is_alive() is True+ assert returned == []++ client.stop()+ thread.join(timeout=2)++ assert thread.is_alive() is False+ assert returned == [True]-def test_multi_im_client_run_raises_multi_platform_runtime_crash_when_all_exit():++def test_multi_im_client_restarts_exited_and_crashed_platform_runtimes(monkeypatch):+ monkeypatch.setattr("modules.im.multi._RUNTIME_RETRY_INITIAL_SECONDS", 0.01)+ for crash_first in (False, True):+ restarting = _RestartOnceClient("slack", crash_first=crash_first)+ client = MultiIMClient({"slack": restarting}, primary_platform="slack")+ thread = threading.Thread(target=client.run, daemon=True)+ thread.start()++ assert restarting.started.wait(timeout=2)+ assert restarting.restarted.wait(timeout=2)+ assert restarting.run_calls == 2+ assert client._threads["slack"].is_alive() is True++ client.stop()+ thread.join(timeout=2)++ assert thread.is_alive() is False+++def test_multi_im_client_isolates_crash_when_all_platform_threads_exit():boom = RuntimeError("discord failed")+ slack = _StubClient("slack")+ discord = _CrashingClient("discord", boom)client = MultiIMClient(- {"slack": _StubClient("slack"), "discord": _CrashingClient("discord", boom)},+ {"slack": slack, "discord": discord},primary_platform="slack",)+ returned: list[bool] = []- try:+ def _run() -> None:client.run()- except RuntimeError as exc:- assert exc is boom- else:- raise AssertionError("MultiIMClient.run should raise the captured platform runtime crash")+ returned.append(True)++ thread = threading.Thread(target=_run, daemon=True)+ thread.start()++ assert slack.started.wait(timeout=2)+ assert discord.started.wait(timeout=2)+ time.sleep(0.6)+ assert thread.is_alive() is True+ assert returned == []++ client.stop()+ thread.join(timeout=2)++ assert thread.is_alive() is False+ assert returned == [True]def test_multi_im_client_remove_client_keeps_maps_when_thread_will_not_stop():@@ -1887,31 +2006,41 @@ def test_multi_im_client_routes_dismiss_form_message_by_context_platform():assert lark.dismissed == [("lark", "om_456")]-def test_multi_im_client_on_ready_fires_only_after_all_platforms():- """on_ready callback must wait for all platform clients to be ready."""+def test_multi_im_client_transport_ready_callbacks_do_not_repeat_runtime_ready():slack = _StubClient("slack")wechat = _StubClient("wechat")client = MultiIMClient({"slack": slack, "wechat": wechat}, primary_platform="slack")ready_calls: list[bool] = []+ transport_ready_calls: list[str] = []async def _on_ready():ready_calls.append(True)- client.register_callbacks(on_message=None, on_ready=_on_ready)+ async def _on_transport_ready(*, platform: str):+ transport_ready_calls.append(platform)++ client.register_callbacks(+ on_message=None,+ on_ready=_on_ready,+ on_transport_ready=_on_transport_ready,+ )- # Simulate only Slack becoming ready — on_ready should NOT fire yetslack_on_ready = slack.on_ready_callbackassert slack_on_ready is not Noneasyncio.run(slack_on_ready())- assert ready_calls == [], "on_ready fired before all platforms were ready"+ assert ready_calls == []+ assert transport_ready_calls == ["slack"]- # Now simulate WeChat becoming ready — on_ready should fire exactly oncewechat_on_ready = wechat.on_ready_callbackassert wechat_on_ready is not Noneasyncio.run(wechat_on_ready())- assert ready_calls == [True], "on_ready should fire exactly once after all platforms are ready"+ assert ready_calls == []+ assert transport_ready_calls == ["slack", "wechat"]+ assert client._ready_platforms == {"slack", "wechat"}- # Calling again should not fire a second timeasyncio.run(wechat_on_ready())- assert len(ready_calls) == 1, "on_ready should not fire more than once"+ assert transport_ready_calls == ["slack", "wechat"]++ client._emit_runtime_ready_once()+ assert ready_calls == [True]diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pyindex 250a1582e..8ccae9f66 100644--- a/tests/test_opencode_restore_polls.py+++ b/tests/test_opencode_restore_polls.py@@ -143,6 +143,53 @@ def test_restored_im_poll_does_not_touch_agent_status():assert status_writes == []+def test_restore_active_polls_filters_for_ready_platform() -> None:+ avibe_poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-avibe")+ discord_poll = _make_poll(+ platform="slack",+ base_session_id="discord:thread",+ opencode_session_id="oc-discord",+ )+ discord_poll.processing_indicator = {"platform": "discord"}+ agent, status_writes, _, request_sessions = _build_agent(+ {"oc-avibe": avibe_poll, "oc-discord": discord_poll}+ )++ async def _run():+ restored = await agent.restore_active_polls({"discord"})+ await asyncio.sleep(0)+ for task in list(agent._active_requests.values()):+ if not task.done():+ await task+ return restored++ restored = asyncio.run(_run())++ assert restored == 1+ assert status_writes == []+ assert [entry[1] for entry in request_sessions] == ["oc-discord"]+++def test_restore_active_polls_derives_legacy_platform_from_session_key() -> None:+ poll = _make_poll(platform="", base_session_id="telegram:thread", opencode_session_id="oc-telegram")+ poll.session_key = "telegram::channel::chat-1"+ agent, status_writes, _, request_sessions = _build_agent({"oc-telegram": poll})++ async def _run():+ restored = await agent.restore_active_polls({"telegram"})+ await asyncio.sleep(0)+ for task in list(agent._active_requests.values()):+ if not task.done():+ await task+ return restored++ restored = asyncio.run(_run())++ assert restored == 1+ assert status_writes == []+ assert [entry[1] for entry in request_sessions] == ["oc-telegram"]++def test_restored_telegram_dm_poll_keeps_typed_user_session_key():poll = ActivePollInfo(opencode_session_id="oc-telegram",diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 84047d8cb..ebf14fa17 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -835,6 +835,35 @@ def test_run_task_records_scheduled_handler_error(tmp_path: Path) -> None:assert updated.enabled is False+def test_run_task_stays_queued_until_target_transport_is_ready(tmp_path: Path) -> None:+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ task = store.add_task(+ session_key="discord::channel::C123",+ prompt="send digest",+ schedule_type="at",+ run_at="2026-03-31T09:00:00+08:00",+ timezone_name="Asia/Shanghai",+ )+ request_store = TaskExecutionStore(tmp_path / "task_requests")+ controller = SimpleNamespace(+ platform_settings_managers={},+ is_im_transport_ready=lambda _platform: False,+ )+ service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)++ asyncio.run(service._run_task(task.id))+ restarted = ScheduledTaskService(controller=controller, store=store, request_store=request_store)+ asyncio.run(restarted._run_task(task.id))++ pending = request_store.list_pending()+ assert len(pending) == 1+ assert pending[0].task_id == task.id+ updated = store.get_task(task.id)+ assert updated is not None+ assert updated.last_run_at is None+ assert updated.enabled is True++def test_reconcile_jobs_skips_invalid_tasks_and_keeps_valid_jobs(tmp_path: Path) -> None:store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")valid = store.add_task(@@ -3949,6 +3978,47 @@ def test_drain_does_not_block_on_hung_execution(tmp_path: Path) -> None:asyncio.run(_exercise())+def test_drain_defers_im_runs_until_transport_ready_without_blocking_workbench(tmp_path: Path) -> None:+ async def _exercise() -> None:+ store = TaskExecutionStore(tmp_path / "reqs")+ workbench = store.enqueue_hook_send(session_key="avibe::project::proj_test", prompt="local")+ discord = store.enqueue_hook_send(session_key="discord::channel::C123", prompt="remote")+ ready_platforms = {"avibe"}+ controller = SimpleNamespace(+ platform_settings_managers={},+ is_im_transport_ready=lambda platform: platform in ready_platforms,+ )+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=store,+ )+ started: list[str] = []++ async def fake_execute(request):+ started.append(request.id)+ service.request_store.complete(request, ok=True)++ service._execute_claimed_request = fake_execute # type: ignore[assignment]++ await service._drain_requests()+ await asyncio.sleep(0)++ assert started == [workbench.id]+ assert [item.id for item in store.list_pending()] == [discord.id]++ ready_platforms.add("discord")+ service.notify_transport_ready("discord")+ assert service._drain_dirty is True+ await service._drain_requests()+ await asyncio.sleep(0)++ assert started == [workbench.id, discord.id]+ assert store.list_pending() == []++ asyncio.run(_exercise())++def test_drain_serializes_executions_per_session(tmp_path: Path) -> None:"""Two requests for the same session never run concurrently; the secondstays queued until the first finishes."""diff --git a/tests/test_update_checker_platforms.py b/tests/test_update_checker_platforms.pyindex 86cfe0284..4c641fd00 100644--- a/tests/test_update_checker_platforms.py+++ b/tests/test_update_checker_platforms.py@@ -11,7 +11,7 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from config.v2_settings import SettingsStore, UserSettings+from config.v2_settings import ChannelSettings, SettingsStore, UserSettingsfrom config.v2_config import UpdateConfigfrom core import update_checkerfrom core.update_checker import UpdateChecker@@ -34,13 +34,19 @@ class _StubController:self.config = type("Config", (), {"platform": "slack"})()self.im_client = object()self.im_clients = {}+ self.ready_platforms = None++ def is_im_transport_ready(self, platform: str) -> bool:+ return self.ready_platforms is None or platform in self.ready_platformsclass _FakeIMClient:- def __init__(self, message_id="msg-1"):+ def __init__(self, message_id="msg-1", edit_result=True):self.message_id = message_id+ self.edit_result = edit_resultself.dm_calls = []self.edit_calls = []+ self.send_calls = []async def send_dm(self, user_id: str, text: str, **kwargs):self.dm_calls.append((user_id, text, kwargs))@@ -48,7 +54,11 @@ class _FakeIMClient:async def edit_message(self, context, message_id: str, text: str, **kwargs):self.edit_calls.append((context, message_id, text, kwargs))- return True+ return self.edit_result++ async def send_message(self, context, text: str, **kwargs):+ self.send_calls.append((context, text, kwargs))+ return self.message_iddef test_get_admin_user_ids_includes_all_platforms(monkeypatch, tmp_path):@@ -199,6 +209,152 @@ def test_failed_update_notification_does_not_defer_idle_auto_update(monkeypatch,assert performed == [("1.0.1", {})]+def test_partial_admin_transport_readiness_defers_all_notifications_and_auto_update(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.set_users_for_platform(+ "discord",+ {"123456789012345678": UserSettings(display_name="Discord", is_admin=True)},+ )+ store.set_users_for_platform("slack", {"U1": UserSettings(display_name="Slack", is_admin=True)})+ store.save()++ controller = _StubController(store)+ controller.ready_platforms = {"slack"}+ discord = _FakeIMClient()+ slack = _FakeIMClient()+ controller.im_clients = {"discord": discord, "slack": slack}+ controller.im_client = slack+ checker = UpdateChecker(+ controller,+ UpdateConfig(check_interval_minutes=1, notify_admins=True, auto_update=True),+ )+ checker.state.last_activity_at = time.time() - 3600+ monkeypatch.setattr(+ update_checker,+ "_fetch_pypi_version_sync",+ lambda: {"current": "1.0.0", "latest": "1.0.1", "has_update": True, "error": None},+ )+ monkeypatch.setattr(+ update_checker,+ "_fetch_update_notification_policy_sync",+ 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):+ performed.append((target_version, kwargs))+ return {"ok": True, "restarting": False, "message": "ok"}++ monkeypatch.setattr(checker, "_perform_update", fake_perform_update)++ asyncio.run(checker._do_check())++ assert discord.dm_calls == []+ assert slack.dm_calls == []+ assert checker.state.notified_at is None+ assert performed == []++ controller.ready_platforms.add("discord")+ asyncio.run(checker._do_check())++ assert len(discord.dm_calls) == 1+ assert len(slack.dm_calls) == 1+ assert checker.state.notified_version == "1.0.1"+ assert checker.state.notified_at is not None+ assert performed == []+++def test_stale_admin_transport_does_not_block_auto_update(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.set_users_for_platform(+ "discord",+ {"123456789012345678": UserSettings(display_name="Disabled Discord", is_admin=True)},+ )+ store.save()++ controller = _StubController(store)+ controller.ready_platforms = {"slack"}+ slack = _FakeIMClient()+ controller.im_clients = {"slack": slack}+ controller.im_client = slack+ checker = UpdateChecker(+ controller,+ UpdateConfig(check_interval_minutes=1, notify_admins=True, auto_update=True),+ )+ checker.state.last_activity_at = time.time() - 3600+ monkeypatch.setattr(+ update_checker,+ "_fetch_pypi_version_sync",+ lambda: {"current": "1.0.0", "latest": "1.0.1", "has_update": True, "error": None},+ )+ monkeypatch.setattr(+ update_checker,+ "_fetch_update_notification_policy_sync",+ 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):+ performed.append((target_version, kwargs))+ return {"ok": True, "restarting": False, "message": "ok"}++ monkeypatch.setattr(checker, "_perform_update", fake_perform_update)++ asyncio.run(checker._do_check())++ assert slack.dm_calls == []+ assert performed == [("1.0.1", {})]+++def test_no_admin_discord_without_fallback_does_not_block_auto_update(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ controller = _StubController(SettingsStore.get_instance())+ controller.config.platform = "discord"+ controller.ready_platforms = set()+ controller.im_clients = {"discord": _FakeIMClient()}+ checker = UpdateChecker(+ controller,+ UpdateConfig(check_interval_minutes=1, notify_admins=True, auto_update=True),+ )+ checker.state.last_activity_at = time.time() - 3600+ monkeypatch.setattr(+ update_checker,+ "_fetch_pypi_version_sync",+ lambda: {"current": "1.0.0", "latest": "1.0.1", "has_update": True, "error": None},+ )+ monkeypatch.setattr(+ update_checker,+ "_fetch_update_notification_policy_sync",+ 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):+ performed.append((target_version, kwargs))+ return {"ok": True, "restarting": False, "message": "ok"}++ monkeypatch.setattr(checker, "_perform_update", fake_perform_update)++ asyncio.run(checker._do_check())++ assert checker.state.notified_at is None+ assert performed == [("1.0.1", {})]++def test_silent_release_metadata_skips_notifications_but_keeps_auto_update(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))SettingsStore.reset_instance()@@ -293,6 +449,43 @@ def test_update_check_reconciles_askill_even_when_product_checks_disabled(monkeyassert reconciled == [True]+def test_update_check_loop_catches_python_310_asyncio_timeout(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ checker = UpdateChecker(+ _StubController(SettingsStore.get_instance()),+ UpdateConfig(check_interval_minutes=1),+ )+ checker._running = True+ checks = []++ class LegacyAsyncioTimeout(Exception):+ pass++ async def fake_sleep(_delay):+ return None++ async def fake_do_check():+ checks.append(True)+ if len(checks) == 2:+ checker._running = False++ async def fake_wait_for(awaitable, *, timeout):+ del timeout+ awaitable.close()+ raise LegacyAsyncioTimeout++ monkeypatch.setattr(asyncio, "TimeoutError", LegacyAsyncioTimeout)+ monkeypatch.setattr(asyncio, "sleep", fake_sleep)+ monkeypatch.setattr(asyncio, "wait_for", fake_wait_for)+ monkeypatch.setattr(checker, "_do_check", fake_do_check)+ monkeypatch.setattr(checker, "_reload_config", lambda: None)++ asyncio.run(checker._check_loop())++ assert checks == [True, True]++def test_suppressed_post_update_notification_writes_verification_marker(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))SettingsStore.reset_instance()@@ -345,6 +538,192 @@ def test_post_update_notification_uses_unicode_emoji_for_non_slack(monkeypatch,assert ":white_check_mark:" not in text+def test_post_update_marker_waits_for_its_transport(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")+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="discord"))++ assert delivered is False+ assert telegram_client.edit_calls == []+ marker = tmp_path / "state" / "pending_update_notification.json"+ assert marker.exists()++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="telegram"))++ assert delivered is True+ assert telegram_client.edit_calls+ assert not marker.exists()+++def test_post_update_marker_is_retained_when_delivery_returns_none(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ controller = _StubController(SettingsStore.get_instance())+ telegram_client = _FakeIMClient(edit_result=None)+ 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)++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="telegram"))++ assert delivered is False+ assert telegram_client.edit_calls+ marker = tmp_path / "state" / "pending_update_notification.json"+ assert marker.exists()+++def test_no_channel_post_update_marker_tracks_completed_admin_platforms(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.set_users_for_platform(+ "discord",+ {"123456789012345678": UserSettings(display_name="Discord", is_admin=True)},+ )+ store.set_users_for_platform(+ "telegram",+ {"123456": UserSettings(display_name="Telegram", is_admin=True)},+ )+ store.save()++ controller = _StubController(store)+ discord = _FakeIMClient()+ telegram = _FakeIMClient()+ controller.im_clients = {"discord": discord, "telegram": telegram}+ checker = UpdateChecker(controller, UpdateConfig())+ checker._write_update_marker("1.0.1")+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="discord"))++ marker = tmp_path / "state" / "pending_update_notification.json"+ assert delivered is False+ assert len(discord.dm_calls) == 1+ assert telegram.dm_calls == []+ assert marker.exists()+ marker_data = json.loads(marker.read_text(encoding="utf-8"))+ assert marker_data["handled_admin_platforms"] == ["discord"]++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="discord"))++ assert delivered is False+ assert len(discord.dm_calls) == 1+ assert marker.exists()++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="telegram"))++ assert delivered is True+ assert len(discord.dm_calls) == 1+ assert len(telegram.dm_calls) == 1+ assert not marker.exists()+++def test_no_channel_post_update_marker_skips_disabled_admin_platforms(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.set_users_for_platform(+ "discord",+ {"123456789012345678": UserSettings(display_name="Disabled Discord", is_admin=True)},+ )+ store.save()++ controller = _StubController(store)+ slack = _FakeIMClient()+ controller.im_clients = {"slack": slack}+ checker = UpdateChecker(controller, UpdateConfig())+ checker._write_update_marker("1.0.1")+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="slack"))++ marker = tmp_path / "state" / "pending_update_notification.json"+ assert delivered is True+ assert slack.dm_calls == []+ assert not marker.exists()+++def test_no_admin_discord_post_update_marker_uses_default_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")+ store.save()++ controller = _StubController(store)+ controller.config.platform = "discord"+ discord = _FakeIMClient()+ controller.im_clients = {"discord": discord, "slack": _FakeIMClient()}+ checker = UpdateChecker(controller, UpdateConfig())+ checker._write_update_marker("1.0.1")+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="slack"))++ marker = tmp_path / "state" / "pending_update_notification.json"+ assert delivered is False+ assert discord.send_calls == []+ assert marker.exists()++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="discord"))++ assert delivered is True+ assert len(discord.send_calls) == 1+ assert discord.send_calls[0][0].channel_id == "123456789012345678"+ assert not marker.exists()+++def test_no_admin_discord_post_update_marker_clears_without_default_channel(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ SettingsStore.reset_instance()+ controller = _StubController(SettingsStore.get_instance())+ controller.config.platform = "discord"+ discord = _FakeIMClient()+ controller.im_clients = {"discord": discord}+ checker = UpdateChecker(controller, UpdateConfig())+ checker._write_update_marker("1.0.1")+ monkeypatch.setattr("vibe.__version__", "1.0.1", raising=False)++ handled = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="discord"))++ marker = tmp_path / "state" / "pending_update_notification.json"+ assert handled is True+ assert discord.send_calls == []+ assert not marker.exists()+++def test_no_admin_discord_version_mismatch_uses_default_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")+ store.save()++ controller = _StubController(store)+ controller.config.platform = "discord"+ discord = _FakeIMClient()+ controller.im_clients = {"discord": discord}+ checker = UpdateChecker(controller, UpdateConfig())+ checker._write_update_marker("1.0.1")+ monkeypatch.setattr("vibe.__version__", "1.0.0", raising=False)++ delivered = asyncio.run(checker.check_and_send_post_update_notification(ready_platform="discord"))++ marker = tmp_path / "state" / "pending_update_notification.json"+ assert delivered is True+ assert len(discord.send_calls) == 1+ assert "did not take effect" in discord.send_calls[0][1]+ assert not marker.exists()++def test_suppressed_post_update_marker_verifies_without_success_message(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))SettingsStore.reset_instance()