Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix: Unify and simplify CWD management across platforms
cyhhaoa5891671ffba
diff --git a/core/controller_refactored.py b/core/controller_refactored.pyindex 5fcae6deb..8249faf9b 100644--- a/core/controller_refactored.py+++ b/core/controller_refactored.py@@ -104,36 +104,52 @@ class Controller:# Utility methods used by handlersdef _restore_saved_cwd(self):- """Restore the last saved working directory from user settings"""+ """Restore saved working directory to the global config on startup"""try:- # Get all user settings+ # Find the most appropriate saved CWD and apply it globallyall_settings = self.settings_manager.settings-- # Find the most recently used custom_cwdsaved_cwd = None- for user_id, user_settings in all_settings.items():++ # For Slack: prefer channel settings over user settings+ # For Telegram: use any saved custom_cwd+ for settings_key, user_settings in all_settings.items():if hasattr(user_settings, 'custom_cwd') and user_settings.custom_cwd:- saved_cwd = user_settings.custom_cwd- logger.info(f"Found saved working directory from user {user_id}: {saved_cwd}")- # Use the first non-null custom_cwd found- # In the future, could use timestamps to find the most recent- break+ if self.config.platform == "slack":+ # Prefer channel settings (start with 'C') over user settings+ if settings_key.startswith('C'):+ saved_cwd = user_settings.custom_cwd+ logger.info(f"Found saved CWD from Slack channel {settings_key}: {saved_cwd}")+ break+ elif not saved_cwd: # Use user setting as fallback+ saved_cwd = user_settings.custom_cwd+ else: # Telegram or other platforms+ saved_cwd = user_settings.custom_cwd+ logger.info(f"Found saved CWD from {settings_key}: {saved_cwd}")+ break- # Apply the saved working directory if found+ # Apply the saved CWD globally if found and existsif saved_cwd and os.path.exists(saved_cwd):self.config.claude.cwd = saved_cwd- logger.info(f"Restored working directory to: {saved_cwd}")+ logger.info(f"✅ Restored global working directory to: {saved_cwd}")else:- logger.info(f"Using default working directory from config: {self.config.claude.cwd}")+ if saved_cwd:+ logger.warning(f"Saved CWD does not exist: {saved_cwd}, using default")+ logger.info(f"Using default working directory from .env: {self.config.claude.cwd}")except Exception as e:logger.error(f"Error restoring saved working directory: {e}")- # Continue with default from config+ # Continue with default from .envdef _get_settings_key(self, context: MessageContext) -> str:"""Get settings key based on context"""- if self.config.platform == "telegram" and context.channel_id != context.user_id:+ if self.config.platform == "slack":+ # For Slack, always use channel_id as the keyreturn context.channel_id+ elif self.config.platform == "telegram":+ # For Telegram groups, use channel_id; for DMs use user_id+ if context.channel_id != context.user_id:+ return context.channel_id+ return context.user_idreturn context.user_iddef _get_target_context(self, context: MessageContext) -> MessageContext:@@ -152,23 +168,25 @@ class Controller: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- settings_key = channel_id if channel_id else user_id+ # 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+ else:+ settings_key = channel_id if channel_id else user_id# Update settingsuser_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.save_settings()+ self.settings_manager.update_user_settings(settings_key, user_settings)logger.info(f"Updated settings for {settings_key}: hidden types = {hidden_message_types}")- # Create context for sending confirmation+ # Create context for sending confirmation (without 'message' field)context = MessageContext(user_id=user_id,channel_id=channel_id if channel_id else user_id,- message="",platform_specific={})@@ -180,11 +198,10 @@ class Controller:except Exception as e:logger.error(f"Error updating settings: {e}")- # Create context for error message+ # Create context for error message (without 'message' field)context = MessageContext(user_id=user_id,channel_id=channel_id if channel_id else user_id,- message="",platform_specific={})await self.im_client.send_message(@@ -194,65 +211,24 @@ class Controller:# Working directory change handler (for Slack modal)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)"""+ """Handle working directory change submission (from Slack modal) - reuse command handler logic"""try:- import os-- # Validate and expand the path- validated_path = os.path.abspath(os.path.expanduser(new_cwd))-- # Create context for messages+ # 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,- message="",platform_specific={})- if not os.path.exists(validated_path):- await self.im_client.send_message(- context,- f"❌ Path does not exist: {new_cwd}"- )- return-- if not os.path.isdir(validated_path):- await self.im_client.send_message(- context,- f"❌ Path is not a directory: {new_cwd}"- )- return-- # Update the global config directly- self.config.claude.cwd = validated_path-- # Save to user settings for persistence- # Determine settings key- settings_key = channel_id if channel_id else user_id- user_settings = self.settings_manager.get_user_settings(settings_key)- user_settings.custom_cwd = validated_path- self.settings_manager.update_user_settings(settings_key, user_settings)-- # Clear all sessions to apply new cwd- # Note: This affects ALL users since we're changing the global config- for session_id in list(self.claude_sessions.keys()):- await self.session_handler.cleanup_session(session_id)-- # Send confirmation- await self.im_client.send_message(- context,- f"✅ Working directory changed to:\n`{validated_path}`\n\nAll sessions have been reset to use the new directory."- )-- logger.info(f"Changed working directory for {settings_key} to {validated_path}")+ # 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+ # Create context for error message (without 'message' field)context = MessageContext(user_id=user_id,channel_id=channel_id if channel_id else user_id,- message="",platform_specific={})await self.im_client.send_message(diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 52fcb99ca..12c9351f3 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -151,7 +151,7 @@ Use the buttons below to manage your Claude Code sessions, or simply type any measync def handle_cwd(self, context: MessageContext, args: str = ""):"""Handle cwd command - show current working directory"""try:- # Always use config.claude.cwd as the single source of truth+ # Simple: use the single global CWDcurrent_cwd = self.config.claude.cwdabsolute_path = os.path.abspath(current_cwd)diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 7dad8c0a0..b6cdb9f52 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -28,8 +28,14 @@ class MessageHandler:def _get_settings_key(self, context: MessageContext) -> str:"""Get settings key based on context"""- if self.config.platform == "telegram" and context.channel_id != context.user_id:+ if self.config.platform == "slack":+ # For Slack, always use channel_id as the keyreturn context.channel_id+ elif self.config.platform == "telegram":+ # For Telegram groups, use channel_id; for DMs use user_id+ if context.channel_id != context.user_id:+ return context.channel_id+ return context.user_idreturn context.user_iddef _get_target_context(self, context: MessageContext) -> MessageContext:@@ -117,11 +123,13 @@ class MessageHandler: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,claude_session_id,- context.user_id+ settings_key)# Skip certain messagesdiff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex feabb71bf..44fbe04e3 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -24,6 +24,18 @@ class SessionHandler:self.receiver_tasks = controller.receiver_tasksself.stored_session_mappings = controller.stored_session_mappings+ def _get_settings_key(self, context: MessageContext) -> str:+ """Get settings key based on context"""+ if self.config.platform == "slack":+ # For Slack, always use channel_id as the key+ return context.channel_id+ elif self.config.platform == "telegram":+ # For Telegram groups, use channel_id; for DMs use user_id+ if context.channel_id != context.user_id:+ return context.channel_id+ return context.user_id+ return context.user_id+def get_base_session_id(self, context: MessageContext) -> str:"""Get base session ID based on platform and context (without path)"""if self.config.platform == "telegram":@@ -39,8 +51,9 @@ class SessionHandler:# Default to user IDreturn f"{self.config.platform}_{context.user_id}"- def get_working_path(self) -> str:- """Get normalized working directory path"""+ def get_working_path(self, context: Optional[MessageContext] = None) -> str:+ """Get normalized working directory path - always use the global config"""+ # Simple and clear: always use the single source of truthworking_dir = self.config.claude.cwdif working_dir:return os.path.abspath(os.path.expanduser(working_dir))@@ -49,7 +62,7 @@ class SessionHandler:def get_session_info(self, context: MessageContext) -> Tuple[str, str, str]:"""Get session info: base_session_id, working_path, and composite_key"""base_session_id = self.get_base_session_id(context)- working_path = self.get_working_path()+ working_path = self.get_working_path() # No need to pass context anymore# Create composite key for internal storagecomposite_key = f"{base_session_id}:{working_path}"return base_session_id, working_path, composite_key@@ -63,8 +76,10 @@ class SessionHandler:return self.claude_sessions[composite_key]# Check if we have a stored session mapping+ # Get correct settings key based on platform+ settings_key = self._get_settings_key(context)stored_claude_session_id = self.settings_manager.get_claude_session_id(- context.user_id, base_session_id, working_path+ settings_key, base_session_id, working_path)# Ensure working directory exists@@ -174,10 +189,10 @@ class SessionHandler:self.formatter.format_error(f"An error occurred: {error_msg}"))- def capture_session_id(self, base_session_id: str, working_path: str, claude_session_id: str, user_id: str):+ def capture_session_id(self, base_session_id: str, working_path: str, claude_session_id: str, settings_key: str):"""Capture and store Claude session ID mapping"""- # Persist to settings with nested structure- self.settings_manager.set_session_mapping(user_id, base_session_id, working_path, claude_session_id)+ # Persist to settings with nested structure (settings_key is channel_id for Slack, user/channel_id for Telegram)+ self.settings_manager.set_session_mapping(settings_key, base_session_id, working_path, claude_session_id)logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id} at {working_path}")diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex be472446c..7cd48ce51 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -19,10 +19,14 @@ class SettingsHandler:def _get_settings_key(self, context: MessageContext) -> str:"""Get settings key based on context"""- # For Telegram groups, use channel ID- # For everything else (DMs, Slack), use user ID- if self.config.platform == "telegram" and context.channel_id != context.user_id:+ if self.config.platform == "slack":+ # For Slack, always use channel_id as the keyreturn context.channel_id+ elif self.config.platform == "telegram":+ # For Telegram groups, use channel_id; for DMs use user_id+ if context.channel_id != context.user_id:+ return context.channel_id+ return context.user_idreturn context.user_idasync def handle_settings(self, context: MessageContext, args: str = ""):@@ -206,4 +210,31 @@ class SettingsHandler:except Exception as e:logger.error(f"Error in info_msg_types handler: {e}", exc_info=True)- await self.im_client.send_message(context, "❌ Error showing message types info")\ No newline at end of file+ await self.im_client.send_message(context, "❌ Error showing message types info")++ async def handle_info_how_it_works(self, context: MessageContext):+ """Show information about how the bot works"""+ try:+ formatter = self.im_client.formatter++ # Use format_info_message for clean, platform-agnostic formatting+ info_text = formatter.format_info_message(+ title="How Claude Code Bot Works:",+ emoji="📚",+ items=[+ ("Real-time", "Messages are immediately sent to Claude Code"),+ ("Persistent", "Each chat maintains its own conversation context"),+ ("Commands", "Use /start for menu, /clear to reset session"),+ ("Work Dir", "Change working directory with /set_cwd or via menu"),+ ("Settings", "Customize message visibility in Settings")+ ],+ footer="Just type normally to chat with Claude Code!"+ )++ # Send as new message+ await self.im_client.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, "❌ Error showing help information")\ No newline at end of file