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
feat(im): configurable ack reactions
cyhhao0e8875876a6b
diff --git a/.env.example b/.env.exampleindex 59b4b6dc7..43063e174 100644--- a/.env.example+++ b/.env.example@@ -40,6 +40,12 @@ CLAUDE_SYSTEM_PROMPT=# Application ConfigurationLOG_LEVEL=INFO+# Acknowledgement mode before agent processing+# Options:+# - reaction (default): add 👀 / :eyes: to the user's message+# - message: send "📨 <agent> received, processing..." as a bot message+ACK_MODE=reaction+# Agent routing & Codex (optional)# Enable Codex CLI support (requires codex to be installed locally). Defaults to true.CODEX_ENABLED=truediff --git a/config/settings.py b/config/settings.pyindex df96ca8e9..b64422e1a 100644--- a/config/settings.py+++ b/config/settings.py@@ -212,6 +212,7 @@ class AppConfig:opencode: Optional[OpenCodeConfig] = Nonelog_level: str = "INFO"cleanup_enabled: bool = False+ ack_mode: str = "reaction" # "reaction" (default) | "message"agent_route_file: Optional[str] = None@classmethod@@ -234,6 +235,16 @@ class AppConfig:cleanup_enabled_env = os.getenv("CLEANUP_ENABLED", "false").lower()cleanup_enabled = cleanup_enabled_env in ["1", "true", "yes", "on"]+ # Acknowledgement behavior before agent processing+ # - reaction: add 👀/:eyes: to the user's message (default)+ # - message: send "📨 <agent> received, processing..." as a bot message+ ack_mode = os.getenv("ACK_MODE", "reaction").strip().lower() or "reaction"+ if ack_mode not in ["reaction", "message"]:+ logger.warning(+ f"Invalid ACK_MODE '{ack_mode}', falling back to 'reaction'"+ )+ ack_mode = "reaction"+agent_route_env = os.getenv("AGENT_ROUTE_FILE")agent_route_file = agent_route_envif not agent_route_file:@@ -274,6 +285,7 @@ class AppConfig:claude=ClaudeConfig.from_env(),log_level=log_level,cleanup_enabled=cleanup_enabled,+ ack_mode=ack_mode,codex=codex_config,opencode=opencode_config,agent_route_file=agent_route_file,diff --git a/core/controller.py b/core/controller.pyindex 5c447b555..ead92c09e 100644--- a/core/controller.py+++ b/core/controller.py@@ -463,17 +463,46 @@ class Controller: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+if oc_agent == "__default__":oc_agent = None-- oc_model = _selected_value("opencode_model_block", "opencode_model_select")if oc_model == "__default__":oc_model = None-- oc_reasoning = _selected_value(- "opencode_reasoning_block", "opencode_reasoning_select"- )if oc_reasoning == "__default__":oc_reasoning = Nonediff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex e3d8fa1a5..f5b457f8f 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -74,15 +74,38 @@ class MessageHandler:settings_key = self._get_settings_key(context)agent_name = self.controller.resolve_agent_for_context(context)- ack_context = self._get_target_context(context)- ack_text = self._get_ack_text(agent_name)+ack_message_id = None- try:- ack_message_id = await self.im_client.send_message(- ack_context, ack_text- )- except Exception as ack_err:- logger.debug(f"Failed to send ack message: {ack_err}")+ ack_mode = getattr(self.config, "ack_mode", "reaction")+ ack_reaction_message_id = None+ ack_reaction_emoji = None++ if ack_mode == "message":+ ack_context = self._get_target_context(context)+ ack_text = self._get_ack_text(agent_name)+ try:+ ack_message_id = await self.im_client.send_message(+ ack_context, ack_text+ )+ except Exception as ack_err:+ logger.debug(f"Failed to send ack message: {ack_err}")+ else:+ # Default: add 👀 / :eyes: reaction to the user's message+ try:+ if context.message_id:+ ack_reaction_message_id = context.message_id+ ack_reaction_emoji = (+ ":eyes:" if self.config.platform == "slack" else "👀"+ )+ ok = await self.im_client.add_reaction(+ context, ack_reaction_message_id, ack_reaction_emoji+ )+ if not ok:+ logger.info(+ "Ack reaction not applied (platform returned False)"+ )+ except Exception as ack_err:+ logger.debug(f"Failed to add reaction ack: {ack_err}")request = AgentRequest(context=context,@@ -100,6 +123,13 @@ class MessageHandler:finally:if request.ack_message_id:await self._delete_ack(context.channel_id, request)+ elif ack_reaction_message_id and ack_reaction_emoji:+ try:+ await self.im_client.remove_reaction(+ context, ack_reaction_message_id, ack_reaction_emoji+ )+ except Exception as err:+ logger.debug(f"Failed to remove reaction ack: {err}")except Exception as e:logger.error(f"Error processing user message: {e}", exc_info=True)await self.im_client.send_message(diff --git a/docs/CODEX_SETUP.md b/docs/CODEX_SETUP.mdindex fe4fb3d75..d07219bbb 100644--- a/docs/CODEX_SETUP.md+++ b/docs/CODEX_SETUP.md@@ -58,7 +58,7 @@ source venv/bin/activate./start.sh```-In a routed Slack channel run `@VibeRemote status` or any question—you should see an acknowledgement like `📨 Codex received, processing...` followed by Codex’s reply. If the CLI is missing, the bot will reply with “Agent `codex` is not configured”.+In a routed Slack channel run `@VibeRemote status` or any question—you should see the bot react with 👀 (default) or an acknowledgement like `📨 Codex received, processing...` (when `ACK_MODE=message`), followed by Codex’s reply. If the CLI is missing, the bot will reply with “Agent `codex` is not configured”.## 5. Troubleshootingdiff --git a/docs/SLACK_SETUP.md b/docs/SLACK_SETUP.mdindex 1770e1e9e..e836b6066 100644--- a/docs/SLACK_SETUP.md+++ b/docs/SLACK_SETUP.md@@ -44,7 +44,7 @@ This guide will walk you through setting up a Slack bot for Vibe Remote.- `files:read` - View files shared in channels (for future file handling)- `files:write` - Upload files (for future file upload support)- `reactions:read` - View emoji reactions-- `reactions:write` - Add emoji reactions+- `reactions:write` - Add emoji reactions (required for `ACK_MODE=reaction`; set `ACK_MODE=message` to use text ack instead)- `users:read.email` - View email addresses (for enhanced user info)- `team:read` - View team/workspace information@@ -352,6 +352,15 @@ If you see `missing_scope` errors with `groups:read`:4. Restart the bot5. Ensure bot is invited to the private channel: `/invite @YourBotName`+### Reaction / Ack Reaction Issues++If you see `missing_scope` errors with `reactions:write` (for 👀 reaction acknowledgement):++1. Add `reactions:write` under **Bot Token Scopes**+2. Click **"Reinstall to Workspace"** (this is mandatory!)+3. Copy the new Bot Token and update your `.env` file+4. Restart the bot+### Thread Reply IssuesIf you see `cannot_reply_to_message` error:diff --git a/docs/SLACK_SETUP_ZH.md b/docs/SLACK_SETUP_ZH.mdindex 0ac8ca971..b2b0cb716 100644--- a/docs/SLACK_SETUP_ZH.md+++ b/docs/SLACK_SETUP_ZH.md@@ -44,7 +44,7 @@- `files:read` - 查看频道中共享的文件(用于未来的文件处理)- `files:write` - 上传文件(用于未来的文件上传支持)- `reactions:read` - 查看表情反应-- `reactions:write` - 添加表情反应+- `reactions:write` - 添加表情反应(`ACK_MODE=reaction` 必需;如需发送文字 ack 可设为 `ACK_MODE=message`)- `users:read.email` - 查看电子邮件地址(用于增强用户信息)- `team:read` - 查看团队/工作区信息@@ -352,6 +352,15 @@ Slack 机器人自动使用线程来组织对话:4. 重启机器人5. 确保机器人被邀请到私有频道:`/invite @YourBotName`+### 表情/ACK Reaction 问题++如果你看到 `missing_scope` 错误与 `reactions:write`(用于 👀 reaction ack):++1. 在 **Bot Token Scopes** 下添加 `reactions:write`+2. 点击 **"Reinstall to Workspace"**(这是强制性的!)+3. 复制新的 Bot Token 并更新你的 `.env` 文件+4. 重启机器人+### 线程回复问题如果你看到 `cannot_reply_to_message` 错误:diff --git a/main.py b/main.pyindex ad7455f97..dec0ddad2 100644--- a/main.py+++ b/main.py@@ -1,5 +1,6 @@#!/usr/bin/env python3import os+import signalimport sysimport loggingimport asyncio@@ -74,6 +75,27 @@ def main():# Create and run controllercontroller = Controller(config)++ shutdown_initiated = False++ def _handle_shutdown(signum, frame):+ nonlocal shutdown_initiated+ if shutdown_initiated:+ return+ shutdown_initiated = True+ try:+ logger.info(f"Received signal {signum}, shutting down...")+ except Exception:+ pass+ try:+ controller.cleanup_sync()+ except Exception as cleanup_err:+ logger.error(f"Cleanup failed: {cleanup_err}")+ raise SystemExit(0)++ signal.signal(signal.SIGTERM, _handle_shutdown)+ signal.signal(signal.SIGINT, _handle_shutdown)+controller.run()except Exception as e:diff --git a/modules/agents/opencode_agent.py b/modules/agents/opencode_agent.pyindex a33a10695..33ff0a97b 100644--- a/modules/agents/opencode_agent.py+++ b/modules/agents/opencode_agent.py@@ -1,10 +1,15 @@"""OpenCode Server API integration as an agent backend."""import asyncio+import jsonimport loggingimport os+import signal+import socket+import subprocessimport timefrom asyncio.subprocess import Process+from pathlib import Pathfrom typing import Any, Dict, List, Optional, Tupleimport aiohttp@@ -38,6 +43,9 @@ class OpenCodeServerManager:self._base_url: Optional[str] = Noneself._http_session: Optional[aiohttp.ClientSession] = Noneself._lock = asyncio.Lock()+ self._pid_file = (+ Path(__file__).resolve().parents[2] / "logs" / "opencode_server.json"+ )@classmethodasync def get_instance(@@ -85,10 +93,182 @@ class OpenCodeServerManager:)return self._http_session+ def _read_pid_file(self) -> Optional[Dict[str, Any]]:+ try:+ raw = self._pid_file.read_text()+ except FileNotFoundError:+ return None+ except Exception as e:+ logger.debug(f"Failed to read OpenCode pid file: {e}")+ return None++ try:+ data = json.loads(raw)+ except Exception as e:+ logger.debug(f"Failed to parse OpenCode pid file: {e}")+ return None++ return data if isinstance(data, dict) else None++ def _write_pid_file(self, pid: int) -> None:+ try:+ self._pid_file.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "pid": pid,+ "port": self.port,+ "host": self.host,+ "started_at": time.time(),+ }+ self._pid_file.write_text(json.dumps(payload))+ except Exception as e:+ logger.debug(f"Failed to write OpenCode pid file: {e}")++ def _clear_pid_file(self) -> None:+ try:+ if self._pid_file.exists():+ self._pid_file.unlink()+ except Exception as e:+ logger.debug(f"Failed to clear OpenCode pid file: {e}")++ @staticmethod+ def _pid_exists(pid: int) -> bool:+ if not isinstance(pid, int) or pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ return True+ except ProcessLookupError:+ return False+ except PermissionError:+ return True++ @staticmethod+ def _get_pid_command(pid: int) -> Optional[str]:+ try:+ result = subprocess.run(+ ["ps", "-p", str(pid), "-o", "command="],+ capture_output=True,+ text=True,+ check=False,+ )+ except Exception:+ return None+ cmd = (result.stdout or "").strip()+ return cmd or None++ @staticmethod+ def _is_opencode_serve_cmd(command: str, port: int) -> bool:+ if not command:+ return False+ return "opencode" in command and " serve" in command and f"--port={port}" in command++ def _is_port_available(self) -> bool:+ try:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind((self.host, self.port))+ return True+ except OSError:+ return False++ @staticmethod+ def _find_opencode_serve_pids(port: int) -> List[int]:+ try:+ result = subprocess.run(+ ["ps", "-ax", "-o", "pid=,command="],+ capture_output=True,+ text=True,+ check=False,+ )+ except Exception:+ return []++ needle = f"--port={port}"+ pids: List[int] = []+ for line in (result.stdout or "").splitlines():+ line = line.strip()+ if not line:+ continue+ parts = line.split(None, 1)+ if len(parts) != 2:+ continue+ pid_str, cmd = parts+ if "opencode" in cmd and " serve" in cmd and needle in cmd:+ try:+ pids.append(int(pid_str))+ except ValueError:+ continue+ return pids++ async def _terminate_pid(self, pid: int, reason: str) -> None:+ logger.info(f"Stopping OpenCode server pid={pid} ({reason})")+ try:+ os.kill(pid, signal.SIGTERM)+ except ProcessLookupError:+ return+ except Exception as e:+ logger.debug(f"Failed to terminate OpenCode server pid={pid}: {e}")+ return++ start_time = time.monotonic()+ while time.monotonic() - start_time < 5:+ if not self._pid_exists(pid):+ return+ await asyncio.sleep(0.25)++ try:+ os.kill(pid, signal.SIGKILL)+ except Exception:+ pass++ async def _cleanup_orphaned_managed_server(self) -> None:+ info = self._read_pid_file()+ if not info:+ return++ pid = info.get("pid")+ port = info.get("port")+ if not isinstance(pid, int) or port != self.port:+ self._clear_pid_file()+ return++ if self._process and self._process.returncode is None and self._process.pid == pid:+ return++ cmd = self._get_pid_command(pid)+ if cmd and self._is_opencode_serve_cmd(cmd, self.port) and self._pid_exists(pid):+ await self._terminate_pid(pid, reason="orphaned from previous run")+ self._clear_pid_file()+async def ensure_running(self) -> str:async with self._lock:+ await self._cleanup_orphaned_managed_server()+if await self._is_healthy():+ # If the server is already running (e.g., started by a previous run),+ # record its PID so shutdown can clean it up.+ if not self._read_pid_file():+ pids = self._find_opencode_serve_pids(self.port)+ if pids:+ pid = pids[0]+ cmd = self._get_pid_command(pid)+ if cmd and self._is_opencode_serve_cmd(cmd, self.port):+ self._write_pid_file(pid)++ self._base_url = f"http://{self.host}:{self.port}"return self.base_url++ if not self._is_port_available():+ for pid in self._find_opencode_serve_pids(self.port):+ await self._terminate_pid(pid, reason="port occupied but unhealthy")+ await asyncio.sleep(0.5)++ if not self._is_port_available():+ raise RuntimeError(+ f"OpenCode port {self.port} is already in use but the server is not responding. "+ "Stop the process using this port or set OPENCODE_PORT to a free port."+ )+await self._start_server()return self.base_url@@ -113,6 +293,9 @@ class OpenCodeServerManager:except Exception:self._process.kill()+ # Ensure any stale pid file is cleared before starting.+ self._clear_pid_file()+cmd = [self.binary,"serve",@@ -132,6 +315,8 @@ class OpenCodeServerManager:stderr=asyncio.subprocess.DEVNULL,env=env,)+ if self._process and self._process.pid:+ self._write_pid_file(self._process.pid)except FileNotFoundError:raise RuntimeError(f"OpenCode CLI not found at '{self.binary}'. "@@ -147,6 +332,8 @@ class OpenCodeServerManager:await asyncio.sleep(0.5)exit_code = self._process.returncode+ self._clear_pid_file()+ self._process = Noneraise RuntimeError(f"OpenCode server failed to start within {SERVER_START_TIMEOUT}s. "f"Process exit code: {exit_code}"@@ -165,18 +352,74 @@ class OpenCodeServerManager:except asyncio.TimeoutError:self._process.kill()logger.info("OpenCode server stopped")+ else:+ info = self._read_pid_file()+ pid = info.get("pid") if isinstance(info, dict) else None+ port = info.get("port") if isinstance(info, dict) else None+ if isinstance(pid, int) and port == self.port and self._pid_exists(pid):+ cmd = self._get_pid_command(pid)+ if cmd and self._is_opencode_serve_cmd(cmd, self.port):+ await self._terminate_pid(pid, reason="shutdown")++ self._clear_pid_file()self._process = Nonedef stop_sync(self) -> None:if self._process and self._process.returncode is None:self._process.terminate()logger.info("OpenCode server terminated (sync)")+ else:+ info = self._read_pid_file()+ pid = info.get("pid") if isinstance(info, dict) else None+ port = info.get("port") if isinstance(info, dict) else None+ if isinstance(pid, int) and port == self.port and self._pid_exists(pid):+ cmd = self._get_pid_command(pid)+ if cmd and self._is_opencode_serve_cmd(cmd, self.port):+ try:+ os.kill(pid, signal.SIGTERM)+ logger.info("OpenCode server terminated (sync via pid file)")+ except Exception as e:+ logger.debug(f"Failed to terminate OpenCode server pid={pid}: {e}")++ self._clear_pid_file()self._process = None@classmethoddef stop_instance_sync(cls) -> None:if cls._instance:cls._instance.stop_sync()+ return++ pid_file = Path(__file__).resolve().parents[2] / "logs" / "opencode_server.json"+ try:+ raw = pid_file.read_text()+ except FileNotFoundError:+ return+ except Exception as e:+ logger.debug(f"Failed to read OpenCode pid file: {e}")+ return++ try:+ info = json.loads(raw)+ except Exception:+ info = None++ pid = info.get("pid") if isinstance(info, dict) else None+ port = info.get("port") if isinstance(info, dict) else None++ if isinstance(pid, int) and isinstance(port, int) and cls._pid_exists(pid):+ cmd = cls._get_pid_command(pid)+ if cmd and cls._is_opencode_serve_cmd(cmd, port):+ try:+ os.kill(pid, signal.SIGTERM)+ logger.info("OpenCode server terminated (sync via pid file)")+ except Exception as e:+ logger.debug(f"Failed to terminate OpenCode server pid={pid}: {e}")++ try:+ pid_file.unlink()+ except Exception:+ passasync def create_session(self, directory: str, title: Optional[str] = Nonediff --git a/modules/im/base.py b/modules/im/base.pyindex 34f7ea954..3d5e2cad5 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -103,7 +103,7 @@ class BaseIMClient(ABC):# Platform-specific formatter will be set by subclassesself.formatter = None- def get_default_parse_mode(self) -> str:+ def get_default_parse_mode(self) -> Optional[str]:"""Get the default parse mode for this platformReturns:@@ -248,7 +248,7 @@ class BaseIMClient(ABC):for key, value in kwargs.items():setattr(self, f"{key}_callback", value)- def log_error(self, message: str, exception: Exception = None):+ def log_error(self, message: str, exception: Optional[Exception] = None):"""Standardized error loggingArgs:@@ -267,7 +267,25 @@ class BaseIMClient(ABC):message: Info message"""logger.info(message)-++ async def add_reaction(+ self, context: MessageContext, message_id: str, emoji: str+ ) -> bool:+ """Add a reaction to an existing message.++ Default implementation returns False (unsupported).+ """+ return False++ async def remove_reaction(+ self, context: MessageContext, message_id: str, emoji: str+ ) -> bool:+ """Remove a reaction from an existing message.++ Default implementation returns False (unsupported).+ """+ return False+@abstractmethoddef format_markdown(self, text: str) -> str:"""Format markdown text for the specific platformdiff --git a/modules/im/slack.py b/modules/im/slack.pyindex 57b4cbf7a..8460f3567 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1,4 +1,5 @@import asyncio+import hashlibimport loggingimport timefrom typing import Dict, Any, Optional, Callable@@ -156,6 +157,81 @@ class SlackBot(BaseIMClient):logger.error(f"Error sending Slack message: {e}")raise+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:+ """Add a reaction emoji to a Slack message."""+ self._ensure_clients()++ name = (emoji or "").strip()+ if name.startswith(":") and name.endswith(":") and len(name) > 2:+ name = name[1:-1]+ if name in ["👀", "eyes", "eye"]:+ name = "eyes"++ if not name:+ return False++ try:+ await self.web_client.reactions_add(+ channel=context.channel_id,+ timestamp=message_id,+ name=name,+ )+ return True+ except SlackApiError as err:+ try:+ if getattr(err, "response", None) and err.response.get("error") == "already_reacted":+ return True+ except Exception:+ pass++ error_code = None+ needed = None+ try:+ if getattr(err, "response", None):+ error_code = err.response.get("error")+ needed = err.response.get("needed")+ except Exception:+ pass++ # NOTE: reaction failures were previously DEBUG-only; surface at INFO/WARN for operability.+ if error_code in ["missing_scope", "not_in_channel", "channel_not_found"]:+ logger.warning(+ f"Slack reaction add failed: error={error_code}, needed={needed}"+ )+ else:+ logger.info(f"Slack reaction add failed: {err}")+ return False+ except Exception as err:+ logger.debug(f"Failed to add Slack reaction: {err}")+ return False++ async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:+ """Remove a reaction emoji from a Slack message."""+ self._ensure_clients()++ name = (emoji or "").strip()+ if name.startswith(":") and name.endswith(":") and len(name) > 2:+ name = name[1:-1]+ if name in ["👀", "eyes", "eye"]:+ name = "eyes"++ if not name:+ return False++ try:+ await self.web_client.reactions_remove(+ channel=context.channel_id,+ timestamp=message_id,+ name=name,+ )+ return True+ except SlackApiError as err:+ logger.debug(f"Failed to remove Slack reaction: {err}")+ return False+ except Exception as err:+ logger.debug(f"Failed to remove Slack reaction: {err}")+ return False+async def send_message_with_buttons(self,context: MessageContext,@@ -569,10 +645,18 @@ class SlackBot(BaseIMClient):async def _handle_interactive(self, payload: Dict[str, Any]):"""Handle interactive components (buttons, modal submissions, etc.)"""if payload.get("type") == "block_actions":- # Handle button clicks+ # Handle button clicks / select changesuser = payload.get("user", {})actions = payload.get("actions", [])- channel_id = payload.get("channel", {}).get("id")+ view = payload.get("view", {})++ # In Slack modals, `channel` is often missing. We store the originating+ # channel_id in `view.private_metadata` when opening the modal.+ channel_id = (+ payload.get("channel", {}).get("id")+ or payload.get("container", {}).get("channel_id")+ or (view.get("private_metadata") if isinstance(view, dict) else None)+ )# Check if channel is authorized for interactive componentsif not await self._is_authorized_channel(channel_id):@@ -693,10 +777,17 @@ class SlackBot(BaseIMClient):oc_model = None# Extract OpenCode reasoning effort (optional)- oc_reasoning_data = values.get("opencode_reasoning_block", {}).get(- "opencode_reasoning_select", {}- )- oc_reasoning = oc_reasoning_data.get("selected_option", {}).get("value")+ oc_reasoning = None+ reasoning_block = values.get("opencode_reasoning_block", {})+ if isinstance(reasoning_block, dict):+ for action_id, action_data in reasoning_block.items():+ if (+ isinstance(action_id, str)+ and action_id.startswith("opencode_reasoning_select")+ and isinstance(action_data, dict)+ ):+ oc_reasoning = action_data.get("selected_option", {}).get("value")+ breakif oc_reasoning == "__default__":oc_reasoning = None@@ -1236,9 +1327,14 @@ class SlackBot(BaseIMClient):}# Build reasoning effort options dynamically based on model variants- # Determine target model for variants lookuptarget_model = current_oc_model or default_model_str- model_variants = {}+ model_variants: Dict[str, Any] = {}++ reasoning_model_key = target_model or "__default__"+ reasoning_action_id = (+ "opencode_reasoning_select__"+ + hashlib.sha1(reasoning_model_key.encode("utf-8")).hexdigest()[:8]+ )if target_model:# Parse provider/model format@@ -1247,13 +1343,31 @@ class SlackBot(BaseIMClient):target_provider, target_model_id = parts# Search for this model in providers datafor provider in providers_data:- if provider.get("id") == target_provider:- models = provider.get("models", {})- if isinstance(models, dict):- model_info = models.get(target_model_id, {})- if isinstance(model_info, dict):- model_variants = model_info.get("variants", {})- break+ if provider.get("id") != target_provider:+ continue++ models = provider.get("models", {})+ model_info: Optional[dict] = None++ if isinstance(models, dict):+ candidate = models.get(target_model_id)+ if isinstance(candidate, dict):+ model_info = candidate+ elif isinstance(models, list):+ for entry in models:+ if (+ isinstance(entry, dict)+ and entry.get("id") == target_model_id+ ):+ model_info = entry+ break++ if isinstance(model_info, dict):+ variants = model_info.get("variants", {})+ if isinstance(variants, dict):+ model_variants = variants++ break# Build options from variants or use fallbackreasoning_effort_options = [@@ -1304,7 +1418,7 @@ class SlackBot(BaseIMClient):reasoning_select = {"type": "static_select",- "action_id": "opencode_reasoning_select",+ "action_id": reasoning_action_id,"placeholder": {"type": "plain_text", "text": "Select reasoning effort"},"options": reasoning_effort_options,"initial_option": initial_reasoning,diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex cfbb3cb46..ace40839f 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -280,6 +280,49 @@ class TelegramBot(BaseIMClient):logger.error(f"Error sending message: {e}")raise+ async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:+ """Add a reaction emoji to a Telegram message."""+ bot = self.application.bot++ reaction = (emoji or "").strip()+ if reaction in [":eyes:", "eyes", "👀"]:+ reaction = "👀"++ if not reaction:+ return False++ try:+ await bot.set_message_reaction(+ chat_id=int(context.channel_id),+ message_id=int(message_id),+ reaction=reaction,+ )+ return True+ except TelegramError as e:+ logger.debug(f"Failed to add Telegram reaction: {e}")+ return False+ except Exception as e:+ logger.debug(f"Failed to add Telegram reaction: {e}")+ return False++ async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:+ """Remove a reaction emoji from a Telegram message."""+ bot = self.application.bot++ try:+ await bot.set_message_reaction(+ chat_id=int(context.channel_id),+ message_id=int(message_id),+ reaction=None,+ )+ return True+ except TelegramError as e:+ logger.debug(f"Failed to remove Telegram reaction: {e}")+ return False+ except Exception as e:+ logger.debug(f"Failed to remove Telegram reaction: {e}")+ return False+async def send_message_with_buttons(self,context: MessageContext,