Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat: safe cleanup toggle and event loop conflict guard

cyhhao1bcc0a8ac8b2
diff --git a/CLAUDE.md b/CLAUDE.md
index db6e345b4..a3641b707 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9,6 +9,7 @@ This is a multi-platform remote control bot for Claude Code, supporting both Tel
## Development Commands
### Environment Setup
+
```bash
# Create virtual environment and install dependencies
python3 -m venv venv
@@ -21,6 +22,7 @@ cp .env.example .env
```
### Running the Bot
+
```bash
# Start the bot (preferred - includes process management)
./start.sh
@@ -36,6 +38,7 @@ python main.py
```
### Development Testing
+
```bash
# Test imports and basic functionality
python3 -c "from config.settings import AppConfig; from modules.im import IMFactory; print('Imports successful!')"
@@ -51,6 +54,7 @@ IM_PLATFORM=slack python main.py
## Architecture Overview
### Multi-Platform Design Pattern
+
The system uses an abstract factory pattern with platform-agnostic interfaces:
1. **BaseIMClient** (`modules/base_im_client.py`): Abstract base class defining the IM interface
@@ -65,10 +69,12 @@ The system uses an abstract factory pattern with platform-agnostic interfaces:
- **Settings Management** (`modules/settings_manager.py`): User preferences, message visibility, and session ID mappings
### Platform Implementations
+
- **TelegramBot** (`modules/telegram_bot.py`): Telegram-specific implementation with inline keyboards
- **SlackBot** (`modules/slack_bot.py`): Slack-specific implementation with thread support and Socket Mode
### Message Flow
+
1. User sends message via IM platform
2. Platform-specific client converts to `MessageContext`
3. Controller immediately sends message to Claude Code via persistent session
@@ -78,10 +84,13 @@ The system uses an abstract factory pattern with platform-agnostic interfaces:
## User Interface
### Slack Commands
+
Slack uses a simplified command structure with only one slash command:
+
- `/start` - Opens the main menu with interactive buttons
All functionality is accessed through buttons in the /start menu:
+
- **Current Dir** - Display current working directory
- **Change Work Dir** - Open modal to change working directory
- **Reset Session** - Clear conversation context and start fresh
@@ -89,7 +98,9 @@ All functionality is accessed through buttons in the /start menu:
- **How it Works** - Display help information
### Telegram Commands
+
Telegram supports traditional slash commands:
+
- `/start` - Show welcome message and available commands
- `/clear` - Reset conversation and start fresh
- `/cwd` - Show current working directory
@@ -99,11 +110,13 @@ Telegram supports traditional slash commands:
## Configuration Requirements
### Essential Environment Variables
+
- `IM_PLATFORM`: Must be "telegram" or "slack"
- Platform-specific tokens (see `.env.example`)
- `CLAUDE_CWD`: Working directory for Claude Code execution
### Platform Switching
+
The system dynamically loads the appropriate IM client based on `IM_PLATFORM`. Configuration validation ensures required tokens are present for the selected platform.
## Adding New IM Platforms
@@ -122,55 +135,69 @@ Reference `modules/slack_bot.py` for a complete implementation example.
## Thread and Session Management
### Slack Thread Handling
+
Slack conversations are automatically organized into threads. Each user message creates a thread, and all bot responses are posted as replies in that thread for better organization.
### Session Management
+
- **Telegram**: Each chat/group maintains its own Claude session
- **Slack**: Each thread maintains its own Claude session
- Sessions persist across messages for continuous conversations
- Use `/clear` or Reset Session button to start fresh
### Callback System
+
The controller registers command handlers with IM clients through a callback system, allowing platform-agnostic command handling while preserving platform-specific features (inline keyboards, thread replies, etc.).
## Deployment Notes
### Process Management
+
- `start.sh` provides daemon-style execution with PID tracking
- Logs are automatically rotated and stored in `logs/` directory
- Virtual environment detection and activation is automatic
### Error Handling
+
- Graceful degradation for missing optional tokens
- Automatic retry with exponential backoff for network failures
- Comprehensive logging for debugging platform-specific issues
### Socket Mode vs Webhooks
+
For Slack, Socket Mode is preferred as it doesn't require public endpoints. The system automatically uses Socket Mode if `SLACK_APP_TOKEN` is provided.
## Technical Implementation Details
### ClaudeSDKClient vs query()
+
The project uses `ClaudeSDKClient` for persistent bidirectional communication instead of the simpler `query()` function. This provides:
+
- Persistent WebSocket-like connections per session
- Real-time message streaming without polling
- Proper session management with resume capability
- Better error handling and reconnection support
### Session ID Mapping
+
The system captures Claude's internal `session_id` from the `SystemMessage` and maintains a mapping:
+
- **Purpose**: Allows precise session restoration after bot restarts
- **Storage**: Maps IM session IDs (chat_id/thread_id) to Claude session_ids in `user_settings.json`
- **Usage**: Uses `resume` parameter with stored session_id instead of deprecated `continue_conversation`
### Concurrent Message Handling
+
Each session has:
+
- A dedicated `ClaudeSDKClient` instance
- A persistent message receiver task running in the background
- Proper cleanup mechanisms to prevent resource leaks
### Platform-Specific Markdown Formatting
+
Different platforms have unique markdown requirements:
+
- **Telegram**: Uses MarkdownV2 with extensive character escaping
- **Slack**: Uses mrkdwn format with different escaping rules
- Formatter pattern allows clean separation of concerns
@@ -178,22 +205,33 @@ Different platforms have unique markdown requirements:
## Common Development Challenges
### Async/Await Error: "read() called while another coroutine is already waiting"
+
**Problem**: Multiple coroutines trying to read from the same ClaudeSDKClient
**Solution**: Implement a single persistent receiver per session that handles all messages
### Session Management Edge Cases
+
1. **Bot Restart**: Sessions are restored using stored session_id mappings
2. **Network Errors**: Broken sessions are cleaned up and recreated automatically
3. **User Switching Chats**: Each chat/thread maintains independent session
+### Safe Cleanup (Runtime Tasks)
+
+- Controlled by `CLEANUP_ENABLED` (default: `false`).
+- When enabled, the system only removes completed receiver tasks in-memory during message handling.
+- It will not disconnect active Claude clients and will not modify persisted session mappings in `user_settings.json`.
+- Goal: prevent task buildup without risking historical session restoration.
+
### Debugging Tips
1. **Enable Debug Logging**:
+
```python
logging.basicConfig(level=logging.DEBUG)
```
2. **Check Session State**:
+
- View active sessions in `user_settings.json`
- Monitor session creation/cleanup in logs
- Use `/cwd` command to verify session is active
@@ -206,10 +244,12 @@ Different platforms have unique markdown requirements:
### Testing Strategies
1. **Session Persistence**:
+
- Send message → Restart bot → Send follow-up message
- Verify conversation context is maintained
2. **Concurrent Users**:
+
- Test multiple users sending messages simultaneously
- Verify sessions don't interfere with each other
@@ -234,4 +274,4 @@ Different platforms have unique markdown requirements:
## Best Practices
- **Process Management**:
- - 不要直接执行杀进程来重启服务,使用./start.sh会自动杀掉对应进程并重启
\ No newline at end of file
+ - 不要直接执行杀进程来重启服务,使用./start.sh 会自动杀掉对应进程并重启
diff --git a/config/settings.py b/config/settings.py
index 879375fcd..68ca56bc8 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -10,42 +10,46 @@ logger = logging.getLogger(__name__)
@dataclass
class TelegramConfig(BaseIMConfig):
bot_token: str
- target_chat_id: Optional[Union[List[int], str]] = None # Whitelist of chat IDs. Empty list = DM only, null/None = accept all
-
+ target_chat_id: Optional[Union[List[int], str]] = (
+ None # Whitelist of chat IDs. Empty list = DM only, null/None = accept all
+ )
+
@classmethod
- def from_env(cls) -> 'TelegramConfig':
+ def from_env(cls) -> "TelegramConfig":
bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
if not bot_token:
raise ValueError("TELEGRAM_BOT_TOKEN environment variable is required")
-
+
target_chat_id = None
target_chat_id_str = os.getenv("TELEGRAM_TARGET_CHAT_ID")
if target_chat_id_str:
# Handle null string
- if target_chat_id_str.lower() in ['null', 'none']:
+ if target_chat_id_str.lower() in ["null", "none"]:
target_chat_id = None
# Handle empty list
- elif target_chat_id_str.strip() in ['[]', '']:
+ elif target_chat_id_str.strip() in ["[]", ""]:
target_chat_id = []
# Handle comma-separated list
else:
try:
# Remove brackets if present and split by comma
- ids_str = target_chat_id_str.strip('[]')
+ ids_str = target_chat_id_str.strip("[]")
if ids_str:
- target_chat_id = [int(id.strip()) for id in ids_str.split(',')]
+ target_chat_id = [int(id.strip()) for id in ids_str.split(",")]
else:
target_chat_id = []
except ValueError:
- raise ValueError(f"Invalid TELEGRAM_TARGET_CHAT_ID format: {target_chat_id_str}")
-
+ raise ValueError(
+ f"Invalid TELEGRAM_TARGET_CHAT_ID format: {target_chat_id_str}"
+ )
+
return cls(bot_token=bot_token, target_chat_id=target_chat_id)
-
+
def validate(self) -> bool:
"""Validate Telegram configuration"""
if not self.bot_token:
raise ValueError("TELEGRAM_BOT_TOKEN is required")
- if not self.bot_token.startswith(('bot', 'xox')):
+ if not self.bot_token.startswith(("bot", "xox")):
# Basic token format check
logger.warning("Telegram bot token format might be invalid")
return True
@@ -56,21 +60,21 @@ class ClaudeConfig:
permission_mode: str
cwd: str
system_prompt: Optional[str] = None
-
+
@classmethod
- def from_env(cls) -> 'ClaudeConfig':
+ def from_env(cls) -> "ClaudeConfig":
permission_mode = os.getenv("CLAUDE_PERMISSION_MODE")
if not permission_mode:
raise ValueError("CLAUDE_PERMISSION_MODE environment variable is required")
-
+
cwd = os.getenv("CLAUDE_CWD")
if not cwd:
raise ValueError("CLAUDE_CWD environment variable is required")
-
+
return cls(
permission_mode=permission_mode,
cwd=cwd,
- system_prompt=os.getenv("CLAUDE_SYSTEM_PROMPT")
+ system_prompt=os.getenv("CLAUDE_SYSTEM_PROMPT"),
)
@@ -79,52 +83,57 @@ class SlackConfig(BaseIMConfig):
bot_token: str
app_token: Optional[str] = None # For Socket Mode
signing_secret: Optional[str] = None # For webhook mode
- target_channel: Optional[Union[List[str], str]] = None # Whitelist of channel IDs. Empty list = DM only, null/None = accept all
+ target_channel: Optional[Union[List[str], str]] = (
+ None # Whitelist of channel IDs. Empty list = DM only, null/None = accept all
+ )
require_mention: bool = False # Require @mention in channels (ignored in DMs)
-
+
@classmethod
- def from_env(cls) -> 'SlackConfig':
+ def from_env(cls) -> "SlackConfig":
bot_token = os.getenv("SLACK_BOT_TOKEN")
if not bot_token:
raise ValueError("SLACK_BOT_TOKEN environment variable is required")
-
+
return cls(
bot_token=bot_token,
app_token=os.getenv("SLACK_APP_TOKEN"),
signing_secret=os.getenv("SLACK_SIGNING_SECRET"),
target_channel=cls._parse_channel_list(os.getenv("SLACK_TARGET_CHANNEL")),
- require_mention=os.getenv("SLACK_REQUIRE_MENTION", "false").lower() == "true"
+ require_mention=os.getenv("SLACK_REQUIRE_MENTION", "false").lower()
+ == "true",
)
-
+
def validate(self) -> bool:
"""Validate Slack configuration"""
if not self.bot_token:
raise ValueError("SLACK_BOT_TOKEN is required")
- if not self.bot_token.startswith('xoxb-'):
+ if not self.bot_token.startswith("xoxb-"):
raise ValueError("Invalid Slack bot token format (should start with xoxb-)")
- if self.app_token and not self.app_token.startswith('xapp-'):
+ if self.app_token and not self.app_token.startswith("xapp-"):
raise ValueError("Invalid Slack app token format (should start with xapp-)")
return True
-
+
@classmethod
- def _parse_channel_list(cls, value: Optional[str]) -> Optional[Union[List[str], str]]:
+ def _parse_channel_list(
+ cls, value: Optional[str]
+ ) -> Optional[Union[List[str], str]]:
"""Parse channel list from environment variable"""
if not value:
return None
-
+
# Handle null string
- if value.lower() in ['null', 'none']:
+ if value.lower() in ["null", "none"]:
return None
-
+
# Handle empty list
- if value.strip() in ['[]', '']:
+ if value.strip() in ["[]", ""]:
return []
-
+
# Handle comma-separated list
# Remove brackets if present and split by comma
- ids_str = value.strip('[]')
+ ids_str = value.strip("[]")
if ids_str:
- return [id.strip() for id in ids_str.split(',')]
+ return [id.strip() for id in ids_str.split(",")]
else:
return []
@@ -136,25 +145,35 @@ class AppConfig:
slack: Optional[SlackConfig] = None
claude: ClaudeConfig = None
log_level: str = "INFO"
-
+ cleanup_enabled: bool = False
+
@classmethod
- def from_env(cls) -> 'AppConfig':
+ def from_env(cls) -> "AppConfig":
platform = os.getenv("IM_PLATFORM")
if not platform:
raise ValueError("IM_PLATFORM environment variable is required")
-
+
platform = platform.lower()
if platform not in ["telegram", "slack"]:
- raise ValueError(f"Invalid IM_PLATFORM: {platform}. Must be 'telegram' or 'slack'")
-
- log_level = os.getenv("LOG_LEVEL", "INFO") # Keep default for log level as it's optional
-
+ raise ValueError(
+ f"Invalid IM_PLATFORM: {platform}. Must be 'telegram' or 'slack'"
+ )
+
+ log_level = os.getenv(
+ "LOG_LEVEL", "INFO"
+ ) # Keep default for log level as it's optional
+
+ # Cleanup toggle (safe cleanup of completed tasks only)
+ cleanup_enabled_env = os.getenv("CLEANUP_ENABLED", "false").lower()
+ cleanup_enabled = cleanup_enabled_env in ["1", "true", "yes", "on"]
+
config = cls(
platform=platform,
claude=ClaudeConfig.from_env(),
- log_level=log_level
+ log_level=log_level,
+ cleanup_enabled=cleanup_enabled,
)
-
+
# Load platform-specific config
if platform == "telegram":
config.telegram = TelegramConfig.from_env()
@@ -162,5 +181,5 @@ class AppConfig:
elif platform == "slack":
config.slack = SlackConfig.from_env()
config.slack.validate()
-
- return config
\ No newline at end of file
+
+ return config
diff --git a/core/controller.py b/core/controller.py
index b36cf60f4..e8153348c 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -14,7 +14,7 @@ from core.handlers import (
CommandHandlers,
SessionHandler,
SettingsHandler,
- MessageHandler
+ MessageHandler,
)
logger = logging.getLogger(__name__)
@@ -22,53 +22,55 @@ logger = logging.getLogger(__name__)
class Controller:
"""Main controller that coordinates all bot operations"""
-
+
def __init__(self, config: AppConfig):
"""Initialize controller with configuration"""
self.config = config
-
+
# Session tracking (must be initialized before handlers)
self.claude_sessions: Dict[str, Any] = {}
self.receiver_tasks: Dict[str, asyncio.Task] = {}
self.stored_session_mappings: Dict[str, str] = {}
-
+
# Initialize core modules
self._init_modules()
-
+
# Initialize handlers
self._init_handlers()
-
+
# Setup callbacks
self._setup_callbacks()
-
+
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
-
+
# Restore session mappings on startup (after handlers are initialized)
self.session_handler.restore_session_mappings()
-
+
def _init_modules(self):
"""Initialize core modules"""
# Create IM client with platform-specific formatter
self.im_client: BaseIMClient = IMFactory.create_client(self.config)
-
+
# Create platform-specific formatter
if self.config.platform == "telegram":
formatter = TelegramFormatter()
elif self.config.platform == "slack":
formatter = SlackFormatter()
else:
- logger.warning(f"Unknown platform: {self.config.platform}, using Telegram formatter")
+ logger.warning(
+ f"Unknown platform: {self.config.platform}, using Telegram formatter"
+ )
formatter = TelegramFormatter()
-
+
# Inject formatter into clients
self.im_client.formatter = formatter
self.claude_client = ClaudeClient(self.config.claude, formatter)
-
+
# Initialize managers
self.session_manager = SessionManager()
self.settings_manager = SettingsManager()
-
+
def _init_handlers(self):
"""Initialize all handlers with controller reference"""
# Initialize session_handler first as other handlers depend on it
@@ -76,57 +78,57 @@ class Controller:
self.command_handler = CommandHandlers(self)
self.settings_handler = SettingsHandler(self)
self.message_handler = MessageHandler(self)
-
+
# Set cross-references between handlers
self.message_handler.set_session_handler(self.session_handler)
-
+
def _setup_callbacks(self):
"""Setup callback connections between modules"""
# Create command handlers dict
command_handlers = {
- 'start': self.command_handler.handle_start,
- 'clear': self.command_handler.handle_clear,
- 'cwd': self.command_handler.handle_cwd,
- 'set_cwd': self.command_handler.handle_set_cwd,
- 'settings': self.settings_handler.handle_settings,
- 'stop': self.command_handler.handle_stop
+ "start": self.command_handler.handle_start,
+ "clear": self.command_handler.handle_clear,
+ "cwd": self.command_handler.handle_cwd,
+ "set_cwd": self.command_handler.handle_set_cwd,
+ "settings": self.settings_handler.handle_settings,
+ "stop": self.command_handler.handle_stop,
}
-
+
# Register callbacks with the IM client
self.im_client.register_callbacks(
on_message=self.message_handler.handle_user_message,
on_command=command_handlers,
on_callback_query=self.message_handler.handle_callback_query,
on_settings_update=self.handle_settings_update,
- on_change_cwd=self.handle_change_cwd_submission
+ on_change_cwd=self.handle_change_cwd_submission,
)
-
+
# Utility methods used by handlers
-
+
def get_cwd(self, context: MessageContext) -> str:
"""Get working directory based on context (channel/chat)
This is the SINGLE source of truth for CWD
"""
# Get the settings key based on context
settings_key = self._get_settings_key(context)
-
+
# Get custom CWD from settings
custom_cwd = self.settings_manager.get_custom_cwd(settings_key)
-
+
# Use custom CWD if available, otherwise use default from .env
if custom_cwd and os.path.exists(custom_cwd):
return os.path.abspath(custom_cwd)
elif custom_cwd:
logger.warning(f"Custom CWD does not exist: {custom_cwd}, using default")
-
+
# Fall back to default from .env
default_cwd = self.config.claude.cwd
if default_cwd:
return os.path.abspath(os.path.expanduser(default_cwd))
-
+
# Last resort: current directory
return os.getcwd()
-
+
def _get_settings_key(self, context: MessageContext) -> str:
"""Get settings key based on context"""
if self.config.platform == "slack":
@@ -138,7 +140,7 @@ class Controller:
return context.channel_id
return context.user_id
return context.user_id
-
+
def _get_target_context(self, context: MessageContext) -> MessageContext:
"""Get target context for sending messages"""
if self.im_client.should_use_thread_for_reply() and context.thread_id:
@@ -147,94 +149,99 @@ class Controller:
channel_id=context.channel_id,
thread_id=context.thread_id,
message_id=context.message_id,
- platform_specific=context.platform_specific
+ platform_specific=context.platform_specific,
)
return context
-
+
# Settings update handler (for Slack modal)
- async def handle_settings_update(self, user_id: str, hidden_message_types: list, channel_id: str = None):
+ async def handle_settings_update(
+ self, user_id: str, hidden_message_types: list, channel_id: str = None
+ ):
"""Handle settings update (typically from Slack modal)"""
try:
# Determine settings key - for Slack, always use channel_id
if self.config.platform == "slack":
- settings_key = channel_id if channel_id else user_id # fallback to user_id if no channel
+ settings_key = (
+ channel_id if channel_id else user_id
+ ) # fallback to user_id if no channel
else:
settings_key = channel_id if channel_id else user_id
-
+
# Update settings
user_settings = self.settings_manager.get_user_settings(settings_key)
user_settings.hidden_message_types = hidden_message_types
-
+
# Save settings - using the correct method name
self.settings_manager.update_user_settings(settings_key, user_settings)
-
- logger.info(f"Updated settings for {settings_key}: hidden types = {hidden_message_types}")
-
+
+ logger.info(
+ f"Updated settings for {settings_key}: hidden types = {hidden_message_types}"
+ )
+
# Create context for sending confirmation (without 'message' field)
context = MessageContext(
user_id=user_id,
channel_id=channel_id if channel_id else user_id,
- platform_specific={}
+ platform_specific={},
)
-
+
# Send confirmation
await self.im_client.send_message(
- context,
- "✅ Settings updated successfully!"
+ context, "✅ Settings updated successfully!"
)
-
+
except Exception as e:
logger.error(f"Error updating settings: {e}")
# Create context for error message (without 'message' field)
context = MessageContext(
user_id=user_id,
channel_id=channel_id if channel_id else user_id,
- platform_specific={}
+ platform_specific={},
)
await self.im_client.send_message(
- context,
- f"❌ Failed to update settings: {str(e)}"
+ context, f"❌ Failed to update settings: {str(e)}"
)
-
+
# Working directory change handler (for Slack modal)
- async def handle_change_cwd_submission(self, user_id: str, new_cwd: str, channel_id: str = None):
+ async def handle_change_cwd_submission(
+ self, user_id: str, new_cwd: str, channel_id: str = None
+ ):
"""Handle working directory change submission (from Slack modal) - reuse command handler logic"""
try:
# Create context for messages (without 'message' field which doesn't exist in MessageContext)
context = MessageContext(
user_id=user_id,
channel_id=channel_id if channel_id else user_id,
- platform_specific={}
+ platform_specific={},
)
-
+
# Reuse the same logic from handle_set_cwd command handler
await self.command_handler.handle_set_cwd(context, new_cwd.strip())
-
+
except Exception as e:
logger.error(f"Error changing working directory: {e}")
# Create context for error message (without 'message' field)
context = MessageContext(
user_id=user_id,
channel_id=channel_id if channel_id else user_id,
- platform_specific={}
+ platform_specific={},
)
await self.im_client.send_message(
- context,
- f"❌ Failed to change working directory: {str(e)}"
+ context, f"❌ Failed to change working directory: {str(e)}"
)
-
+
# Main run method
def run(self):
"""Run the controller"""
- logger.info(f"Starting Claude Proxy Controller with {self.config.platform} platform...")
-
- # Start cleanup task
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
-
- # Start cleanup task
- self.cleanup_task = loop.create_task(self.periodic_cleanup())
-
+ logger.info(
+ f"Starting Claude Proxy Controller with {self.config.platform} platform..."
+ )
+
+ # 不再创建额外事件循环,避免与 IM 客户端的内部事件循环冲突
+ # 清理职责改为:
+ # - 仅当收到消息且开启 cleanup_enabled 时,在消息入口清理已完成任务(见 MessageHandler)
+ # - 进程退出时做一次同步的 best-effort 取消(不跨循环 await)
+
try:
# Run the IM client (blocking)
self.im_client.run()
@@ -243,68 +250,40 @@ class Controller:
except Exception as e:
logger.error(f"Error in main run loop: {e}", exc_info=True)
finally:
- loop.run_until_complete(self.cleanup())
-
+ # Best-effort 同步清理,避免跨事件循环 await
+ self.cleanup_sync()
+
async def periodic_cleanup(self):
- """Periodically clean up inactive sessions"""
- while True:
- try:
- await asyncio.sleep(300) # Check every 5 minutes
-
- # Clean up completed receiver tasks
- completed_tasks = []
- for session_id, task in self.receiver_tasks.items():
- if task.done():
- completed_tasks.append(session_id)
-
- for session_id in completed_tasks:
- del self.receiver_tasks[session_id]
- logger.info(f"Cleaned up completed receiver task for session {session_id}")
-
- # Clean up inactive Claude sessions
- inactive_sessions = []
- current_time = asyncio.get_event_loop().time()
-
- for session_id, client in self.claude_sessions.items():
- # Check if client has been inactive (customize as needed)
- if hasattr(client, 'last_activity'):
- if current_time - client.last_activity > 1800: # 30 minutes
- inactive_sessions.append(session_id)
-
- for session_id in inactive_sessions:
- await self.session_handler.cleanup_session(session_id)
- logger.info(f"Cleaned up inactive session {session_id}")
-
- except Exception as e:
- logger.error(f"Error in periodic cleanup: {e}")
-
- async def cleanup(self):
- """Cleanup resources"""
- logger.info("Cleaning up controller resources...")
-
- # Cancel cleanup task
- if self.cleanup_task and not self.cleanup_task.done():
- self.cleanup_task.cancel()
- try:
- await self.cleanup_task
- except asyncio.CancelledError:
- pass
-
- # Cancel all receiver tasks
- for session_id, task in self.receiver_tasks.items():
- if not task.done():
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- # Cleanup all Claude sessions
- for session_id in list(self.claude_sessions.keys()):
- await self.session_handler.cleanup_session(session_id)
-
- # Stop IM client if it has a stop method
- if self.im_client and hasattr(self.im_client, 'stop'):
- await self.im_client.stop()
-
- logger.info("Controller cleanup complete")
\ No newline at end of file
+ """[Deprecated] Periodic cleanup is disabled in favor of safe on-demand cleanup"""
+ logger.info("periodic_cleanup is deprecated and not scheduled.")
+ return
+
+ def cleanup_sync(self):
+ """Best-effort synchronous cleanup without cross-loop awaits"""
+ logger.info("Cleaning up controller resources (sync, best-effort)...")
+
+ # Cancel receiver tasks without awaiting (they may belong to other loops)
+ try:
+ for session_id, task in list(self.receiver_tasks.items()):
+ if not task.done():
+ task.cancel()
+ # Remove from registry regardless
+ del self.receiver_tasks[session_id]
+ except Exception as e:
+ logger.debug(f"Receiver tasks cleanup skipped due to: {e}")
+
+ # Do not attempt to await SessionHandler cleanup here to avoid cross-loop issues.
+ # Active connections will be closed by process exit; mappings are persisted separately.
+
+ # Attempt to call stop if it's a plain function; skip if coroutine to avoid cross-loop awaits
+ try:
+ stop_attr = getattr(self.im_client, "stop", None)
+ if callable(stop_attr):
+ import inspect
+
+ if not inspect.iscoroutinefunction(stop_attr):
+ stop_attr()
+ except Exception:
+ pass
+
+ logger.info("Controller cleanup (sync) complete")
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 01d8683e3..0c4a986e7 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -5,12 +5,13 @@ import logging
import os
from typing import Optional, Dict, Any, List
from modules.im import MessageContext
+
logger = logging.getLogger(__name__)
class MessageHandler:
"""Handles message routing and Claude communication"""
-
+
def __init__(self, controller):
"""Initialize with reference to main controller"""
self.controller = controller
@@ -21,15 +22,15 @@ class MessageHandler:
self.formatter = controller.im_client.formatter
self.session_handler = None # Will be set after creation
self.receiver_tasks = controller.receiver_tasks
-
+
def set_session_handler(self, session_handler):
"""Set reference to session handler"""
self.session_handler = session_handler
-
+
def _get_settings_key(self, context: MessageContext) -> str:
"""Get settings key - delegate to controller"""
return self.controller._get_settings_key(context)
-
+
def _get_target_context(self, context: MessageContext) -> MessageContext:
"""Get target context for sending messages"""
# For Slack, use thread for replies if enabled
@@ -39,103 +40,135 @@ class MessageHandler:
channel_id=context.channel_id,
thread_id=context.thread_id,
message_id=context.message_id,
- platform_specific=context.platform_specific
+ platform_specific=context.platform_specific,
)
return context
-
+
def get_relative_path(self, abs_path: str, context: MessageContext = None) -> str:
"""Convert absolute path to relative path from working directory"""
try:
# Use unified method to get working path
cwd = self.session_handler.get_working_path(context)
-
+
# Convert input path to absolute
abs_path = os.path.abspath(os.path.expanduser(abs_path))
-
+
# Try to get relative path
rel_path = os.path.relpath(abs_path, cwd)
-
+
# If relative path goes up too many directories, use absolute
if rel_path.startswith("../.."):
return abs_path
-
+
return rel_path
except Exception:
# If any error, return original path
return abs_path
-
+
async def handle_user_message(self, context: MessageContext, message: str):
"""Process regular user messages and send to Claude"""
try:
+ # Safe cleanup: only remove completed receiver tasks when enabled
+ if getattr(self.config, "cleanup_enabled", False):
+ try:
+ completed_keys = [
+ key
+ for key, task in list(self.receiver_tasks.items())
+ if task.done()
+ ]
+ for key in completed_keys:
+ del self.receiver_tasks[key]
+ logger.info(
+ f"Safely cleaned completed receiver task for session {key}"
+ )
+ except Exception as cleanup_err:
+ logger.debug(f"Safe cleanup skipped due to error: {cleanup_err}")
+
# Check if message is a stop command in thread (for Slack)
# This handles the case where slash commands don't work in threads
- if context.thread_id and message.strip().lower() in ['stop', '/stop']:
+ if context.thread_id and message.strip().lower() in ["stop", "/stop"]:
logger.info(f"Detected stop command in thread: '{message}'")
# Delegate to the stop command handler
- if hasattr(self.controller, 'command_handler'):
+ if hasattr(self.controller, "command_handler"):
await self.controller.command_handler.handle_stop(context, "")
return
-
+
# Get or create Claude session
- base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)
+ base_session_id, working_path, composite_key = (
+ self.session_handler.get_session_info(context)
+ )
client = await self.session_handler.get_or_create_claude_session(context)
-
+
# Send immediate acknowledgment for better UX
ack_message = await self.im_client.send_message(
- context,
- "📨 Message received, processing..."
+ context, "📨 Message received, processing..."
)
-
+
# Send message to Claude
await client.query(message, session_id=composite_key)
logger.info(f"Sent message to Claude for session {composite_key}")
-
+
# Delete acknowledgment message
- if ack_message and hasattr(self.im_client, 'delete_message'):
+ if ack_message and hasattr(self.im_client, "delete_message"):
try:
await self.im_client.delete_message(context.channel_id, ack_message)
except Exception as e:
logger.debug(f"Could not delete ack message: {e}")
-
+
# Start receiver if not already running
- if composite_key not in self.receiver_tasks or self.receiver_tasks[composite_key].done():
+ if (
+ composite_key not in self.receiver_tasks
+ or self.receiver_tasks[composite_key].done()
+ ):
logger.info(f"Starting message receiver for session {composite_key}")
self.receiver_tasks[composite_key] = asyncio.create_task(
- self._receive_messages(client, base_session_id, working_path, context)
+ self._receive_messages(
+ client, base_session_id, working_path, context
+ )
)
-
+
except Exception as e:
logger.error(f"Error processing user message: {e}", exc_info=True)
_, _, composite_key = self.session_handler.get_session_info(context)
await self.session_handler.handle_session_error(composite_key, context, e)
-
- async def _receive_messages(self, client, base_session_id: str, working_path: str, context: MessageContext):
+
+ async def _receive_messages(
+ self, client, base_session_id: str, working_path: str, context: MessageContext
+ ):
"""Receive messages from Claude SDK client"""
try:
settings_key = self._get_settings_key(context)
settings = self.settings_manager.get_user_settings(settings_key)
target_context = self._get_target_context(context)
-
+
async for message in client.receive_messages():
try:
# Check for SystemMessage init to capture session_id
- if hasattr(message, "__class__") and message.__class__.__name__ == "SystemMessage":
- if hasattr(message, 'subtype') and message.subtype == 'init':
- if hasattr(message, 'data') and 'session_id' in message.data:
- claude_session_id = message.data['session_id']
+ if (
+ hasattr(message, "__class__")
+ and message.__class__.__name__ == "SystemMessage"
+ ):
+ if hasattr(message, "subtype") and message.subtype == "init":
+ if (
+ hasattr(message, "data")
+ and "session_id" in message.data
+ ):
+ claude_session_id = message.data["session_id"]
# Get correct settings key based on platform
settings_key = self._get_settings_key(context)
self.session_handler.capture_session_id(
base_session_id,
- working_path,
+ working_path,
claude_session_id,
- settings_key
+ settings_key,
)
-
+
# Skip certain messages
- if hasattr(self.controller, 'claude_client') and self.controller.claude_client._is_skip_message(message):
+ if hasattr(
+ self.controller, "claude_client"
+ ) and self.controller.claude_client._is_skip_message(message):
continue
-
+
# Determine message type by class name
message_type = None
if hasattr(message, "__class__"):
@@ -148,59 +181,71 @@ class MessageHandler:
message_type = "assistant"
elif class_name == "ResultMessage":
message_type = "result"
-
+
# Check if this message type should be hidden
- if message_type and self.settings_manager.is_message_type_hidden(settings_key, message_type):
- logger.info(f"Skipping {message_type} message for settings key {settings_key} (hidden in settings)")
+ if message_type and self.settings_manager.is_message_type_hidden(
+ settings_key, message_type
+ ):
+ logger.info(
+ f"Skipping {message_type} message for settings key {settings_key} (hidden in settings)"
+ )
continue
-
+
# Format and send message using claude_client
- if hasattr(self.controller, 'claude_client'):
- formatted_message = self.controller.claude_client.format_message(message)
+ if hasattr(self.controller, "claude_client"):
+ formatted_message = (
+ self.controller.claude_client.format_message(message)
+ )
if formatted_message and formatted_message.strip():
# Add separator line for Slack to improve message separation
if self.config.platform == "slack":
formatted_message = formatted_message + "\n---"
-
+
await self.im_client.send_message(
- target_context,
- formatted_message,
- parse_mode='markdown'
+ target_context, formatted_message, parse_mode="markdown"
)
-
+
# Check if this was a ResultMessage (query complete)
if message_type == "result":
# Mark session as not active
- session = await self.controller.session_manager.get_or_create_session(
- context.user_id,
- context.channel_id
+ session = (
+ await self.controller.session_manager.get_or_create_session(
+ context.user_id, context.channel_id
+ )
)
if session:
composite_key = f"{base_session_id}:{working_path}"
session.session_active[composite_key] = False
-
+
except Exception as e:
- logger.error(f"Error processing message from Claude: {e}", exc_info=True)
+ logger.error(
+ f"Error processing message from Claude: {e}", exc_info=True
+ )
# Continue processing other messages
continue
-
+
except Exception as e:
composite_key = f"{base_session_id}:{working_path}"
- logger.error(f"Error in message receiver for session {composite_key}: {e}", exc_info=True)
+ logger.error(
+ f"Error in message receiver for session {composite_key}: {e}",
+ exc_info=True,
+ )
await self.session_handler.handle_session_error(composite_key, context, e)
-
+
async def handle_callback_query(self, context: MessageContext, callback_data: str):
"""Route callback queries to appropriate handlers"""
try:
- logger.info(f"handle_callback_query called with data: {callback_data} for user {context.user_id}")
-
+ logger.info(
+ f"handle_callback_query called with data: {callback_data} for user {context.user_id}"
+ )
+
# Import handlers to avoid circular dependency
from .settings_handler import SettingsHandler
from .command_handlers import CommandHandlers
-
+
settings_handler = SettingsHandler(self.controller)
command_handlers = CommandHandlers(self.controller)
-
+
# Route based on callback data
if callback_data.startswith("toggle_msg_"):
# Toggle message type visibility
@@ -209,48 +254,52 @@ class MessageHandler:
elif callback_data.startswith("toggle_"):
# Legacy toggle handler (if any)
setting_type = callback_data.replace("toggle_", "")
- if hasattr(settings_handler, 'handle_toggle_setting'):
+ if hasattr(settings_handler, "handle_toggle_setting"):
await settings_handler.handle_toggle_setting(context, setting_type)
-
+
elif callback_data == "info_msg_types":
- logger.info(f"Handling info_msg_types callback for user {context.user_id}")
+ logger.info(
+ f"Handling info_msg_types callback for user {context.user_id}"
+ )
await settings_handler.handle_info_message_types(context)
-
+
elif callback_data == "info_how_it_works":
await settings_handler.handle_info_how_it_works(context)
-
+
elif callback_data == "cmd_cwd":
await command_handlers.handle_cwd(context)
-
+
elif callback_data == "cmd_change_cwd":
await command_handlers.handle_change_cwd_modal(context)
-
+
elif callback_data == "cmd_clear":
await command_handlers.handle_clear(context)
-
+
elif callback_data == "cmd_settings":
await settings_handler.handle_settings(context)
-
- elif callback_data.startswith("info_") and callback_data != "info_msg_types":
+
+ elif (
+ callback_data.startswith("info_") and callback_data != "info_msg_types"
+ ):
# Generic info handler
info_type = callback_data.replace("info_", "")
info_text = self.formatter.format_info_message(
title=f"Info: {info_type}",
emoji="ℹ️",
- footer="This feature is coming soon!"
+ footer="This feature is coming soon!",
)
await self.im_client.send_message(context, info_text)
-
+
else:
logger.warning(f"Unknown callback data: {callback_data}")
await self.im_client.send_message(
context,
- self.formatter.format_warning(f"Unknown action: {callback_data}")
+ self.formatter.format_warning(f"Unknown action: {callback_data}"),
)
-
+
except Exception as e:
logger.error(f"Error handling callback query: {e}", exc_info=True)
await self.im_client.send_message(
context,
- self.formatter.format_error(f"Error processing action: {str(e)}")
- )
\ No newline at end of file
+ self.formatter.format_error(f"Error processing action: {str(e)}"),
+ )