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
refactor(architecture): centralize runtime policy and state boundaries
cyha9505f1f0cd4
diff --git a/core/auth.py b/core/auth.pyindex a06222957..f9d091ec2 100644--- a/core/auth.py+++ b/core/auth.py@@ -63,6 +63,7 @@ def check_auth(channel_id: str,is_dm: bool,action: str = "",+ settings_manager: object | None = None,store: "SettingsStore | None" = None,) -> AuthResult:"""Run the centralized authorization pipeline.@@ -83,6 +84,12 @@ def check_auth(store: ``SettingsStore`` instance for permission lookups.When *None* (no settings configured), everything is allowed."""+ if store is None and settings_manager is not None and hasattr(settings_manager, "get_store"):+ try:+ store = settings_manager.get_store()+ except Exception:+ store = None+if store is None:return AuthResult(allowed=True, is_dm=is_dm)diff --git a/core/controller.py b/core/controller.pyindex c35d9b914..40543e4a4 100644--- a/core/controller.py+++ b/core/controller.py@@ -19,6 +19,7 @@ from core.handlers import (SettingsHandler,MessageHandler,)+from core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.update_checker import UpdateCheckerfrom vibe.i18n import get_supported_languages, t as i18n_t@@ -38,14 +39,6 @@ class Controller:self.receiver_tasks: Dict[str, asyncio.Task] = {}self.stored_session_mappings: Dict[str, str] = {}- # Consolidated message tracking (system/assistant/toolcall)- self._consolidated_message_ids: Dict[str, str] = {}- self._consolidated_message_buffers: Dict[str, str] = {}- self._consolidated_message_locks: Dict[str, asyncio.Lock] = {}- # Track current message_id per thread - ensures log messages follow the latest user message- # Key: "{settings_key}:{thread_id}", Value: message_id- self._thread_current_message_id: Dict[str, str] = {}-# Initialize core modulesself._init_modules()@@ -61,6 +54,9 @@ class Controller:# Setup callbacksself._setup_callbacks()+ # Consolidated message dispatcher+ self.message_dispatcher = ConsolidatedMessageDispatcher(self)+# Background task for cleanupself.cleanup_task: Optional[asyncio.Task] = None@@ -95,6 +91,7 @@ class Controller:# Initialize managersself.session_manager = SessionManager()self.settings_manager = SettingsManager()+ self.sessions = self.settings_manager.sessions# Migrate legacy per-channel language into global configself._migrate_language_from_settings()@@ -293,11 +290,11 @@ class Controller: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_routing_update=self.handle_routing_update,- on_routing_modal_update=self.handle_routing_modal_update,- on_resume_session=self.handle_resume_session_submission,+ on_settings_update=self.settings_handler.handle_settings_update,+ on_change_cwd=self.command_handler.handle_change_cwd_submission,+ on_routing_update=self.settings_handler.handle_routing_update,+ on_routing_modal_update=self.settings_handler.handle_routing_modal_update,+ on_resume_session=self.session_handler.handle_resume_session_submission,on_ready=self._on_im_ready,)@@ -310,7 +307,7 @@ class Controller:opencode_agent = self.agent_service.agents.get("opencode")if opencode_agent and hasattr(opencode_agent, "restore_active_polls"):try:- restored = await opencode_agent.restore_active_polls()+ restored = await opencode_agent.restore_active_polls() # type: ignore[attr-defined]if restored > 0:logger.info(f"Restored {restored} active OpenCode poll(s)")except Exception as e:@@ -368,116 +365,15 @@ class Controller:is_dm = (context.platform_specific or {}).get("is_dm", False)return context.user_id if is_dm else context.channel_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:- return MessageContext(- user_id=context.user_id,- channel_id=context.channel_id,- thread_id=context.thread_id,- message_id=context.message_id,- platform_specific=context.platform_specific,- )- return context-- def _get_consolidated_message_key(self, context: MessageContext) -> str:- settings_key = self._get_settings_key(context)- thread_key = context.thread_id or context.channel_id- # Use the tracked current message_id for this thread if available- # This ensures log messages follow the latest user message, even when- # agent receivers hold stale context references- tracking_key = f"{settings_key}:{thread_key}"- trigger_id = self._thread_current_message_id.get(tracking_key) or context.message_id or ""- return f"{settings_key}:{thread_key}:{trigger_id}"-def update_thread_message_id(self, context: MessageContext) -> None:- """Update the current message_id for a thread.-- Call this when processing a new user message to ensure subsequent- log messages (from agents) are grouped with this message.- """- if not context.message_id:- return- settings_key = self._get_settings_key(context)- thread_key = context.thread_id or context.channel_id- tracking_key = f"{settings_key}:{thread_key}"- self._thread_current_message_id[tracking_key] = context.message_id-- def _get_consolidated_message_lock(self, key: str) -> asyncio.Lock:- if key not in self._consolidated_message_locks:- self._consolidated_message_locks[key] = asyncio.Lock()- return self._consolidated_message_locks[key]+ """Update message tracking for consolidated log dispatch."""+ self.message_dispatcher.update_thread_message_id(context)async def clear_consolidated_message_id(self, context: MessageContext, trigger_message_id: Optional[str] = None) -> None:- """Clear consolidated message ID so next log message starts fresh.-- Call this after user answers a question to make subsequent log messages- appear after the user's reply instead of editing the old consolidated message.-- Args:- context: The message context- trigger_message_id: If provided, use this instead of context.message_id- for the consolidated key (needed when context is from- user's answer message, not original request)- """- # Build key with the original trigger message_id if provided- settings_key = self._get_settings_key(context)- thread_key = context.thread_id or context.channel_id- msg_id = trigger_message_id if trigger_message_id else (context.message_id or "")- key = f"{settings_key}:{thread_key}:{msg_id}"-- # Use the same per-key lock as emit_agent_message to avoid race conditions- lock = self._get_consolidated_message_lock(key)- async with lock:- self._consolidated_message_ids.pop(key, None)- # Also clear the buffer so we don't append to stale content- self._consolidated_message_buffers.pop(key, None)-- def _get_consolidated_max_bytes(self) -> int:- if self.config.platform == "discord":- return 2000- # Slack API hard limit is exactly 4000 BYTES (not characters) for chat.update- # Chinese/emoji characters take 3-4 bytes each in UTF-8- return 4000-- def _get_consolidated_split_threshold(self) -> int:- # When accumulated message exceeds this threshold (in bytes), start a new message- # to avoid edit failures. Use 90% of max to leave some buffer.- if self.config.platform == "discord":- return 1800- return 3600-- def _get_text_byte_length(self, text: str) -> int:- """Get UTF-8 byte length of text (Slack counts bytes, not characters)."""- return len(text.encode("utf-8"))-- def _get_result_max_chars(self) -> int:- if self.config.platform == "discord":- return 1900- return 30000-- def _build_result_summary(self, text: str, max_chars: int) -> str:- if len(text) <= max_chars:- return text- prefix = "Result too long; showing a summary.\n\n"- suffix = "\n\n…(truncated; see result.md for full output)"- keep = max(0, max_chars - len(prefix) - len(suffix))- return f"{prefix}{text[:keep]}{suffix}"-- def _truncate_consolidated(self, text: str, max_bytes: int) -> str:- """Truncate text to fit within max_bytes (UTF-8 encoded)."""- if self._get_text_byte_length(text) <= max_bytes:- return text- # Reserve space for ellipsis (3 bytes for "…")- ellipsis = "…"- ellipsis_bytes = len(ellipsis.encode("utf-8")) # 3 bytes- target_bytes = max_bytes - ellipsis_bytes- # Truncate bytes and decode, handling partial characters- encoded = text.encode("utf-8")- truncated = encoded[:target_bytes].decode("utf-8", errors="ignore")- return truncated.rstrip() + ellipsis+ """Clear consolidated message anchor so next log chunk starts fresh."""+ await self.message_dispatcher.clear_consolidated_message_id(context, trigger_message_id)def resolve_agent_for_context(self, context: MessageContext) -> str:"""Unified agent resolution with dynamic override support.@@ -530,659 +426,13 @@ class Controller:text: str,parse_mode: Optional[str] = "markdown",):- """Centralized dispatch for agent messages.-- Message Types:- - Log Messages (system/assistant/toolcall): Consolidated into a single- editable message per conversation round. Can be hidden by user settings.- - Result Message: Final output, always sent immediately, not hideable.- - Notify Message: Notifications, always sent immediately.-- Log Messages are accumulated and edited in-place until they exceed the- Slack byte limit (4000 bytes UTF-8), then a new message is started.- """- if not text or not text.strip():- return-- canonical_type = self.settings_manager._canonicalize_message_type(message_type or "")- settings_key = self._get_settings_key(context)-- if canonical_type == "notify":- target_context = self._get_target_context(context)- await self.im_client.send_message(target_context, text, parse_mode=parse_mode)- return-- if canonical_type == "result":- target_context = self._get_target_context(context)- if len(text) <= self._get_result_max_chars():- await self.im_client.send_message(target_context, text, parse_mode=parse_mode)- return-- summary = self._build_result_summary(text, self._get_result_max_chars())- await self.im_client.send_message(target_context, summary, parse_mode=parse_mode)-- if self.config.platform in {"slack", "discord", "lark"} and hasattr(self.im_client, "upload_markdown"):- try:- await self.im_client.upload_markdown(- target_context,- title="result.md",- content=text,- filetype="markdown",- )- except Exception as err:- logger.warning(f"Failed to upload result attachment: {err}")- await self.im_client.send_message(- target_context,- "Failed to upload attachment. Want me to split the result into multiple messages?",- parse_mode=parse_mode,- )- return-- # Log Messages: system/assistant/toolcall - consolidated into editable message- if canonical_type not in {"system", "assistant", "toolcall"}:- canonical_type = "assistant"-- if self.settings_manager.is_message_type_hidden(settings_key, canonical_type):- preview = text if len(text) <= 500 else f"{text[:500]}…"- logger.info(- "Skipping %s message for settings %s (hidden). Preview: %s",- canonical_type,- settings_key,- preview,- )- return-- consolidated_key = self._get_consolidated_message_key(context)- lock = self._get_consolidated_message_lock(consolidated_key)-- async with lock:- chunk = text.strip()- max_bytes = self._get_consolidated_max_bytes()- split_threshold = self._get_consolidated_split_threshold()- existing = self._consolidated_message_buffers.get(consolidated_key, "")- existing_message_id = self._consolidated_message_ids.get(consolidated_key)-- separator = "\n\n---\n\n" if existing else ""- updated = f"{existing}{separator}{chunk}" if existing else chunk-- target_context = self._get_target_context(context)- continuation_notice = "\n\n---\n\n_(continued below...)_"- continuation_bytes = self._get_text_byte_length(continuation_notice)-- # Case 1: Accumulated message exceeds threshold (in bytes), split off old message- if existing_message_id and self._get_text_byte_length(updated) > split_threshold:- old_text = existing + continuation_notice- old_text = self._truncate_consolidated(old_text, max_bytes)-- try:- await self.im_client.edit_message(- target_context,- existing_message_id,- text=old_text,- parse_mode="markdown",- )- except Exception as err:- logger.warning(f"Failed to finalize old Log Message: {err}")-- # Start fresh with just the new chunk- self._consolidated_message_buffers[consolidated_key] = chunk- self._consolidated_message_ids.pop(consolidated_key, None)- updated = chunk- existing_message_id = None- logger.info(- "Log Message exceeded %d bytes, starting new message",- split_threshold,- )-- # Case 2: Single chunk (including first message) exceeds max_bytes- # Split into multiple messages to avoid truncation- while self._get_text_byte_length(updated) > max_bytes:- # Find split point that fits within threshold (accounting for continuation notice)- target_bytes = split_threshold - continuation_bytes- first_part = self._truncate_consolidated(updated, target_bytes)- first_part = first_part.rstrip("…") + continuation_notice # Replace truncation marker-- send_ok = False- if existing_message_id:- try:- await self.im_client.edit_message(- target_context,- existing_message_id,- text=first_part,- parse_mode="markdown",- )- send_ok = True- except Exception as err:- logger.warning(f"Failed to edit oversized Log Message: {err}")- else:- try:- await self.im_client.send_message(target_context, first_part, parse_mode="markdown")- send_ok = True- except Exception as err:- logger.error(f"Failed to send oversized Log Message: {err}")-- if not send_ok:- # Failed to send/edit - stop splitting and truncate the remainder- logger.warning("Stopping split loop due to send failure, truncating remainder")- break-- # Continue with remainder (skip the part we already sent)- # Don't lstrip() - preserve intentional indentation in code blocks- sent_chars = len(first_part) - len(continuation_notice)- updated = updated[sent_chars:]- # Clear both local var and stored ID to avoid editing old message on failure- existing_message_id = None- self._consolidated_message_ids.pop(consolidated_key, None)- logger.info(- "Log Message chunk exceeded %d bytes, split and continuing",- max_bytes,- )-- updated = self._truncate_consolidated(updated, max_bytes)- self._consolidated_message_buffers[consolidated_key] = updated-- if existing_message_id:- try:- ok = await self.im_client.edit_message(- target_context,- existing_message_id,- text=updated,- parse_mode="markdown",- )- except Exception as err:- logger.warning(f"Failed to edit Log Message: {err}")- ok = False- if ok:- return- self._consolidated_message_ids.pop(consolidated_key, None)-- try:- new_id = await self.im_client.send_message(target_context, updated, parse_mode="markdown")- self._consolidated_message_ids[consolidated_key] = new_id- except Exception as err:- logger.error(f"Failed to send Log Message: {err}", exc_info=True)-- # Settings update handler (for Slack modal)- async def handle_settings_update(- self,- user_id: str,- show_message_types: list,- channel_id: Optional[str] = None,- require_mention: Optional[bool] = None,- language: Optional[str] = None,- notify_user: bool = True,- is_dm: bool = False,- ):- """Handle settings update (typically from Slack modal)"""- try:- # Determine settings key — for DM contexts use user_id- settings_key = user_id if is_dm else (channel_id or user_id)-- # Update settings- user_settings = self.settings_manager.get_user_settings(settings_key)- user_settings.show_message_types = show_message_types-- # Save settings - using the correct method name- self.settings_manager.update_user_settings(settings_key, user_settings)-- # Save require_mention setting (channel-only, not applicable in DM)- if not is_dm:- self.settings_manager.set_require_mention(settings_key, require_mention)-- # Save language setting to global config- language_saved = True- if language is not None and language != self.config.language:- try:- from config.v2_config import V2Config-- v2_config = V2Config.load()- v2_config.language = language- v2_config.save()- self.config.language = language- except Exception as err:- language_saved = False- logger.error(f"Failed to persist language setting: {err}")-- logger.info(- f"Updated settings for {settings_key}: show types = {show_message_types}, "- f"require_mention = {require_mention}, language = {language}"- )-- # 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={},- )-- # Send confirmation- if notify_user:- await self.im_client.send_message(context, f"✅ {self._t('success.settingsUpdated')}")- if not language_saved:- await self.im_client.send_message(- context,- f"⚠️ {self._t('error.languageUpdateFailed')}",- )-- except Exception as e:- logger.error(f"Error updating settings: {e}")- if notify_user:- # 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={},- )- await self.im_client.send_message(- context,- f"❌ {self._t('error.settingsUpdateFailed', error=str(e))}",- )- else:- raise-- # Working directory change handler (for Slack modal)- async def handle_change_cwd_submission(- self, user_id: str, new_cwd: str, channel_id: Optional[str] = None, is_dm: bool = False- ):- """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={"is_dm": is_dm},- )-- # 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={"is_dm": is_dm},- )- await self.im_client.send_message(- context,- f"❌ {self._t('error.cwdSetFailed', error=str(e))}",- )-- async def handle_resume_session_submission(- self,- user_id: str,- channel_id: Optional[str],- thread_id: Optional[str],- agent: Optional[str],- session_id: Optional[str],- host_message_ts: Optional[str] = None,- is_dm: bool = False,- ) -> None:- """Bind a provided session_id to the current thread for the chosen agent."""- from modules.settings_manager import ChannelRouting-- try:- if not agent or not session_id:- raise ValueError("Agent and session ID are required to resume.")-- if getattr(self, "agent_service", None):- available_agents = set(self.agent_service.agents.keys())- if agent not in available_agents:- raise ValueError(f"Agent '{agent}' is not enabled.")-- # Decide whether to reuse current thread or start a new one for clarity.- reuse_thread = True- if host_message_ts and thread_id and thread_id == host_message_ts:- # Resume was initiated from the /start menu message; start a fresh thread.- reuse_thread = False-- # If DM and no thread provided, reuse channel unless we intentionally create new thread later- target_thread = thread_id if reuse_thread else None-- # Build confirmation context (top-level message when starting fresh)- context = MessageContext(- user_id=user_id,- channel_id=channel_id or user_id,- thread_id=target_thread or None,- platform_specific={"is_dm": is_dm},- )-- settings_key = self._get_settings_key(context)- current_routing = self.settings_manager.get_channel_routing(settings_key)- opencode_agent = current_routing.opencode_agent if current_routing else None- opencode_model = current_routing.opencode_model if current_routing else None- opencode_reasoning_effort = current_routing.opencode_reasoning_effort if current_routing else None-- routing = ChannelRouting(- agent_backend=agent,- opencode_agent=opencode_agent,- opencode_model=opencode_model,- opencode_reasoning_effort=opencode_reasoning_effort,- )- self.settings_manager.set_channel_routing(settings_key, routing)-- agent_label = agent.capitalize()- confirmation = "\n".join(- [- f"✅ {self._t('success.sessionResumed', agent=agent_label, sessionId=session_id)}",- self._t("success.sessionResumedTip1"),- self._t("success.sessionResumedTip2"),- ]- )-- confirmation_ts = await self.im_client.send_message(context, confirmation, parse_mode="markdown")-- # If we created a fresh top-level message, use it as the new thread anchor- mapped_thread = target_thread or confirmation_ts- platform = getattr(self.config, "platform", "slack")- base_session_id = f"{platform}_{mapped_thread}"-- # Persist mapping- self.settings_manager.set_agent_session_mapping(settings_key, agent, base_session_id, session_id)- # Mark thread active- self.settings_manager.mark_thread_active(user_id, context.channel_id, mapped_thread)- except Exception as e:- logger.error(f"Error resuming session: {e}", exc_info=True)- context = MessageContext(- user_id=user_id,- channel_id=channel_id or user_id,- thread_id=thread_id or None,- platform_specific={"is_dm": is_dm},- )- await self.im_client.send_message(- context,- f"❌ {self._t('error.resumeSubmitFailed', error=str(e))}",- )-- async def handle_routing_modal_update(- self,- user_id: str,- channel_id: str,- view: dict,- action: dict,- is_dm: bool = False,- ) -> None:- """Handle routing modal updates when selections change."""- try:- view_id = view.get("id")- view_hash = view.get("hash")- if not view_id or not view_hash:- logger.warning("Routing modal update missing view id/hash")- return-- resolved_channel_id = channel_id if channel_id else user_id- context = MessageContext(- user_id=user_id,- channel_id=resolved_channel_id,- platform_specific={"is_dm": is_dm},- )-- settings_key = self._get_settings_key(context)- current_routing = self.settings_manager.get_channel_routing(settings_key)- all_backends = list(self.agent_service.agents.keys())- registered_backends = sorted(all_backends, key=lambda x: (x != "opencode", x))- current_backend = self.resolve_agent_for_context(context)-- values = view.get("state", {}).get("values", {})- backend_data = values.get("backend_block", {}).get("backend_select", {})- selected_backend = backend_data.get("selected_option", {}).get("value")- if not selected_backend:- selected_backend = current_backend-- def _selected_value(block_id: str, action_id: str) -> Optional[str]:- data = values.get(block_id, {}).get(action_id, {})- return data.get("selected_option", {}).get("value")-- def _selected_prefixed_value(block_id: str, action_prefix: str) -> Optional[str]:- block = values.get(block_id, {})- if not isinstance(block, dict):- return None- for action_id, action_data in block.items():- if (- isinstance(action_id, str)- and action_id.startswith(action_prefix)- and isinstance(action_data, dict)- ):- return action_data.get("selected_option", {}).get("value")- return None-- oc_agent = _selected_value("opencode_agent_block", "opencode_agent_select")- oc_model = _selected_value("opencode_model_block", "opencode_model_select")- oc_reasoning = _selected_prefixed_value("opencode_reasoning_block", "opencode_reasoning_select")-- # For block_actions, the latest selection is carried on the `action` payload.- action_id = action.get("action_id")- selected_value = None- selected_option = action.get("selected_option")- if isinstance(selected_option, dict):- selected_value = selected_option.get("value")-- if isinstance(action_id, str) and isinstance(selected_value, str):- if action_id == "opencode_agent_select":- oc_agent = selected_value- elif action_id == "opencode_model_select":- oc_model = selected_value- elif action_id.startswith("opencode_reasoning_select"):- oc_reasoning = selected_value-- # Extract Claude/Codex selections from current action or state- claude_agent = _selected_value("claude_agent_block", "claude_agent_select")- claude_model = _selected_value("claude_model_block", "claude_model_select")- codex_model = _selected_value("codex_model_block", "codex_model_select")- codex_reasoning = _selected_prefixed_value("codex_reasoning_block", "codex_reasoning_select")-- # Handle action payload for Claude/Codex- if isinstance(action_id, str) and isinstance(selected_value, str):- if action_id == "claude_agent_select":- claude_agent = selected_value- elif action_id == "claude_model_select":- claude_model = selected_value- elif action_id == "codex_model_select":- codex_model = selected_value- elif action_id.startswith("codex_reasoning_select"):- codex_reasoning = selected_value-- if oc_agent == "__default__":- oc_agent = None- if oc_model == "__default__":- oc_model = None- if oc_reasoning == "__default__":- oc_reasoning = None- if claude_agent == "__default__":- claude_agent = None- if claude_model == "__default__":- claude_model = None- if codex_model == "__default__":- codex_model = None- if codex_reasoning == "__default__":- codex_reasoning = None-- opencode_agents = []- opencode_models = {}- opencode_default_config = {}- claude_agents = []- claude_models = []- codex_models = []-- if "opencode" in registered_backends:- try:- opencode_agent = self.agent_service.agents.get("opencode")- if opencode_agent and hasattr(opencode_agent, "_get_server"):- server = await opencode_agent._get_server() # type: ignore[attr-defined]- await server.ensure_running()- cwd = self.get_cwd(context)- opencode_agents = await server.get_available_agents(cwd)- opencode_models = await server.get_available_models(cwd)- opencode_default_config = await server.get_default_config(cwd)- except Exception as e:- logger.warning(f"Failed to fetch OpenCode data: {e}")-- # Fetch Claude data- if "claude" in registered_backends:- try:- from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models-- cwd = self.get_cwd(context)- agents_result = get_claude_agents(cwd)- if agents_result.get("ok"):- claude_agents = agents_result.get("agents", [])- models_result = get_claude_models()- if models_result.get("ok"):- claude_models = models_result.get("models", [])- except Exception as e:- logger.warning(f"Failed to fetch Claude data: {e}")-- # Fetch Codex data- if "codex" in registered_backends:- try:- from vibe.api import codex_models as get_codex_models-- models_result = get_codex_models()- if models_result.get("ok"):- codex_models = models_result.get("models", [])- except Exception as e:- logger.warning(f"Failed to fetch Codex data: {e}")-- if hasattr(self.im_client, "update_routing_modal"):- await self.im_client.update_routing_modal( # type: ignore[attr-defined]- view_id=view_id,- view_hash=view_hash,- channel_id=resolved_channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_models=codex_models,- selected_backend=selected_backend,- selected_opencode_agent=oc_agent,- selected_opencode_model=oc_model,- selected_opencode_reasoning=oc_reasoning,- selected_claude_agent=claude_agent,- selected_claude_model=claude_model,- selected_codex_model=codex_model,- selected_codex_reasoning=codex_reasoning,- )- except Exception as e:- logger.error(f"Error updating routing modal: {e}", exc_info=True)-- # Routing update handler (for Slack modal)- async def handle_routing_update(- self,- user_id: str,- channel_id: str,- backend: str,- opencode_agent: Optional[str],- opencode_model: Optional[str],- opencode_reasoning_effort: Optional[str] = None,- claude_agent: Optional[str] = None,- claude_model: Optional[str] = None,- codex_model: Optional[str] = None,- codex_reasoning_effort: Optional[str] = None,- notify_user: bool = True,- is_dm: bool = False,- ):- """Handle routing update submission (from Slack modal)"""- from modules.settings_manager import ChannelRouting-- try:- # Get settings key- settings_key = user_id if is_dm else (channel_id or user_id)-- # Get existing routing to preserve settings for other backends- existing_routing = self.settings_manager.get_channel_routing(settings_key)-- # Merge with existing routing - only update fields for the selected backend- routing = ChannelRouting(- agent_backend=backend,- # OpenCode settings: update if opencode is selected, otherwise preserve existing- opencode_agent=opencode_agent- if backend == "opencode"- else (existing_routing.opencode_agent if existing_routing else None),- opencode_model=opencode_model- if backend == "opencode"- else (existing_routing.opencode_model if existing_routing else None),- opencode_reasoning_effort=opencode_reasoning_effort- if backend == "opencode"- else (existing_routing.opencode_reasoning_effort if existing_routing else None),- # Claude settings: update if claude is selected, otherwise preserve existing- claude_agent=claude_agent- if backend == "claude"- else (existing_routing.claude_agent if existing_routing else None),- claude_model=claude_model- if backend == "claude"- else (existing_routing.claude_model if existing_routing else None),- # Codex settings: update if codex is selected, otherwise preserve existing- codex_model=codex_model- if backend == "codex"- else (existing_routing.codex_model if existing_routing else None),- codex_reasoning_effort=codex_reasoning_effort- if backend == "codex"- else (existing_routing.codex_reasoning_effort if existing_routing else None),- )-- # Save routing- self.settings_manager.set_channel_routing(settings_key, routing)-- # Build confirmation message- parts = [f"{self._t('routing.label.backend')}: **{backend}**"]- if backend == "opencode":- if opencode_agent:- parts.append(f"{self._t('routing.label.agent')}: **{opencode_agent}**")- if opencode_model:- parts.append(f"{self._t('routing.label.model')}: **{opencode_model}**")- if opencode_reasoning_effort:- parts.append(f"{self._t('routing.label.reasoningEffort')}: **{opencode_reasoning_effort}**")- elif backend == "claude":- if claude_agent:- parts.append(f"{self._t('routing.label.agent')}: **{claude_agent}**")- if claude_model:- parts.append(f"{self._t('routing.label.model')}: **{claude_model}**")- elif backend == "codex":- if codex_model:- parts.append(f"{self._t('routing.label.model')}: **{codex_model}**")- if codex_reasoning_effort:- parts.append(f"{self._t('routing.label.reasoningEffort')}: **{codex_reasoning_effort}**")-- # Create context for confirmation message- context = MessageContext(- user_id=user_id,- channel_id=channel_id if channel_id else user_id,- platform_specific={},- )-- if notify_user:- await self.im_client.send_message(- context,- f"✅ {self._t('success.routingUpdated')}\n" + "\n".join(parts),- parse_mode="markdown",- )-- logger.info(- f"Routing updated for {settings_key}: backend={backend}, "- f"opencode_agent={opencode_agent}, opencode_model={opencode_model}, "- f"claude_agent={claude_agent}, claude_model={claude_model}, "- f"codex_model={codex_model}"- )-- except Exception as e:- logger.error(f"Error updating routing: {e}")- context = MessageContext(- user_id=user_id,- channel_id=channel_id if channel_id else user_id,- platform_specific={},- )- if notify_user:- await self.im_client.send_message(- context,- f"❌ {self._t('error.routingUpdateFailed', error=str(e))}",- )- else:- raise+ """Backward-compatible entrypoint; delegated to message dispatcher."""+ await self.message_dispatcher.emit_agent_message(+ context=context,+ message_type=message_type,+ text=text,+ parse_mode=parse_mode,+ )# Main run methoddef run(self):diff --git a/core/handlers/__init__.py b/core/handlers/__init__.pyindex f987ddf99..f5304d9e5 100644--- a/core/handlers/__init__.py+++ b/core/handlers/__init__.py@@ -1,13 +1,9 @@"""Handler modules for organizing controller functionality"""+from .base import BaseHandlerfrom .command_handlers import CommandHandlersfrom .session_handler import SessionHandlerfrom .settings_handler import SettingsHandlerfrom .message_handler import MessageHandler-__all__ = [- 'CommandHandlers',- 'SessionHandler',- 'SettingsHandler',- 'MessageHandler'-]\ No newline at end of file+__all__ = ["BaseHandler", "CommandHandlers", "SessionHandler", "SettingsHandler", "MessageHandler"]diff --git a/core/handlers/base.py b/core/handlers/base.pynew file mode 100644index 000000000..f80caae28--- /dev/null+++ b/core/handlers/base.py@@ -0,0 +1,31 @@+"""Shared handler foundation for controller-owned handlers."""++from modules.im import MessageContext+from vibe.i18n import t as i18n_t+++class BaseHandler:+ """Provide shared controller references and common helper methods."""++ def __init__(self, controller):+ self.controller = controller+ self.config = controller.config+ self.im_client = controller.im_client+ self.settings_manager = controller.settings_manager+ self.sessions = (+ getattr(controller, "sessions", None)+ or getattr(controller.settings_manager, "sessions", None)+ or controller.settings_manager+ )+ self.formatter = getattr(controller.im_client, "formatter", None)++ def _get_settings_key(self, context: MessageContext) -> str:+ return self.controller._get_settings_key(context)++ def _get_lang(self) -> str:+ if hasattr(self.controller, "_get_lang"):+ return self.controller._get_lang()+ return getattr(self.config, "language", "en")++ def _t(self, key: str, **kwargs) -> str:+ return i18n_t(key, self._get_lang(), **kwargs)diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex a9ac268eb..91a4fe9a2 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -5,31 +5,19 @@ import loggingfrom typing import Optionalfrom modules.agents import AgentRequest, get_agent_display_namefrom modules.im import MessageContext, InlineKeyboard, InlineButton-from vibe.i18n import t as i18n_t++from .base import BaseHandlerlogger = logging.getLogger(__name__)-class CommandHandlers:+class CommandHandlers(BaseHandler):"""Handles all bot command operations"""def __init__(self, controller):"""Initialize with reference to main controller"""- self.controller = controller- self.config = controller.config- self.im_client = controller.im_client+ super().__init__(controller)self.session_manager = controller.session_manager- self.settings_manager = controller.settings_manager-- def _get_lang(self) -> str:- """Get the global language setting from config."""- if hasattr(self.controller, "_get_lang"):- return self.controller._get_lang()- return getattr(self.config, "language", "en")-- def _t(self, key: str, **kwargs) -> str:- """Translate a key using the global language setting."""- return i18n_t(key, self._get_lang(), **kwargs)def _get_channel_context(self, context: MessageContext) -> MessageContext:"""Get context for channel messages (no thread)"""@@ -146,7 +134,7 @@ class CommandHandlers:"""Handle clear command - clears all sessions across configured agents"""try:# Get the correct settings key (channel_id for Slack, not user_id)- settings_key = self.controller._get_settings_key(context)+ settings_key = self._get_settings_key(context)cleared = await self.controller.agent_service.clear_sessions(settings_key)if not cleared:@@ -236,7 +224,7 @@ class CommandHandlers:return# Save to user settings- settings_key = self.controller._get_settings_key(context)+ settings_key = self._get_settings_key(context)self.settings_manager.set_custom_cwd(settings_key, absolute_path)logger.info(f"User {context.user_id} changed cwd to: {absolute_path}")@@ -251,6 +239,29 @@ class CommandHandlers:channel_context = self._get_channel_context(context)await self.im_client.send_message(channel_context, f"❌ {self._t('error.cwdSetFailed', error=str(e))}")+ async def handle_change_cwd_submission(+ self, user_id: str, new_cwd: str, channel_id: Optional[str] = None, is_dm: bool = False+ ):+ """Handle working directory change submission from modal."""+ try:+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ platform_specific={"is_dm": is_dm},+ )+ await self.handle_set_cwd(context, new_cwd.strip())+ except Exception as e:+ logger.error(f"Error changing working directory: {e}")+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ platform_specific={"is_dm": is_dm},+ )+ await self.im_client.send_message(+ context,+ f"❌ {self._t('error.cwdSetFailed', error=str(e))}",+ )+async def handle_change_cwd_modal(self, context: MessageContext):"""Handle Change Work Dir button - open modal for Slack"""if self.config.platform == "discord":@@ -323,8 +334,8 @@ class CommandHandlers:"""Open resume-session modal (Slack) or explain availability."""if self.config.platform == "discord":interaction = context.platform_specific.get("interaction") if context.platform_specific else None- settings_key = self.controller._get_settings_key(context)- sessions_by_agent = self.settings_manager.list_all_agent_sessions(settings_key)+ settings_key = self._get_settings_key(context)+ sessions_by_agent = self.sessions.list_all_agent_sessions(settings_key)if not sessions_by_agent:channel_context = self._get_channel_context(context)await self.im_client.send_message(@@ -351,8 +362,8 @@ class CommandHandlers:)returnif self.config.platform == "lark":- settings_key = self.controller._get_settings_key(context)- sessions_by_agent = self.settings_manager.list_all_agent_sessions(settings_key)+ settings_key = self._get_settings_key(context)+ sessions_by_agent = self.sessions.list_all_agent_sessions(settings_key)# Allow opening modal even with no sessions (user can paste manually)if hasattr(self.im_client, "open_resume_session_modal"):try:@@ -390,8 +401,8 @@ class CommandHandlers:)return- settings_key = self.controller._get_settings_key(context)- sessions_by_agent = self.settings_manager.list_all_agent_sessions(settings_key)+ settings_key = self._get_settings_key(context)+ sessions_by_agent = self.sessions.list_all_agent_sessions(settings_key)if not sessions_by_agent:channel_context = self._get_channel_context(context)@@ -420,7 +431,7 @@ class CommandHandlers:"""try:# Check if this is a DM context (settings_key == user_id means DM)- settings_key = self.controller._get_settings_key(context)+ settings_key = self._get_settings_key(context)if settings_key != context.user_id:# Not a DM — instruct user to use DMchannel_context = self._get_channel_context(context)@@ -433,10 +444,8 @@ class CommandHandlers:await self.im_client.send_message(channel_context, self._t("bind.usage"))return- store = self.settings_manager.store-# Check if user is already bound- if store.is_bound_user(context.user_id):+ if self.settings_manager.is_bound_user(context.user_id):channel_context = self._get_channel_context(context)await self.im_client.send_message(channel_context, self._t("bind.alreadyBound"))return@@ -453,13 +462,13 @@ class CommandHandlers:)# Atomic bind: validate code + create user + consume code in one operation- success, is_admin = store.bind_user_with_code(+ success, is_admin = self.settings_manager.bind_user_with_code(context.user_id, display_name, code, dm_chat_id=context.channel_id)if not success:# Could be already bound (race) or invalid code- if store.is_bound_user(context.user_id):+ if self.settings_manager.is_bound_user(context.user_id):channel_context = self._get_channel_context(context)await self.im_client.send_message(channel_context, self._t("bind.alreadyBound"))else:@@ -489,7 +498,7 @@ class CommandHandlers:try:session_handler = self.controller.session_handlerbase_session_id, working_path, composite_key = session_handler.get_session_info(context)- settings_key = self.controller._get_settings_key(context)+ settings_key = self._get_settings_key(context)agent_name = self.controller.resolve_agent_for_context(context)request = AgentRequest(context=context,diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 990762ab1..6fbafb57b 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -6,22 +6,19 @@ from typing import Optional, Listfrom modules.agents import AgentRequestfrom modules.im import MessageContextfrom modules.im.base import FileAttachment-from vibe.i18n import t as i18n_t++from .base import BaseHandlerlogger = logging.getLogger(__name__)-class MessageHandler:+class MessageHandler(BaseHandler):"""Handles message routing and Claude communication"""def __init__(self, controller):"""Initialize with reference to main controller"""- self.controller = controller- self.config = controller.config- self.im_client = controller.im_client+ super().__init__(controller)self.session_manager = controller.session_manager- self.settings_manager = controller.settings_manager- self.formatter = controller.im_client.formatterself.session_handler = None # Will be set after creationself.receiver_tasks = controller.receiver_tasks@@ -29,18 +26,6 @@ class MessageHandler:"""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_lang(self) -> str:- if hasattr(self.controller, "_get_lang"):- return self.controller._get_lang()- return getattr(self.config, "language", "en")-- def _t(self, key: str, **kwargs) -> str:- return i18n_t(key, self._get_lang(), **kwargs)-def _get_target_context(self, context: MessageContext) -> MessageContext:"""Get target context for sending messages"""# For Slack, use thread for replies if enabled@@ -74,7 +59,7 @@ class MessageHandler:message_ts = context.message_idthread_ts = context.thread_id or context.message_idif message_ts and thread_ts:- if self.settings_manager.is_message_already_processed(context.channel_id, thread_ts, message_ts):+ if self.sessions.is_message_already_processed(context.channel_id, thread_ts, message_ts):logger.info(f"Skipping already processed message: channel={context.channel_id}, "f"thread={thread_ts}, message={message_ts}"@@ -82,7 +67,7 @@ class MessageHandler:return# Record this message as processed immediately to prevent duplicates# even if processing fails (we don't want to retry failed messages forever)- self.settings_manager.record_processed_message(context.channel_id, thread_ts, message_ts)+ self.sessions.record_processed_message(context.channel_id, thread_ts, message_ts)# Skip automatic cleanup; receiver tasks are retained until shutdown@@ -294,12 +279,8 @@ class MessageHandler:try: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)+ settings_handler = self.controller.settings_handler+ command_handlers = self.controller.command_handler# Route based on callback data# Note: admin permission for protected callbacks is enforced by@@ -369,7 +350,7 @@ class MessageHandler:parts = callback_data.split(":", 2)agent = parts[1] if len(parts) > 1 else Nonesession_id = parts[2] if len(parts) > 2 else None- await self.controller.handle_resume_session_submission(+ await self.controller.session_handler.handle_resume_session_submission(user_id=context.user_id,channel_id=context.channel_id,thread_id=context.thread_id,diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 428de9d86..623b65dbc 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -5,38 +5,23 @@ import loggingfrom typing import Optional, Dict, Any, Tuplefrom modules.im import MessageContextfrom claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions-from vibe.i18n import t as i18n_t++from .base import BaseHandlerlogger = logging.getLogger(__name__)-class SessionHandler:+class SessionHandler(BaseHandler):"""Handles all session-related operations"""def __init__(self, controller):"""Initialize with reference to main controller"""- self.controller = controller- self.config = controller.config- self.im_client = controller.im_client+ super().__init__(controller)self.session_manager = controller.session_manager- self.settings_manager = controller.settings_manager- self.formatter = controller.im_client.formatterself.claude_sessions = controller.claude_sessionsself.receiver_tasks = controller.receiver_tasksself.stored_session_mappings = controller.stored_session_mappings- def _get_settings_key(self, context: MessageContext) -> str:- """Get settings key - delegate to controller"""- return self.controller._get_settings_key(context)-- def _get_lang(self) -> str:- if hasattr(self.controller, "_get_lang"):- return self.controller._get_lang()- return getattr(self.config, "language", "en")-- def _t(self, key: str, **kwargs) -> str:- return i18n_t(key, self._get_lang(), **kwargs)-def get_base_session_id(self, context: MessageContext) -> str:"""Get base session ID based on platform and context (without path)"""platform = getattr(self.config, "platform", "slack")@@ -97,7 +82,7 @@ class SessionHandler:base_session_id, working_path, composite_key = self.get_session_info(context)settings_key = self._get_settings_key(context)- stored_claude_session_id = self.settings_manager.get_claude_session_id(settings_key, base_session_id)+ stored_claude_session_id = self.sessions.get_claude_session_id(settings_key, base_session_id)# Read configuration overrides using settings_key (user_id for DM, channel_id for channels)channel_settings = self.settings_manager.get_channel_settings(settings_key)@@ -117,7 +102,7 @@ class SessionHandler:if effective_agent:cached_base = f"{base_session_id}:{effective_agent}"cached_key = f"{cached_base}:{working_path}"- cached_session_id = self.settings_manager.get_agent_session_id(+ cached_session_id = self.sessions.get_agent_session_id(settings_key,cached_base,agent_name="claude",@@ -183,20 +168,24 @@ class SessionHandler:if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):claude_env[key] = os.environ[key]- options = ClaudeAgentOptions(- permission_mode=self.config.claude.permission_mode,- cwd=working_path,- system_prompt=final_system_prompt,- resume=stored_claude_session_id if stored_claude_session_id else None,- extra_args=extra_args,- # Only set allowed_tools if agent file specifies tools; None = use SDK defaults- allowed_tools=agent_allowed_tools if agent_allowed_tools else None,- setting_sources=["user"], # Load user settings from ~/.claude/settings.json+ option_kwargs: Dict[str, Any] = {+ "permission_mode": self.config.claude.permission_mode,+ "cwd": working_path,+ "system_prompt": final_system_prompt,+ "resume": stored_claude_session_id if stored_claude_session_id else None,+ "extra_args": extra_args,+ "setting_sources": ["user"], # Load user settings from ~/.claude/settings.json# Disable AskUserQuestion tool - SDK cannot respond to it programmatically# See: https://github.com/anthropics/claude-code/issues/10168- disallowed_tools=["AskUserQuestion"],- env=claude_env, # Pass Anthropic/Claude env vars- )+ "disallowed_tools": ["AskUserQuestion"],+ "env": claude_env, # Pass Anthropic/Claude env vars+ }+ # Only set allowed_tools if agent file specifies tools.+ # Omitting the field keeps SDK default tool behavior.+ if agent_allowed_tools:+ option_kwargs["allowed_tools"] = agent_allowed_tools++ options = ClaudeAgentOptions(**option_kwargs)# Log session creation detailslogger.info(f"Creating Claude client for {base_session_id} at {working_path}")@@ -235,6 +224,85 @@ class SessionHandler:return client+ async def handle_resume_session_submission(+ self,+ user_id: str,+ channel_id: Optional[str],+ thread_id: Optional[str],+ agent: Optional[str],+ session_id: Optional[str],+ host_message_ts: Optional[str] = None,+ is_dm: bool = False,+ ) -> None:+ """Bind a provided session_id to the current thread for the chosen agent."""+ from modules.settings_manager import ChannelRouting++ try:+ if not agent or not session_id:+ raise ValueError("Agent and session ID are required to resume.")++ if getattr(self.controller, "agent_service", None):+ available_agents = set(self.controller.agent_service.agents.keys())+ if agent not in available_agents:+ raise ValueError(f"Agent '{agent}' is not enabled.")++ reuse_thread = True+ if host_message_ts and thread_id and thread_id == host_message_ts:+ reuse_thread = False++ target_thread = thread_id if reuse_thread else None++ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id or user_id,+ thread_id=target_thread or None,+ platform_specific={"is_dm": is_dm},+ )++ settings_key = self._get_settings_key(context)+ current_routing = self.settings_manager.get_channel_routing(settings_key)+ opencode_agent = current_routing.opencode_agent if current_routing else None+ opencode_model = current_routing.opencode_model if current_routing else None+ opencode_reasoning_effort = current_routing.opencode_reasoning_effort if current_routing else None++ routing = ChannelRouting(+ agent_backend=agent,+ opencode_agent=opencode_agent,+ opencode_model=opencode_model,+ opencode_reasoning_effort=opencode_reasoning_effort,+ )+ self.settings_manager.set_channel_routing(settings_key, routing)++ agent_label = agent.capitalize()+ confirmation = "\n".join(+ [+ f"✅ {self._t('success.sessionResumed', agent=agent_label, sessionId=session_id)}",+ self._t("success.sessionResumedTip1"),+ self._t("success.sessionResumedTip2"),+ ]+ )++ confirmation_ts = await self.im_client.send_message(context, confirmation, parse_mode="markdown")++ mapped_thread = target_thread or confirmation_ts+ platform = getattr(self.config, "platform", "slack")+ base_session_id = f"{platform}_{mapped_thread}"++ self.sessions.set_agent_session_mapping(settings_key, agent, base_session_id, session_id)+ self.sessions.mark_thread_active(user_id, context.channel_id, mapped_thread)+ except Exception as e:+ logger.error(f"Error resuming session: {e}", exc_info=True)+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id or user_id,+ thread_id=thread_id or None,+ platform_specific={"is_dm": is_dm},+ )+ await self.im_client.send_message(+ context,+ f"❌ {self._t('error.resumeSubmitFailed', error=str(e))}",+ )+async def cleanup_session(self, composite_key: str):"""Clean up a specific session by composite key"""# Cancel receiver task if exists@@ -288,7 +356,7 @@ class SessionHandler:def capture_session_id(self, base_session_id: str, claude_session_id: str, settings_key: str):"""Capture and store Claude session ID mapping"""# Persist to settings (settings_key is channel_id for Slack)- self.settings_manager.set_session_mapping(settings_key, base_session_id, claude_session_id)+ self.sessions.set_session_mapping(settings_key, base_session_id, claude_session_id)logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id}")@@ -296,7 +364,7 @@ class SessionHandler:"""Restore session mappings from settings on startup"""logger.info("Initializing session mappings from saved settings...")- session_state = self.settings_manager.sessions_store.state.session_mappings+ session_state = self.sessions.get_all_session_mappings()restored_count = 0for user_id, agent_map in session_state.items():diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.pyindex 44cbbcbfe..125320528 100644--- a/core/handlers/settings_handler.py+++ b/core/handlers/settings_handler.py@@ -1,35 +1,23 @@"""Settings and configuration handlers"""import logging+from typing import Optional+from modules.agents import get_agent_display_namefrom modules.im import MessageContext, InlineKeyboard, InlineButton-from vibe.i18n import t as i18n_t+from core.modals import RoutingModalData, RoutingModalSelection++from .base import BaseHandlerlogger = logging.getLogger(__name__)-class SettingsHandler:+class SettingsHandler(BaseHandler):"""Handles settings and configuration operations"""def __init__(self, controller):"""Initialize with reference to main controller"""- self.controller = controller- self.config = controller.config- self.im_client = controller.im_client- self.settings_manager = controller.settings_manager- self.formatter = controller.im_client.formatter-- def _get_settings_key(self, context: MessageContext) -> str:- """Get settings key - delegate to controller"""- return self.controller._get_settings_key(context)-- def _get_lang(self) -> str:- if hasattr(self.controller, "_get_lang"):- return self.controller._get_lang()- return getattr(self.config, "language", "en")-- def _t(self, key: str, **kwargs) -> str:- return i18n_t(key, self._get_lang(), **kwargs)+ super().__init__(controller)def _message_type_display_names(self) -> dict:return {@@ -336,50 +324,27 @@ class SettingsHandler:logger.error(f"Error showing routing settings: {e}", exc_info=True)await self.im_client.send_message(context, f"❌ {self._t('error.routingFailed', error=str(e))}")- async def _handle_routing_slack(self, context: MessageContext):- """Handle routing for Slack using modal dialog"""- trigger_id = context.platform_specific.get("trigger_id") if context.platform_specific else None-- if not trigger_id:- # No trigger_id, show button to open modal- buttons = [- [- InlineButton(- text=f"🤖 {self._t('button.agentSettings')}",- callback_data="open_routing_modal",- )- ]- ]- keyboard = InlineKeyboard(buttons=buttons)- await self.im_client.send_message_with_buttons(- context,- f"🤖 *{self._t('routing.introTitle')}*\n\n{self._t('routing.introDesc')}",- keyboard,- )- return-- # Gather data for the modal+ async def _gather_routing_modal_data(self, context: MessageContext) -> RoutingModalData:+ """Collect backend/agent/model data for routing modal renderers."""settings_key = self._get_settings_key(context)current_routing = self.settings_manager.get_channel_routing(settings_key)- # Get registered backends, prioritize opencode firstall_backends = list(self.controller.agent_service.agents.keys())registered_backends = sorted(all_backends, key=lambda x: (x != "opencode", x))-- # Get current backend (from routing or default)current_backend = self.controller.resolve_agent_for_context(context)- # Get OpenCode agents/models if availableopencode_agents = []opencode_models = {}opencode_default_config = {}+ claude_agents = []+ claude_models = []+ codex_models = []if "opencode" in registered_backends:try:- # Get OpenCode server manageropencode_agent = self.controller.agent_service.agents.get("opencode")if opencode_agent and hasattr(opencode_agent, "_get_server"):- server = await opencode_agent._get_server()+ server = await opencode_agent._get_server() # type: ignore[attr-defined]await server.ensure_running()cwd = self.controller.get_cwd(context)@@ -389,10 +354,6 @@ class SettingsHandler:except Exception as e:logger.warning(f"Failed to fetch OpenCode data: {e}")- # Get Claude agents/models if available- claude_agents = []- claude_models = []-if "claude" in registered_backends:try:from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models@@ -407,9 +368,6 @@ class SettingsHandler:except Exception as e:logger.warning(f"Failed to fetch Claude data: {e}")- # Get Codex models if available- codex_models = []-if "codex" in registered_backends:try:from vibe.api import codex_models as get_codex_models@@ -420,20 +378,48 @@ class SettingsHandler:except Exception as e:logger.warning(f"Failed to fetch Codex data: {e}")+ return RoutingModalData(+ registered_backends=registered_backends,+ current_backend=current_backend,+ current_routing=current_routing,+ opencode_agents=opencode_agents,+ opencode_models=opencode_models,+ opencode_default_config=opencode_default_config,+ claude_agents=claude_agents,+ claude_models=claude_models,+ codex_models=codex_models,+ )++ async def _handle_routing_slack(self, context: MessageContext):+ """Handle routing for Slack using modal dialog"""+ trigger_id = context.platform_specific.get("trigger_id") if context.platform_specific else None++ if not trigger_id:+ # No trigger_id, show button to open modal+ buttons = [+ [+ InlineButton(+ text=f"🤖 {self._t('button.agentSettings')}",+ callback_data="open_routing_modal",+ )+ ]+ ]+ keyboard = InlineKeyboard(buttons=buttons)+ await self.im_client.send_message_with_buttons(+ context,+ f"🤖 *{self._t('routing.introTitle')}*\n\n{self._t('routing.introDesc')}",+ keyboard,+ )+ return++ routing_data = await self._gather_routing_modal_data(context)+# Open modaltry:await self.im_client.open_routing_modal(trigger_id=trigger_id,channel_id=context.channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_models=codex_models,+ **routing_data.as_kwargs(),)except Exception as e:logger.error(f"Error opening routing modal: {e}", exc_info=True)@@ -441,73 +427,13 @@ class SettingsHandler:async def _handle_routing_discord(self, context: MessageContext):interaction = context.platform_specific.get("interaction") if context.platform_specific else None-- settings_key = self._get_settings_key(context)- current_routing = self.settings_manager.get_channel_routing(settings_key)-- all_backends = list(self.controller.agent_service.agents.keys())- registered_backends = sorted(all_backends, key=lambda x: (x != "opencode", x))- current_backend = self.controller.resolve_agent_for_context(context)-- opencode_agents = []- opencode_models = {}- opencode_default_config = {}-- if "opencode" in registered_backends:- try:- opencode_agent = self.controller.agent_service.agents.get("opencode")- if opencode_agent and hasattr(opencode_agent, "_get_server"):- server = await opencode_agent._get_server()- await server.ensure_running()-- cwd = self.controller.get_cwd(context)- opencode_agents = await server.get_available_agents(cwd)- opencode_models = await server.get_available_models(cwd)- opencode_default_config = await server.get_default_config(cwd)- except Exception as e:- logger.warning(f"Failed to fetch OpenCode data: {e}")-- claude_agents = []- claude_models = []-- if "claude" in registered_backends:- try:- from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models-- cwd = self.controller.get_cwd(context)- agents_result = get_claude_agents(cwd)- if agents_result.get("ok"):- claude_agents = agents_result.get("agents", [])- models_result = get_claude_models()- if models_result.get("ok"):- claude_models = models_result.get("models", [])- except Exception as e:- logger.warning(f"Failed to fetch Claude data: {e}")-- codex_models = []- if "codex" in registered_backends:- try:- from vibe.api import codex_models as get_codex_models-- models_result = get_codex_models()- if models_result.get("ok"):- codex_models = models_result.get("models", [])- except Exception as e:- logger.warning(f"Failed to fetch Codex data: {e}")+ routing_data = await self._gather_routing_modal_data(context)try:await self.im_client.open_routing_modal(trigger_id=interaction or context,channel_id=context.channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_models=codex_models,+ **routing_data.as_kwargs(),)except Exception as e:logger.error(f"Error opening routing modal: {e}", exc_info=True)@@ -519,73 +445,239 @@ class SettingsHandler:Gathers the same backend/model/agent data as Slack/Discord so theFeishu card can display selectors for all available options."""- settings_key = self._get_settings_key(context)- current_routing = self.settings_manager.get_channel_routing(settings_key)+ routing_data = await self._gather_routing_modal_data(context)- all_backends = list(self.controller.agent_service.agents.keys())- registered_backends = sorted(all_backends, key=lambda x: (x != "opencode", x))- current_backend = self.controller.resolve_agent_for_context(context)+ try:+ await self.im_client.open_routing_modal(+ trigger_id=context,+ channel_id=context.channel_id,+ **routing_data.as_kwargs(),+ )+ except Exception as e:+ logger.error(f"Error opening routing card for Lark: {e}", exc_info=True)+ await self.im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")- opencode_agents = []- opencode_models = {}- opencode_default_config = {}+ async def handle_settings_update(+ self,+ user_id: str,+ show_message_types: list,+ channel_id: Optional[str] = None,+ require_mention: Optional[bool] = None,+ language: Optional[str] = None,+ notify_user: bool = True,+ is_dm: bool = False,+ ):+ """Handle settings update (typically from modal submissions)."""+ try:+ settings_key = user_id if is_dm else (channel_id or user_id)- if "opencode" in registered_backends:- try:- opencode_agent = self.controller.agent_service.agents.get("opencode")- if opencode_agent and hasattr(opencode_agent, "_get_server"):- server = await opencode_agent._get_server()- await server.ensure_running()+ user_settings = self.settings_manager.get_user_settings(settings_key)+ user_settings.show_message_types = show_message_types+ self.settings_manager.update_user_settings(settings_key, user_settings)++ if not is_dm:+ self.settings_manager.set_require_mention(settings_key, require_mention)++ language_saved = True+ if language is not None and language != self.config.language:+ try:+ from config.v2_config import V2Config++ v2_config = V2Config.load()+ v2_config.language = language+ v2_config.save()+ self.config.language = language+ except Exception as err:+ language_saved = False+ logger.error(f"Failed to persist language setting: {err}")++ logger.info(+ f"Updated settings for {settings_key}: show types = {show_message_types}, "+ f"require_mention = {require_mention}, language = {language}"+ )- cwd = self.controller.get_cwd(context)- opencode_agents = await server.get_available_agents(cwd)- opencode_models = await server.get_available_models(cwd)- opencode_default_config = await server.get_default_config(cwd)- except Exception as e:- logger.warning(f"Failed to fetch OpenCode data: {e}")+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ platform_specific={},+ )- claude_agents = []- claude_models = []+ if notify_user:+ await self.im_client.send_message(context, f"✅ {self._t('success.settingsUpdated')}")+ if not language_saved:+ await self.im_client.send_message(+ context,+ f"⚠️ {self._t('error.languageUpdateFailed')}",+ )- if "claude" in registered_backends:- try:- from vibe.api import claude_agents as get_claude_agents, claude_models as get_claude_models+ except Exception as e:+ logger.error(f"Error updating settings: {e}")+ if notify_user:+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ platform_specific={},+ )+ await self.im_client.send_message(+ context,+ f"❌ {self._t('error.settingsUpdateFailed', error=str(e))}",+ )+ else:+ raise++ async def handle_routing_modal_update(+ self,+ user_id: str,+ channel_id: str,+ view_id: str,+ view_hash: str,+ selection: RoutingModalSelection,+ is_dm: bool = False,+ ) -> None:+ """Handle routing modal updates using normalized selection data."""+ try:+ if not view_id or not view_hash:+ logger.warning("Routing modal update missing view id/hash")+ return++ resolved_channel_id = channel_id if channel_id else user_id+ context = MessageContext(+ user_id=user_id,+ channel_id=resolved_channel_id,+ platform_specific={"is_dm": is_dm},+ )- cwd = self.controller.get_cwd(context)- agents_result = get_claude_agents(cwd)- if agents_result.get("ok"):- claude_agents = agents_result.get("agents", [])- models_result = get_claude_models()- if models_result.get("ok"):- claude_models = models_result.get("models", [])- except Exception as e:- logger.warning(f"Failed to fetch Claude data: {e}")+ routing_data = await self._gather_routing_modal_data(context)+ current_routing = routing_data.current_routing+ registered_backends = routing_data.registered_backends+ current_backend = routing_data.current_backend+ selected_backend = selection.selected_backend or current_backend++ if hasattr(self.im_client, "update_routing_modal"):+ await self.im_client.update_routing_modal( # type: ignore[attr-defined]+ view_id=view_id,+ view_hash=view_hash,+ channel_id=resolved_channel_id,+ registered_backends=registered_backends,+ current_backend=current_backend,+ current_routing=current_routing,+ opencode_agents=routing_data.opencode_agents,+ opencode_models=routing_data.opencode_models,+ opencode_default_config=routing_data.opencode_default_config,+ claude_agents=routing_data.claude_agents,+ claude_models=routing_data.claude_models,+ codex_models=routing_data.codex_models,+ selected_backend=selected_backend,+ selected_opencode_agent=selection.selected_opencode_agent,+ selected_opencode_model=selection.selected_opencode_model,+ selected_opencode_reasoning=selection.selected_opencode_reasoning,+ selected_claude_agent=selection.selected_claude_agent,+ selected_claude_model=selection.selected_claude_model,+ selected_codex_model=selection.selected_codex_model,+ selected_codex_reasoning=selection.selected_codex_reasoning,+ )+ except Exception as e:+ logger.error(f"Error updating routing modal: {e}", exc_info=True)++ async def handle_routing_update(+ self,+ user_id: str,+ channel_id: str,+ backend: str,+ opencode_agent: Optional[str],+ opencode_model: Optional[str],+ opencode_reasoning_effort: Optional[str] = None,+ claude_agent: Optional[str] = None,+ claude_model: Optional[str] = None,+ codex_model: Optional[str] = None,+ codex_reasoning_effort: Optional[str] = None,+ notify_user: bool = True,+ is_dm: bool = False,+ ):+ """Handle routing update submission (from modal)."""+ from config.v2_settings import RoutingSettings- codex_models = []- if "codex" in registered_backends:- try:- from vibe.api import codex_models as get_codex_models+ try:+ settings_key = user_id if is_dm else (channel_id or user_id)+ existing_routing = self.settings_manager.get_channel_routing(settings_key)++ routing = RoutingSettings(+ agent_backend=backend,+ opencode_agent=opencode_agent+ if backend == "opencode"+ else (existing_routing.opencode_agent if existing_routing else None),+ opencode_model=opencode_model+ if backend == "opencode"+ else (existing_routing.opencode_model if existing_routing else None),+ opencode_reasoning_effort=opencode_reasoning_effort+ if backend == "opencode"+ else (existing_routing.opencode_reasoning_effort if existing_routing else None),+ claude_agent=claude_agent+ if backend == "claude"+ else (existing_routing.claude_agent if existing_routing else None),+ claude_model=claude_model+ if backend == "claude"+ else (existing_routing.claude_model if existing_routing else None),+ codex_model=codex_model+ if backend == "codex"+ else (existing_routing.codex_model if existing_routing else None),+ codex_reasoning_effort=codex_reasoning_effort+ if backend == "codex"+ else (existing_routing.codex_reasoning_effort if existing_routing else None),+ )- models_result = get_codex_models()- if models_result.get("ok"):- codex_models = models_result.get("models", [])- except Exception as e:- logger.warning(f"Failed to fetch Codex data: {e}")+ self.settings_manager.set_channel_routing(settings_key, routing)++ parts = [f"{self._t('routing.label.backend')}: **{backend}**"]+ if backend == "opencode":+ if opencode_agent:+ parts.append(f"{self._t('routing.label.agent')}: **{opencode_agent}**")+ if opencode_model:+ parts.append(f"{self._t('routing.label.model')}: **{opencode_model}**")+ if opencode_reasoning_effort:+ parts.append(f"{self._t('routing.label.reasoningEffort')}: **{opencode_reasoning_effort}**")+ elif backend == "claude":+ if claude_agent:+ parts.append(f"{self._t('routing.label.agent')}: **{claude_agent}**")+ if claude_model:+ parts.append(f"{self._t('routing.label.model')}: **{claude_model}**")+ elif backend == "codex":+ if codex_model:+ parts.append(f"{self._t('routing.label.model')}: **{codex_model}**")+ if codex_reasoning_effort:+ parts.append(f"{self._t('routing.label.reasoningEffort')}: **{codex_reasoning_effort}**")++ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ platform_specific={},+ )- try:- await self.im_client.open_routing_modal(- trigger_id=context,- channel_id=context.channel_id,- registered_backends=registered_backends,- current_backend=current_backend,- current_routing=current_routing,- opencode_agents=opencode_agents,- opencode_models=opencode_models,- opencode_default_config=opencode_default_config,- claude_agents=claude_agents,- claude_models=claude_models,- codex_models=codex_models,+ if notify_user:+ await self.im_client.send_message(+ context,+ f"✅ {self._t('success.routingUpdated')}\n" + "\n".join(parts),+ parse_mode="markdown",+ )++ logger.info(+ f"Routing updated for {settings_key}: backend={backend}, "+ f"opencode_agent={opencode_agent}, opencode_model={opencode_model}, "+ f"claude_agent={claude_agent}, claude_model={claude_model}, "+ f"codex_model={codex_model}")+except Exception as e:- logger.error(f"Error opening routing card for Lark: {e}", exc_info=True)- await self.im_client.send_message(context, f"❌ {self._t('error.routingModalFailed')}")+ logger.error(f"Error updating routing: {e}")+ context = MessageContext(+ user_id=user_id,+ channel_id=channel_id if channel_id else user_id,+ platform_specific={},+ )+ if notify_user:+ await self.im_client.send_message(+ context,+ f"❌ {self._t('error.routingUpdateFailed', error=str(e))}",+ )+ else:+ raisediff --git a/core/message_dispatcher.py b/core/message_dispatcher.pynew file mode 100644index 000000000..d09f1735b--- /dev/null+++ b/core/message_dispatcher.py@@ -0,0 +1,283 @@+"""Consolidated agent message dispatcher.++Owns the main log/result/notify dispatch state machine that was previously+embedded in ``Controller.emit_agent_message``.+"""++from __future__ import annotations++import logging+import asyncio+from typing import Optional++from modules.im import MessageContext++logger = logging.getLogger(__name__)+++class ConsolidatedMessageDispatcher:+ """Dispatch agent messages while preserving existing product behavior."""++ def __init__(self, controller):+ self.controller = controller+ self._consolidated_message_ids: dict[str, str] = {}+ self._consolidated_message_buffers: dict[str, str] = {}+ self._consolidated_message_locks: dict[str, asyncio.Lock] = {}+ self._thread_current_message_id: dict[str, str] = {}++ def _get_settings_key(self, context: MessageContext) -> str:+ return self.controller._get_settings_key(context)++ def _get_target_context(self, context: MessageContext) -> MessageContext:+ if self.controller.im_client.should_use_thread_for_reply() and context.thread_id:+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ thread_id=context.thread_id,+ message_id=context.message_id,+ platform_specific=context.platform_specific,+ )+ return context++ def _get_consolidated_message_key(self, context: MessageContext) -> str:+ settings_key = self._get_settings_key(context)+ thread_key = context.thread_id or context.channel_id+ tracking_key = f"{settings_key}:{thread_key}"+ trigger_id = self._thread_current_message_id.get(tracking_key) or context.message_id or ""+ return f"{settings_key}:{thread_key}:{trigger_id}"++ def update_thread_message_id(self, context: MessageContext) -> None:+ if not context.message_id:+ return+ settings_key = self._get_settings_key(context)+ thread_key = context.thread_id or context.channel_id+ tracking_key = f"{settings_key}:{thread_key}"+ self._thread_current_message_id[tracking_key] = context.message_id++ def _get_consolidated_message_lock(self, key: str) -> asyncio.Lock:+ if key not in self._consolidated_message_locks:+ self._consolidated_message_locks[key] = asyncio.Lock()+ return self._consolidated_message_locks[key]++ async def clear_consolidated_message_id(+ self,+ context: MessageContext,+ trigger_message_id: Optional[str] = None,+ ) -> None:+ settings_key = self._get_settings_key(context)+ thread_key = context.thread_id or context.channel_id+ msg_id = trigger_message_id if trigger_message_id else (context.message_id or "")+ key = f"{settings_key}:{thread_key}:{msg_id}"++ lock = self._get_consolidated_message_lock(key)+ async with lock:+ self._consolidated_message_ids.pop(key, None)+ self._consolidated_message_buffers.pop(key, None)++ def _get_consolidated_max_bytes(self) -> int:+ if self.controller.config.platform == "discord":+ return 2000+ return 4000++ def _get_consolidated_split_threshold(self) -> int:+ if self.controller.config.platform == "discord":+ return 1800+ return 3600++ @staticmethod+ def _get_text_byte_length(text: str) -> int:+ return len(text.encode("utf-8"))++ def _get_result_max_chars(self) -> int:+ if self.controller.config.platform == "discord":+ return 1900+ return 30000++ @staticmethod+ def _build_result_summary(text: str, max_chars: int) -> str:+ if len(text) <= max_chars:+ return text+ prefix = "Result too long; showing a summary.\n\n"+ suffix = "\n\n…(truncated; see result.md for full output)"+ keep = max(0, max_chars - len(prefix) - len(suffix))+ return f"{prefix}{text[:keep]}{suffix}"++ def _truncate_consolidated(self, text: str, max_bytes: int) -> str:+ if self._get_text_byte_length(text) <= max_bytes:+ return text+ ellipsis = "…"+ target_bytes = max_bytes - len(ellipsis.encode("utf-8"))+ encoded = text.encode("utf-8")+ truncated = encoded[:target_bytes].decode("utf-8", errors="ignore")+ return truncated.rstrip() + ellipsis++ async def emit_agent_message(+ self,+ context: MessageContext,+ message_type: str,+ text: str,+ parse_mode: Optional[str] = "markdown",+ ) -> None:+ """Centralized dispatch for agent messages.++ Message Types:+ - Log Messages (system/assistant/toolcall): consolidated into a single+ editable message per conversation round. Can be hidden by user settings.+ - Result Message: final output, always sent immediately, not hideable.+ - Notify Message: notifications, always sent immediately.+ """+ if not text or not text.strip():+ return++ settings_manager = self.controller.settings_manager+ im_client = self.controller.im_client++ canonical_type = settings_manager._canonicalize_message_type(message_type or "")+ settings_key = self._get_settings_key(context)++ if canonical_type == "notify":+ target_context = self._get_target_context(context)+ await im_client.send_message(target_context, text, parse_mode=parse_mode)+ return++ if canonical_type == "result":+ target_context = self._get_target_context(context)+ if len(text) <= self._get_result_max_chars():+ await im_client.send_message(target_context, text, parse_mode=parse_mode)+ return++ summary = self._build_result_summary(text, self._get_result_max_chars())+ await im_client.send_message(target_context, summary, parse_mode=parse_mode)++ if self.controller.config.platform in {"slack", "discord", "lark"} and hasattr(+ im_client, "upload_markdown"+ ):+ try:+ await im_client.upload_markdown(+ target_context,+ title="result.md",+ content=text,+ filetype="markdown",+ )+ except Exception as err:+ logger.warning(f"Failed to upload result attachment: {err}")+ await im_client.send_message(+ target_context,+ "Failed to upload attachment. Want me to split the result into multiple messages?",+ parse_mode=parse_mode,+ )+ return++ if canonical_type not in {"system", "assistant", "toolcall"}:+ canonical_type = "assistant"++ if settings_manager.is_message_type_hidden(settings_key, canonical_type):+ preview = text if len(text) <= 500 else f"{text[:500]}…"+ logger.info(+ "Skipping %s message for settings %s (hidden). Preview: %s",+ canonical_type,+ settings_key,+ preview,+ )+ return++ consolidated_key = self._get_consolidated_message_key(context)+ lock = self._get_consolidated_message_lock(consolidated_key)++ async with lock:+ chunk = text.strip()+ max_bytes = self._get_consolidated_max_bytes()+ split_threshold = self._get_consolidated_split_threshold()+ existing = self._consolidated_message_buffers.get(consolidated_key, "")+ existing_message_id = self._consolidated_message_ids.get(consolidated_key)++ separator = "\n\n---\n\n" if existing else ""+ updated = f"{existing}{separator}{chunk}" if existing else chunk++ target_context = self._get_target_context(context)+ continuation_notice = "\n\n---\n\n_(continued below...)_"+ continuation_bytes = self._get_text_byte_length(continuation_notice)++ if existing_message_id and self._get_text_byte_length(updated) > split_threshold:+ old_text = existing + continuation_notice+ old_text = self._truncate_consolidated(old_text, max_bytes)++ try:+ await im_client.edit_message(+ target_context,+ existing_message_id,+ text=old_text,+ parse_mode="markdown",+ )+ except Exception as err:+ logger.warning(f"Failed to finalize old Log Message: {err}")++ self._consolidated_message_buffers[consolidated_key] = chunk+ self._consolidated_message_ids.pop(consolidated_key, None)+ updated = chunk+ existing_message_id = None+ logger.info(+ "Log Message exceeded %d bytes, starting new message",+ split_threshold,+ )++ while self._get_text_byte_length(updated) > max_bytes:+ target_bytes = split_threshold - continuation_bytes+ first_part = self._truncate_consolidated(updated, target_bytes)+ first_part = first_part.rstrip("…") + continuation_notice++ send_ok = False+ if existing_message_id:+ try:+ await im_client.edit_message(+ target_context,+ existing_message_id,+ text=first_part,+ parse_mode="markdown",+ )+ send_ok = True+ except Exception as err:+ logger.warning(f"Failed to edit oversized Log Message: {err}")+ else:+ try:+ await im_client.send_message(target_context, first_part, parse_mode="markdown")+ send_ok = True+ except Exception as err:+ logger.error(f"Failed to send oversized Log Message: {err}")++ if not send_ok:+ logger.warning("Stopping split loop due to send failure, truncating remainder")+ break++ sent_chars = len(first_part) - len(continuation_notice)+ updated = updated[sent_chars:]+ existing_message_id = None+ self._consolidated_message_ids.pop(consolidated_key, None)+ logger.info(+ "Log Message chunk exceeded %d bytes, split and continuing",+ max_bytes,+ )++ updated = self._truncate_consolidated(updated, max_bytes)+ self._consolidated_message_buffers[consolidated_key] = updated++ if existing_message_id:+ try:+ ok = await im_client.edit_message(+ target_context,+ existing_message_id,+ text=updated,+ parse_mode="markdown",+ )+ except Exception as err:+ logger.warning(f"Failed to edit Log Message: {err}")+ ok = False+ if ok:+ return+ self._consolidated_message_ids.pop(consolidated_key, None)++ try:+ new_id = await im_client.send_message(target_context, updated, parse_mode="markdown")+ self._consolidated_message_ids[consolidated_key] = new_id+ except Exception as err:+ logger.error(f"Failed to send Log Message: {err}", exc_info=True)diff --git a/core/modals.py b/core/modals.pynew file mode 100644index 000000000..112df68f6--- /dev/null+++ b/core/modals.py@@ -0,0 +1,50 @@+"""Platform-neutral modal data models."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Optional++from modules.settings_manager import ChannelRouting+++@dataclass+class RoutingModalData:+ """Shared routing modal payload consumed by platform renderers."""++ registered_backends: list[str]+ current_backend: str+ current_routing: ChannelRouting | None+ opencode_agents: list[str]+ opencode_models: dict[str, list[str]]+ opencode_default_config: dict[str, Any]+ claude_agents: list[str]+ claude_models: list[str]+ codex_models: list[str]++ def as_kwargs(self) -> dict[str, Any]:+ return {+ "registered_backends": self.registered_backends,+ "current_backend": self.current_backend,+ "current_routing": self.current_routing,+ "opencode_agents": self.opencode_agents,+ "opencode_models": self.opencode_models,+ "opencode_default_config": self.opencode_default_config,+ "claude_agents": self.claude_agents,+ "claude_models": self.claude_models,+ "codex_models": self.codex_models,+ }+++@dataclass+class RoutingModalSelection:+ """Normalized routing modal selection state."""++ selected_backend: str+ selected_opencode_agent: Optional[str] = None+ selected_opencode_model: Optional[str] = None+ selected_opencode_reasoning: Optional[str] = None+ selected_claude_agent: Optional[str] = None+ selected_claude_model: Optional[str] = None+ selected_codex_model: Optional[str] = None+ selected_codex_reasoning: Optional[str] = Nonediff --git a/core/update_checker.py b/core/update_checker.pyindex 41ff49a10..0b2401eb1 100644--- a/core/update_checker.py+++ b/core/update_checker.py@@ -270,8 +270,8 @@ class UpdateChecker:"""Check if any agent has active sessions."""try:# Check OpenCode active polls- if hasattr(self.controller, "settings_manager"):- active_polls = self.controller.settings_manager.get_all_active_polls()+ if hasattr(self.controller, "sessions"):+ active_polls = self.controller.sessions.get_all_active_polls()if active_polls:return True@@ -296,7 +296,7 @@ class UpdateChecker:"""try:if hasattr(self.controller, "settings_manager"):- store = getattr(self.controller.settings_manager, "store", None)+ store = self.controller.settings_manager.get_store()if store and hasattr(store, "get_admins"):admins = store.get_admins()return list(admins.keys())diff --git a/docs/plans/architecture-cleanup.md b/docs/plans/architecture-cleanup.mdindex c6537ba89..6549e6ef8 100644--- a/docs/plans/architecture-cleanup.md+++ b/docs/plans/architecture-cleanup.md@@ -1,370 +1,238 @@-# Architecture Cleanup Plan+# Architecture Cleanup Plan (First-Principles, Non-Regression First)-> **Branch**: `refactor/architecture-cleanup`-> **Prerequisite**: PR #69 (settings/auth refactoring) merged-> **Status**: Planning+> **Branch**: `refactor/architecture-cleanup`+> **Prerequisite**: PR #69 merged+> **Mode**: Aggressive cleanup in one branch, with strict compatibility gates+> **Status**: Completed-## 1. Background+## 1. Why This Refactor Exists++This repository currently implements one product behavior through several duplicated decision paths.+The real risk is not file size. The real risk is **decision drift** (same user action, different behavior by platform/code path).++This plan does a large cleanup, but enforces one hard priority:++**Product behavior stays intact. Refactor may change ownership and structure, not user-visible logic.**++## Progress Update++- Completed: `BaseHandler` introduced and adopted by all 4 handlers.+- Completed: callback query path now reuses controller-owned handler instances (no per-event re-instantiation).+- Completed: modal submission/update callbacks now routed directly to handler-owned methods.+- Completed: controller-heavy submission/update methods replaced with compatibility wrappers.+- Completed: `SessionsFacade` introduced; session/thread/dedup/poll usage migrated from direct `SettingsManager` methods to session facade paths.+- Completed: IM auth checks now go through `BaseIMClient.check_authorization` (shared command-action extraction + centralized auth call).+- Completed: routing modal data collection unified in a single handler helper (`_gather_routing_modal_data`) and reused by Slack/Discord/Feishu routing entrypoints.+- Completed: routing model duplication reduced in `SettingsManager` by converging runtime routing conversion onto `RoutingSettings`-based helpers.+- Completed: `emit_agent_message` state machine extracted into `core/message_dispatcher.py` and controller now delegates dispatching.+- Completed: regression guard tests added for auth invariants and IM auth action extraction.+- Completed: introduced platform-neutral `RoutingModalData` (`core/modals.py`) and switched routing modal data flow to typed model instead of ad-hoc dicts.+- Completed: introduced shared command parsing/dispatch helpers in `BaseIMClient` and migrated Slack/Discord/Feishu text command handling to shared path.+- Completed: extracted routing modal selection parsing into Slack adapter helper (`modules/im/slack_modal.py::parse_routing_modal_selection`) to keep core handler logic platform-agnostic.+- Completed: removed controller compatibility wrappers for migrated handlers (controller now delegates via direct callback wiring).+- Completed: moved Slack routing selection parsing out of core into Slack adapter helper (`modules/im/slack_modal.py`).+- Completed: removed temporary `SettingsManager` session-compat shim methods after all call sites migrated to `SessionsFacade`.-PR #69 解决了 settings store / auth pipeline 层面的 5 个根因问题。但在 review 过程中对整体架构做了一次全面审计,发现还有 4 类系统性技术债务。这些债务不影响功能正确性,但拖慢开发速度、增加 bug 引入风险、阻碍新平台接入。+## 2. First-Principles Invariants (Must Always Hold)-**审计数据摘要**:+The refactor is complete only if these invariants are true:-| 指标 | 当前值 |-|------|--------|-| controller.py | 1,270 行 / 35 方法 / 12 种职责 |-| IM 层总行数 | 7,565 行(slack 3,224 + discord 1,648 + feishu 2,693) |-| IM 层预估重复率 | ~60-65% |-| settings_manager.py | 690 行 / 40 方法 / 5 种不相关职责 |-| Handler 间重复方法 | `_get_lang()`, `_t()`, `_get_settings_key()` × 4 份 |+1. **Authorize before side effects**+ No state write or agent call before auth decision.+2. **Idempotent inbound handling**+ Same message event cannot be processed twice.+3. **Stable session identity**+ Session key generation is single-source and deterministic.+4. **Core/transport separation**+ Core does not parse platform UI details (`block_id`, card schema internals, etc.).+5. **State ownership clarity**+ IM layer cannot bypass state facades via direct store mutation.-## 2. 问题详解+## 3. Current Evidence (Code Audit Snapshot)-### 问题 A:Controller God Object+| Area | Current State |+|---|---|+| `core/controller.py` | 1,270 LOC, mixed orchestration + business logic |+| IM layer | 7,565 LOC total, substantial duplicated flow |+| `modules/settings_manager.py` | 690 LOC, mixed settings + sessions + pass-through methods |+| Handlers | duplicated helper methods across 4 classes |+| Largest hot spot | `SlackBot._build_routing_modal_view` ~523 LOC |++## 4. Target Architecture (Single Behavior Graph)++### 4.1 Layers++- **Policy Core**: auth, dedup, routing/session decision, command normalization.+- **Application Orchestrator**: controller wires dependencies and delegates.+- **Platform Adapters**: Slack/Discord/Feishu extract events + render UI only.+- **State Facades**: clear separation of configuration state and session/runtime state.-**现状**:`core/controller.py` 承载 12 种职责,其中 ~652 行是 handler 级别的业务逻辑(5 个 modal/submission handler),本应在 handler 层。+### 4.2 Ownership Rules-**5 个应下沉的方法**:+- `controller` orchestrates; it does not own modal parsing details.+- `handlers` own business workflows for settings/routing/sessions/commands.+- `BaseIMClient` owns shared inbound pipeline steps.+- platform clients own transport specifics only.-| 方法 | 行数 | 应归属 |-|------|------|--------|-| `handle_settings_update` | 76 | `SettingsHandler` |-| `handle_change_cwd_submission` | 27 | `CommandHandlers` |-| `handle_resume_session_submission` | 85 | `SessionHandler` |-| `handle_routing_modal_update` | 174 | `SettingsHandler`(或新建 `RoutingHandler`) |-| `handle_routing_update` | 112 | `SettingsHandler`(或新建 `RoutingHandler`) |+## 5. Execution Plan (Aggressive, Guarded)-**其他问题**:-- `emit_agent_message` 178 行,包含完整的消息合并/拆分/截断状态机。可提取为 `ConsolidatedMessageDispatcher` 类。-- `_init_modules` 中 3 个 `isinstance` 检查 + 平台特定导入,破坏了 `IMFactory` 的抽象。-- `handle_routing_modal_update` 解析 Slack Block Kit 的 `block_id`/`action_id`,纯 Slack 特定逻辑不该在 core 层。+## Phase 0 - Baseline and Safety Net (mandatory before structural moves)-### 问题 B:IM 层巨量 Copy-Paste+**Goal**: lock current behavior before moving code.-**现状**:3 个 IM 客户端独立实现了相同的业务流程,只是 UI 序列化格式不同。`BaseIMClient`(353 行)只抽象了消息传输层,未覆盖 UI 构建和入站处理。+Deliverables:+- Add focused regression tests for:+ - auth gate outcomes (`unbound_dm`, `unauthorized_channel`, `not_admin`)+ - `/bind` flow and first-admin invariant+ - resume-session selection + manual session submit+ - routing save/update flow+ - inbound dedup behavior+- Keep a single runtime path (no long-lived feature switch) to avoid dual-path drift.-**重复最严重的 5 块**:+Implementation note:+- To keep complexity low and avoid long-lived dual paths, migration shipped directly with behavior guards (tests + phased delegation) instead of adding a runtime feature toggle.-| 功能 | Slack | Discord | Feishu | 重复性质 |-|------|-------|---------|--------|---------|-| 消息处理主循环 | 238 行 | 127 行 | 175 行 | 业务流程相同,提取数据的 hook 不同 |-| Routing Modal | 523 行 | 441 行 | 315 行 | 选项构造逻辑完全相同,只是序列化格式不同 |-| Settings Modal | 223 行 | 216 行 | 142 行 | 选项构造逻辑相同 |-| Resume Session Modal | 163 行 | 105 行 | 149 行 | 选项构造逻辑相同 |-| Auth Denial | 27 行 | 22 行 | 11 行 | 三种拒绝分支 + i18n key 完全一致 |+No-regression constraints:+- Existing command names, callback IDs, and i18n keys remain unchanged.+- Existing settings/session JSON formats remain backward compatible.++## Phase 1 - Controller Decomposition + Handler Foundation++**Goal**: remove business logic from `controller`, keep behavior identical.++Deliverables:+- Create `core/handlers/base.py` and migrate shared helper methods there.+- Move these methods out of `controller` into handlers:+ - `handle_settings_update`+ - `handle_change_cwd_submission`+ - `handle_resume_session_submission`+ - `handle_routing_modal_update`+ - `handle_routing_update`+- Update callback wiring to handler-owned methods.+- Stop per-call handler re-instantiation in `message_handler`.+- Extract `emit_agent_message` state machine into dedicated dispatcher class.++No-regression constraints:+- Callback payload contracts unchanged.+- Threading, chunking, and reaction behavior in outbound replies unchanged.++## Phase 2 - State Layer Split (Settings vs Sessions)++**Goal**: enforce clear state ownership and remove mixed responsibilities.++Deliverables:+- Introduce `SessionsFacade` and migrate all session/thread/dedup/poll APIs to it.+- Keep temporary compatibility wrappers in `SettingsManager` for one migration window.+- Replace direct `settings_manager.store` usage in IM/handlers with explicit facade methods.+- Normalize duplicated data models where semantically safe.-**单个最长方法**:`SlackBot._build_routing_modal_view` = 523 行。+No-regression constraints:+- Existing persisted files can be read without migration scripts.+- Admin and bind invariants preserved exactly.-### 问题 C:SettingsManager / SettingsStore 分层不清+## Phase 3 - Shared Inbound Pipeline Across IM Platforms-**三个子问题**:+**Goal**: unify decisions, not transport.-**C1. 双重 dataclass**:-- `settings_manager.UserSettings` ≈ `v2_settings.ChannelSettings`-- `settings_manager.ChannelRouting` ≈ `v2_settings.RoutingSettings`-- 4 个纯搬运字段的转换方法:`_from_channel_settings`, `_to_channel_settings`, `_from_bound_user_settings`, `_sync_to_bound_user`+Deliverables:+- Implement shared inbound pipeline in `BaseIMClient` for:+ - hot reload trigger+ - auth check+ - dedup check+ - command action normalization+ - unified denial routing+- Keep platform hooks for extraction and platform-specific mention/thread semantics.-**C2. Leaky facade**:-- IM 层 15 处直接 `self.settings_manager.store` 穿透访问(主要是传给 `check_auth(store=...)`)-- `vibe/api.py` 完全绕过 SettingsManager 直接操作 SettingsStore+No-regression constraints:+- Slack `app_mention`, Discord guild/thread behavior, and Feishu shared-content extraction remain platform-correct.-**C3. God object(690 行 / 40 方法)**:-- 真正的 settings 逻辑:~20 方法-- Session mapping / thread tracking / message dedup / active polls:~20 方法,全部委托给 `SessionsStore`-- 23% 的方法是 pass-through 或 alias+## Phase 4 - Modal Schema Unification + Renderers-**C4. 业务逻辑下沉到存储层**:-- `SettingsStore.bind_user_with_code`:验证码 + 首用户自动 admin + 原子绑定,是完整业务流程-- `SettingsStore.set_admin`:enforces "不能移除最后一个 admin"+**Goal**: one modal definition, three renderers.-### 问题 D:Handler 缺少 Base Class+Deliverables:+- Build platform-neutral modal schema objects for settings/routing/resume/cwd.+- Add per-platform renderers:+ - Slack Block Kit renderer+ - Discord View renderer+ - Feishu Card renderer+- Keep existing callback IDs and submission payload semantics stable.-**现状**:4 个 handler 各自 copy-paste 初始化 + 3 个工具方法。+No-regression constraints:+- User can complete the same flows with identical outputs and permissions.-```python-# 重复 4 次的模式-class XxxHandler:- def __init__(self, controller):- self.controller = controller- self.config = controller.config- self.im_client = controller.im_client- self.settings_manager = controller.settings_manager- ...+## Phase 5 - Compatibility Cleanup and Dead Code Removal- def _get_lang(self): ... # 同一实现 × 4- def _t(self, key, **kw): ... # 同一实现 × 4- def _get_settings_key(self, context): ... # 同一实现 × 4-```+**Goal**: remove temporary shims once parity is proven.-另外 `message_handler.handle_callback_query()` 每次调用都新建 `SettingsHandler` 和 `CommandHandlers` 实例,而不是复用 controller 上已有的实例。+Deliverables:+- Remove deprecated wrappers and duplicate conversion helpers.+- Remove temporary compatibility paths once parity is proven.+- Finalize docs and architecture map.-## 3. 重构方案+No-regression constraints:+- All Phase 0 tests remain green with compatibility code removed.-### Phase A:Handler Base Class + Controller 瘦身+## 6. Behavior-Compatibility Matrix (Release Gate)-**目标**:消除 handler 间 copy-paste,将 controller 中的 handler 逻辑下沉。+All rows must pass on Slack + Discord + Feishu unless marked platform-specific.-**Phase A1:Handler Base Class**+| Capability | Expected Compatibility |+|---|---|+| DM message handling | identical accept/reject behavior |+| Channel auth enforcement | identical denial outcomes |+| Admin-protected actions | identical permission checks |+| `/bind` | identical success/failure semantics |+| settings update | identical persisted values |+| routing update | identical backend/model/reasoning persistence |+| resume session | identical mapping and resume behavior |+| message dedup | no duplicate downstream processing |+| i18n text keys | no key regressions |-```python-# core/handlers/base.py (新建)-class BaseHandler:- """Shared base for all handlers."""+## 7. Validation Strategy- def __init__(self, controller):- self.controller = controller- self.config = controller.config- self.im_client = controller.im_client- self.settings_manager = controller.settings_manager- self.formatter = getattr(controller, "formatter", None)+Automated checks (minimum per major step):+- targeted unit tests for changed module+- existing `tests/test_resume_session.py`+- existing `tests/test_v2_sessions.py`+- existing `tests/test_ui_api.py` (for API-facing setting behavior)- def _get_lang(self) -> str:- return self.config.language or "en"+Manual sanity checks (required before enabling new path by default):+- start bot and send regular message in channel+- run `/settings`, `/routing`, `/set_cwd`, `/resume`+- verify DM bind and admin restrictions+- verify thread continuation and dedup- def _t(self, key: str, **kwargs) -> str:- from vibe.i18n import t- return t(key, self._get_lang(), **kwargs)+## 8. Rollout and Fallback- def _get_settings_key(self, context: MessageContext) -> str:- is_dm = (context.platform_specific or {}).get("is_dm", False)- return context.user_id if is_dm else context.channel_id-```+- Roll out by incremental commits with behavior-preserving tests at each step.+- Avoid dual runtime paths to reduce maintenance and drift risk.+- Keep rollback via git history and branch-level revert points.-让 4 个 handler 继承 `BaseHandler`,删除各自的重复定义。+## 9. Scope and Risk Posture-**Phase A2:下沉 5 个 handler 方法**+This is intentionally a large cleanup. To control risk without reducing scope:-| 方法 | 从 controller 移至 | 改动要点 |-|------|-------------------|---------|-| `handle_settings_update` | `SettingsHandler` | 直接搬运,依赖通过 base 获取 |-| `handle_change_cwd_submission` | `CommandHandlers` | 直接搬运 |-| `handle_resume_session_submission` | `SessionHandler` | 需要传入 `claude_sessions` dict |-| `handle_routing_modal_update` | `SettingsHandler`(或新建 `RoutingHandler`) | **注意**:包含 Slack Block Kit 解析,后续 Phase B 进一步抽象 |-| `handle_routing_update` | `SettingsHandler`(或新建 `RoutingHandler`) | 直接搬运 |+- Use small, reviewable commits inside one branch.+- Keep each commit behavior-preserving where possible.+- Add tests before moving logic whenever practical.+- Prefer root-cause ownership fixes over wrappers, except temporary compatibility shims.-Controller 的 `_setup_callbacks` 改为指向 handler 上的方法。+## 10. Definition of Done-**Phase A3:修复 `handle_callback_query` 实例化**+The refactor is done only when all are true:-```python-# Before: 每次新建-settings_handler = SettingsHandler(self.controller)-command_handler = CommandHandlers(self.controller)+- Controller returns to orchestration role.+- Platform adapters no longer contain duplicated policy decisions.+- State boundaries are explicit and enforced.+- Modal logic is single-source with platform renderers.+- Compatibility matrix is fully green.+- Temporary migration shims are removed.-# After: 复用已有实例-settings_handler = self.controller.settings_handler-command_handler = self.controller.command_handler-```+## Final Check-**Phase A4:提取 ConsolidatedMessageDispatcher(可选)**--`emit_agent_message` 的消息合并/拆分状态机(~178 行)可提取为独立类,但因为与 controller 的 `im_client` 和 `settings_manager` 耦合较深,改动量不小。建议在 A1-A3 完成后评估是否值得。--**预期收益**:-- Controller 从 1,270 行降至 ~600 行-- 消除 12 处 `_get_lang`/`_t`/`_get_settings_key` 重复-- Handler 职责清晰,新功能知道该加在哪里--### Phase B:IM 消息处理主循环抽象--**目标**:消除 3 个平台各自 ~200 行的消息处理主循环重复。--**设计思路**:在 `BaseIMClient` 中实现共享的入站消息处理流程,平台子类只实现数据提取 hook。--```python-# modules/im/base.py-class BaseIMClient:- async def process_inbound_message(self, raw_event: dict) -> Optional[MessageContext]:- """Shared inbound message processing pipeline.-- Subclasses implement the extract_* hooks.- """- # 1. Extract basic info- event_data = self.extract_event_data(raw_event)- if event_data is None:- return None-- # 2. Dedup check- if self._is_duplicate(event_data):- return None-- # 3. Config hot-reload- self._refresh_config()-- # 4. Build context with is_dm- context = self.build_message_context(event_data)-- # 5. Auth check- auth = check_auth(- user_id=context.user_id,- channel_id=context.channel_id,- is_dm=context.platform_specific.get("is_dm", False),- action=self._parse_command_action(event_data.text),- store=self.settings_manager.store if self.settings_manager else None,- )- if not auth.allowed:- await self._send_auth_denial(context.channel_id, context.user_id, auth)- return None-- # 6. require_mention + thread check- if not self._should_process(event_data, context):- return None-- # 7. Parse commands- if self._is_command(event_data.text):- await self._dispatch_command(event_data, context)- return None-- # 8. Dispatch to message handler- return context-- # --- Platform hooks (abstract) ---- def extract_event_data(self, raw_event) -> Optional[EventData]: ...- def build_message_context(self, event_data: EventData) -> MessageContext: ...- def _should_process(self, event_data, context) -> bool: ...-```--**注意**:这个改动风险最高,因为 3 个平台各自有微妙差异(Slack 有 `app_mention` 事件、Feishu 有 shared content 提取、Discord 有 guild/thread 检查)。需要仔细设计 hook 点,避免过度抽象。--**建议**:先只抽 auth + dedup + command 解析这几个高置信度的共享步骤,不要试图抽象整个 pipeline。--**预期收益**:-- 减少 ~300-400 行重复-- 新平台接入只需实现 hook,不需要复制整个主循环-- Auth 逻辑不会再漏--### Phase C:SettingsManager 拆分--**目标**:将 SettingsManager 的 5 种职责分离为清晰的模块。--**Phase C1:分离 SessionsFacade**--SettingsManager 的 ~20 个 session/thread/dedup/poll 方法全部委托给 `SessionsStore`。将它们提取为独立的 `SessionsFacade` 类(或直接让消费方使用 `SessionsStore`)。--```python-# Before: controller.settings_manager.set_agent_session_mapping(...)-# After: controller.sessions.set_agent_session_mapping(...)-```--消费方:`session_handler.py`, `message_handler.py`, `controller.py`(emit_agent_message 中的 session 追踪)。--**Phase C2:统一 dataclass**--消除 `settings_manager.UserSettings` / `settings_manager.ChannelRouting`,直接使用 `v2_settings.ChannelSettings` / `v2_settings.RoutingSettings`。删除 4 个转换方法。--这要求 `v2_settings` 的 dataclass 足够好用(字段名、默认值等),可能需要小幅调整。--**Phase C3:封装 store 访问**--IM 层 15 处 `self.settings_manager.store` 穿透。主要用途是传给 `check_auth(store=...)`。解决方案:--```python-# Option A: SettingsManager 暴露 auth 需要的方法-class SettingsManager:- def get_store(self) -> SettingsStore:- """Explicit store access for auth pipeline."""- return self.store--# Option B: check_auth 接受 SettingsManager 而非 SettingsStore-def check_auth(..., settings_manager=None):- store = settings_manager.store if settings_manager else None-```--Option A 更诚实(store 就是需要被外部访问的),Option B 增加了不必要的间接层。**建议 Option A**。--**预期收益**:-- SettingsManager 从 690 行 / 40 方法降至 ~400 行 / ~20 方法-- 消除双重 dataclass 和 4 个转换方法-- 职责边界清晰:SettingsManager 管 settings,SessionsFacade 管 sessions--### Phase D:IM Modal 逻辑抽象(长期)--**目标**:消除 3 个平台 ~1000+ 行的 modal 构建重复。--**设计思路**:引入平台无关的 Modal Data Model + 平台特定 Renderer。--```python-# core/modals.py (新建)-@dataclass-class ModalField:- id: str- label: str- type: Literal["select", "multi_select", "text_input"]- options: List[ModalOption] = field(default_factory=list)- default: Any = None--@dataclass-class ModalDefinition:- title: str- fields: List[ModalField]- submit_label: str = "Save"--# 构建 modal 数据(平台无关)-def build_settings_modal(user_settings, message_types, ...) -> ModalDefinition:- ...--def build_routing_modal(current_routing, backends, ...) -> ModalDefinition:- ...-```--每个平台实现 `render_modal(definition: ModalDefinition) -> PlatformView`。--**风险**:-- 三个平台的 UI 能力差异大(Slack Block Kit vs Discord Views vs Feishu Cards)-- 过度抽象可能导致 "lowest common denominator" 问题-- 投入产出比不一定划算--**建议**:先做 Phase A-C,观察实际开发速度提升后再决定是否做 Phase D。如果后续不再新增 IM 平台,这个投入可能不值得。--## 4. 实现顺序与依赖--```-Phase A1 (Handler Base Class)- ↓-Phase A2 (Controller 瘦身) ← depends on A1- ↓-Phase A3 (fix callback_query) ← independent, can merge early- ↓-Phase B (IM 主循环抽象) ← independent of A- ↓-Phase C1 (SessionsFacade 分离) ← independent of A/B- ↓-Phase C2 (统一 dataclass) ← after C1- ↓-Phase C3 (封装 store 访问) ← after C2- ↓-Phase D (Modal 抽象) ← after all above, optional-```--Phase A1-A3 和 Phase C1 可以并行。Phase B 独立但风险最高,建议放在 A 完成后。--## 5. 文件改动预估--| Phase | 新建文件 | 修改文件 | 预估行数变化 |-|-------|---------|---------|-------------|-| A1 | `core/handlers/base.py` | 4 handler files | +50 / -60 |-| A2 | — | controller.py, 3 handler files, 3 IM files | +500 / -650 |-| A3 | — | message_handler.py | +2 / -4 |-| B | — | base.py, slack.py, discord.py, feishu.py | +150 / -400 |-| C1 | `modules/sessions_facade.py`(可选) | controller.py, session_handler.py, message_handler.py, settings_manager.py | +100 / -80 |-| C2 | — | settings_manager.py, v2_settings.py | +20 / -120 |-| C3 | — | settings_manager.py | +5 / -0 |-| D | `core/modals.py` | 3 IM files, settings_handler.py | +300 / -800 |--## 6. 风险与缓解--| 风险 | 缓解 |-|------|------|-| Phase A2 搬运时遗漏 controller 内部状态引用 | 每步 lint + 手动验证一个平台 |-| Phase B 过度抽象导致平台特性丢失 | 只抽高置信度步骤(auth/dedup/command),保留平台 hook |-| Phase C2 统一 dataclass 破坏序列化 | 先写转换测试,确认 JSON 格式不变 |-| 改动量大导致引入回归 | 每 phase 独立 PR,可增量 merge |--## 7. 验证清单--- [ ] 每 phase lint 通过-- [ ] Bot 启动正常(至少 Slack 平台)-- [ ] 消息收发正常-- [ ] Settings / Routing / CWD modal 正常-- [ ] DM bind 流程正常-- [ ] Admin 权限控制正常+- Controller orchestration-only shape achieved; handler wrappers removed.+- Shared policy decisions (auth + command normalization + session facade usage) are centralized.+- Core no longer parses Slack routing modal block/action identifiers.+- Modal data flow is typed (`RoutingModalData`, `RoutingModalSelection`) and adapter-facing.+- Focused compatibility tests pass (`auth`, `routing parsing`, `sessions`, `paths`, `ui api`).diff --git a/modules/agents/base.py b/modules/agents/base.pyindex aa639eccb..392b5d9ca 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -59,6 +59,11 @@ class BaseAgent(ABC):self.config = controller.configself.im_client = controller.im_clientself.settings_manager = controller.settings_manager+ self.sessions = (+ getattr(controller, "sessions", None)+ or getattr(controller.settings_manager, "sessions", None)+ or controller.settings_manager+ )def _calculate_duration_ms(self, started_at: Optional[float]) -> int:if not started_at:diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex e03e53dde..e3c576d23 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -112,10 +112,10 @@ class ClaudeAgent(BaseAgent):async def clear_sessions(self, settings_key: str) -> int:"""Clear Claude sessions scoped to the provided settings key."""- agent_map = self.settings_manager.sessions_store.get_agent_map(settings_key, self.name)+ agent_map = self.sessions.list_agent_sessions(settings_key, self.name)session_bases_to_clear = set(agent_map.keys())- self.settings_manager.clear_agent_sessions(settings_key, self.name)+ self.sessions.clear_agent_sessions(settings_key, self.name)sessions_to_clear = []for session_key in list(self.claude_sessions.keys()):diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 4e4843556..5e4b146ca 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -188,7 +188,7 @@ class CodexAgent(BaseAgent):async def clear_sessions(self, settings_key: str) -> int:"""Clear sessions scoped to a specific settings_key."""- self.settings_manager.clear_agent_sessions(settings_key, self.name)+ self.sessions.clear_agent_sessions(settings_key, self.name)# Get base_session_ids to clear before removing themto_clear = [@@ -272,7 +272,7 @@ class CodexAgent(BaseAgent):self._session_mgr.set_thread_id(request.base_session_id, thread_id)# Also persist for resume support- self.settings_manager.set_agent_session_mapping(+ self.sessions.set_agent_session_mapping(request.settings_key,self.name,request.base_session_id,@@ -287,7 +287,7 @@ class CodexAgent(BaseAgent):) -> str:"""Try to resume a persisted thread, fall back to creating a new one."""# Check if we have a persisted Codex thread_id from settings_manager- persisted = self.settings_manager.get_agent_session_id(+ persisted = self.sessions.get_agent_session_id(request.settings_key,request.base_session_id,self.name,diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex e2a2d77d6..7c78a6f94 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -50,7 +50,7 @@ class CodexEventHandler:if thread_id:self._agent._session_mgr.set_thread_id(request.base_session_id, thread_id)# Persist thread_id in settings_manager for /clear resume- self._agent.settings_manager.set_agent_session_mapping(+ self._agent.sessions.set_agent_session_mapping(request.settings_key,self._agent.name,request.base_session_id,diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 0828ec626..81cffb316 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -241,7 +241,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request.working_path,)- self.settings_manager.add_active_poll(+ self.sessions.add_active_poll(opencode_session_id=session_id,base_session_id=request.base_session_id,channel_id=request.context.channel_id,@@ -288,14 +288,14 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# Clean up answer reaction after result is sentawait self._question_handler.clear(request.base_session_id)- self.settings_manager.remove_active_poll(session_id)+ self.sessions.remove_active_poll(session_id)except asyncio.CancelledError:logger.info(f"OpenCode request cancelled for {request.base_session_id}")await self._question_handler.clear(request.base_session_id)await self._remove_ack_reaction(request)if session_id:- self.settings_manager.remove_active_poll(session_id)+ self.sessions.remove_active_poll(session_id)raiseexcept Exception as e:error_name = type(e).__name__@@ -312,7 +312,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await self._question_handler.clear(request.base_session_id)await self._remove_ack_reaction(request)if session_id:- self.settings_manager.remove_active_poll(session_id)+ self.sessions.remove_active_poll(session_id)await self.controller.emit_agent_message(request.context,@@ -342,14 +342,14 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):passif opencode_session_id:- self.settings_manager.remove_active_poll(opencode_session_id)+ self.sessions.remove_active_poll(opencode_session_id)await self.controller.emit_agent_message(request.context, "notify", "Terminated OpenCode execution.")logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")return Trueasync def clear_sessions(self, settings_key: str) -> int:- self.settings_manager.clear_agent_sessions(settings_key, self.name)+ self.sessions.clear_agent_sessions(settings_key, self.name)terminated = 0for base_id, task in list(self._active_requests.items()):req_info = self._session_manager.get_request_session(base_id)@@ -367,7 +367,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):except asyncio.CancelledError:passterminated += 1- self.settings_manager.remove_active_poll(opencode_session_id)+ self.sessions.remove_active_poll(opencode_session_id)return terminatedasync def _delete_ack(self, request: AgentRequest) -> None:@@ -385,7 +385,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):async def restore_active_polls(self) -> int:"""Restore active poll loops that were interrupted by vibe-remote restart."""- active_polls = self.settings_manager.get_all_active_polls()+ active_polls = self.sessions.get_all_active_polls()if not active_polls:logger.debug("No active polls to restore")return 0@@ -439,7 +439,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):restored_count += 1for session_id in stale_poll_ids:- self.settings_manager.remove_active_poll(session_id)+ self.sessions.remove_active_poll(session_id)if restored_count > 0:logger.info(f"Restored {restored_count} active poll loop(s)")diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex acc35c993..94b2a61fe 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -387,7 +387,7 @@ class OpenCodePollLoop:"Detected question in restored poll for %s, exiting poll loop",session_id,)- self._agent.settings_manager.remove_active_poll(session_id)+ self._agent.sessions.remove_active_poll(session_id)await _remove_ack_reaction()await self._agent.controller.emit_agent_message(context,@@ -399,7 +399,7 @@ class OpenCodePollLoop:seen_tool_calls.add(call_key)poll_info.seen_tool_calls = list(seen_tool_calls)- self._agent.settings_manager.update_active_poll_state(+ self._agent.sessions.update_active_poll_state(session_id, seen_tool_calls=poll_info.seen_tool_calls)@@ -443,7 +443,7 @@ class OpenCodePollLoop:"notify",f"OpenCode error: {error_text}",)- self._agent.settings_manager.remove_active_poll(session_id)+ self._agent.sessions.remove_active_poll(session_id)await _remove_ack_reaction()return@@ -488,13 +488,13 @@ class OpenCodePollLoop:await _remove_ack_reaction()# Clean up answer reaction after result is sentawait self._question_handler.clear(poll_info.base_session_id)- self._agent.settings_manager.remove_active_poll(session_id)+ self._agent.sessions.remove_active_poll(session_id)except asyncio.CancelledError:logger.info(f"Restored OpenCode poll cancelled for {poll_info.base_session_id}")await _remove_ack_reaction()await self._question_handler.clear(poll_info.base_session_id)- self._agent.settings_manager.remove_active_poll(session_id)+ self._agent.sessions.remove_active_poll(session_id)raiseexcept Exception as e:error_name = type(e).__name__@@ -507,7 +507,7 @@ class OpenCodePollLoop:except Exception as abort_err:logger.warning(f"Failed to abort OpenCode session after error: {abort_err}")- self._agent.settings_manager.remove_active_poll(session_id)+ self._agent.sessions.remove_active_poll(session_id)await _remove_ack_reaction()await self._agent.controller.emit_agent_message(diff --git a/modules/agents/opencode/question_handler.py b/modules/agents/opencode/question_handler.pyindex 1eb9c0d28..5d415d845 100644--- a/modules/agents/opencode/question_handler.py+++ b/modules/agents/opencode/question_handler.py@@ -157,7 +157,8 @@ class OpenCodeQuestionHandler:self._pending_questions.pop(request.base_session_id, None)# Stop restoring this on restart (since we're abandoning the run)- self._settings_manager.remove_active_poll(session_id)+ sessions = getattr(self._settings_manager, "sessions", self._settings_manager)+ sessions.remove_active_poll(session_id)# Abort the OpenCode session so rerun starts freshdirectory = pending.get("directory")diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.pyindex f9727b8b8..3ed609003 100644--- a/modules/agents/opencode/session.py+++ b/modules/agents/opencode/session.py@@ -84,9 +84,7 @@ class OpenCodeSessionManager:try:messages = await server.list_messages(session_id, directory)except Exception as err:- logger.debug(- f"Failed to poll OpenCode session {session_id} for idle: {err}"- )+ logger.debug(f"Failed to poll OpenCode session {session_id} for idle: {err}")await asyncio.sleep(1.0)continue@@ -115,12 +113,12 @@ class OpenCodeSessionManager:if not os.path.exists(working_path):os.makedirs(working_path, exist_ok=True)- async def get_or_create_session_id(- self, request: AgentRequest, server: OpenCodeServerManager- ) -> Optional[str]:+ async def get_or_create_session_id(self, request: AgentRequest, server: OpenCodeServerManager) -> Optional[str]:"""Get a cached OpenCode session id, or create a new session."""- session_id = self._settings_manager.get_agent_session_id(+ sessions = getattr(self._settings_manager, "sessions", self._settings_manager)++ session_id = sessions.get_agent_session_id(request.settings_key,request.base_session_id,agent_name=self._agent_name,@@ -134,15 +132,13 @@ class OpenCodeSessionManager:)session_id = session_data.get("id")if session_id:- self._settings_manager.set_agent_session_mapping(+ sessions.set_agent_session_mapping(request.settings_key,self._agent_name,request.base_session_id,session_id,)- logger.info(- f"Created OpenCode session {session_id} for {request.base_session_id}"- )+ logger.info(f"Created OpenCode session {session_id} for {request.base_session_id}")except Exception as e:logger.error(f"Failed to create OpenCode session: {e}", exc_info=True)return None@@ -159,15 +155,13 @@ class OpenCodeSessionManager:)new_session_id = session_data.get("id")if new_session_id:- self._settings_manager.set_agent_session_mapping(+ sessions.set_agent_session_mapping(request.settings_key,self._agent_name,request.base_session_id,new_session_id,)- logger.info(- f"Recreated OpenCode session {new_session_id} for {request.base_session_id}"- )+ logger.info(f"Recreated OpenCode session {new_session_id} for {request.base_session_id}")return new_session_idexcept Exception as e:logger.error(f"Failed to recreate session: {e}", exc_info=True)diff --git a/modules/im/base.py b/modules/im/base.pyindex 2a97732e1..8b3a0716c 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -2,7 +2,7 @@import loggingfrom abc import ABC, abstractmethod-from typing import Optional, Callable, Dict, Any, List+from typing import Optional, Callable, Dict, Any, List, Tuplefrom dataclasses import dataclasslogger = logging.getLogger(__name__)@@ -128,6 +128,74 @@ class BaseIMClient(ABC):# Default implementation - subclasses should overridereturn False+ @staticmethod+ def extract_command_action(text: str) -> str:+ """Extract command action name from slash command text.++ Examples:+ "/settings" -> "settings"+ "/set_cwd /tmp" -> "set_cwd"+ "hello" -> ""+ """+ if not text or not text.startswith("/"):+ return ""+ parts = text.split(maxsplit=1)+ return parts[0][1:] if parts and len(parts[0]) > 1 else ""++ @staticmethod+ def parse_text_command(text: str) -> Optional[Tuple[str, str]]:+ """Parse slash-style command text.++ Returns:+ (command, args) when ``text`` starts with ``/`` and contains a+ non-empty command; otherwise ``None``.+ """+ if not text or not text.startswith("/"):+ return None+ parts = text.split(maxsplit=1)+ command = parts[0][1:] if parts and len(parts[0]) > 1 else ""+ if not command:+ return None+ args = parts[1] if len(parts) > 1 else ""+ return command, args++ async def dispatch_text_command(self, context: MessageContext, text: str) -> bool:+ """Dispatch slash-style text command if registered.++ Returns ``True`` if a matching command handler ran.+ """+ parsed = self.parse_text_command(text)+ if not parsed:+ return False+ command, args = parsed+ handler = self.on_command_callbacks.get(command)+ if not handler:+ return False+ await handler(context, args)+ return True++ def check_authorization(+ self,+ *,+ user_id: str,+ channel_id: str,+ is_dm: bool,+ text: str = "",+ action: str = "",+ settings_manager: Any = None,+ ):+ """Run centralized auth with shared action extraction logic."""+ from core.auth import check_auth++ resolved_action = action or self.extract_command_action(text)+ return check_auth(+ user_id=user_id,+ channel_id=channel_id,+ is_dm=is_dm,+ action=resolved_action,+ settings_manager=settings_manager,+ )+@abstractmethodasync def send_message(self, context: MessageContext, text: str, parse_mode: Optional[str] = None, reply_to: Optional[str] = Nonediff --git a/modules/im/discord.py b/modules/im/discord.pyindex 91c6789a0..edb3ea853 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -9,7 +9,6 @@ import discordfrom .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachmentfrom config.v2_config import DiscordConfig-from core.auth import check_authfrom .formatters import DiscordFormatterfrom vibe.i18n import get_supported_languages, t as i18n_tfrom modules.agents.opencode.utils import (@@ -42,6 +41,7 @@ class DiscordBot(BaseIMClient):self.formatter = DiscordFormatter()self.settings_manager = None+ self.sessions = Noneself._controller = Noneself._on_ready: Optional[Callable] = Noneself._user_info_cache: Dict[str, Dict[str, Any]] = {}@@ -51,6 +51,7 @@ class DiscordBot(BaseIMClient):def set_settings_manager(self, settings_manager):self.settings_manager = settings_manager+ self.sessions = getattr(settings_manager, "sessions", None)def set_controller(self, controller):self._controller = controller@@ -186,7 +187,8 @@ class DiscordBot(BaseIMClient):message = await target.send(content=text)if self.settings_manager and context.thread_id:try:- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, context.thread_id)+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, context.thread_id)except Exception:passreturn str(message.id)@@ -216,7 +218,8 @@ class DiscordBot(BaseIMClient):message = await target.send(content=text, view=view)if self.settings_manager and context.thread_id:try:- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, context.thread_id)+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, context.thread_id)except Exception:passreturn str(message.id)@@ -476,19 +479,12 @@ class DiscordBot(BaseIMClient):# Determine if this is a DMis_dm = isinstance(channel, discord.DMChannel) or message.guild is None- # Centralized auth check — parse command name before auth so- # admin-protected text commands (e.g. /settings, /set_cwd) are checked.- if content.startswith("/"):- _cmd_parts = content.split(maxsplit=1)- action = _cmd_parts[0][1:] # strip leading "/"- else:- action = ""- auth_result = check_auth(+ auth_result = self.check_authorization(user_id=str(message.author.id),channel_id=channel_id,is_dm=is_dm,- action=action,- store=self.settings_manager.store if self.settings_manager else None,+ text=content,+ settings_manager=self.settings_manager,)if not auth_result.allowed:await self._send_auth_denial(channel_id, str(message.author.id), auth_result)@@ -506,7 +502,9 @@ class DiscordBot(BaseIMClient):if effective_require_mention and not is_dm:if isinstance(channel, discord.Thread):if self.settings_manager:- if not self.settings_manager.is_thread_active(str(message.author.id), channel_id, str(channel.id)):+ if self.sessions and not self.sessions.is_thread_active(+ str(message.author.id), channel_id, str(channel.id)+ ):returnelse:return@@ -520,7 +518,7 @@ class DiscordBot(BaseIMClient):content = content.replace(f"<@{bot_id}>", "").replace(f"<@!{bot_id}>", "").strip()# Handle slash-like commands in plain messages- if content.startswith("/"):+ if self.parse_text_command(content):command_context = MessageContext(user_id=str(message.author.id),channel_id=channel_id,@@ -529,12 +527,7 @@ class DiscordBot(BaseIMClient):platform_specific={"message": message, "is_dm": is_dm},files=files,)- parts = content.split(maxsplit=1)- command = parts[0][1:]- args = parts[1] if len(parts) > 1 else ""- if command in self.on_command_callbacks:- handler = self.on_command_callbacks[command]- await handler(command_context, args)+ if await self.dispatch_text_command(command_context, content):returnif not content and not files:@@ -748,12 +741,12 @@ class DiscordBot(BaseIMClient):save_uid = str(save_interaction.user.id)save_cid = channel_id or str(save_interaction.channel_id or "")save_is_dm = save_interaction.guild is None- auth = check_auth(+ auth = self.check_authorization(user_id=save_uid,channel_id=save_cid,is_dm=save_is_dm,action="settings",- store=self.settings_manager.store if self.settings_manager else None,+ settings_manager=self.settings_manager,)if not auth.allowed:await self._send_auth_denial(save_cid, save_uid, auth, interaction=save_interaction)@@ -1537,12 +1530,12 @@ class _PersistentStartView(discord.ui.View):if guild_id and not self.outer._is_allowed_guild(guild_id):returnis_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)- auth_result = check_auth(+ auth_result = self.outer.check_authorization(user_id=str(interaction.user.id),channel_id=channel_id,is_dm=is_dm,action=data,- store=self.outer.settings_manager.store if self.outer.settings_manager else None,+ settings_manager=self.outer.settings_manager,)if not auth_result.allowed:await self.outer._send_auth_denial(@@ -1616,12 +1609,12 @@ class _DiscordButtonView(discord.ui.View):if guild_id and not self.outer._is_allowed_guild(guild_id):returnis_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)- auth_result = check_auth(+ auth_result = self.outer.check_authorization(user_id=str(interaction.user.id),channel_id=channel_id,is_dm=is_dm,action=data,- store=self.outer.settings_manager.store if self.outer.settings_manager else None,+ settings_manager=self.outer.settings_manager,)if not auth_result.allowed:await self.outer._send_auth_denial(diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 583963878..64f460006 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -86,6 +86,7 @@ class FeishuBot(BaseIMClient):self._bot_open_id: Optional[str] = Noneself.settings_manager = None+ self.sessions = Noneself._controller = Noneself._on_ready: Optional[Callable] = Noneself._on_settings_update: Optional[Callable] = None@@ -109,6 +110,7 @@ class FeishuBot(BaseIMClient):def set_settings_manager(self, settings_manager):"""Set the settings manager for thread tracking."""self.settings_manager = settings_manager+ self.sessions = getattr(settings_manager, "sessions", None)def set_controller(self, controller):"""Set the controller reference for handling update button clicks."""@@ -117,7 +119,7 @@ class FeishuBot(BaseIMClient):def _populate_dm_chat_ids(self):"""Pre-populate DM chat IDs from bound users for restart survival."""if self.settings_manager:- for user_id, user in self.settings_manager.store.settings.users.items():+ for user_id, user in self.settings_manager.iter_bound_users():if user.dm_chat_id:self._dm_chat_ids.add(user.dm_chat_id)@@ -340,7 +342,8 @@ class FeishuBot(BaseIMClient):if root_id:message_id = await self._reply_message(root_id, text)if self.settings_manager:- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, root_id)+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)return message_idresponse = await self._lark_client.im.v1.message.acreate(request)@@ -355,7 +358,8 @@ class FeishuBot(BaseIMClient):message_id = response.data.message_idif self.settings_manager and (context.thread_id or reply_to):thread = context.thread_id or reply_to- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, thread)+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread)return message_idasync def _reply_message(self, parent_id: str, text: str) -> str:@@ -502,7 +506,8 @@ class FeishuBot(BaseIMClient):if root_id:message_id = await self._reply_message_with_card(root_id, card_json)if self.settings_manager:- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, root_id)+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)return message_idrequest = (@@ -529,7 +534,8 @@ class FeishuBot(BaseIMClient):message_id = response.data.message_idif self.settings_manager and context.thread_id:- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, context.thread_id)+ if self.sessions:+ self.sessions.mark_thread_active(context.user_id, context.channel_id, context.thread_id)return message_idasync def _reply_message_with_card(self, parent_id: str, card_json: str) -> str:@@ -1113,27 +1119,18 @@ class FeishuBot(BaseIMClient):returnelse:if self.settings_manager:- if not self.settings_manager.is_thread_active(user_id, chat_id, root_id):+ if self.sessions and not self.sessions.is_thread_active(user_id, chat_id, root_id):logger.debug("Ignoring message in inactive thread %s", root_id)returnelse:return- # Centralized auth check — parse command name before auth so- # admin-protected text commands (e.g. /settings, /set_cwd) are checked.- from core.auth import check_auth-- if text.startswith("/"):- _cmd_parts = text.split(maxsplit=1)- _action = _cmd_parts[0][1:] # strip leading "/"- else:- _action = ""- auth_result = check_auth(+ auth_result = self.check_authorization(user_id=user_id,channel_id=chat_id,is_dm=is_p2p,- action=_action,- store=self.settings_manager.store if self.settings_manager else None,+ text=text,+ settings_manager=self.settings_manager,)if not auth_result.allowed:try:@@ -1160,14 +1157,8 @@ class FeishuBot(BaseIMClient):)# Handle commands (messages starting with /)- if text.startswith("/"):- parts = text.split(maxsplit=1)- command = parts[0][1:]- args = parts[1] if len(parts) > 1 else ""- if command in self.on_command_callbacks:- handler = self.on_command_callbacks[command]- await handler(context, args)- return+ if await self.dispatch_text_command(context, text):+ return# Append shared contentif shared_text:@@ -1240,14 +1231,12 @@ class FeishuBot(BaseIMClient):# --- Centralized auth check ---is_dm = chat_id in self._dm_chat_ids_card_action = button_name if form_value is not None else (callback_data or "")- from core.auth import check_auth-- auth_result = check_auth(+ auth_result = self.check_authorization(user_id=user_id,channel_id=chat_id,is_dm=is_dm,action=_card_action,- store=self.settings_manager.store if self.settings_manager else None,+ settings_manager=self.settings_manager,)if not auth_result.allowed:if auth_result.denial == "not_admin":diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 39b472ada..4244eafdf 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -13,8 +13,9 @@ from markdown_to_mrkdwn import SlackMarkdownConverterfrom .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachmentfrom config.v2_config import SlackConfig-from core.auth import check_auth, AuthResult+from core.auth import AuthResultfrom .formatters import SlackFormatter+from .slack_modal import parse_routing_modal_selectionfrom vibe.i18n import get_supported_languages, t as i18n_tfrom modules.agents.opencode.utils import (build_opencode_model_option_items,@@ -55,6 +56,7 @@ class SlackBot(BaseIMClient):# Settings manager for thread tracking (will be injected later)self.settings_manager = None+ self.sessions = None# Controller reference for update button handling (will be injected later)self._controller = Noneself._recent_event_ids: Dict[str, float] = {}@@ -66,6 +68,7 @@ class SlackBot(BaseIMClient):def set_settings_manager(self, settings_manager):"""Set the settings manager for thread tracking"""self.settings_manager = settings_manager+ self.sessions = getattr(settings_manager, "sessions", None)def set_controller(self, controller):"""Set the controller reference for handling update button clicks"""@@ -208,7 +211,8 @@ class SlackBot(BaseIMClient):# Mark thread as active if we sent a message to a threadif 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)+ if self.sessions:+ self.sessions.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"]@@ -649,7 +653,8 @@ class SlackBot(BaseIMClient):# Mark thread as active if we sent a message to a threadif self.settings_manager and context.thread_id:- self.settings_manager.mark_thread_active(context.user_id, context.channel_id, context.thread_id)+ if self.sessions:+ self.sessions.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"]@@ -887,7 +892,7 @@ class SlackBot(BaseIMClient):thread_ts = event.get("thread_ts")# If we have settings_manager, check if thread is activeif self.settings_manager:- if not self.settings_manager.is_thread_active(user_id, channel_id, thread_ts):+ if self.sessions and not self.sessions.is_thread_active(user_id, channel_id, thread_ts):logger.debug(f"Ignoring message in inactive thread {thread_ts}: '{text}'")returnelse:@@ -895,20 +900,13 @@ class SlackBot(BaseIMClient):logger.debug(f"No settings_manager, ignoring thread message: '{text}'")return- # Centralized auth gate — parse command name before auth so- # admin-protected text commands (e.g. /settings, /set_cwd) are checked.is_dm = channel_id.startswith("D")- if text.startswith("/"):- _cmd_parts = text.split(maxsplit=1)- auth_action = _cmd_parts[0][1:] # strip leading "/"- else:- auth_action = ""- auth = check_auth(+ auth = self.check_authorization(user_id=user_id,channel_id=channel_id,is_dm=is_dm,- action=auth_action,- store=self.settings_manager.store if self.settings_manager else None,+ text=text,+ settings_manager=self.settings_manager,)if not auth.allowed:await self._send_auth_denial(channel_id, user_id, auth)@@ -944,15 +942,8 @@ class SlackBot(BaseIMClient):# Handle slash commands in regular messages (before appending shared content)# Use only the user's original text for command detection- if text.startswith("/"):- parts = text.split(maxsplit=1)- command = parts[0][1:] # Remove the /- args = parts[1] if len(parts) > 1 else ""-- if command in self.on_command_callbacks:- handler = self.on_command_callbacks[command]- await handler(context, args)- return+ if await self.dispatch_text_command(context, text):+ return# Append shared content to user text (after command parsing)if shared_text:@@ -971,12 +962,12 @@ class SlackBot(BaseIMClient):# Centralized auth gate (app_mention is always in a channel, not DM)user_id_mention = event.get("user")- auth = check_auth(+ auth = self.check_authorization(user_id=user_id_mention or "",channel_id=channel_id,is_dm=False,action="",- store=self.settings_manager.store if self.settings_manager else None,+ settings_manager=self.settings_manager,)if not auth.allowed:await self._send_auth_denial(channel_id, user_id_mention or "", auth)@@ -1004,7 +995,8 @@ class SlackBot(BaseIMClient):# Mark thread as active when bot is @mentionedif self.settings_manager and thread_id:- self.settings_manager.mark_thread_active(event.get("user"), channel_id, thread_id)+ if self.sessions:+ self.sessions.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@@ -1019,20 +1011,17 @@ class SlackBot(BaseIMClient):logger.info(f"App mention processed: original='{event.get('text')}', cleaned='{text}'")# Check if this is a command after mention (before appending shared content)- if text.startswith("/"):- parts = text.split(maxsplit=1)- command = parts[0][1:] # Remove the /- args = parts[1] if len(parts) > 1 else ""-+ parsed_command = self.parse_text_command(text)+ if parsed_command:+ command, args = parsed_commandlogger.info(f"Command detected: '{command}', available: {list(self.on_command_callbacks.keys())}")- if command in self.on_command_callbacks:+ handler = self.on_command_callbacks.get(command)+ if handler:logger.info(f"Executing command handler for: {command}")- handler = self.on_command_callbacks[command]await handler(context, args)return- else:- logger.warning(f"Command '{command}' not found in callbacks")+ logger.warning(f"Command '{command}' not found in callbacks")# Append shared content to user text (after command parsing)if shared_text:@@ -1055,12 +1044,12 @@ class SlackBot(BaseIMClient):# Centralized auth gateis_dm = isinstance(channel_id, str) and channel_id.startswith("D")- auth = check_auth(+ auth = self.check_authorization(user_id=user_id,channel_id=channel_id,is_dm=is_dm,action=command,- store=self.settings_manager.store if self.settings_manager else None,+ settings_manager=self.settings_manager,)if not auth.allowed:await self._send_auth_denial(channel_id, user_id, auth, response_url=response_url)@@ -1147,12 +1136,12 @@ class SlackBot(BaseIMClient):# Centralized auth gateis_dm = isinstance(channel_id, str) and channel_id.startswith("D")- auth = check_auth(+ auth = self.check_authorization(user_id=user.get("id", ""),channel_id=channel_id or "",is_dm=is_dm,action=primary_action,- store=self.settings_manager.store if self.settings_manager else None,+ settings_manager=self.settings_manager,)if not auth.allowed:try:@@ -1218,11 +1207,17 @@ class SlackBot(BaseIMClient):if hasattr(self, "_on_routing_modal_update"):channel_from_view = view.get("private_metadata")effective_channel = channel_from_view or channel_id+ selection = parse_routing_modal_selection(+ view=view,+ action=action,+ default_backend="",+ )await self._on_routing_modal_update(user.get("id"),effective_channel,- view,- action,+ view.get("id"),+ view.get("hash"),+ selection,is_dm=isinstance(effective_channel, str) and effective_channel.startswith("D"),)elif action_type == "plain_text_input":@@ -1353,9 +1348,12 @@ class SlackBot(BaseIMClient):if hasattr(self, "_on_resume_session"):is_dm = isinstance(channel_id, str) and channel_id.startswith("D")- await self._on_resume_session(- user_id, channel_id, thread_id, chosen_agent, chosen_session, host_message_ts, is_dm- )+ callback = self._on_resume_session+ try:+ await callback(user_id, channel_id, thread_id, chosen_agent, chosen_session, host_message_ts, is_dm)+ except TypeError:+ # Backward compatibility: older callback signature omitted is_dm.+ await callback(user_id, channel_id, thread_id, chosen_agent, chosen_session, host_message_ts)elif callback_id == "opencode_question_modal" or callback_id == "claude_question_modal":# Generic question modal handling for both OpenCode and Claudediff --git a/modules/im/slack_modal.py b/modules/im/slack_modal.pynew file mode 100644index 000000000..656684c5a--- /dev/null+++ b/modules/im/slack_modal.py@@ -0,0 +1,86 @@+"""Slack-specific modal parsing helpers."""++from __future__ import annotations++from typing import Optional++from core.modals import RoutingModalSelection+++def _extract_selected_value(values: dict, block_id: str, action_id: str) -> Optional[str]:+ data = values.get(block_id, {}).get(action_id, {})+ return data.get("selected_option", {}).get("value")+++def _extract_prefixed_selected_value(values: dict, block_id: str, action_prefix: str) -> Optional[str]:+ block = values.get(block_id, {})+ if not isinstance(block, dict):+ return None+ for dynamic_action_id, action_data in block.items():+ if (+ isinstance(dynamic_action_id, str)+ and dynamic_action_id.startswith(action_prefix)+ and isinstance(action_data, dict)+ ):+ return action_data.get("selected_option", {}).get("value")+ return None+++def _normalize_default(value: Optional[str]) -> Optional[str]:+ if value == "__default__":+ return None+ return value+++def parse_routing_modal_selection(+ *,+ view: dict,+ action: dict,+ default_backend: str,+) -> RoutingModalSelection:+ """Parse Slack routing modal state into normalized selection model."""+ values = view.get("state", {}).get("values", {})++ selected_backend = _extract_selected_value(values, "backend_block", "backend_select") or default_backend+ selected_action_id = action.get("action_id")++ selected_value = None+ selected_option = action.get("selected_option")+ if isinstance(selected_option, dict):+ selected_value = selected_option.get("value")++ oc_agent = _extract_selected_value(values, "opencode_agent_block", "opencode_agent_select")+ oc_model = _extract_selected_value(values, "opencode_model_block", "opencode_model_select")+ oc_reasoning = _extract_prefixed_selected_value(values, "opencode_reasoning_block", "opencode_reasoning_select")++ claude_agent = _extract_selected_value(values, "claude_agent_block", "claude_agent_select")+ claude_model = _extract_selected_value(values, "claude_model_block", "claude_model_select")+ codex_model = _extract_selected_value(values, "codex_model_block", "codex_model_select")+ codex_reasoning = _extract_prefixed_selected_value(values, "codex_reasoning_block", "codex_reasoning_select")++ if isinstance(selected_action_id, str) and isinstance(selected_value, str):+ if selected_action_id == "opencode_agent_select":+ oc_agent = selected_value+ elif selected_action_id == "opencode_model_select":+ oc_model = selected_value+ elif selected_action_id.startswith("opencode_reasoning_select"):+ oc_reasoning = selected_value+ elif selected_action_id == "claude_agent_select":+ claude_agent = selected_value+ elif selected_action_id == "claude_model_select":+ claude_model = selected_value+ elif selected_action_id == "codex_model_select":+ codex_model = selected_value+ elif selected_action_id.startswith("codex_reasoning_select"):+ codex_reasoning = selected_value++ return RoutingModalSelection(+ selected_backend=selected_backend,+ selected_opencode_agent=_normalize_default(oc_agent),+ selected_opencode_model=_normalize_default(oc_model),+ selected_opencode_reasoning=_normalize_default(oc_reasoning),+ selected_claude_agent=_normalize_default(claude_agent),+ selected_claude_model=_normalize_default(claude_model),+ selected_codex_model=_normalize_default(codex_model),+ selected_codex_reasoning=_normalize_default(codex_reasoning),+ )diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pynew file mode 100644index 000000000..d07818874--- /dev/null+++ b/modules/sessions_facade.py@@ -0,0 +1,211 @@+"""Facade for runtime session/thread/dedup/poll state.++This facade centralizes runtime conversation state operations that are+backed by ``config.v2_sessions.SessionsStore``.+"""++from __future__ import annotations++import logging+import time+from typing import Any, Dict, List, Optional, Union++from config.v2_sessions import ActivePollInfo, SessionsStore++logger = logging.getLogger(__name__)+++class SessionsFacade:+ """High-level APIs for session and runtime state operations."""++ def __init__(self, sessions_store: SessionsStore):+ self.sessions_store = sessions_store++ def _normalize_user_id(self, user_id: Union[int, str]) -> str:+ return str(user_id)++ def _ensure_agent_namespace(self, user_id: Union[int, str], agent_name: str) -> Dict[str, str]:+ user_key = self._normalize_user_id(user_id)+ return self.sessions_store.get_agent_map(user_key, agent_name)++ def set_agent_session_mapping(+ self,+ user_id: Union[int, str],+ agent_name: str,+ thread_id: str,+ session_id: str,+ ) -> None:+ agent_map = self._ensure_agent_namespace(user_id, agent_name)+ agent_map[thread_id] = session_id+ self.sessions_store.save()+ logger.info("Stored %s session mapping for %s: %s -> %s", agent_name, user_id, thread_id, session_id)++ def get_agent_session_id(+ self,+ user_id: Union[int, str],+ thread_id: str,+ agent_name: str,+ ) -> Optional[str]:+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)+ return agent_map.get(thread_id)++ def clear_agent_session_mapping(+ self,+ user_id: Union[int, str],+ agent_name: str,+ thread_id: str,+ ) -> None:+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)+ if thread_id in agent_map:+ del agent_map[thread_id]+ self.sessions_store.save()+ logger.info("Cleared %s session mapping for user %s: %s", agent_name, user_id, thread_id)++ def clear_agent_sessions(self, user_id: Union[int, str], agent_name: str) -> None:+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)+ if agent_map:+ self.sessions_store.state.session_mappings[user_key][agent_name] = {}+ self.sessions_store.save()+ logger.info("Cleared all %s session namespaces for user %s", agent_name, user_id)++ def clear_all_session_mappings(self, user_id: Union[int, str]) -> None:+ user_key = self._normalize_user_id(user_id)+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})+ if agent_maps:+ count = sum(len(agent_map) for agent_map in agent_maps.values())+ self.sessions_store.state.session_mappings[user_key] = {}+ self.sessions_store.save()+ logger.info("Cleared all session mappings (%s bases) for user %s", count, user_id)++ def list_agent_sessions(self, user_id: Union[int, str], agent_name: str) -> Dict[str, str]:+ user_key = self._normalize_user_id(user_id)+ agent_map = self.sessions_store.get_agent_map(user_key, agent_name)+ return dict(agent_map)++ def list_all_agent_sessions(self, user_id: Union[int, str]) -> Dict[str, Dict[str, str]]:+ user_key = self._normalize_user_id(user_id)+ self.sessions_store._ensure_user_namespace(user_key)+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})+ return {agent: dict(mapping) for agent, mapping in agent_maps.items()}++ def get_all_session_mappings(self) -> Dict[str, Dict[str, Dict[str, str]]]:+ """Return all persisted session mappings grouped by user and agent."""+ mappings = self.sessions_store.state.session_mappings+ return {+ user_id: {agent: dict(agent_map) for agent, agent_map in (agents or {}).items()}+ for user_id, agents in mappings.items()+ }++ def set_session_mapping(self, user_id: Union[int, str], thread_id: str, claude_session_id: str) -> None:+ self.set_agent_session_mapping(user_id, "claude", thread_id, claude_session_id)++ def get_claude_session_id(self, user_id: Union[int, str], thread_id: str) -> Optional[str]:+ return self.get_agent_session_id(user_id, thread_id, agent_name="claude")++ def clear_session_mapping(self, user_id: Union[int, str], thread_id: str) -> None:+ self.clear_agent_session_mapping(user_id, "claude", thread_id)++ def mark_thread_active(self, user_id: Union[int, str], channel_id: str, thread_ts: str) -> None:+ user_key = self._normalize_user_id(user_id)+ channel_map = self.sessions_store.get_thread_map(user_key, channel_id)+ channel_map[thread_ts] = time.time()+ self.sessions_store.save()+ logger.info("Marked thread active for user %s: channel=%s, thread=%s", user_id, channel_id, thread_ts)++ def is_thread_active(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 _cleanup_expired_threads_for_channel(self, user_id: Union[int, str], channel_id: str) -> None:+ user_key = self._normalize_user_id(user_id)+ channel_map = self.sessions_store.get_thread_map(user_key, channel_id)+ if not channel_map:+ return++ current_time = time.time()+ twenty_four_hours_ago = current_time - (24 * 60 * 60)+ expired_threads = [+ thread_ts for thread_ts, last_active in channel_map.items() if last_active < twenty_four_hours_ago+ ]++ if not expired_threads:+ return++ for thread_ts in expired_threads:+ del channel_map[thread_ts]++ if not channel_map:+ self.sessions_store.state.active_slack_threads[user_key].pop(channel_id, None)++ self.sessions_store.save()+ logger.info("Cleaned up %s expired threads for channel %s", len(expired_threads), channel_id)++ def cleanup_all_expired_threads(self, user_id: Union[int, str]) -> None:+ user_key = self._normalize_user_id(user_id)+ channel_map = self.sessions_store.state.active_slack_threads.get(user_key, {})+ if not channel_map:+ return+ for channel_id in list(channel_map.keys()):+ self._cleanup_expired_threads_for_channel(user_id, channel_id)++ def is_message_already_processed(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:+ return self.sessions_store.is_message_in_processed_set(channel_id, thread_ts, message_ts)++ def record_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> None:+ self.sessions_store.add_to_processed_set(channel_id, thread_ts, message_ts)+ logger.debug("Recorded processed message: channel=%s, thread=%s, message=%s", channel_id, thread_ts, message_ts)++ def add_active_poll(+ self,+ opencode_session_id: str,+ base_session_id: str,+ channel_id: str,+ thread_id: str,+ settings_key: str,+ working_path: str,+ baseline_message_ids: List[str],+ ack_reaction_message_id: Optional[str] = None,+ ack_reaction_emoji: Optional[str] = None,+ ) -> None:+ poll_info = ActivePollInfo(+ opencode_session_id=opencode_session_id,+ base_session_id=base_session_id,+ channel_id=channel_id,+ thread_id=thread_id,+ settings_key=settings_key,+ working_path=working_path,+ baseline_message_ids=baseline_message_ids,+ seen_tool_calls=[],+ emitted_assistant_messages=[],+ started_at=time.time(),+ ack_reaction_message_id=ack_reaction_message_id,+ ack_reaction_emoji=ack_reaction_emoji,+ )+ self.sessions_store.add_active_poll(poll_info)+ logger.debug("Added active poll: session=%s, thread=%s", opencode_session_id, thread_id)++ def remove_active_poll(self, opencode_session_id: str) -> None:+ self.sessions_store.remove_active_poll(opencode_session_id)+ logger.debug("Removed active poll: session=%s", opencode_session_id)++ def update_active_poll_state(+ self,+ opencode_session_id: str,+ seen_tool_calls: Optional[List[str]] = None,+ emitted_assistant_messages: Optional[List[str]] = None,+ ) -> None:+ poll_info = self.sessions_store.get_active_poll(opencode_session_id)+ if poll_info:+ if seen_tool_calls is not None:+ poll_info.seen_tool_calls = seen_tool_calls+ if emitted_assistant_messages is not None:+ poll_info.emitted_assistant_messages = emitted_assistant_messages+ self.sessions_store.update_active_poll(poll_info)++ def get_all_active_polls(self) -> Dict[str, Any]:+ return self.sessions_store.get_all_active_polls()diff --git a/modules/settings_manager.py b/modules/settings_manager.pyindex 09e601a0c..ab279f5af 100644--- a/modules/settings_manager.py+++ b/modules/settings_manager.py@@ -1,5 +1,4 @@import logging-import timefrom dataclasses import asdict, dataclass, fieldfrom typing import Any, Dict, List, Optional, Unionfrom pathlib import Path@@ -8,6 +7,7 @@ from config import pathsfrom config.v2_sessions import SessionsStorefrom config.v2_settings import SettingsStore, ChannelSettings, RoutingSettingsfrom config.v2_settings import UserSettings as BoundUserSettings+from modules.sessions_facade import SessionsFacadelogger = logging.getLogger(__name__)@@ -16,43 +16,31 @@ logger = logging.getLogger(__name__)DEFAULT_SHOW_MESSAGE_TYPES: List[str] = []-@dataclass-class ChannelRouting:- """Per-channel agent routing configuration."""-- agent_backend: Optional[str] = None # "claude" | "codex" | "opencode" | None- # OpenCode settings- opencode_agent: Optional[str] = None # "build" | "plan" | ... | None- opencode_model: Optional[str] = None # "provider/model" | None- opencode_reasoning_effort: Optional[str] = None # "low" | "medium" | "high" | "xhigh" | None- # Claude Code settings- claude_agent: Optional[str] = None # subagent name from ~/.claude/agents/- claude_model: Optional[str] = None # "claude-sonnet-4" | "claude-opus-4" | ...- # Note: Claude Code has no CLI parameter for reasoning effort- # Codex settings- codex_model: Optional[str] = None # "gpt-5-codex" | "o3" | ...- codex_reasoning_effort: Optional[str] = None # "minimal" | "low" | "medium" | "high" | "xhigh"- # Note: Codex subagent not supported yet+ChannelRouting = RoutingSettings- def to_dict(self) -> dict:- """Convert to dictionary for JSON serialization"""- return asdict(self)- @classmethod- def from_dict(cls, data: dict) -> "ChannelRouting":- """Create from dictionary"""- if data is None:- return None- return cls(- agent_backend=data.get("agent_backend"),- opencode_agent=data.get("opencode_agent"),- opencode_model=data.get("opencode_model"),- opencode_reasoning_effort=data.get("opencode_reasoning_effort"),- claude_agent=data.get("claude_agent"),- claude_model=data.get("claude_model"),- codex_model=data.get("codex_model"),- codex_reasoning_effort=data.get("codex_reasoning_effort"),- )+def _routing_to_dict(routing: Optional[RoutingSettings]) -> dict:+ if routing is None:+ return {}+ return asdict(routing)+++def _routing_from_dict(payload: Optional[dict]) -> RoutingSettings:+ data = payload or {}+ return RoutingSettings(+ agent_backend=data.get("agent_backend"),+ opencode_agent=data.get("opencode_agent"),+ opencode_model=data.get("opencode_model"),+ opencode_reasoning_effort=data.get("opencode_reasoning_effort"),+ claude_agent=data.get("claude_agent"),+ claude_model=data.get("claude_model"),+ codex_model=data.get("codex_model"),+ codex_reasoning_effort=data.get("codex_reasoning_effort"),+ )+++def _clone_routing(routing: Optional[RoutingSettings]) -> RoutingSettings:+ return _routing_from_dict(_routing_to_dict(routing))@dataclass@@ -69,7 +57,7 @@ class UserSettings:"custom_cwd": self.custom_cwd,}if self.channel_routing is not None:- result["routing"] = self.channel_routing.to_dict()+ result["routing"] = _routing_to_dict(self.channel_routing)return result@classmethod@@ -87,7 +75,7 @@ class UserSettings:custom_cwd=payload.get("custom_cwd"),)if routing_data is not None:- settings.channel_routing = ChannelRouting.from_dict(routing_data)+ settings.channel_routing = _routing_from_dict(routing_data)return settings@@ -107,6 +95,7 @@ class SettingsManager:self.store = SettingsStore.get_instance(self.settings_file)self.sessions_store = SessionsStore()self.sessions_store.load()+ self.sessions = SessionsFacade(self.sessions_store)self._last_seen_store_mtime: Optional[float] = Noneself._load_settings()@@ -121,59 +110,57 @@ class SettingsManager:"""return str(user_id)+ def get_store(self) -> SettingsStore:+ """Explicit access to underlying SettingsStore.++ Intended for shared auth pipeline and API integrations that require+ store-level operations.+ """+ return self.store++ def iter_bound_users(self):+ """Iterate over bound users from persisted settings."""+ self._reload_if_changed()+ return self.store.settings.users.items()++ def is_bound_user(self, user_id: Union[int, str]) -> bool:+ """Check whether a user is already bound."""+ return self.store.is_bound_user(str(user_id))++ def bind_user_with_code(+ self,+ user_id: Union[int, str],+ display_name: str,+ code: str,+ dm_chat_id: str = "",+ ) -> tuple[bool, bool]:+ """Atomically validate bind code and create user binding."""+ return self.store.bind_user_with_code(str(user_id), display_name, code, dm_chat_id=dm_chat_id)+def _from_channel_settings(self, channel_settings: ChannelSettings) -> UserSettings:- routing = ChannelRouting(- agent_backend=channel_settings.routing.agent_backend,- opencode_agent=channel_settings.routing.opencode_agent,- opencode_model=channel_settings.routing.opencode_model,- opencode_reasoning_effort=channel_settings.routing.opencode_reasoning_effort,- claude_agent=channel_settings.routing.claude_agent,- claude_model=channel_settings.routing.claude_model,- codex_model=channel_settings.routing.codex_model,- codex_reasoning_effort=channel_settings.routing.codex_reasoning_effort,- )return UserSettings(show_message_types=self._normalize_show_message_types(channel_settings.show_message_types),custom_cwd=channel_settings.custom_cwd,- channel_routing=routing,+ channel_routing=_clone_routing(channel_settings.routing),enabled=channel_settings.enabled,)def _from_bound_user_settings(self, bound_user: BoundUserSettings) -> UserSettings:"""Convert a bound user's settings (from v2_settings.UserSettings) to runtime UserSettings."""- routing = ChannelRouting(- agent_backend=bound_user.routing.agent_backend,- opencode_agent=bound_user.routing.opencode_agent,- opencode_model=bound_user.routing.opencode_model,- opencode_reasoning_effort=bound_user.routing.opencode_reasoning_effort,- claude_agent=bound_user.routing.claude_agent,- claude_model=bound_user.routing.claude_model,- codex_model=bound_user.routing.codex_model,- codex_reasoning_effort=bound_user.routing.codex_reasoning_effort,- )return UserSettings(show_message_types=self._normalize_show_message_types(bound_user.show_message_types),custom_cwd=bound_user.custom_cwd,- channel_routing=routing,+ channel_routing=_clone_routing(bound_user.routing),enabled=bound_user.enabled,)def _to_channel_settings(self, settings: UserSettings) -> ChannelSettings:- routing = settings.channel_routing or ChannelRouting()+ routing = _clone_routing(settings.channel_routing)return ChannelSettings(enabled=settings.enabled,show_message_types=self._normalize_show_message_types(settings.show_message_types),custom_cwd=settings.custom_cwd,- routing=RoutingSettings(- agent_backend=routing.agent_backend,- opencode_agent=routing.opencode_agent,- opencode_model=routing.opencode_model,- opencode_reasoning_effort=routing.opencode_reasoning_effort,- claude_agent=routing.claude_agent,- claude_model=routing.claude_model,- codex_model=routing.codex_model,- codex_reasoning_effort=routing.codex_reasoning_effort,- ),+ routing=routing,)def _sync_to_bound_user(self, user_id: str, settings: UserSettings) -> None:@@ -181,20 +168,10 @@ class SettingsManager:bound = self.store.settings.users.get(user_id)if not bound:return- routing = settings.channel_routing or ChannelRouting()bound.enabled = settings.enabledbound.show_message_types = self._normalize_show_message_types(settings.show_message_types)bound.custom_cwd = settings.custom_cwd- bound.routing = RoutingSettings(- agent_backend=routing.agent_backend,- opencode_agent=routing.opencode_agent,- opencode_model=routing.opencode_model,- opencode_reasoning_effort=routing.opencode_reasoning_effort,- claude_agent=routing.claude_agent,- claude_model=routing.claude_model,- codex_model=routing.codex_model,- codex_reasoning_effort=routing.codex_reasoning_effort,- )+ bound.routing = _clone_routing(settings.channel_routing)def _load_settings(self):"""Load settings from JSON file"""@@ -355,34 +332,6 @@ class SettingsManager:"toolcall": "Toolcall",}- def _ensure_agent_namespace(self, user_id: Union[int, str], agent_name: str) -> Dict[str, str]:- user_key = self._normalize_user_id(user_id)- return self.sessions_store.get_agent_map(user_key, agent_name)-- def set_agent_session_mapping(- self,- user_id: Union[int, str],- agent_name: str,- thread_id: str,- session_id: str,- ):- """Store mapping between thread ID and agent session ID"""- agent_map = self._ensure_agent_namespace(user_id, agent_name)- agent_map[thread_id] = session_id- self.sessions_store.save()- logger.info(f"Stored {agent_name} session mapping for {user_id}: {thread_id} -> {session_id}")-- def get_agent_session_id(- self,- user_id: Union[int, str],- thread_id: str,- agent_name: str,- ) -> Optional[str]:- """Get agent session ID for given thread ID"""- user_key = self._normalize_user_id(user_id)- agent_map = self.sessions_store.get_agent_map(user_key, agent_name)- return agent_map.get(thread_id)-def _canonicalize_message_type(self, message_type: str) -> str:"""Normalize message type to canonical form to support aliases."""return self.MESSAGE_TYPE_ALIASES.get(message_type, message_type)@@ -406,152 +355,6 @@ class SettingsManager:return normalized- def clear_agent_session_mapping(- self,- user_id: Union[int, str],- agent_name: str,- thread_id: str,- ):- """Clear session mapping for given thread ID"""- user_key = self._normalize_user_id(user_id)- agent_map = self.sessions_store.get_agent_map(user_key, agent_name)- if thread_id in agent_map:- del agent_map[thread_id]- logger.info(f"Cleared {agent_name} session mapping for user {user_id}: {thread_id}")- self.sessions_store.save()-- def clear_agent_sessions(self, user_id: Union[int, str], agent_name: str):- """Clear every session mapping for the specified agent."""- user_key = self._normalize_user_id(user_id)- agent_map = self.sessions_store.get_agent_map(user_key, agent_name)- if agent_map:- self.sessions_store.state.session_mappings[user_key][agent_name] = {}- logger.info(f"Cleared all {agent_name} session namespaces for user {user_id}")- self.sessions_store.save()-- def clear_all_session_mappings(self, user_id: Union[int, str]):- """Clear all session mappings for a user across agents"""- user_key = self._normalize_user_id(user_id)- agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})- if agent_maps:- count = sum(len(agent_map) for agent_map in agent_maps.values())- self.sessions_store.state.session_mappings[user_key] = {}- logger.info(f"Cleared all session mappings ({count} bases) for user {user_id}")- self.sessions_store.save()-- def list_agent_sessions(self, user_id: Union[int, str], agent_name: str) -> Dict[str, str]:- """Get copy of session mappings (thread_id -> session_id) for an agent."""- user_key = self._normalize_user_id(user_id)- agent_map = self.sessions_store.get_agent_map(user_key, agent_name)- return dict(agent_map)-- def list_all_agent_sessions(self, user_id: Union[int, str]) -> Dict[str, Dict[str, str]]:- """Return all stored session mappings for the user, grouped by agent.-- Structure: {agent_name: {thread_id: session_id}}- """- user_key = self._normalize_user_id(user_id)- # Ensure namespaces exist- self.sessions_store._ensure_user_namespace(user_key)- agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})- # Shallow copies to avoid accidental mutation- return {agent: dict(mapping) for agent, mapping in agent_maps.items()}-- # Backwards-compatible helpers for Claude-specific call sites- def set_session_mapping(- self,- user_id: Union[int, str],- thread_id: str,- claude_session_id: str,- ):- self.set_agent_session_mapping(user_id, "claude", thread_id, claude_session_id)-- def get_claude_session_id(self, user_id: Union[int, str], thread_id: str) -> Optional[str]:- return self.get_agent_session_id(user_id, thread_id, agent_name="claude")-- def clear_session_mapping(- self,- user_id: Union[int, str],- thread_id: str,- ):- self.clear_agent_session_mapping(user_id, "claude", thread_id)-- # ---------------------------------------------- # 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"""- user_key = self._normalize_user_id(user_id)- channel_map = self.sessions_store.get_thread_map(user_key, channel_id)- channel_map[thread_ts] = time.time()- self.sessions_store.save()- 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)"""- user_key = self._normalize_user_id(user_id)-- # First cleanup expired threads for this channel- 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 _cleanup_expired_threads_for_channel(self, user_id: Union[int, str], channel_id: str):- """Remove threads older than 24 hours for a specific channel"""- user_key = self._normalize_user_id(user_id)- channel_map = self.sessions_store.get_thread_map(user_key, channel_id)-- if not channel_map:- return-- current_time = time.time()- twenty_four_hours_ago = current_time - (24 * 60 * 60)-- expired_threads = [- thread_ts for thread_ts, last_active in channel_map.items() if last_active < twenty_four_hours_ago- ]-- if expired_threads:- for thread_ts in expired_threads:- del channel_map[thread_ts]-- if not channel_map:- self.sessions_store.state.active_slack_threads[user_key].pop(channel_id, None)-- self.sessions_store.save()- 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"""- user_key = self._normalize_user_id(user_id)- channel_map = self.sessions_store.state.active_slack_threads.get(user_key, {})-- if not channel_map:- return-- channels_to_clean = list(channel_map.keys())- for channel_id in channels_to_clean:- self._cleanup_expired_threads_for_channel(user_id, channel_id)-- # ---------------------------------------------- # Message deduplication- # ---------------------------------------------- def is_message_already_processed(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:- """Check if a message has already been processed.-- Uses set-based exact-match dedup to support all platforms:- - Slack timestamps (epoch.sequence) — monotonic but set-match still works- - Feishu message IDs (om_xxxxx) — NOT monotonic, need exact match- - Discord message IDs — snowflake integers- """- return self.sessions_store.is_message_in_processed_set(channel_id, thread_ts, message_ts)-- def record_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> None:- """Record that a message has been processed."""- self.sessions_store.add_to_processed_set(channel_id, thread_ts, message_ts)- logger.debug(f"Recorded processed message: channel={channel_id}, thread={thread_ts}, message={message_ts}")-# ---------------------------------------------# Channel routing management# ---------------------------------------------@@ -625,66 +428,3 @@ class SettingsManager:if channel_settings is not None:return channel_settings.require_mentionreturn None-- # ---------------------------------------------- # Active polls management (for poll restoration on restart)- # ---------------------------------------------- def add_active_poll(- self,- opencode_session_id: str,- base_session_id: str,- channel_id: str,- thread_id: str,- settings_key: str,- working_path: str,- baseline_message_ids: List[str],- ack_reaction_message_id: Optional[str] = None,- ack_reaction_emoji: Optional[str] = None,- ) -> None:- """Record an active poll for potential restoration on restart."""- from config.v2_sessions import ActivePollInfo-- poll_info = ActivePollInfo(- opencode_session_id=opencode_session_id,- base_session_id=base_session_id,- channel_id=channel_id,- thread_id=thread_id,- settings_key=settings_key,- working_path=working_path,- baseline_message_ids=baseline_message_ids,- seen_tool_calls=[],- emitted_assistant_messages=[],- started_at=time.time(),- ack_reaction_message_id=ack_reaction_message_id,- ack_reaction_emoji=ack_reaction_emoji,- )- self.sessions_store.add_active_poll(poll_info)- logger.debug(f"Added active poll: session={opencode_session_id}, thread={thread_id}")-- def remove_active_poll(self, opencode_session_id: str) -> None:- """Remove an active poll record."""- self.sessions_store.remove_active_poll(opencode_session_id)- logger.debug(f"Removed active poll: session={opencode_session_id}")-- def update_active_poll_state(- self,- opencode_session_id: str,- seen_tool_calls: Optional[List[str]] = None,- emitted_assistant_messages: Optional[List[str]] = None,- ) -> None:- """Update the state of an active poll (for restoration accuracy)."""- from config.v2_sessions import ActivePollInfo-- poll_info = self.sessions_store.get_active_poll(opencode_session_id)- if poll_info:- if seen_tool_calls is not None:- poll_info.seen_tool_calls = seen_tool_calls- if emitted_assistant_messages is not None:- poll_info.emitted_assistant_messages = emitted_assistant_messages- self.sessions_store.update_active_poll(poll_info)-- def get_all_active_polls(self) -> Dict[str, Any]:- """Get all active polls for restoration."""- from config.v2_sessions import ActivePollInfo-- return self.sessions_store.get_all_active_polls()diff --git a/tests/test_auth_pipeline.py b/tests/test_auth_pipeline.pynew file mode 100644index 000000000..7bedb0e3c--- /dev/null+++ b/tests/test_auth_pipeline.py@@ -0,0 +1,106 @@+from types import SimpleNamespace++from core.auth import check_auth+++class _Store:+ def __init__(self):+ self.reload_calls = 0+ self.settings = SimpleNamespace(channels={})+ self._bound_users = set()+ self._admins = set()++ def maybe_reload(self):+ self.reload_calls += 1++ def is_bound_user(self, user_id: str) -> bool:+ return user_id in self._bound_users++ def has_any_admin(self) -> bool:+ return bool(self._admins)++ def is_admin(self, user_id: str) -> bool:+ return user_id in self._admins+++class _SettingsManager:+ def __init__(self, store):+ self._store = store++ def get_store(self):+ return self._store+++def test_check_auth_uses_settings_manager_store():+ store = _Store()+ manager = _SettingsManager(store)++ result = check_auth(+ user_id="U1",+ channel_id="D1",+ is_dm=True,+ action="bind",+ settings_manager=manager,+ )++ assert result.allowed is True+ assert store.reload_calls == 1+++def test_dm_bind_gate_denies_unbound_user():+ store = _Store()+ result = check_auth(+ user_id="U2",+ channel_id="D2",+ is_dm=True,+ action="settings",+ store=store,+ )++ assert result.allowed is False+ assert result.denial == "unbound_dm"+++def test_dm_bind_command_is_exempt():+ store = _Store()+ result = check_auth(+ user_id="U3",+ channel_id="D3",+ is_dm=True,+ action="bind",+ store=store,+ )++ assert result.allowed is True+++def test_channel_auth_denies_unconfigured_channel():+ store = _Store()+ result = check_auth(+ user_id="U4",+ channel_id="C-missing",+ is_dm=False,+ action="",+ store=store,+ )++ assert result.allowed is False+ assert result.denial == "unauthorized_channel"+++def test_admin_guard_denies_non_admin_for_protected_action():+ store = _Store()+ store.settings.channels["C1"] = SimpleNamespace(enabled=True)+ store._bound_users.add("U5")+ store._admins.add("U-admin")++ result = check_auth(+ user_id="U5",+ channel_id="C1",+ is_dm=False,+ action="cmd_settings",+ store=store,+ )++ assert result.allowed is False+ assert result.denial == "not_admin"diff --git a/tests/test_im_base_auth.py b/tests/test_im_base_auth.pynew file mode 100644index 000000000..d01dd05cf--- /dev/null+++ b/tests/test_im_base_auth.py@@ -0,0 +1,87 @@+import asyncio++from modules.im import MessageContext+from modules.im.base import BaseIMClient, BaseIMConfig+++class _Cfg(BaseIMConfig):+ def validate(self) -> None:+ return None+++class _IM(BaseIMClient):+ async def send_message(self, context, text, parse_mode=None, reply_to=None):+ return ""++ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ return ""++ async def edit_message(self, context, message_id, text=None, keyboard=None, parse_mode=None):+ return True++ async def answer_callback(self, callback_id, text=None, show_alert=False):+ return True++ def register_handlers(self):+ return None++ def run(self):+ return None++ async def get_user_info(self, user_id):+ return {}++ async def get_channel_info(self, channel_id):+ return {}++ def format_markdown(self, text):+ return text+++def test_extract_command_action():+ assert BaseIMClient.extract_command_action("/settings") == "settings"+ assert BaseIMClient.extract_command_action("/set_cwd /tmp") == "set_cwd"+ assert BaseIMClient.extract_command_action("hello") == ""+ assert BaseIMClient.extract_command_action("") == ""+++def test_parse_text_command():+ assert BaseIMClient.parse_text_command("/settings") == ("settings", "")+ assert BaseIMClient.parse_text_command("/set_cwd /tmp") == ("set_cwd", "/tmp")+ assert BaseIMClient.parse_text_command("hello") is None+ assert BaseIMClient.parse_text_command("/") is None+++def test_check_authorization_uses_text_when_action_missing():+ im = _IM(_Cfg())+ result = im.check_authorization(+ user_id="U1",+ channel_id="D1",+ is_dm=True,+ text="/bind code",+ )+ assert result.allowed is True+++def test_dispatch_text_command_executes_handler():+ im = _IM(_Cfg())+ received = {}++ async def _handler(context, args):+ received["user"] = context.user_id+ received["args"] = args++ im.on_command_callbacks = {"start": _handler}+ context = MessageContext(user_id="U1", channel_id="C1")++ handled = asyncio.run(im.dispatch_text_command(context, "/start now"))++ assert handled is True+ assert received == {"user": "U1", "args": "now"}+++def test_dispatch_text_command_returns_false_for_unknown():+ im = _IM(_Cfg())+ context = MessageContext(user_id="U1", channel_id="C1")+ handled = asyncio.run(im.dispatch_text_command(context, "/unknown"))+ assert handled is Falsediff --git a/tests/test_resume_session.py b/tests/test_resume_session.pyindex cf4b50d01..a97306421 100644--- a/tests/test_resume_session.py+++ b/tests/test_resume_session.py@@ -2,6 +2,7 @@ import unittestfrom core.controller import Controllerfrom core.handlers.command_handlers import CommandHandlers+from core.handlers.session_handler import SessionHandlerfrom modules.im import MessageContextfrom modules.im.slack import SlackBotfrom config.v2_config import SlackConfig@@ -56,9 +57,15 @@ class _StubController(Controller):def init_minimal(self, im_client, settings_manager, config, session_manager=None):self.im_client = im_clientself.settings_manager = settings_manager+ self.sessions = settings_managerself.config = configself.session_manager = session_manager+ self.claude_sessions = {}+ self.receiver_tasks = {}+ self.stored_session_mappings = {}+ self.agent_service = type("A", (), {"agents": {"claude": object(), "codex": object()}})()self.command_handler = CommandHandlers(self)+ self.session_handler = SessionHandler(self)def _get_settings_key(self, context: MessageContext) -> str:return context.channel_id@@ -71,7 +78,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):ctrl = _StubController()ctrl.init_minimal(im_client, settings, _StubConfig())- await ctrl.handle_resume_session_submission(+ await ctrl.session_handler.handle_resume_session_submission(user_id="U123",channel_id="C111",thread_id="169999.123",@@ -92,7 +99,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):ctrl = _StubController()ctrl.init_minimal(im_client, settings, _StubConfig())- await ctrl.handle_resume_session_submission(+ await ctrl.session_handler.handle_resume_session_submission(user_id="U999",channel_id="DXYZ",thread_id=None,diff --git a/tests/test_routing_modal_selection.py b/tests/test_routing_modal_selection.pynew file mode 100644index 000000000..c2cf2aec9--- /dev/null+++ b/tests/test_routing_modal_selection.py@@ -0,0 +1,35 @@+from modules.im.slack_modal import parse_routing_modal_selection+++def test_parse_routing_modal_selection_uses_action_override():+ view = {+ "state": {+ "values": {+ "backend_block": {"backend_select": {"selected_option": {"value": "opencode"}}},+ "opencode_model_block": {"opencode_model_select": {"selected_option": {"value": "m1"}}},+ }+ }+ }+ action = {"action_id": "opencode_model_select", "selected_option": {"value": "m2"}}++ selection = parse_routing_modal_selection(view=view, action=action, default_backend="claude")++ assert selection.selected_backend == "opencode"+ assert selection.selected_opencode_model == "m2"+++def test_parse_routing_modal_selection_normalizes_default_values():+ view = {+ "state": {+ "values": {+ "claude_model_block": {"claude_model_select": {"selected_option": {"value": "__default__"}}},+ "codex_reasoning_block": {"codex_reasoning_select_1": {"selected_option": {"value": "__default__"}}},+ }+ }+ }++ selection = parse_routing_modal_selection(view=view, action={}, default_backend="claude")++ assert selection.selected_backend == "claude"+ assert selection.selected_claude_model is None+ assert selection.selected_codex_reasoning is None