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
feat: Add confirmation reply when starting message processing
cyhhaoe5a6a753ba43
diff --git a/CLAUDE.md b/CLAUDE.mdindex e4ae966da..e4f0e87b0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -38,7 +38,7 @@ python main.py### Development Testing```bash# Test imports and basic functionality-python3 -c "from config.settings import AppConfig; from modules.im_factory import IMFactory; print('Imports successful!')"+python3 -c "from config.settings import AppConfig; from modules.im import IMFactory; print('Imports successful!')"# Check logs in real-timetail -f logs/bot_*.logdiff --git a/config/settings.py b/config/settings.pyindex 9e78fa5e9..fbe7af886 100644--- a/config/settings.py+++ b/config/settings.py@@ -2,7 +2,7 @@ import osimport loggingfrom dataclasses import dataclassfrom typing import Optional-from modules.base_im_config import BaseIMConfig+from modules.im.base import BaseIMConfiglogger = logging.getLogger(__name__)diff --git a/core/controller.py b/core/controller.pyindex f853a5756..4da2ee057 100644--- a/core/controller.py+++ b/core/controller.py@@ -3,8 +3,7 @@ import loggingimport osfrom typing import Optionalfrom config.settings import AppConfig-from modules.base_im_client import BaseIMClient, MessageContext, InlineKeyboard, InlineButton-from modules.im_factory import IMFactory+from modules.im import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, IMFactoryfrom modules.claude_client import ClaudeClientfrom modules.session_manager import SessionManagerfrom modules.settings_manager import SettingsManager@@ -45,7 +44,8 @@ class Controller:self.im_client.register_callbacks(on_message=self.handle_user_message,on_command=self.command_handlers,- on_callback_query=self.handle_callback_query+ on_callback_query=self.handle_callback_query,+ on_settings_update=self.handle_settings_update)async def handle_start(self, context: MessageContext, args: str = ""):@@ -131,14 +131,48 @@ Choose a command below or type any message to add it to the processing queue."""async def handle_user_message(self, context: MessageContext, message: str):"""Handle incoming user message"""try:- await self.session_manager.add_message(context.user_id, context.channel_id, message)+ # Send confirmation reply immediately+ target_context = self._get_target_context(context)++ # For Slack, establish thread with the confirmation message+ confirmation_msg = None+ if self.config.platform == "slack" and hasattr(self.im_client, 'get_or_create_thread'):+ # Create thread if needed+ thread_ts = await self.im_client.get_or_create_thread(+ target_context.channel_id,+ target_context.user_id+ )+ if thread_ts:+ target_context.thread_id = thread_ts++ # Send confirmation with thread context+ confirmation_msg = await self.im_client.send_message(+ target_context,+ f"📝 *Received:* {message}\n⏳ *Processing...*",+ parse_mode='markdown'+ )+ else:+ # For non-Slack platforms, just send confirmation+ confirmation_msg = await self.im_client.send_message(+ target_context,+ f"📝 *Received:* {message}\n⏳ *Processing...*",+ parse_mode='markdown'+ )++ # Store thread context with the message+ thread_id = getattr(target_context, 'thread_id', None)+ await self.session_manager.add_message_with_context(+ context.user_id,+ context.channel_id,+ message,+ thread_id=thread_id+ )logger.info(f"User {context.user_id} added message to queue")# Check if not already executing, then start processingif not await self.session_manager.is_executing(context.user_id):asyncio.create_task(self.process_user_queue(context))- # Don't send confirmation - user doesn't want itexcept Exception as e:logger.error(f"Error handling message: {e}")await self.im_client.send_message(context, "Error adding message to queue.")@@ -153,11 +187,14 @@ Choose a command below or type any message to add it to the processing queue."""target_context = self._get_target_context(context)while await self.session_manager.has_messages(context.user_id):- # Get next message- message = await self.session_manager.get_next_message(context.user_id)- if not message:+ # Get next message with context+ message_data = await self.session_manager.get_next_message_with_context(context.user_id)+ if not message_data:break+ message = message_data['message']+ thread_id = message_data.get('thread_id')+# Get user's CWD from settings if availablecustom_cwd = self.settings_manager.get_custom_cwd(context.user_id)if custom_cwd:@@ -173,15 +210,9 @@ Choose a command below or type any message to add it to the processing queue."""return# Send Claude's formatted output- # For Slack, we want to maintain thread context- if self.config.platform == "slack" and hasattr(self.im_client, 'get_or_create_thread'):- # Get or create thread for this conversation- thread_ts = await self.im_client.get_or_create_thread(- target_context.channel_id,- target_context.user_id- )- if thread_ts:- target_context.thread_id = thread_ts+ # Use stored thread context if available+ if thread_id:+ target_context.thread_id = thread_idawait self.im_client.send_message(target_context, claude_msg, parse_mode='markdown')@@ -369,55 +400,116 @@ Choose a command below or type any message to add it to the processing queue."""await self.im_client.send_message(context, f"Error getting queue information: {str(e)}")async def handle_settings(self, context: MessageContext, args: str = ""):- """Handle settings command - show settings menu with inline keyboard"""+ """Handle settings command - show settings menu"""try:- # Get current settings+ # For Slack, use modal dialog+ if self.config.platform == "slack":+ await self._handle_settings_slack(context)+ else:+ # For other platforms, use inline keyboard+ await self._handle_settings_traditional(context)++ except Exception as e:+ logger.error(f"Error showing settings: {e}")+ target_context = self._get_target_context(context)+ await self.im_client.send_message(+ target_context,+ f"❌ Error showing settings: {str(e)}"+ )++ async def _handle_settings_traditional(self, context: MessageContext):+ """Handle settings for non-Slack platforms (Telegram, etc)"""+ # Get current settings+ user_settings = self.settings_manager.get_user_settings(context.user_id)++ # Get available message types and display names+ message_types = self.settings_manager.get_available_message_types()+ display_names = self.settings_manager.get_message_type_display_names()++ # Create inline keyboard buttons+ buttons = []++ for msg_type in message_types:+ is_hidden = msg_type in user_settings.hidden_message_types+ checkbox = "☑️" if is_hidden else "⬜"+ display_name = display_names.get(msg_type, msg_type)+ button = InlineButton(+ text=f"{checkbox} Hide {display_name}",+ callback_data=f"toggle_msg_{msg_type}"+ )+ buttons.append([button]) # One button per row for now++ # Add info button+ buttons.append([InlineButton("ℹ️ About Message Types", callback_data="info_msg_types")])++ keyboard = InlineKeyboard(buttons=buttons)++ # Send settings message+ target_context = self._get_target_context(context)+ await self.im_client.send_message_with_buttons(+ target_context,+ "⚙️ *Settings - Message Visibility*\n\nSelect which message types to hide from Claude output:",+ keyboard,+ parse_mode='markdown'+ )++ async def _handle_settings_slack(self, context: MessageContext):+ """Handle settings for Slack using modal dialog"""+ # For slash commands or direct triggers, we might have trigger_id+ trigger_id = context.platform_specific.get('trigger_id') if context.platform_specific else None++ if trigger_id and hasattr(self.im_client, 'open_settings_modal'):+ # We have trigger_id, open modal directlyuser_settings = self.settings_manager.get_user_settings(context.user_id)-- # Get available message types and display namesmessage_types = self.settings_manager.get_available_message_types()display_names = self.settings_manager.get_message_type_display_names()- # Create inline keyboard buttons- buttons = []-- for msg_type in message_types:- is_hidden = msg_type in user_settings.hidden_message_types- checkbox = "☑️" if is_hidden else "⬜"- display_name = display_names.get(msg_type, msg_type)- button = InlineButton(- text=f"{checkbox} Hide {display_name}",- callback_data=f"toggle_msg_{msg_type}"+ try:+ await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names)+ except Exception as e:+ logger.error(f"Error opening settings modal: {e}")+ await self.im_client.send_message(context, "❌ Failed to open settings. Please try again.")+ else:+ # No trigger_id, show button to open modal+ buttons = [[+ InlineButton(+ text="🛠️ Open Settings",+ callback_data="open_settings_modal")- buttons.append([button]) # One button per row for now-- # Add info button- buttons.append([InlineButton("ℹ️ About Message Types", callback_data="info_msg_types")])+ ]]keyboard = InlineKeyboard(buttons=buttons)- # Send settings messagetarget_context = self._get_target_context(context)await self.im_client.send_message_with_buttons(target_context,- "⚙️ *Settings - Message Visibility*\n\nSelect which message types to hide from Claude output:",+ "⚙️ *Personalization Settings*\n\nConfigure how Claude Code messages appear in your Slack workspace.",keyboard,parse_mode='markdown')-- except Exception as e:- logger.error(f"Error showing settings: {e}")- target_context = self._get_target_context(context)- await self.im_client.send_message(- target_context,- f"❌ Error showing settings: {str(e)}"- )async def handle_callback_query(self, context: MessageContext, callback_data: str):"""Handle inline keyboard callbacks"""try:+ # Handle settings modal open request (Slack)+ if callback_data == "open_settings_modal" and self.config.platform == "slack":+ trigger_id = context.platform_specific.get('trigger_id') if context.platform_specific else None+ if trigger_id and hasattr(self.im_client, 'open_settings_modal'):+ user_settings = self.settings_manager.get_user_settings(context.user_id)+ message_types = self.settings_manager.get_available_message_types()+ display_names = self.settings_manager.get_message_type_display_names()++ try:+ await self.im_client.open_settings_modal(trigger_id, user_settings, message_types, display_names)+ except Exception as e:+ logger.error(f"Error opening settings modal: {e}")+ await self.im_client.send_message(context, "❌ Failed to open settings. Please try again.")+ else:+ await self.im_client.send_message(context, "❌ Unable to open settings. Please try using the /settings command.")+ return+# Handle command button clicks from /start message- if callback_data.startswith("cmd_"):+ elif callback_data.startswith("cmd_"):command = callback_data.replace("cmd_", "")logger.info(f"Executing command via button click: {command}")@@ -552,6 +644,29 @@ _Tip: All commands work in DMs, channels, and threads!_"""logger.error(f"Error handling callback query: {e}")await self.im_client.send_message(context, f"Error: {str(e)}")+ async def handle_settings_update(self, user_id: str, hidden_message_types: list):+ """Handle settings update from modal submission (Slack)"""+ try:+ # Get current settings+ user_settings = self.settings_manager.get_user_settings(user_id)++ # Update hidden message types+ user_settings.hidden_message_types = hidden_message_types++ # Save settings+ self.settings_manager.save_user_settings(user_id, user_settings)++ logger.info(f"Updated settings for user {user_id}: hidden types = {hidden_message_types}")++ # Send confirmation message (if we have a way to reach the user)+ # Note: In Slack modals, we don't have direct context to send messages+ # The modal will close automatically indicating success++ except Exception as e:+ logger.error(f"Error updating settings: {e}")+ # In modal context, errors are handled differently+ raise+async def periodic_cleanup(self):"""Periodic cleanup of inactive sessions"""while True:diff --git a/modules/base_im_config.py b/modules/base_im_config.pydeleted file mode 100644index 410d2a8d3..000000000--- a/modules/base_im_config.py+++ /dev/null@@ -1,26 +0,0 @@-from abc import ABC, abstractmethod-from dataclasses import dataclass-from typing import Optional---@dataclass-class BaseIMConfig(ABC):- """Abstract base class for IM platform configurations"""-- @classmethod- @abstractmethod- def from_env(cls) -> 'BaseIMConfig':- """Create configuration from environment variables"""- pass-- @abstractmethod- def validate(self) -> bool:- """Validate the configuration-- Returns:- True if configuration is valid-- Raises:- ValueError: If configuration is invalid- """- pass\ No newline at end of filediff --git a/modules/im/__init__.py b/modules/im/__init__.pynew file mode 100644index 000000000..53879f334--- /dev/null+++ b/modules/im/__init__.py@@ -0,0 +1,79 @@+"""IM platform abstraction package++Provides unified interface for different instant messaging platforms.++Example usage:+ from modules.im import BaseIMClient, IMFactory, MessageContext++ # Create client via factory+ client = IMFactory.create_client(config)++ # Use platform-agnostic messaging+ context = MessageContext(user_id="123", channel_id="456")+ await client.send_message(context, "Hello!")+"""++# Core abstractions+from .base import (+ BaseIMClient,+ BaseIMConfig,+ MessageContext,+ InlineButton,+ InlineKeyboard,+)++# Factory for client creation+from .factory import IMFactory++# Platform implementations are available but not imported by default+# to avoid circular import issues. Import them explicitly if needed:+# from .telegram import TelegramBot+# from .slack import SlackBot++# Package metadata+__version__ = "1.0.0"+__all__ = [+ # Core abstractions+ "BaseIMClient",+ "BaseIMConfig",+ "MessageContext",+ "InlineButton",+ "InlineKeyboard",+ # Factory+ "IMFactory",+ # Implementations available via dynamic import+ # "TelegramBot",+ # "SlackBot",+]++# Convenience function for quick client creation+def create_client(config):+ """Convenience function to create IM client++ Args:+ config: Application configuration++ Returns:+ Platform-specific IM client instance+ """+ return IMFactory.create_client(config)+++# Platform information+def get_supported_platforms():+ """Get list of supported IM platforms++ Returns:+ List of supported platform names+ """+ return IMFactory.get_supported_platforms()+++# Version info+def get_version():+ """Get package version++ Returns:+ Version string+ """+ return __version__\ No newline at end of filediff --git a/modules/base_im_client.py b/modules/im/base.pysimilarity index 62%rename from modules/base_im_client.pyrename to modules/im/base.pyindex 91f6427ca..30d9a2534 100644--- a/modules/base_im_client.py+++ b/modules/im/base.py@@ -1,8 +1,14 @@+"""Base classes and data structures for IM platform abstraction"""++import loggingfrom abc import ABC, abstractmethodfrom typing import Optional, Callable, Dict, Anyfrom dataclasses import dataclass+logger = logging.getLogger(__name__)++# Data structures for platform-agnostic messaging@dataclassclass MessageContext:"""Platform-agnostic message context"""@@ -26,11 +32,74 @@ class InlineKeyboard:buttons: list[list[InlineButton]] # 2D array for row/column layout+# Configuration base class+@dataclass+class BaseIMConfig(ABC):+ """Abstract base class for IM platform configurations"""++ @classmethod+ @abstractmethod+ def from_env(cls) -> 'BaseIMConfig':+ """Create configuration from environment variables"""+ pass++ @abstractmethod+ def validate(self) -> bool:+ """Validate the configuration++ Returns:+ True if configuration is valid++ Raises:+ ValueError: If configuration is invalid+ """+ pass++ def validate_required_string(self, value: Optional[str], field_name: str) -> None:+ """Helper method to validate required string fields++ Args:+ value: The value to validate+ field_name: Name of the field for error messages++ Raises:+ ValueError: If value is None or empty+ """+ if not value or not value.strip():+ raise ValueError(f"{field_name} is required and cannot be empty")++ def validate_optional_int(self, value: Optional[str], field_name: str) -> Optional[int]:+ """Helper method to validate and convert optional integer fields++ Args:+ value: String value to convert+ field_name: Name of the field for error messages++ Returns:+ Converted integer or None++ Raises:+ ValueError: If value is not a valid integer+ """+ if not value:+ return None++ try:+ return int(value)+ except ValueError:+ raise ValueError(f"{field_name} must be a valid integer, got: {value}")+++# IM Client base classclass BaseIMClient(ABC):"""Abstract base class for IM platform clients"""- def __init__(self, config: Any):+ def __init__(self, config: BaseIMConfig):self.config = config+ # Initialize callback storage+ self.on_message_callback: Optional[Callable] = None+ self.on_command_callbacks: Dict[str, Callable] = {}+ self.on_callback_query_callback: Optional[Callable] = None@abstractmethodasync def send_message(self, context: MessageContext, text: str,@@ -132,7 +201,6 @@ class BaseIMClient(ABC):"""pass- # Callback registration methodsdef register_callbacks(self,on_message: Optional[Callable] = None,on_command: Optional[Dict[str, Callable]] = None,@@ -152,4 +220,24 @@ class BaseIMClient(ABC):# Store any additional callbacksfor key, value in kwargs.items():- setattr(self, f"{key}_callback", value)\ No newline at end of file+ setattr(self, f"{key}_callback", value)++ def log_error(self, message: str, exception: Exception = None):+ """Standardized error logging++ Args:+ message: Error message+ exception: Optional exception to log+ """+ if exception:+ logger.error(f"{message}: {exception}")+ else:+ logger.error(message)++ def log_info(self, message: str):+ """Standardized info logging++ Args:+ message: Info message+ """+ logger.info(message)\ No newline at end of filediff --git a/modules/im_factory.py b/modules/im/factory.pysimilarity index 50%rename from modules/im_factory.pyrename to modules/im/factory.pyindex c4fa83259..629ab4cd2 100644--- a/modules/im_factory.py+++ b/modules/im/factory.py@@ -1,10 +1,13 @@+"""Factory for creating IM platform clients"""+import logging-from typing import Union+from typing import Union, TYPE_CHECKING++from .base import BaseIMClient-from .base_im_client import BaseIMClient-from .telegram_bot import TelegramBot-from .slack_bot import SlackBot-from config.settings import AppConfig, TelegramConfig, SlackConfig+# Use delayed imports to avoid circular import issues+if TYPE_CHECKING:+ from config.settings import AppConfig, TelegramConfig, SlackConfiglogger = logging.getLogger(__name__)@@ -13,7 +16,7 @@ class IMFactory:"""Factory class to create the appropriate IM client based on platform"""@staticmethod- def create_client(config: AppConfig) -> BaseIMClient:+ def create_client(config) -> BaseIMClient:"""Create and return the appropriate IM client based on configurationArgs:@@ -25,6 +28,10 @@ class IMFactory:Raises:ValueError: If platform is not supported"""+ # Dynamic imports to avoid circular dependency+ from .telegram import TelegramBot+ from .slack import SlackBot+platform = config.platform.lower()if platform == "telegram":@@ -49,4 +56,27 @@ class IMFactory:Returns:List of supported platform names"""- return ["telegram", "slack"]\ No newline at end of file+ return ["telegram", "slack"]++ @staticmethod+ def validate_platform_config(config) -> None:+ """Validate platform configuration before creating client++ Args:+ config: Application configuration++ Raises:+ ValueError: If configuration is invalid+ """+ platform = config.platform.lower()++ if platform not in IMFactory.get_supported_platforms():+ raise ValueError(f"Unsupported platform: {platform}")++ # Validate platform-specific configuration+ if platform == "telegram" and config.telegram:+ config.telegram.validate()+ elif platform == "slack" and config.slack:+ config.slack.validate()+ else:+ raise ValueError(f"Missing configuration for platform: {platform}")\ No newline at end of filediff --git a/modules/slack_bot.py b/modules/im/slack.pysimilarity index 74%rename from modules/slack_bot.pyrename to modules/im/slack.pyindex 84fb192e2..625b84989 100644--- a/modules/slack_bot.py+++ b/modules/im/slack.py@@ -7,7 +7,7 @@ from slack_sdk.socket_mode.request import SocketModeRequestfrom slack_sdk.socket_mode.response import SocketModeResponsefrom slack_sdk.errors import SlackApiError-from .base_im_client import BaseIMClient, MessageContext, InlineKeyboard, InlineButton+from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButtonfrom config.settings import SlackConfiglogger = logging.getLogger(__name__)@@ -28,6 +28,9 @@ class SlackBot(BaseIMClient):# Store callback handlersself.command_handlers: Dict[str, Callable] = {}self.slash_command_handlers: Dict[str, Callable] = {}++ # Store trigger IDs for modal interactions+ self.trigger_ids: Dict[str, str] = {}def _ensure_clients(self):"""Ensure web and socket clients are initialized"""@@ -335,7 +338,13 @@ class SlackBot(BaseIMClient):context = MessageContext(user_id=payload.get("user_id"),channel_id=payload.get("channel_id"),- platform_specific=payload+ platform_specific={+ "trigger_id": payload.get("trigger_id"),+ "response_url": payload.get("response_url"),+ "command": command,+ "text": payload.get("text"),+ "payload": payload+ })# Send immediate acknowledgment to Slack@@ -363,7 +372,7 @@ class SlackBot(BaseIMClient):)async def _handle_interactive(self, payload: Dict[str, Any]):- """Handle interactive components (buttons, etc.)"""+ """Handle interactive components (buttons, modal submissions, etc.)"""if payload.get("type") == "block_actions":# Handle button clicksuser = payload.get("user", {})@@ -388,6 +397,35 @@ class SlackBot(BaseIMClient):)await self.on_callback_query_callback(context, callback_data)++ elif payload.get("type") == "view_submission":+ # Handle modal submissions+ await self._handle_view_submission(payload)++ async def _handle_view_submission(self, payload: Dict[str, Any]):+ """Handle modal dialog submissions"""+ view = payload.get("view", {})+ callback_id = view.get("callback_id")++ if callback_id == "settings_modal":+ # Handle settings modal submission+ user_id = payload.get("user", {}).get("id")+ values = view.get("state", {}).get("values", {})++ # Extract selected hidden message types+ hidden_types_data = values.get("hidden_message_types", {}).get("hidden_types_select", {})+ selected_options = hidden_types_data.get("selected_options", [])++ # Get the values from selected options+ hidden_types = [opt.get("value") for opt in selected_options]++ # Update settings - need access to settings manager+ if hasattr(self, '_on_settings_update'):+ await self._on_settings_update(user_id, hidden_types)++ # Send success message to the user (via DM or channel)+ # We need to find the right channel to send the message+ # For now, we'll rely on the controller to handle thisdef run(self):"""Run the Slack bot"""@@ -449,6 +487,139 @@ class SlackBot(BaseIMClient):logger.error(f"Error getting channel info: {e}")raise+ async def open_settings_modal(self, trigger_id: str, user_settings: Any, message_types: list, display_names: dict):+ """Open a modal dialog for settings"""+ self._ensure_clients()++ # Create options for the multi-select menu+ options = []+ selected_options = []++ for msg_type in message_types:+ display_name = display_names.get(msg_type, msg_type)+ option = {+ "text": {+ "type": "plain_text",+ "text": display_name,+ "emoji": True+ },+ "value": msg_type,+ "description": {+ "type": "plain_text",+ "text": self._get_message_type_description(msg_type),+ "emoji": True+ }+ }+ options.append(option)++ # If this type is hidden, add THE SAME option object to selected options+ if msg_type in user_settings.hidden_message_types:+ selected_options.append(option) # Same object reference!++ logger.info(f"Creating modal with {len(options)} options, {len(selected_options)} selected")+ logger.info(f"Hidden types: {user_settings.hidden_message_types}")++ # Debug: Log the actual data being sent+ import json+ logger.info(f"Options: {json.dumps(options, indent=2)}")+ logger.info(f"Selected options: {json.dumps(selected_options, indent=2)}")++ # Create the multi-select element+ multi_select_element = {+ "type": "multi_static_select",+ "placeholder": {+ "type": "plain_text",+ "text": "Select message types to hide",+ "emoji": True+ },+ "options": options,+ "action_id": "hidden_types_select"+ }++ # Only add initial_options if there are selected options+ if selected_options:+ multi_select_element["initial_options"] = selected_options++ # Create the modal view+ view = {+ "type": "modal",+ "callback_id": "settings_modal",+ "title": {+ "type": "plain_text",+ "text": "Settings",+ "emoji": True+ },+ "submit": {+ "type": "plain_text",+ "text": "Save",+ "emoji": True+ },+ "close": {+ "type": "plain_text",+ "text": "Cancel",+ "emoji": True+ },+ "blocks": [+ {+ "type": "header",+ "text": {+ "type": "plain_text",+ "text": "Message Visibility Settings",+ "emoji": True+ }+ },+ {+ "type": "section",+ "text": {+ "type": "mrkdwn",+ "text": "Choose which message types to *hide* from Claude Code output. Hidden messages won't appear in your Slack workspace."+ }+ },+ {+ "type": "divider"+ },+ {+ "type": "input",+ "block_id": "hidden_message_types",+ "element": multi_select_element,+ "label": {+ "type": "plain_text",+ "text": "Hide these message types:",+ "emoji": True+ },+ "optional": True+ },+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": "_💡 Tip: You can show/hide message types at any time. Changes apply immediately to new messages._"+ }+ ]+ }+ ]+ }++ try:+ await self.web_client.views_open(+ trigger_id=trigger_id,+ view=view+ )+ except SlackApiError as e:+ logger.error(f"Error opening modal: {e}")+ raise++ def _get_message_type_description(self, msg_type: str) -> str:+ """Get description for a message type"""+ descriptions = {+ "system": "System initialization and status messages",+ "response": "Tool execution responses and results",+ "assistant": "Claude's messages and explanations",+ "result": "Final execution results and summaries"+ }+ return descriptions.get(msg_type, f"{msg_type} messages")+def register_callbacks(self, on_message: Optional[Callable] = None,on_command: Optional[Dict[str, Callable]] = None,on_callback_query: Optional[Callable] = None,@@ -465,6 +636,10 @@ class SlackBot(BaseIMClient):slash_commands = kwargs['on_slash_command']if isinstance(slash_commands, dict):self.slash_command_handlers.update(slash_commands)++ # Register settings update handler+ if 'on_settings_update' in kwargs:+ self._on_settings_update = kwargs['on_settings_update']async def get_or_create_thread(self, channel_id: str, user_id: str) -> Optional[str]:"""Get existing thread timestamp or return None for new thread"""diff --git a/modules/telegram_bot.py b/modules/im/telegram.pysimilarity index 99%rename from modules/telegram_bot.pyrename to modules/im/telegram.pyindex 87f5f25ac..c06bf4920 100644--- a/modules/telegram_bot.py+++ b/modules/im/telegram.py@@ -6,7 +6,7 @@ from telegram.ext import Application, CommandHandler, MessageHandler, filters, Cfrom telegram.helpers import escape_markdownfrom telegram.error import TelegramErrorfrom config.settings import TelegramConfig-from .base_im_client import BaseIMClient, MessageContext, InlineKeyboard, InlineButton+from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButtonlogger = logging.getLogger(__name__)diff --git a/modules/session_manager.py b/modules/session_manager.pyindex c4db01f50..8081d15ad 100644--- a/modules/session_manager.py+++ b/modules/session_manager.py@@ -1,34 +1,42 @@import asyncioimport loggingfrom dataclasses import dataclass, field-from typing import Dict, List, Optional+from typing import Dict, List, Optional, Union, Anyfrom datetime import datetimelogger = logging.getLogger(__name__)+@dataclass+class MessageData:+ message: str+ thread_id: Optional[str] = None+@dataclassclass UserSession:- user_id: int- chat_id: int- message_queue: List[str] = field(default_factory=list)+ user_id: Union[int, str]+ chat_id: Union[int, str]+ message_queue: List[MessageData] = field(default_factory=list)is_executing: bool = Falsecreated_at: datetime = field(default_factory=datetime.now)last_activity: datetime = field(default_factory=datetime.now)- def add_message(self, message: str):+ def add_message(self, message: str, thread_id: Optional[str] = None):"""Add message to queue"""- self.message_queue.append(message)+ self.message_queue.append(MessageData(message=message, thread_id=thread_id))self.last_activity = datetime.now()- def get_next_message(self) -> Optional[str]:+ def get_next_message(self) -> Optional[Dict[str, Any]]:"""Get and remove the next message from queue"""if self.message_queue:- message = self.message_queue.pop(0)+ message_data = self.message_queue.pop(0)self.last_activity = datetime.now()- return message+ return {+ 'message': message_data.message,+ 'thread_id': message_data.thread_id+ }return Nonedef clear_queue(self):@@ -47,7 +55,8 @@ class UserSession:if self.message_queue:status += "\n\n📋 Queued messages:"- for idx, msg in enumerate(self.message_queue, 1):+ for idx, msg_data in enumerate(self.message_queue, 1):+ msg = msg_data.messagepreview = msg[:50] + "..." if len(msg) > 50 else msgstatus += f"\n{idx}. {preview}"elif self.is_executing:@@ -60,10 +69,10 @@ class UserSession:class SessionManager:def __init__(self):- self.sessions: Dict[int, UserSession] = {}+ self.sessions: Dict[Union[int, str], UserSession] = {}self._lock = asyncio.Lock()- async def get_or_create_session(self, user_id: int, chat_id: int) -> UserSession:+ async def get_or_create_session(self, user_id: Union[int, str], chat_id: Union[int, str]) -> UserSession:"""Get existing session or create new one"""async with self._lock:if user_id not in self.sessions:@@ -72,28 +81,41 @@ class SessionManager:return self.sessions[user_id]- async def add_message(self, user_id: int, chat_id: int, message: str) -> str:+ async def add_message(self, user_id: Union[int, str], chat_id: Union[int, str], message: str) -> str:"""Add message to user's queue"""session = await self.get_or_create_session(user_id, chat_id)session.add_message(message)return f"Message added to queue. Total messages: {len(session.message_queue)}"- async def get_next_message(self, user_id: int) -> Optional[str]:- """Get next message from user's queue"""+ async def add_message_with_context(self, user_id: Union[int, str], chat_id: Union[int, str],+ message: str, thread_id: Optional[str] = None) -> str:+ """Add message with thread context to user's queue"""+ session = await self.get_or_create_session(user_id, chat_id)+ session.add_message(message, thread_id=thread_id)++ return f"Message added to queue. Total messages: {len(session.message_queue)}"++ async def get_next_message(self, user_id: Union[int, str]) -> Optional[str]:+ """Get next message from user's queue (legacy method)"""+ message_data = await self.get_next_message_with_context(user_id)+ return message_data['message'] if message_data else None++ async def get_next_message_with_context(self, user_id: Union[int, str]) -> Optional[Dict[str, Any]]:+ """Get next message with thread context from user's queue"""if user_id not in self.sessions:return Nonesession = self.sessions[user_id]return session.get_next_message()- async def has_messages(self, user_id: int) -> bool:+ async def has_messages(self, user_id: Union[int, str]) -> bool:"""Check if user has messages in queue"""if user_id not in self.sessions:return Falsereturn len(self.sessions[user_id].message_queue) > 0- async def get_queue_details(self, user_id: int) -> str:+ async def get_queue_details(self, user_id: Union[int, str]) -> str:"""Get detailed queue information for user"""if user_id not in self.sessions:return "No active session. Send a message to start."@@ -109,8 +131,9 @@ class SessionManager:queue_info = f"📋 Message Queue ({len(session.message_queue)} messages)\n"queue_info += f"Status: {'🟢 Processing' if session.is_executing else '⭕ Waiting'}\n\n"- for idx, msg in enumerate(session.message_queue, 1):+ for idx, msg_data in enumerate(session.message_queue, 1):# Show first 100 characters of each message+ msg = msg_data.messagepreview = msg[:100] + "..." if len(msg) > 100 else msg# Replace newlines with spaces for better displaypreview = preview.replace('\n', ' ').replace('\r', ' ')@@ -118,7 +141,7 @@ class SessionManager:return queue_info- async def clear_queue(self, user_id: int) -> str:+ async def clear_queue(self, user_id: Union[int, str]) -> str:"""Clear user's message queue"""if user_id not in self.sessions:return "No active session found."@@ -129,7 +152,7 @@ class SessionManager:return f"Cleared {message_count} messages from queue."- async def get_status(self, user_id: int) -> str:+ async def get_status(self, user_id: Union[int, str]) -> str:"""Get user's session status"""if user_id not in self.sessions:return "No active session. Send a message to start."@@ -137,14 +160,14 @@ class SessionManager:session = self.sessions[user_id]return session.get_status()- async def set_executing(self, user_id: int, is_executing: bool):+ async def set_executing(self, user_id: Union[int, str], is_executing: bool):"""Set execution status for user session"""if user_id in self.sessions:async with self._lock:self.sessions[user_id].is_executing = is_executingself.sessions[user_id].last_activity = datetime.now()- async def is_executing(self, user_id: int) -> bool:+ async def is_executing(self, user_id: Union[int, str]) -> bool:"""Check if user has an active execution"""if user_id not in self.sessions:return Falsediff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex fe6783517..c62602a7a 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -2,7 +2,7 @@ import jsonimport loggingimport osfrom dataclasses import dataclass, asdict, field-from typing import Dict, List, Optional+from typing import Dict, List, Optional, Unionfrom pathlib import Path@@ -30,7 +30,7 @@ class SettingsManager:def __init__(self, settings_file: str = "user_settings.json"):self.settings_file = Path(settings_file)- self.settings: Dict[int, UserSettings] = {}+ self.settings: Dict[Union[int, str], UserSettings] = {}self._load_settings()def _load_settings(self):@@ -40,7 +40,11 @@ class SettingsManager:with open(self.settings_file, 'r') as f:data = json.load(f)for user_id_str, user_data in data.items():- user_id = int(user_id_str)+ # Try to convert to int for Telegram, keep as string for Slack+ try:+ user_id = int(user_id_str)+ except ValueError:+ user_id = user_id_strself.settings[user_id] = UserSettings.from_dict(user_data)logger.info(f"Loaded settings for {len(self.settings)} users")else:@@ -62,19 +66,19 @@ class SettingsManager:except Exception as e:logger.error(f"Error saving settings: {e}")- def get_user_settings(self, user_id: int) -> UserSettings:+ def get_user_settings(self, user_id: Union[int, str]) -> UserSettings:"""Get settings for a specific user"""if user_id not in self.settings:self.settings[user_id] = UserSettings()self._save_settings()return self.settings[user_id]- def update_user_settings(self, user_id: int, settings: UserSettings):+ def update_user_settings(self, user_id: Union[int, str], settings: UserSettings):"""Update settings for a specific user"""self.settings[user_id] = settingsself._save_settings()- def toggle_hidden_message_type(self, user_id: int, message_type: str) -> bool:+ def toggle_hidden_message_type(self, user_id: Union[int, str], message_type: str) -> bool:"""Toggle a message type in hidden list, returns new state"""settings = self.get_user_settings(user_id)