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(slack): implement thread-aware mention requirements with 24-hour activity tracking

yh cdd0d6c1518ec
diff --git a/core/controller.py b/core/controller.py
index e8153348c..e41d65350 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -71,6 +71,14 @@ class Controller:
self.session_manager = SessionManager()
self.settings_manager = SettingsManager()
+ # Inject settings_manager into SlackBot if it's Slack platform
+ if self.config.platform == "slack":
+ # Import here to avoid circular dependency
+ from modules.im.slack import SlackBot
+ if isinstance(self.im_client, SlackBot):
+ self.im_client.set_settings_manager(self.settings_manager)
+ logger.info("Injected settings_manager into SlackBot for thread tracking")
+
def _init_handlers(self):
"""Initialize all handlers with controller reference"""
# Initialize session_handler first as other handlers depend on it
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 593565a1b..888b44ebe 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -39,6 +39,13 @@ class SlackBot(BaseIMClient):
# Store trigger IDs for modal interactions
self.trigger_ids: Dict[str, str] = {}
+ # Settings manager for thread tracking (will be injected later)
+ self.settings_manager = None
+
+ def set_settings_manager(self, settings_manager):
+ """Set the settings manager for thread tracking"""
+ self.settings_manager = settings_manager
+
def get_default_parse_mode(self) -> str:
"""Get the default parse mode for Slack"""
return "markdown"
@@ -116,6 +123,14 @@ class SlackBot(BaseIMClient):
# Send message
response = await self.web_client.chat_postMessage(**kwargs)
+ # Mark thread as active if we sent a message to a thread
+ if self.settings_manager and (context.thread_id or reply_to):
+ thread_ts = context.thread_id or reply_to
+ self.settings_manager.mark_thread_active(
+ context.user_id, context.channel_id, thread_ts
+ )
+ logger.debug(f"Marked thread {thread_ts} as active after bot message")
+
return response["ts"]
except SlackApiError as e:
@@ -184,6 +199,14 @@ class SlackBot(BaseIMClient):
kwargs["thread_ts"] = context.thread_id
response = await self.web_client.chat_postMessage(**kwargs)
+
+ # Mark thread as active if we sent a message to a thread
+ if self.settings_manager and context.thread_id:
+ self.settings_manager.mark_thread_active(
+ context.user_id, context.channel_id, context.thread_id
+ )
+ logger.debug(f"Marked thread {context.thread_id} as active after bot message with buttons")
+
return response["ts"]
except SlackApiError as e:
@@ -338,12 +361,28 @@ class SlackBot(BaseIMClient):
await self._send_unauthorized_message(channel_id)
return
- # Check if we require mention in channels (not DMs or threads)
- # In threads, we don't require mention even if SLACK_REQUIRE_MENTION is true
+ # Check if we require mention in channels (not DMs)
+ # For threads: only respond if the bot is active in that thread
is_thread_reply = event.get("thread_ts") is not None
- if self.config.require_mention and not channel_id.startswith("D") and not is_thread_reply:
- logger.info(f"Ignoring non-mention message in channel: '{text}'")
- return
+
+ if self.config.require_mention and not channel_id.startswith("D"):
+ # In channel main thread: require mention
+ if not is_thread_reply:
+ logger.info(f"Ignoring non-mention message in channel: '{text}'")
+ return
+
+ # In thread: check if bot is active in this thread
+ if is_thread_reply:
+ thread_ts = event.get("thread_ts")
+ # If we have settings_manager, check if thread is active
+ if self.settings_manager:
+ if not self.settings_manager.is_thread_active(user_id, channel_id, thread_ts):
+ logger.info(f"Ignoring message in inactive thread {thread_ts}: '{text}'")
+ return
+ else:
+ # Without settings_manager, fall back to ignoring non-mention in threads
+ logger.info(f"No settings_manager, ignoring thread message: '{text}'")
+ return
# Extract context
# For Slack: if no thread_ts, use the message's own ts as thread_id (start of thread)
@@ -393,6 +432,13 @@ class SlackBot(BaseIMClient):
platform_specific={"team_id": payload.get("team_id"), "event": event},
)
+ # Mark thread as active when bot is @mentioned
+ if self.settings_manager and thread_id:
+ self.settings_manager.mark_thread_active(
+ event.get("user"), channel_id, thread_id
+ )
+ logger.info(f"Marked thread {thread_id} as active due to @mention")
+
# Remove the mention from the text
text = event.get("text", "")
import re
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 13d22ae2a..a2ca45200 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -1,6 +1,7 @@
import json
import logging
import os
+import time
from dataclasses import dataclass, asdict, field
from typing import Dict, List, Optional, Union
from pathlib import Path
@@ -19,6 +20,8 @@ class UserSettings:
custom_cwd: Optional[str] = None # Custom working directory
# Nested map: {base_session_id: {working_path: claude_session_id}}
session_mappings: Dict[str, Dict[str, str]] = field(default_factory=dict)
+ # Slack active threads: {channel_id: {thread_ts: last_active_timestamp}}
+ active_slack_threads: Dict[str, Dict[str, float]] = field(default_factory=dict)
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
@@ -65,6 +68,10 @@ class SettingsManager:
cleaned_mappings[key] = value
user_data["session_mappings"] = cleaned_mappings
+ # Ensure active_slack_threads exists and is properly formatted
+ if "active_slack_threads" not in user_data:
+ user_data["active_slack_threads"] = {}
+
# Always keep user_id as string in memory
user_id = user_id_str
self.settings[user_id] = UserSettings.from_dict(user_data)
@@ -214,3 +221,81 @@ class SettingsManager:
settings.session_mappings.clear()
logger.info(f"Cleared all {count} session mappings for user {user_id}")
self.update_user_settings(user_id, settings)
+
+ # ---------------------------------------------
+ # Slack thread management
+ # ---------------------------------------------
+ def mark_thread_active(
+ self, user_id: Union[int, str], channel_id: str, thread_ts: str
+ ):
+ """Mark a Slack thread as active with current timestamp"""
+ settings = self.get_user_settings(user_id)
+
+ if channel_id not in settings.active_slack_threads:
+ settings.active_slack_threads[channel_id] = {}
+
+ settings.active_slack_threads[channel_id][thread_ts] = time.time()
+ self.update_user_settings(user_id, settings)
+ logger.info(
+ f"Marked thread active for user {user_id}: channel={channel_id}, thread={thread_ts}"
+ )
+
+ def is_thread_active(
+ self, user_id: Union[int, str], channel_id: str, thread_ts: str
+ ) -> bool:
+ """Check if a Slack thread is active (within 24 hours)"""
+ settings = self.get_user_settings(user_id)
+
+ # First cleanup expired threads for this channel
+ self._cleanup_expired_threads_for_channel(user_id, channel_id)
+
+ # Then check if thread is active
+ if channel_id in settings.active_slack_threads:
+ if thread_ts in settings.active_slack_threads[channel_id]:
+ return True
+
+ return False
+
+ def _cleanup_expired_threads_for_channel(
+ self, user_id: Union[int, str], channel_id: str
+ ):
+ """Remove threads older than 24 hours for a specific channel"""
+ settings = self.get_user_settings(user_id)
+
+ if channel_id not in settings.active_slack_threads:
+ return
+
+ current_time = time.time()
+ twenty_four_hours_ago = current_time - (24 * 60 * 60)
+
+ # Find expired threads
+ expired_threads = [
+ thread_ts
+ for thread_ts, last_active in settings.active_slack_threads[channel_id].items()
+ if last_active < twenty_four_hours_ago
+ ]
+
+ # Remove expired threads
+ if expired_threads:
+ for thread_ts in expired_threads:
+ del settings.active_slack_threads[channel_id][thread_ts]
+
+ # Clean up empty channel dict
+ if not settings.active_slack_threads[channel_id]:
+ del settings.active_slack_threads[channel_id]
+
+ self.update_user_settings(user_id, settings)
+ logger.info(
+ f"Cleaned up {len(expired_threads)} expired threads for channel {channel_id}"
+ )
+
+ def cleanup_all_expired_threads(self, user_id: Union[int, str]):
+ """Remove all threads older than 24 hours for all channels"""
+ settings = self.get_user_settings(user_id)
+
+ if not settings.active_slack_threads:
+ return
+
+ channels_to_clean = list(settings.active_slack_threads.keys())
+ for channel_id in channels_to_clean:
+ self._cleanup_expired_threads_for_channel(user_id, channel_id)