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(platforms): align handlers with scoped clients

cyhhao0c941cea8452
diff --git a/config/v2_config.py b/config/v2_config.py
index 18b5d70db..42545f597 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -147,7 +147,7 @@ class UpdateConfig:
auto_update: bool = True # Auto-install updates when idle
check_interval_minutes: int = 60 # How often to check for updates (0 = disable)
idle_minutes: int = 30 # Minutes of inactivity before auto-update
- notify_slack: bool = True # Send update notification when update is available
+ notify_admins: bool = True # Send update notification to admins when update is available
@dataclass
@@ -325,6 +325,9 @@ class V2Config:
update_payload = payload.get("update") or {}
if not isinstance(update_payload, dict):
raise ValueError("Config 'update' must be an object")
+ # Backward compat: rename legacy "notify_slack" → "notify_admins"
+ if "notify_slack" in update_payload and "notify_admins" not in update_payload:
+ update_payload["notify_admins"] = update_payload.pop("notify_slack")
update = UpdateConfig(**_filter_dataclass_fields(UpdateConfig, update_payload))
ack_mode = payload.get("ack_mode", "typing")
diff --git a/core/controller.py b/core/controller.py
index ad38c6025..6a5412be6 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -419,6 +419,9 @@ class Controller:
platform = context.platform or (context.platform_specific or {}).get("platform") or self.primary_platform
return self.im_clients.get(platform, self.im_clients[self.primary_platform])
+ def _get_im_client_for_platform(self, platform: str) -> BaseIMClient:
+ return self.im_clients.get(platform, self.im_clients[self.primary_platform])
+
def get_settings_manager_for_context(self, context: Optional[MessageContext] = None) -> SettingsManager:
if context is None:
return self.platform_settings_managers[self.primary_platform]
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index e57d18228..feab7d250 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -348,7 +348,9 @@ class SessionHandler(BaseHandler):
]
)
- confirmation_ts = await self.im_client.send_message(context, confirmation, parse_mode="markdown")
+ confirmation_ts = await self._get_im_client(context).send_message(
+ context, confirmation, parse_mode="markdown"
+ )
mapped_thread = target_thread or confirmation_ts
mapping_context = MessageContext(
@@ -372,7 +374,7 @@ class SessionHandler(BaseHandler):
thread_id=thread_id or None,
platform_specific={"is_dm": is_dm},
)
- await self.im_client.send_message(
+ await self._get_im_client(context).send_message(
context,
f"❌ {self._t('error.resumeSubmitFailed', error=str(e))}",
)
@@ -411,20 +413,25 @@ class SessionHandler(BaseHandler):
await self.cleanup_session(composite_key)
# Notify user and suggest retry
- await self.im_client.send_message(context, self.formatter.format_error(self._t("error.sessionReset")))
+ await self._get_im_client(context).send_message(
+ context,
+ self._get_formatter(context).format_error(self._t("error.sessionReset")),
+ )
elif "Session is broken" in error_msg or "Connection closed" in error_msg or "Connection lost" in error_msg:
logger.error(f"Session {composite_key} is broken - cleaning up")
await self.cleanup_session(composite_key)
# Notify user
- await self.im_client.send_message(
- context, self.formatter.format_error(self._t("error.sessionConnectionLost"))
+ await self._get_im_client(context).send_message(
+ context,
+ self._get_formatter(context).format_error(self._t("error.sessionConnectionLost")),
)
else:
# Generic error handling
logger.error(f"Error in session {composite_key}: {error}")
- await self.im_client.send_message(
- context, self.formatter.format_error(self._t("error.sessionGeneric", error=error_msg))
+ await self._get_im_client(context).send_message(
+ context,
+ self._get_formatter(context).format_error(self._t("error.sessionGeneric", error=error_msg)),
)
def capture_session_id(self, base_session_id: str, claude_session_id: str, settings_key: str):
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 5f34eb6b3..42badee07 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -235,6 +235,7 @@ class SettingsHandler(BaseHandler):
async def handle_toggle_message_type(self, context: MessageContext, msg_type: str):
"""Handle toggle for message type visibility"""
try:
+ im_client = self._get_im_client(context)
# Toggle message type visibility
settings_key = self._get_settings_key(context)
is_shown = self.settings_manager.toggle_show_message_type(settings_key, msg_type)
@@ -268,29 +269,29 @@ class SettingsHandler(BaseHandler):
# Update message
if context.message_id:
- await self.im_client.edit_message(context, context.message_id, keyboard=keyboard)
+ await im_client.edit_message(context, context.message_id, keyboard=keyboard)
# Answer callback (for Telegram)
display_name = display_names.get(msg_type, msg_type)
action = self._t("settings.visibilityShown") if is_shown else self._t("settings.visibilityHidden")
# Platform-specific callback answering
- await self.im_client.send_message(
+ await im_client.send_message(
context,
self._t("settings.messageTypeStatus", name=display_name, action=action),
)
except Exception as e:
logger.error(f"Error toggling message type {msg_type}: {e}")
- await self.im_client.send_message(
+ await self._get_im_client(context).send_message(
context,
- self.formatter.format_error(self._t("error.toggleSettingFailed", error=str(e))),
+ self._get_formatter(context).format_error(self._t("error.toggleSettingFailed", error=str(e))),
)
async def handle_info_message_types(self, context: MessageContext):
"""Show information about different message types"""
try:
- formatter = self.im_client.formatter
+ formatter = self._get_formatter(context)
# Use the new format_info_message method for clean, platform-agnostic formatting
info_text = formatter.format_info_message(
@@ -306,17 +307,17 @@ class SettingsHandler(BaseHandler):
)
# Send as new message
- await self.im_client.send_message(context, info_text)
+ await self._get_im_client(context).send_message(context, info_text)
logger.info(f"Sent info_msg_types message to user {context.user_id}")
except Exception as e:
logger.error(f"Error in info_msg_types handler: {e}", exc_info=True)
- await self.im_client.send_message(context, f"❌ {self._t('error.messageTypesInfoFailed')}")
+ await self._get_im_client(context).send_message(context, f"❌ {self._t('error.messageTypesInfoFailed')}")
async def handle_info_how_it_works(self, context: MessageContext):
"""Show information about how the bot works"""
try:
- formatter = self.im_client.formatter
+ formatter = self._get_formatter(context)
agent_label = self._get_agent_display_name(context)
# Use format_info_message for clean, platform-agnostic formatting
@@ -337,12 +338,12 @@ class SettingsHandler(BaseHandler):
)
# Send as new message
- await self.im_client.send_message(context, info_text)
+ await self._get_im_client(context).send_message(context, info_text)
logger.info(f"Sent how_it_works info to user {context.user_id}")
except Exception as e:
logger.error(f"Error in handle_info_how_it_works: {e}", exc_info=True)
- await self.im_client.send_message(context, f"❌ {self._t('error.helpInfoFailed')}")
+ await self._get_im_client(context).send_message(context, f"❌ {self._t('error.helpInfoFailed')}")
async def handle_routing(self, context: MessageContext):
"""Handle routing command - show agent/model selection"""
diff --git a/core/update_checker.py b/core/update_checker.py
index 93aaa3684..3370d83c1 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -14,12 +14,13 @@ import logging
import tempfile
import time
import urllib.request
-from dataclasses import dataclass
+from dataclasses import dataclass, fields
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Optional
from config import paths
from config.v2_config import UpdateConfig
+from config.v2_settings import _infer_channel_platform, _infer_user_platform, _split_scoped_key
from modules.im import MessageContext
if TYPE_CHECKING:
@@ -180,7 +181,11 @@ class UpdateChecker:
if config_path.exists():
data = json.loads(config_path.read_text(encoding="utf-8"))
update_data = data.get("update") or {}
- self.config = UpdateConfig(**update_data)
+ # Backward compat: rename legacy "notify_slack" → "notify_admins"
+ if "notify_slack" in update_data and "notify_admins" not in update_data:
+ update_data["notify_admins"] = update_data.pop("notify_slack")
+ valid = {f.name for f in fields(UpdateConfig)}
+ self.config = UpdateConfig(**{k: v for k, v in update_data.items() if k in valid})
except Exception as e:
logger.warning(f"Failed to reload update config: {e}")
@@ -233,7 +238,7 @@ class UpdateChecker:
logger.info(f"Update available: {current} -> {latest}")
# Notification flow — failure must not block auto-update
- if self.config.notify_slack and self.state.notified_version != latest:
+ if self.config.notify_admins and self.state.notified_version != latest:
try:
await self._send_update_notification(current, latest)
# Only record delivery time on success — grace period depends on this
@@ -337,13 +342,24 @@ class UpdateChecker:
logger.warning(f"Failed to get admin user IDs: {e}")
return []
+ def _get_im_client_for_platform(self, platform: str):
+ im_clients = getattr(self.controller, "im_clients", None)
+ if isinstance(im_clients, dict) and platform in im_clients:
+ return im_clients[platform]
+ return self.controller.im_client
+
+ def _get_im_client_for_user(self, user_id: str):
+ scoped_platform, raw_user_id = _split_scoped_key(str(user_id))
+ platform = scoped_platform or _infer_user_platform(raw_user_id)
+ return self._get_im_client_for_platform(platform), raw_user_id, platform
+
async def _get_workspace_owner_id(self) -> Optional[str]:
"""Get the Slack workspace primary owner's user ID.
Legacy fallback: used only when no admins are configured.
"""
try:
- im_client = self.controller.im_client
+ im_client = self._get_im_client_for_platform("slack")
if not im_client or not hasattr(im_client, "web_client"):
return None
@@ -398,7 +414,7 @@ class UpdateChecker:
return self._cached_owner_dm_channel
try:
- im_client = self.controller.im_client
+ im_client = self._get_im_client_for_platform("slack")
if not im_client or not hasattr(im_client, "web_client"):
return None
@@ -431,66 +447,47 @@ class UpdateChecker:
async def _send_notification_to_admins(self, admin_ids: list, current: str, latest: str, platform: str) -> None:
"""Send update notification DM to each admin user."""
- im_client = self.controller.im_client
- if not im_client:
- return
-
- if platform == "slack":
- text = f"Vibe Remote update available: {current} → {latest}"
- blocks = [
- {
- "type": "section",
- "text": {
- "type": "mrkdwn",
- "text": f":rocket: *Vibe Remote Update Available*\n\n"
- f"A new version is available: `{current}` → `{latest}`",
- },
- },
- {
- "type": "actions",
- "elements": [
+ for uid in admin_ids:
+ im_client, raw_user_id, user_platform = self._get_im_client_for_user(uid)
+ try:
+ if user_platform == "slack":
+ text = f"Vibe Remote update available: {current} → {latest}"
+ blocks = [
{
- "type": "button",
- "text": {"type": "plain_text", "text": "Update Now", "emoji": True},
- "style": "primary",
- "action_id": UPDATE_BUTTON_ACTION_ID,
- "value": latest,
- }
- ],
- },
- ]
- for uid in admin_ids:
- try:
- result = await im_client.send_dm(uid, text, blocks=blocks)
- if result:
- logger.info(f"Sent update notification to admin {uid}")
- else:
- logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
- except Exception as e:
- logger.error(f"Failed to send update notification to admin {uid}: {e}")
- elif platform == "discord":
- text = f"🚀 **Vibe Remote Update Available**\n\nUpdate from `{current}` → `{latest}`"
- for uid in admin_ids:
- try:
- result = await im_client.send_dm(uid, text)
- if result:
- logger.info(f"Sent update notification to admin {uid}")
- else:
- logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
- except Exception as e:
- logger.error(f"Failed to send update notification to admin {uid}: {e}")
- else:
- # Lark/Feishu
- text = f"🚀 Vibe Remote Update Available\n\nUpdate from {current} → {latest}"
- for uid in admin_ids:
- try:
- result = await im_client.send_dm(uid, text)
- if result:
- logger.info(f"Sent update notification to admin {uid}")
- else:
- logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
- except Exception as e:
- logger.error(f"Failed to send update notification to admin {uid}: {e}")
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f":rocket: *Vibe Remote Update Available*\n\n"
+ f"A new version is available: `{current}` → `{latest}`",
+ },
+ },
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Update Now", "emoji": True},
+ "style": "primary",
+ "action_id": UPDATE_BUTTON_ACTION_ID,
+ "value": latest,
+ }
+ ],
+ },
+ ]
+ result = await im_client.send_dm(raw_user_id, text, blocks=blocks)
+ elif user_platform == "discord":
+ text = f"🚀 **Vibe Remote Update Available**\n\nUpdate from `{current}` → `{latest}`"
+ result = await im_client.send_dm(raw_user_id, text)
+ else:
+ text = f"🚀 Vibe Remote Update Available\n\nUpdate from {current} → {latest}"
+ result = await im_client.send_dm(raw_user_id, text)
+
+ if result:
+ logger.info(f"Sent update notification to admin {uid}")
+ else:
+ logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
+ except Exception as e:
+ logger.error(f"Failed to send update notification to admin {uid}: {e}")
async def _send_slack_notification_legacy(self, current: str, latest: str) -> None:
"""Legacy Slack notification: send to workspace owner when no admins configured."""
@@ -506,7 +503,7 @@ class UpdateChecker:
return
try:
- im_client = self.controller.im_client
+ im_client = self._get_im_client_for_platform("slack")
blocks = [
{
"type": "section",
@@ -550,8 +547,10 @@ class UpdateChecker:
keyboard = InlineKeyboard(
buttons=[[InlineButton(text="Update Now", callback_data=f"vibe_update_now:{latest}")]]
)
- context = MessageContext(user_id="system", channel_id=channel_id)
- await self.controller.im_client.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+ context = MessageContext(user_id="system", channel_id=channel_id, platform="discord")
+ await self.controller.get_im_client_for_context(context).send_message_with_buttons(
+ context, text, keyboard, parse_mode="markdown"
+ )
logger.info("Sent update notification to Discord channel %s", channel_id)
except Exception as e:
logger.error(f"Failed to send Discord update notification: {e}")
@@ -559,12 +558,11 @@ class UpdateChecker:
def _get_default_notification_channel_id(self) -> Optional[str]:
if not hasattr(self.controller, "settings_manager"):
return None
- store = getattr(self.controller.settings_manager, "store", None)
- channels = getattr(store, "settings", None)
- if not channels or not hasattr(channels, "channels"):
+ store = self.controller.settings_manager.get_store()
+ if store is None:
return None
platform = getattr(self.controller.config, "platform", "slack")
- for channel_id, settings in channels.channels.items():
+ 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():
continue
@@ -573,7 +571,7 @@ class UpdateChecker:
async def handle_update_button_click(self, context: MessageContext, target_version: Optional[str] = None) -> None:
"""Handle update button click for Discord (non-Slack)."""
- im_client = self.controller.im_client
+ im_client = self.controller.get_im_client_for_context(context)
message_id = context.message_id
if not message_id:
await im_client.send_message(context, "Update action unavailable for this message.")
@@ -692,9 +690,10 @@ class UpdateChecker:
# Use the target version from marker (more reliable than __version__ in edge cases)
target_version = data.get("version", "unknown")
- im_client = self.controller.im_client
-
platform = getattr(self.controller.config, "platform", "slack")
+ if channel_id:
+ platform = _infer_channel_platform(channel_id)
+ im_client = self._get_im_client_for_platform(platform)
if platform == "discord":
success_text = f"✅ Vibe Remote has been updated to `{target_version}`"
else:
@@ -723,7 +722,7 @@ class UpdateChecker:
try:
from modules.im import MessageContext
- context = MessageContext(user_id="system", channel_id=channel_id)
+ context = MessageContext(user_id="system", channel_id=channel_id, platform="discord")
await im_client.edit_message(context, message_id, text=success_text)
logger.info("Updated Discord message with post-update notification")
except Exception as e:
@@ -764,7 +763,11 @@ async def handle_update_button_click(controller: "Controller", payload: Dict[str
"""
channel_id = payload.get("channel", {}).get("id")
message_id = payload.get("message", {}).get("ts")
- im_client = controller.im_client
+ im_client = (
+ controller._get_im_client_for_platform("slack")
+ if hasattr(controller, "_get_im_client_for_platform")
+ else controller.im_client
+ )
# Check if upgrade is already in progress
if hasattr(controller, "update_checker") and controller.update_checker._upgrade_lock.locked():
@@ -815,7 +818,11 @@ async def _do_update_from_button(controller: "Controller", channel_id: str, mess
return
update_checker = controller.update_checker
- im_client = controller.im_client
+ im_client = (
+ controller._get_im_client_for_platform("slack")
+ if hasattr(controller, "_get_im_client_for_platform")
+ else controller.im_client
+ )
# Check for updates
version_info = await update_checker._get_version_info_async()
diff --git a/scripts/prepare_three_regression.py b/scripts/prepare_three_regression.py
index 7eeb48afc..c0bcd4b7a 100755
--- a/scripts/prepare_three_regression.py
+++ b/scripts/prepare_three_regression.py
@@ -202,7 +202,7 @@ def _build_config_payload(service_name: str) -> dict:
"auto_update": False,
"check_interval_minutes": 0,
"idle_minutes": 30,
- "notify_slack": False,
+ "notify_admins": False,
},
"ack_mode": "reaction",
"show_duration": True,
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index 725d5ac48..8085c7e5b 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -70,7 +70,7 @@ def _full_config_payload() -> dict:
"auto_update": False,
"check_interval_minutes": 0,
"idle_minutes": 30,
- "notify_slack": False,
+ "notify_admins": False,
},
"ack_mode": "reaction",
"show_duration": True,