Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(platform): stabilize runtime and routing interactions
cyhd8e3bfbe6469
diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex b0b65bf44..995e34f3d 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -1569,6 +1569,10 @@ class FeishuBot(BaseIMClient):await self.dismiss_form_message(context)return+ if action.get("tag") in {"select_static", "multi_select_static"}:+ if await self._handle_routing_select_change(context, action):+ return+# --- Regular button callbacks ---if not callback_data:return@@ -1658,6 +1662,115 @@ class FeishuBot(BaseIMClient):**cached,)+ @staticmethod+ def _normalize_routing_field_value(value: Any) -> Optional[str]:+ if value in (None, "", "__default__"):+ return None+ return str(value)++ @staticmethod+ def _routing_draft_from_current(current_routing: Any) -> Dict[str, Optional[str]]:+ fields = (+ "opencode_agent",+ "opencode_model",+ "opencode_reasoning_effort",+ "claude_agent",+ "claude_model",+ "claude_reasoning_effort",+ "codex_model",+ "codex_reasoning_effort",+ )+ draft: Dict[str, Optional[str]] = {}+ for field_name in fields:+ draft[field_name] = getattr(current_routing, field_name, None) if current_routing else None+ return draft++ @staticmethod+ def _extract_select_action_value(action: Dict[str, Any]) -> Optional[str]:+ option = action.get("option")+ if isinstance(option, dict):+ value = option.get("value")+ if isinstance(value, str):+ return value+ elif isinstance(option, str):+ return option++ options = action.get("options")+ if isinstance(options, list) and options:+ first = options[0]+ if isinstance(first, dict):+ value = first.get("value")+ if isinstance(value, str):+ return value+ elif isinstance(first, str):+ return first++ return None++ async def _patch_card_message(self, message_id: str, card: Dict[str, Any]) -> None:+ if not message_id:+ return++ from lark_oapi.api.im.v1 import PatchMessageRequest, PatchMessageRequestBody++ request = (+ PatchMessageRequest.builder()+ .message_id(message_id)+ .request_body(PatchMessageRequestBody.builder().content(json.dumps(card, ensure_ascii=False)).build())+ .build()+ )+ response = await self._lark_client.im.v1.message.apatch(request)+ if not response.success():+ raise RuntimeError(f"Feishu patch card failed: {response.msg}")++ async def _handle_routing_select_change(self, context: MessageContext, action: Dict[str, Any]) -> bool:+ field_name = action.get("name", "")+ if not field_name:+ return False++ routing_field_map = {+ "opencode_agent": "opencode_agent",+ "opencode_model": "opencode_model",+ "opencode_reasoning": "opencode_reasoning_effort",+ "claude_agent": "claude_agent",+ "claude_model": "claude_model",+ "claude_reasoning": "claude_reasoning_effort",+ "codex_model": "codex_model",+ "codex_reasoning": "codex_reasoning_effort",+ }+ routing_field = routing_field_map.get(field_name)+ if not routing_field:+ return False++ cache_key = f"{context.channel_id}:{context.user_id}"+ cache = self._routing_cache.get(cache_key)+ if not cache:+ return False++ draft_routing = dict(+ cache.get("draft_routing") or self._routing_draft_from_current(cache.get("current_routing"))+ )+ selected_value = self._normalize_routing_field_value(self._extract_select_action_value(action))+ draft_routing[routing_field] = selected_value++ if routing_field == "claude_model":+ draft_routing["claude_reasoning_effort"] = None++ cache["draft_routing"] = draft_routing+ self._routing_cache[cache_key] = cache++ if routing_field != "claude_model" or cache.get("_selected_backend") != "claude":+ return True++ card = self._build_routing_backend_options_card(+ channel_id=context.channel_id,+ selected_backend="claude",+ _user_id=context.user_id,+ **cache,+ )+ await self._patch_card_message(context.message_id, card)+ return True+async def _handle_routing_form_submit(self, context: MessageContext, form_value: Dict[str, Any]):"""Handle step 2 routing form submission (backend-specific options)."""# Backend is embedded in form as a disabled select or retrieved from cache@@ -2062,6 +2175,7 @@ class FeishuBot(BaseIMClient):cache_key = f"{channel_id or ''}:{cache_user_id}"self._routing_cache[cache_key] = {"current_routing": kwargs.get("current_routing"),+ "draft_routing": self._routing_draft_from_current(kwargs.get("current_routing")),"registered_backends": registered_backends,"opencode_agents": kwargs.get("opencode_agents", []),"opencode_models": kwargs.get("opencode_models", {}),@@ -2138,16 +2252,17 @@ class FeishuBot(BaseIMClient):except Exception as exc:logger.error("Failed to send routing backend card: %s", exc)- async def _send_routing_backend_options_card(+ def _build_routing_backend_options_card(self,channel_id: str,selected_backend: str,**kwargs,- ):- """Step 2: send a card with options specific to the selected backend."""+ ) -> Dict[str, Any]:+ """Build the step-2 routing card for a selected backend."""t = lambda key, **kw: self._t(key, channel_id, **kw)current_routing = kwargs.get("current_routing")+ draft_routing = kwargs.get("draft_routing") or {}opencode_agents = kwargs.get("opencode_agents", [])opencode_models = kwargs.get("opencode_models", {})opencode_default_config = kwargs.get("opencode_default_config", {})@@ -2155,11 +2270,17 @@ class FeishuBot(BaseIMClient):claude_models = kwargs.get("claude_models", [])codex_models = kwargs.get("codex_models", [])+ def _routing_value(field_name: str) -> Optional[str]:+ if field_name in draft_routing:+ return draft_routing[field_name]+ return getattr(current_routing, field_name, None) if current_routing else None+# Store selected backend for the final submit handleruser_id = kwargs.get("_user_id", "unknown")cache_key = f"{channel_id}:{user_id}"cache = self._routing_cache.get(cache_key, {})cache["_selected_backend"] = selected_backend+ cache.setdefault("draft_routing", self._routing_draft_from_current(current_routing))self._routing_cache[cache_key] = cacheform_elements: list = [@@ -2175,7 +2296,7 @@ class FeishuBot(BaseIMClient):for agent_info in opencode_agents:name = agent_info if isinstance(agent_info, str) else agent_info.get("name", str(agent_info))oc_agent_options.append({"text": {"tag": "plain_text", "content": name}, "value": name})- oc_current_agent = getattr(current_routing, "opencode_agent", None) if current_routing else None+ oc_current_agent = _routing_value("opencode_agent")form_elements.append({"tag": "markdown", "content": t("modal.routing.opencodeAgent")})form_elements.append({@@ -2188,7 +2309,7 @@ class FeishuBot(BaseIMClient):)# OpenCode model selector (using shared utility)- oc_current_model = getattr(current_routing, "opencode_model", None) if current_routing else None+ oc_current_model = _routing_value("opencode_model")preferred_providers = resolve_opencode_provider_preferences(opencode_default_config,oc_current_model,@@ -2231,7 +2352,7 @@ class FeishuBot(BaseIMClient):if not label or not value:continuere_options.append({"text": {"tag": "plain_text", "content": label}, "value": value})- oc_current_re = getattr(current_routing, "opencode_reasoning_effort", None) if current_routing else None+ oc_current_re = _routing_value("opencode_reasoning_effort")if re_options:form_elements.append({"tag": "markdown", "content": t("modal.routing.reasoningEffort")})form_elements.append(@@ -2246,14 +2367,14 @@ class FeishuBot(BaseIMClient):# ---- Claude section ----elif selected_backend == "claude":- cl_current_model = getattr(current_routing, "claude_model", None) if current_routing else None+ cl_current_model = _routing_value("claude_model")# Claude agent selectorif claude_agents:cl_agent_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]for agent_info in claude_agents:name = agent_info if isinstance(agent_info, str) else agent_info.get("name", str(agent_info))cl_agent_options.append({"text": {"tag": "plain_text", "content": name}, "value": name})- cl_current_agent = getattr(current_routing, "claude_agent", None) if current_routing else None+ cl_current_agent = _routing_value("claude_agent")form_elements.append({"tag": "markdown", "content": t("modal.routing.claudeAgent")})form_elements.append({@@ -2282,7 +2403,7 @@ class FeishuBot(BaseIMClient):})- cl_current_re = getattr(current_routing, "claude_reasoning_effort", None) if current_routing else None+ cl_current_re = _routing_value("claude_reasoning_effort")cl_re_defs = build_claude_reasoning_options(cl_current_model)cl_re_options = []for item in cl_re_defs:@@ -2306,7 +2427,7 @@ class FeishuBot(BaseIMClient):for m in codex_models:mid = m if isinstance(m, str) else m.get("id", str(m))cx_model_options.append({"text": {"tag": "plain_text", "content": mid}, "value": mid})- cx_current_model = getattr(current_routing, "codex_model", None) if current_routing else None+ cx_current_model = _routing_value("codex_model")form_elements.append({"tag": "markdown", "content": t("modal.routing.model")})form_elements.append({@@ -2322,7 +2443,7 @@ class FeishuBot(BaseIMClient):cx_re_options = []for item in codex_re_defs:cx_re_options.append({"text": {"tag": "plain_text", "content": item["label"]}, "value": item["value"]})- cx_current_re = getattr(current_routing, "codex_reasoning_effort", None) if current_routing else None+ cx_current_re = _routing_value("codex_reasoning_effort")form_elements.append({"tag": "markdown", "content": t("modal.routing.codexReasoningEffort")})form_elements.append({@@ -2345,7 +2466,7 @@ class FeishuBot(BaseIMClient):})- card = {+ return {"schema": "2.0","header": {"title": {"tag": "plain_text", "content": f"{t('modal.routing.title')} — {selected_backend}"},@@ -2363,6 +2484,15 @@ class FeishuBot(BaseIMClient):},}+ async def _send_routing_backend_options_card(+ self,+ channel_id: str,+ selected_backend: str,+ **kwargs,+ ):+ """Step 2: send a card with options specific to the selected backend."""+ card = self._build_routing_backend_options_card(channel_id, selected_backend, **kwargs)+ctx = MessageContext(user_id="system", channel_id=channel_id or "")try:await self._send_card_to_channel(ctx, card)diff --git a/modules/im/slack.py b/modules/im/slack.pyindex d842a6ff8..8acba0fd8 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1,6 +1,7 @@import asyncioimport hashlibimport logging+import reimport timeimport aiohttpfrom typing import Dict, Any, Optional, Callable, List@@ -62,6 +63,7 @@ class SlackBot(BaseIMClient):self._controller = Noneself._recent_event_ids: Dict[str, float] = {}self._user_info_cache: Dict[str, Dict[str, Any]] = {}+ self._bot_user_id: Optional[str] = Noneself._stop_event: Optional[asyncio.Event] = Noneself._loop: Optional[asyncio.AbstractEventLoop] = Noneself._on_ready: Optional[Callable] = None@@ -124,6 +126,63 @@ class SlackBot(BaseIMClient):if self.socket_client is None and self.config.app_token:self.socket_client = SocketModeClient(app_token=self.config.app_token, web_client=self.web_client)+ def _extract_bot_user_id_from_payload(self, payload: Dict[str, Any]) -> Optional[str]:+ authorizations = payload.get("authorizations") or []+ for authorization in authorizations:+ if isinstance(authorization, dict):+ user_id = authorization.get("user_id")+ if isinstance(user_id, str) and user_id:+ return user_id++ authed_users = payload.get("authed_users") or []+ for user_id in authed_users:+ if isinstance(user_id, str) and user_id:+ return user_id++ return None++ async def _get_bot_user_id(self, payload: Optional[Dict[str, Any]] = None) -> Optional[str]:+ payload_user_id = self._extract_bot_user_id_from_payload(payload or {})+ if payload_user_id:+ self._bot_user_id = payload_user_id+ return payload_user_id++ if self._bot_user_id:+ return self._bot_user_id++ self._ensure_clients()+ auth_test = getattr(self.web_client, "auth_test", None)+ if not callable(auth_test):+ return None++ try:+ response = await auth_test()+ except Exception as exc:+ logger.debug("Failed to resolve Slack bot user id: %s", exc)+ return None++ user_id = response.get("user_id") if isinstance(response, dict) else None+ if isinstance(user_id, str) and user_id:+ self._bot_user_id = user_id+ return user_id+ return None++ @staticmethod+ def _has_specific_mention(text: str, user_id: Optional[str]) -> bool:+ if not user_id:+ return False+ return bool(re.search(rf"<@{re.escape(user_id)}>", text))++ @staticmethod+ def _strip_specific_mention(text: str, user_id: Optional[str], *, anywhere: bool = False) -> str:+ if not user_id:+ return text+ if anywhere:+ pattern = rf"<@{re.escape(user_id)}>\s*"+ else:+ pattern = rf"^\s*<@{re.escape(user_id)}>\s*"+ return re.sub(pattern, "", text, count=1).strip()+def _convert_markdown_to_slack_mrkdwn(self, text: str) -> str:"""Convert standard markdown to Slack mrkdwn format using third-party library@@ -897,12 +956,14 @@ class SlackBot(BaseIMClient):# In channels, app_mention will handle it. In DMs, Slack does not# emit app_mention, so we strip the mention and continue.text = (event.get("text") or "").strip()- import rehad_dm_mention_only = False- if re.search(r"<@[\w]+>", text):+ bot_user_id = await self._get_bot_user_id(payload)+ has_bot_mention = self._has_specific_mention(text, bot_user_id)+ cleaned_text = self._strip_specific_mention(text, bot_user_id)+ if has_bot_mention:if is_dm:- text = re.sub(r"<@[\w]+>", "", text).strip()+ text = cleaned_texthad_dm_mention_only = not textelse:logger.info(f"Skipping message event with bot mention: '{text}'")@@ -1027,10 +1088,11 @@ class SlackBot(BaseIMClient):user_id_mention = event.get("user")# Remove the mention from the text first so we can parse commands for auth- text = event.get("text", "")- import re-- text = re.sub(r"<@[\w]+>", "", text).strip()+ text = self._strip_specific_mention(+ event.get("text", ""),+ await self._get_bot_user_id(payload),+ anywhere=True,+ )# Parse command action for proper admin-protected auth checkparsed_command = self.parse_text_command(text)diff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.shindex 6658fdf9b..136b6ba8f 100755--- a/scripts/docker-entrypoint.sh+++ b/scripts/docker-entrypoint.sh@@ -28,6 +28,33 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})echo "$ui_pid"}+write_runtime_status() {+ local state="$1"+ local detail="$2"+ local service_pid="${3:-None}"+ local ui_pid="${4:-None}"++ python -c "+from vibe import runtime+runtime.write_status('${state}', '${detail}', ${service_pid}, ${ui_pid})+"+}++exit_if_service_stopped() {+ local service_pid="$1"+ local ui_pid="$2"++ if kill -0 "$service_pid" 2>/dev/null; then+ return 0+ fi++ local service_exit_code=0+ wait "$service_pid" 2>/dev/null || service_exit_code=$?+ echo "Service exited unexpectedly (code: ${service_exit_code}), stopping container..." >&2+ write_runtime_status "stopped" "service exited unexpectedly" "$service_pid" "$ui_pid"+ exit "$service_exit_code"+}+# Ensure runtime directories exist and seed default config if missingpython -c "from config.paths import ensure_data_dirs, get_config_path@@ -62,10 +89,7 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})UI_PID="$(start_ui_process "$RUNTIME_DIR")"- python -c "-from vibe import runtime-runtime.write_status('running', 'started', ${SERVICE_PID}, ${UI_PID})-"+ write_runtime_status "running" "started" "$SERVICE_PID" "$UI_PID"while true; doCURRENT_UI_PID=""@@ -73,20 +97,17 @@ runtime.write_status('running', 'started', ${SERVICE_PID}, ${UI_PID})CURRENT_UI_PID="$(cat "$RUNTIME_DIR/vibe-ui.pid")"fi+ exit_if_service_stopped "$SERVICE_PID" "${CURRENT_UI_PID:-$UI_PID}"+if [ -z "$CURRENT_UI_PID" ]; thenUI_PID="$(start_ui_process "$RUNTIME_DIR")"- python -c "-from vibe import runtime-runtime.write_status('running', 'ui restarted', ${SERVICE_PID}, ${UI_PID})-"+ write_runtime_status "running" "ui restarted" "$SERVICE_PID" "$UI_PID"elif ! kill -0 "$CURRENT_UI_PID" 2>/dev/null; then+ UI_EXIT_CODE=0wait "$CURRENT_UI_PID" 2>/dev/null || UI_EXIT_CODE=$?echo "UI server exited unexpectedly (code: ${UI_EXIT_CODE:-unknown}), restarting..."UI_PID="$(start_ui_process "$RUNTIME_DIR")"- python -c "-from vibe import runtime-runtime.write_status('running', 'ui restarted after crash', ${SERVICE_PID}, ${UI_PID})-"+ write_runtime_status "running" "ui restarted after crash" "$SERVICE_PID" "$UI_PID"fisleep 1diff --git a/tests/test_docker_entrypoint_supervisor.py b/tests/test_docker_entrypoint_supervisor.pynew file mode 100644index 000000000..116076387--- /dev/null+++ b/tests/test_docker_entrypoint_supervisor.py@@ -0,0 +1,61 @@+import os+import stat+import subprocess+import tempfile+import textwrap+import unittest+from pathlib import Path+++REPO_ROOT = Path(__file__).resolve().parents[1]+ENTRYPOINT = REPO_ROOT / "scripts" / "docker-entrypoint.sh"+++class DockerEntrypointSupervisorTests(unittest.TestCase):+ def test_full_mode_exits_when_service_process_dies(self):+ with tempfile.TemporaryDirectory() as tmpdir:+ tmp_path = Path(tmpdir)+ fake_python = tmp_path / "python"+ fake_python.write_text(+ textwrap.dedent(+ """\+ #!/usr/bin/env python3+ import sys+ import time++ args = sys.argv[1:]+ if args and args[0] == "main.py":+ sys.exit(42)++ if len(args) >= 2 and args[0] == "-c":+ code = args[1]+ if "run_ui_server" in code:+ time.sleep(30)+ sys.exit(0)++ sys.exit(0)+ """+ ),+ encoding="utf-8",+ )+ fake_python.chmod(fake_python.stat().st_mode | stat.S_IEXEC)++ env = os.environ.copy()+ env["PATH"] = f"{tmp_path}{os.pathsep}{env.get('PATH', '')}"+ env["VIBE_REMOTE_HOME"] = str(tmp_path / "home")++ result = subprocess.run(+ ["bash", str(ENTRYPOINT), "full"],+ cwd=REPO_ROOT,+ env=env,+ capture_output=True,+ text=True,+ timeout=10,+ )++ self.assertEqual(result.returncode, 42, result.stdout + result.stderr)+ self.assertIn("Service exited unexpectedly", result.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.pynew file mode 100644index 000000000..32669825e--- /dev/null+++ b/tests/test_feishu_routing_card.py@@ -0,0 +1,105 @@+import importlib.util+import sys+import types+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++from config.v2_config import LarkConfig+from modules.im.base import MessageContext+++def _install_opencode_utils_module() -> None:+ if "modules.agents.opencode.utils" in sys.modules:+ return++ repo_root = Path(__file__).resolve().parents[1]+ agents_mod = types.ModuleType("modules.agents")+ agents_mod.__path__ = [str(repo_root / "modules" / "agents")]+ opencode_mod = types.ModuleType("modules.agents.opencode")+ opencode_mod.__path__ = [str(repo_root / "modules" / "agents" / "opencode")]++ sys.modules["modules.agents"] = agents_mod+ sys.modules["modules.agents.opencode"] = opencode_mod++ spec = importlib.util.spec_from_file_location(+ "modules.agents.opencode.utils",+ repo_root / "modules" / "agents" / "opencode" / "utils.py",+ )+ assert spec is not None+ assert spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules["modules.agents.opencode.utils"] = module+ spec.loader.exec_module(module)+++_install_opencode_utils_module()++from modules.im.feishu import FeishuBot+++class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):+ def _make_bot(self) -> FeishuBot:+ return FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret"))++ @staticmethod+ def _find_select(card, field_name):+ form = card["body"]["elements"][0]+ for element in form["elements"]:+ if element.get("tag") == "select_static" and element.get("name") == field_name:+ return element+ raise AssertionError(f"select_static {field_name} not found")++ async def test_claude_model_change_refreshes_reasoning_options(self):+ bot = self._make_bot()+ bot._patch_card_message = AsyncMock()++ current_routing = SimpleNamespace(+ claude_agent="helper",+ claude_model="claude-sonnet-4-5",+ claude_reasoning_effort="high",+ opencode_agent=None,+ opencode_model=None,+ opencode_reasoning_effort=None,+ codex_model=None,+ codex_reasoning_effort=None,+ )+ bot._routing_cache["chat:user"] = {+ "current_routing": current_routing,+ "draft_routing": bot._routing_draft_from_current(current_routing),+ "_selected_backend": "claude",+ "claude_agents": ["helper", "reviewer"],+ "claude_models": ["claude-sonnet-4-5", "claude-opus-4-6"],+ "opencode_agents": [],+ "opencode_models": {},+ "opencode_default_config": {},+ "codex_models": [],+ }++ context = MessageContext(user_id="user", channel_id="chat", message_id="om_123")++ handled = await bot._handle_routing_select_change(+ context,+ {"tag": "select_static", "name": "claude_model", "option": {"value": "claude-opus-4-6"}},+ )++ self.assertTrue(handled)+ bot._patch_card_message.assert_awaited_once()+ _, card = bot._patch_card_message.await_args.args++ reasoning_select = self._find_select(card, "claude_reasoning")+ reasoning_values = [option["value"] for option in reasoning_select["options"]]+ self.assertIn("max", reasoning_values)+ self.assertEqual(reasoning_select.get("initial_option"), "__default__")++ agent_select = self._find_select(card, "claude_agent")+ self.assertEqual(agent_select.get("initial_option"), "helper")++ draft = bot._routing_cache["chat:user"]["draft_routing"]+ self.assertEqual(draft["claude_model"], "claude-opus-4-6")+ self.assertIsNone(draft["claude_reasoning_effort"])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.pyindex 28e00a0ca..e84c6127d 100644--- a/tests/test_slack_dm_mentions.py+++ b/tests/test_slack_dm_mentions.py@@ -1,6 +1,8 @@+import importlib.utilimport unittestimport sysimport types+from pathlib import Pathfrom config.v2_config import SlackConfig@@ -35,6 +37,9 @@ def _install_slack_stubs() -> None:def __init__(self, *args, **kwargs):pass+ async def auth_test(self):+ return {"user_id": "U_BOT"}+class _SocketModeClient:def __init__(self, *args, **kwargs):pass@@ -66,26 +71,24 @@ def _install_slack_stubs() -> None:sys.modules["slack_sdk.errors"] = errors_modif "modules.agents.opencode.utils" not in sys.modules:+ repo_root = Path(__file__).resolve().parents[1]agents_mod = types.ModuleType("modules.agents")+ agents_mod.__path__ = [str(repo_root / "modules" / "agents")]opencode_mod = types.ModuleType("modules.agents.opencode")- utils_mod = types.ModuleType("modules.agents.opencode.utils")-- def _empty_list(*args, **kwargs):- return []-- def _none(*args, **kwargs):- return None-- utils_mod.build_claude_reasoning_options = _empty_list- utils_mod.build_opencode_model_option_items = _empty_list- utils_mod.build_codex_reasoning_options = _empty_list- utils_mod.build_reasoning_effort_options = _empty_list- utils_mod.resolve_opencode_allowed_providers = _none- utils_mod.resolve_opencode_provider_preferences = _none+ opencode_mod.__path__ = [str(repo_root / "modules" / "agents" / "opencode")]sys.modules["modules.agents"] = agents_modsys.modules["modules.agents.opencode"] = opencode_mod- sys.modules["modules.agents.opencode.utils"] = utils_mod++ spec = importlib.util.spec_from_file_location(+ "modules.agents.opencode.utils",+ repo_root / "modules" / "agents" / "opencode" / "utils.py",+ )+ assert spec is not None+ assert spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules["modules.agents.opencode.utils"] = module+ spec.loader.exec_module(module)_install_slack_stubs()@@ -108,6 +111,7 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):payload = {"event_id": "evt-dm-mention-only","team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],"event": {"type": "message","channel": "D123",@@ -140,6 +144,7 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):payload = {"event_id": "evt-dm-mention-text","team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],"event": {"type": "message","channel": "D123",@@ -165,6 +170,7 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):payload = {"event_id": "evt-channel-mention","team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],"event": {"type": "message","channel": "C123",@@ -178,6 +184,110 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):self.assertFalse(received["called"])+ async def test_dm_preserves_non_bot_mentions(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ received = {}++ async def _on_message(_context, text):+ received["text"] = text++ slack.register_callbacks(on_message=_on_message)++ payload = {+ "event_id": "evt-dm-mention-preserve-other",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "message",+ "channel": "D123",+ "user": "U123",+ "text": "<@U_BOT> summarize what <@U_OTHER> said",+ "ts": "1710000000.000400",+ },+ }++ await slack._handle_event(payload)++ self.assertEqual(received, {"text": "summarize what <@U_OTHER> said"})++ async def test_channel_message_with_other_mentions_is_not_skipped(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ received = {}++ async def _on_message(_context, text):+ received["text"] = text++ slack.register_callbacks(on_message=_on_message)++ payload = {+ "event_id": "evt-channel-other-mention",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "message",+ "channel": "C123",+ "user": "U123",+ "text": "please ask <@U_OTHER> to check",+ "ts": "1710000000.000500",+ },+ }++ await slack._handle_event(payload)++ self.assertEqual(received, {"text": "please ask <@U_OTHER> to check"})++ async def test_channel_message_with_bot_mention_mid_text_is_skipped(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ received = {"called": False}++ async def _on_message(_context, _text):+ received["called"] = True++ slack.register_callbacks(on_message=_on_message)++ payload = {+ "event_id": "evt-channel-bot-mention-middle",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "message",+ "channel": "C123",+ "user": "U123",+ "text": "hello <@U_BOT> please help",+ "ts": "1710000000.000550",+ },+ }++ await slack._handle_event(payload)++ self.assertFalse(received["called"])++ async def test_app_mention_preserves_non_bot_mentions(self):+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))+ received = {}++ async def _on_message(_context, text):+ received["text"] = text++ slack.register_callbacks(on_message=_on_message)++ payload = {+ "event_id": "evt-app-mention-preserve-other",+ "team_id": "T1",+ "authorizations": [{"user_id": "U_BOT"}],+ "event": {+ "type": "app_mention",+ "channel": "C123",+ "user": "U123",+ "text": "<@U_BOT> summarize what <@U_OTHER> said",+ "ts": "1710000000.000600",+ },+ }++ await slack._handle_event(payload)++ self.assertEqual(received, {"text": "summarize what <@U_OTHER> said"})+if __name__ == "__main__":unittest.main()