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(im): preserve mention gate in active threads (#593)
Call White39717d89c808
diff --git a/modules/im/base.py b/modules/im/base.pyindex 97d1aed6a..7dba6c88e 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -170,6 +170,16 @@ class BaseIMClient(ABC):"""Whether non-thread channel messages should default to per-message sessions."""return True+ def is_scheduled_thread_active(self, channel_id: Optional[str], thread_id: Optional[str]) -> bool:+ """Return whether a thread is active for the synthetic scheduled owner."""+ sessions = getattr(self, "sessions", None)+ if not sessions or not channel_id or not thread_id:+ return False+ exact_checker = getattr(sessions, "is_thread_active_for_user", None)+ if callable(exact_checker):+ return bool(exact_checker("scheduled", channel_id, thread_id))+ return False+async def prepare_turn_context(self, context: MessageContext, source: str) -> MessageContext:"""Allow IM adapters to adjust reply topology for a turn source.diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 638b3c71b..f6086a489 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -282,13 +282,6 @@ class DiscordBot(BaseIMClient):return await self._run_on_client_loop(_impl())- def _is_thread_reply_allowed(self, author_id: str, channel_id: str, thread_id: str) -> bool:- if not self.settings_manager or not self.sessions:- return False- if self.sessions.is_thread_active(author_id, channel_id, thread_id):- return True- return self.sessions.is_thread_active("scheduled", channel_id, thread_id)-@staticmethoddef _get_reference_message_id(message: discord.Message) -> Optional[str]:reference = getattr(message, "reference", None)@@ -946,11 +939,7 @@ class DiscordBot(BaseIMClient):if effective_require_mention and not is_dm:if isinstance(channel, discord.Thread):- if self.settings_manager:- thread_active = self._is_thread_reply_allowed(str(message.author.id), channel_id, str(channel.id))- if not thread_active:- return- else:+ if not mentioned_bot and not self.is_scheduled_thread_active(channel_id, str(channel.id)):returnelse:if referenced_anchor_base:diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 206201ab6..cc7b8bda5 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -1523,15 +1523,8 @@ class FeishuBot(BaseIMClient):logger.debug("Ignoring non-mention message in channel")returnelse:- if self.settings_manager:- thread_active = self.sessions.is_thread_active(user_id, chat_id, root_id) if self.sessions else False- scheduled_thread_active = (- self.sessions.is_thread_active("scheduled", chat_id, root_id) if self.sessions else False- )- if not thread_active and not scheduled_thread_active:- logger.debug("Ignoring message in inactive thread %s", root_id)- return- else:+ if not bot_mentioned and not self.is_scheduled_thread_active(chat_id, root_id):+ logger.debug("Ignoring non-mention message in thread %s", root_id)returnauth_result = self.check_authorization(diff --git a/modules/im/slack.py b/modules/im/slack.pyindex f56e3b769..63a64abc8 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1731,8 +1731,9 @@ class SlackBot(BaseIMClient):):return- # Check if we require mention in channels (not DMs)- # For threads: only respond if the bot is active in that thread+ # Check if we require mention in channels (not DMs).+ # In threads, human activity does not bypass the mention requirement;+ # scheduled follow-up threads are the only no-mention exception.is_thread_reply = event.get("thread_ts") is not None# Resolve effective require_mention: per-channel override or global default@@ -1750,20 +1751,12 @@ class SlackBot(BaseIMClient):logger.debug(f"Ignoring non-mention message in channel: '{route_text}'")return- # In thread: check if bot is active in this thread+ # In thread: require a fresh bot mention unless this is a scheduled follow-up thread.elif is_thread_reply:thread_ts = event.get("thread_ts")- # If we have settings_manager, check if thread is activeif self.settings_manager:- thread_active = (- self.sessions.is_thread_active(user_id, channel_id, thread_ts) if self.sessions else False- )- scheduled_thread_active = (- self.sessions.is_thread_active("scheduled", channel_id, thread_ts)- if self.sessions- else False- )- if not thread_active and not scheduled_thread_active:+ scheduled_thread_active = self.is_scheduled_thread_active(channel_id, thread_ts)+ if not scheduled_thread_active:logger.debug(f"Ignoring message in inactive thread {thread_ts}: '{route_text}'")returnelse:diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex 478de6621..cc20eb269 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -321,6 +321,12 @@ class SessionsFacade:return Truereturn self._is_thread_active_for_any_user(channel_id, thread_ts)+ def is_thread_active_for_user(self, user_id: Union[int, str], channel_id: str, thread_ts: str) -> bool:+ user_key = self._normalize_user_id(user_id)+ self._cleanup_expired_threads_for_channel(user_id, channel_id)+ channel_map = self.sessions_store.get_thread_map(user_key, channel_id)+ return thread_ts in channel_map+def _is_thread_active_for_any_user(self, channel_id: str, thread_ts: str) -> bool:"""Return whether a channel thread is active for any participant.diff --git a/tests/test_discord_reply_anchor.py b/tests/test_discord_reply_anchor.pyindex 72e6a28a8..e0d749feb 100644--- a/tests/test_discord_reply_anchor.py+++ b/tests/test_discord_reply_anchor.py@@ -8,6 +8,7 @@ from unittest.mock import AsyncMocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from config.v2_config import DiscordConfigfrom modules.im import MessageContextfrom modules.im.discord import DiscordBotfrom core.auth import AuthResult@@ -20,6 +21,9 @@ class _FakeSessions:def is_thread_active(self, user_id, channel_id, thread_ts):return user_id == "scheduled" and channel_id == "C123" and thread_ts == "777"+ def is_thread_active_for_user(self, user_id, channel_id, thread_ts):+ return user_id == "scheduled" and channel_id == "C123" and thread_ts == "777"+class _FakeChannel:async def fetch_message(self, message_id):@@ -57,14 +61,125 @@ class DiscordReplyAnchorTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(prepared.platform_specific["reply_anchor_base_session_id"], "discord_555")self.assertEqual(prepared.platform_specific["reply_anchor_message_id"], "555")- def test_scheduled_thread_activity_allows_replies_under_mention_gating(self):+ def test_scheduled_thread_activity_is_checked_with_exact_owner(self):bot = object.__new__(DiscordBot)bot.sessions = _FakeSessions()bot.settings_manager = object()- allowed = DiscordBot._is_thread_reply_allowed(bot, "U123", "C123", "777")+ self.assertTrue(DiscordBot.is_scheduled_thread_active(bot, "C123", "777"))++ def test_human_active_thread_does_not_count_as_scheduled_activity(self):+ bot = object.__new__(DiscordBot)++ class _Sessions:+ def is_thread_active(self, _user_id, _channel_id, _thread_id):+ return True++ def is_thread_active_for_user(self, _user_id, _channel_id, _thread_id):+ return False++ bot.sessions = _Sessions()+ bot.settings_manager = object()++ self.assertFalse(DiscordBot.is_scheduled_thread_active(bot, "C123", "777"))++ async def test_human_active_thread_requires_fresh_mention_when_require_mention_enabled(self):+ import modules.im.discord as discord_module++ bot = object.__new__(DiscordBot)+ bot.config = DiscordConfig(require_mention=True)+ bot._controller = None+ bot.client = SimpleNamespace(user=SimpleNamespace(id=42))+ bot.on_message_callback = AsyncMock()++ class _Sessions:+ def is_thread_active(self, _user_id, _channel_id, _thread_id):+ return True++ def is_thread_active_for_user(self, _user_id, _channel_id, _thread_id):+ return False++ class _SettingsManager:+ sessions = _Sessions()+ platform = "discord"++ def get_require_mention(self, _channel_id, global_default=False):+ return global_default++ bot.sessions = _Sessions()+ bot.settings_manager = _SettingsManager()+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=False)+ bot.dispatch_text_command = AsyncMock(return_value=False)++ original_thread = discord_module.discord.Thread++ class _FakeThread:+ id = 777+ parent_id = "C123"++ try:+ discord_module.discord.Thread = _FakeThread+ message = SimpleNamespace(+ author=SimpleNamespace(id=456, bot=False),+ content="@colleague take a look",+ channel=_FakeThread(),+ guild=SimpleNamespace(id=999),+ attachments=[],+ mentions=[SimpleNamespace(id=9999)],+ id=888,+ )++ await DiscordBot._on_message_event(bot, message)+ finally:+ discord_module.discord.Thread = original_thread++ bot.on_message_callback.assert_not_awaited()++ async def test_scheduled_active_thread_bypasses_mention_requirement(self):+ import modules.im.discord as discord_module++ bot = object.__new__(DiscordBot)+ bot.config = DiscordConfig(require_mention=True)+ bot._controller = None+ bot.client = SimpleNamespace(user=SimpleNamespace(id=42))+ bot.on_message_callback = AsyncMock()+ bot.sessions = _FakeSessions()++ class _SettingsManager:+ sessions = _FakeSessions()+ platform = "discord"++ def get_require_mention(self, _channel_id, global_default=False):+ return global_default++ bot.settings_manager = _SettingsManager()+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=False)+ bot.dispatch_text_command = AsyncMock(return_value=False)++ original_thread = discord_module.discord.Thread++ class _FakeThread:+ id = 777+ parent_id = "C123"++ try:+ discord_module.discord.Thread = _FakeThread+ message = SimpleNamespace(+ author=SimpleNamespace(id=456, bot=False),+ content="scheduled follow-up context",+ channel=_FakeThread(),+ guild=SimpleNamespace(id=999),+ attachments=[],+ mentions=[],+ id=888,+ )++ await DiscordBot._on_message_event(bot, message)+ finally:+ discord_module.discord.Thread = original_thread- self.assertTrue(allowed)+ bot.on_message_callback.assert_awaited_once()+ self.assertEqual(bot.on_message_callback.await_args.args[1], "scheduled follow-up context")async def test_send_auth_denial_acknowledges_silent_interaction_denial(self):bot = object.__new__(DiscordBot)diff --git a/tests/test_feishu_post_messages.py b/tests/test_feishu_post_messages.pyindex 79b93cb3a..96b8e7491 100644--- a/tests/test_feishu_post_messages.py+++ b/tests/test_feishu_post_messages.py@@ -15,7 +15,10 @@ sys.path.insert(0, str(ROOT))def _install_opencode_utils_module() -> None:if "aiohttp" not in sys.modules:- sys.modules["aiohttp"] = types.ModuleType("aiohttp")+ try:+ __import__("aiohttp")+ except ImportError:+ sys.modules["aiohttp"] = types.ModuleType("aiohttp")if "modules.agents.opencode.utils" in sys.modules:return@@ -129,6 +132,91 @@ class FeishuPostMessageTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(len(context.files), 1)self.assertEqual(context.files[0].name, "img_123.image")+ async def test_active_thread_requires_fresh_mention_when_require_mention_enabled(self):+ bot = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret", require_mention=True))+ bot._bot_open_id = "ou_bot"+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=False)+ bot.dispatch_text_command = AsyncMock(return_value=False)+ bot.on_message_callback = AsyncMock()++ class _Sessions:+ def is_thread_active(self, _user_id, _chat_id, _root_id):+ return True++ def is_thread_active_for_user(self, _user_id, _chat_id, _root_id):+ return False++ class _SettingsManager:+ sessions = _Sessions()++ def get_require_mention(self, _chat_id, global_default=False):+ return global_default++ bot.set_settings_manager(_SettingsManager())++ await bot._async_handle_message(+ {+ "sender": {+ "sender_type": "user",+ "sender_id": {"open_id": "ou_user"},+ },+ "message": {+ "chat_id": "oc_chat",+ "chat_type": "group",+ "message_id": "om_child",+ "root_id": "om_root",+ "message_type": "text",+ "content": json.dumps({"text": "@colleague take a look"}),+ "mentions": [{"key": "@colleague", "id": {"open_id": "ou_colleague"}}],+ },+ }+ )++ bot.on_message_callback.assert_not_awaited()++ async def test_scheduled_active_thread_still_bypasses_mention_requirement(self):+ bot = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret", require_mention=True))+ bot._bot_open_id = "ou_bot"+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=False)+ bot.dispatch_text_command = AsyncMock(return_value=False)+ bot.on_message_callback = AsyncMock()++ class _Sessions:+ def is_thread_active(self, _user_id, _chat_id, _root_id):+ return True++ def is_thread_active_for_user(self, user_id, chat_id, root_id):+ return user_id == "scheduled" and chat_id == "oc_chat" and root_id == "om_root"++ class _SettingsManager:+ sessions = _Sessions()++ def get_require_mention(self, _chat_id, global_default=False):+ return global_default++ bot.set_settings_manager(_SettingsManager())++ await bot._async_handle_message(+ {+ "sender": {+ "sender_type": "user",+ "sender_id": {"open_id": "ou_user"},+ },+ "message": {+ "chat_id": "oc_chat",+ "chat_type": "group",+ "message_id": "om_child",+ "root_id": "om_root",+ "message_type": "text",+ "content": json.dumps({"text": "scheduled follow-up context"}),+ "mentions": [],+ },+ }+ )++ bot.on_message_callback.assert_awaited_once()+ self.assertEqual(bot.on_message_callback.await_args.args[1], "scheduled follow-up context")+if __name__ == "__main__":unittest.main()diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.pyindex 6bbdf4bc2..d0912c457 100644--- a/tests/test_slack_dm_mentions.py+++ b/tests/test_slack_dm_mentions.py@@ -12,23 +12,26 @@ from modules.im.base import InlineButton, InlineKeyboard, MessageContextdef _install_slack_stubs() -> None:if "aiohttp" not in sys.modules:- aiohttp_mod = types.ModuleType("aiohttp")+ try:+ __import__("aiohttp")+ except ImportError:+ aiohttp_mod = types.ModuleType("aiohttp")- class _ClientWebSocketResponse:- closed = False+ class _ClientWebSocketResponse:+ closed = False- class _ClientSession:- async def close(self):- return None+ class _ClientSession:+ async def close(self):+ return None- class _ClientTimeout:- def __init__(self, *args, **kwargs):- pass+ class _ClientTimeout:+ def __init__(self, *args, **kwargs):+ pass- aiohttp_mod.ClientWebSocketResponse = _ClientWebSocketResponse- aiohttp_mod.ClientSession = _ClientSession- aiohttp_mod.ClientTimeout = _ClientTimeout- sys.modules["aiohttp"] = aiohttp_mod+ aiohttp_mod.ClientWebSocketResponse = _ClientWebSocketResponse+ aiohttp_mod.ClientSession = _ClientSession+ aiohttp_mod.ClientTimeout = _ClientTimeout+ sys.modules["aiohttp"] = aiohttp_modif "markdown_to_mrkdwn" not in sys.modules:markdown_mod = types.ModuleType("markdown_to_mrkdwn")@@ -1375,6 +1378,88 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(marked, [("U123", "C_CONNECT", "1710000000.000360")])+ async def test_active_thread_requires_fresh_mention_when_require_mention_enabled(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test", require_mention=True))+ received = []++ class _Sessions:+ def is_thread_active(self, _user_id, _channel_id, _thread_ts):+ return True++ def is_thread_active_for_user(self, _user_id, _channel_id, _thread_ts):+ return False++ class _SettingsManager:+ sessions = _Sessions()++ def get_require_mention(self, _channel_id, global_default=False):+ return global_default++ async def _on_message(_context, text):+ received.append(text)++ slack.set_settings_manager(_SettingsManager())+ slack.register_callbacks(on_message=_on_message)++ payload = {+ "event_id": "evt-active-thread-no-mention",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "message",+ "channel": "C123",+ "user": "U123",+ "text": "@colleague take a look",+ "ts": "1710000000.000361",+ "thread_ts": "1710000000.000360",+ },+ }++ await slack._handle_event(payload)++ self.assertEqual(received, [])++ async def test_scheduled_active_thread_still_bypasses_mention_requirement(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test", require_mention=True))+ received = []++ class _Sessions:+ def is_thread_active(self, _user_id, _channel_id, _thread_ts):+ return True++ def is_thread_active_for_user(self, user_id, channel_id, thread_ts):+ return user_id == "scheduled" and channel_id == "C123" and thread_ts == "1710000000.000360"++ class _SettingsManager:+ sessions = _Sessions()++ def get_require_mention(self, _channel_id, global_default=False):+ return global_default++ async def _on_message(_context, text):+ received.append(text)++ slack.set_settings_manager(_SettingsManager())+ slack.register_callbacks(on_message=_on_message)++ payload = {+ "event_id": "evt-scheduled-thread-no-mention",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "message",+ "channel": "C123",+ "user": "U123",+ "text": "scheduled follow-up context",+ "ts": "1710000000.000362",+ "thread_ts": "1710000000.000360",+ },+ }++ await slack._handle_event(payload)++ self.assertEqual(received, ["scheduled follow-up context"])+async def test_socket_mode_events_ack_before_message_processing_finishes(self):slack = SlackBot(SlackConfig(bot_token="xoxb-test"))started = asyncio.Event()diff --git a/tests/test_v2_sessions.py b/tests/test_v2_sessions.pyindex ad1074f4c..34d4d7da3 100644--- a/tests/test_v2_sessions.py+++ b/tests/test_v2_sessions.py@@ -42,6 +42,8 @@ def test_active_thread_is_shared_across_users(tmp_path, monkeypatch):sessions.mark_thread_active("U1", "C1", "123.456")assert sessions.is_thread_active("U2", "C1", "123.456")+ assert not sessions.is_thread_active_for_user("U2", "C1", "123.456")+ assert sessions.is_thread_active_for_user("U1", "C1", "123.456")def test_shared_active_thread_ignores_expired_entries(tmp_path, monkeypatch):