Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(platform): harden quick-reply callback handling

cyhc00a35563dc8
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 122c7c0b3..3aa2f7f0f 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -395,24 +395,53 @@ class MessageHandler(BaseHandler):
# Quick-reply button: treat the button text as a new user message
reply_text = callback_data[len("quick_reply:") :]
if reply_text:
- # Update the card: preserve original text, append user
- # action, and strip the buttons.
- if context.message_id:
- try:
- original = self.controller.message_dispatcher.pop_quick_reply_text(context.message_id)
- if original is not None:
- note = self._t("message.quickReplyNote", text=reply_text)
- updated = f"{original}\n\n---\n{note}"
- else:
- updated = None
- await self.im_client.remove_inline_keyboard(context, context.message_id, text=updated)
- except Exception as err:
- logger.debug(f"Failed to remove quick-reply buttons: {err}")
-
- # Add ack reaction on the card message before dispatching
- if context.message_id:
+ # Remove buttons from the original message card.
+ remove_target_message_id = context.message_id
+ platform_payload_raw = context.platform_specific or {}
+ platform_payload = platform_payload_raw if isinstance(platform_payload_raw, dict) else {}
+ can_remove_via_interaction = bool(platform_payload.get("interaction"))
+ if not remove_target_message_id:
+ event_payload = platform_payload.get("event")
+ event_payload = event_payload if isinstance(event_payload, dict) else {}
+ event_context = event_payload.get("context")
+ event_context = event_context if isinstance(event_context, dict) else {}
+ event_open_message_id = (
+ event_payload.get("open_message_id") if isinstance(event_payload, dict) else ""
+ )
+ remove_target_message_id = (
+ platform_payload.get("message_id")
+ or platform_payload.get("open_message_id")
+ or event_context.get("open_message_id")
+ or event_open_message_id
+ or ""
+ )
+ try:
+ if remove_target_message_id or can_remove_via_interaction:
+ await self.im_client.remove_inline_keyboard(context, remove_target_message_id or "")
+ else:
+ logger.debug("Skip quick-reply keyboard removal: message id unavailable")
+ except Exception as err:
+ logger.debug(f"Failed to remove quick-reply buttons: {err}")
+
+ # Echo the selected quick reply as a bot message.
+ quick_reply_echo_id = None
+ try:
+ quick_reply_echo = self._t("message.quickReplyNote", text=reply_text)
+ quick_reply_echo_id = await self.im_client.send_message(
+ self._get_target_context(context),
+ quick_reply_echo,
+ )
+ except Exception as err:
+ logger.debug(f"Failed to send quick-reply echo message: {err}")
+
+ # Add ack reaction on the echo message before dispatching.
+ if quick_reply_echo_id:
try:
- await self.im_client.add_reaction(context, context.message_id, ":eyes:")
+ await self.im_client.add_reaction(
+ self._get_target_context(context),
+ quick_reply_echo_id,
+ ":eyes:",
+ )
except Exception as err:
logger.debug(f"Failed to add quick-reply ack reaction: {err}")
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index e4b57b5c7..3e88e0de4 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -25,9 +25,6 @@ class ConsolidatedMessageDispatcher:
self._consolidated_message_buffers: dict[str, str] = {}
self._consolidated_message_locks: dict[str, asyncio.Lock] = {}
self._thread_current_message_id: dict[str, str] = {}
- # Cache the body text of quick-reply card messages so the callback
- # handler can retrieve the original text when updating the card.
- self._quick_reply_text_cache: dict[str, str] = {}
def _get_settings_key(self, context: MessageContext) -> str:
return self.controller._get_settings_key(context)
@@ -339,18 +336,12 @@ class ConsolidatedMessageDispatcher:
row.append(InlineButton(text=btn.text, callback_data=callback))
keyboard = InlineKeyboard(buttons=[row])
- msg_id = await im_client.send_message_with_buttons(
+ await im_client.send_message_with_buttons(
context,
text,
keyboard,
parse_mode=parse_mode,
)
- if msg_id:
- self._quick_reply_text_cache[msg_id] = text
-
- def pop_quick_reply_text(self, message_id: str) -> str | None:
- """Pop and return the cached text for a quick-reply card message."""
- return self._quick_reply_text_cache.pop(message_id, None)
async def _upload_file_links(
self,
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 6f9d11739..96a4c939f 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -4,6 +4,7 @@ import json
import logging
import os
from typing import Dict, Any, Optional, Callable, List
+from urllib.parse import urlsplit
import aiohttp
import discord
@@ -114,7 +115,7 @@ class DiscordBot(BaseIMClient):
from aiohttp_socks import ProxyConnector
self.client.http.connector = ProxyConnector.from_url(socks_url, rdns=True)
- logger.info("Discord using SOCKS proxy: %s", socks_url)
+ logger.info("Discord using SOCKS proxy: %s", self._redact_proxy_url(socks_url))
except ImportError:
logger.warning("SOCKS proxy detected but aiohttp_socks not installed")
@@ -126,6 +127,22 @@ class DiscordBot(BaseIMClient):
except KeyboardInterrupt:
return
+ @staticmethod
+ def _redact_proxy_url(proxy_url: str) -> str:
+ """Return a proxy URL safe for logs (credentials stripped)."""
+ try:
+ parts = urlsplit(proxy_url)
+ if parts.scheme and parts.hostname:
+ host = parts.hostname
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ if parts.port:
+ return f"{parts.scheme}://{host}:{parts.port}"
+ return f"{parts.scheme}://{host}"
+ except Exception:
+ pass
+ return "<configured>"
+
async def shutdown(self) -> None:
await self.client.close()
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index 333b2f156..f035b2b9d 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -616,6 +616,92 @@ class FeishuBot(BaseIMClient):
logger.error("Error editing Feishu message %s: %s", message_id, exc)
return False
+ async def _fetch_message_card_content(self, message_id: str) -> Optional[Dict[str, Any]]:
+ """Fetch and parse card content JSON for an existing message."""
+ try:
+ token = await self._get_tenant_token()
+ if not token:
+ return None
+
+ url = f"{self.config.api_base_url}/open-apis/im/v1/messages/{message_id}"
+ timeout = aiohttp.ClientTimeout(total=10)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.get(url, headers={"Authorization": f"Bearer {token}"}) as resp:
+ if resp.status != 200:
+ logger.warning("Feishu get message failed: id=%s status=%s", message_id, resp.status)
+ return None
+ result = await resp.json()
+
+ if result.get("code") != 0:
+ logger.warning(
+ "Feishu get message failed: id=%s code=%s msg=%s",
+ message_id,
+ result.get("code"),
+ result.get("msg"),
+ )
+ return None
+
+ data = result.get("data", {})
+ message = data.get("message") or data.get("item") or data
+ content_raw = message.get("body", {}).get("content") or message.get("content")
+ if not content_raw:
+ return None
+ if isinstance(content_raw, dict):
+ return content_raw
+ if isinstance(content_raw, str):
+ return json.loads(content_raw)
+ return None
+ except Exception as exc:
+ logger.debug("Failed to fetch Feishu message content for %s: %s", message_id, exc)
+ return None
+
+ @staticmethod
+ def _extract_text_from_card_content(card_content: Dict[str, Any]) -> Optional[str]:
+ """Extract human-visible text from card content for button removal."""
+ collected_texts: list[str] = []
+
+ def _collect(node: Any) -> None:
+ if isinstance(node, list):
+ for item in node:
+ _collect(item)
+ return
+
+ if not isinstance(node, dict):
+ return
+
+ tag = node.get("tag")
+ if tag == "button":
+ return
+
+ if tag == "markdown":
+ markdown_content = node.get("content")
+ if isinstance(markdown_content, str) and markdown_content.strip():
+ collected_texts.append(markdown_content)
+
+ text_obj = node.get("text")
+ if isinstance(text_obj, dict):
+ content = text_obj.get("content")
+ if isinstance(content, str) and content.strip():
+ collected_texts.append(content)
+ elif isinstance(text_obj, str) and text_obj.strip():
+ collected_texts.append(text_obj)
+
+ for key in ("body", "elements", "columns"):
+ if key in node:
+ _collect(node.get(key))
+
+ for key, value in node.items():
+ if key in {"tag", "text", "body", "elements", "columns"}:
+ continue
+ _collect(value)
+
+ _collect(card_content)
+
+ if not collected_texts:
+ return None
+
+ return "\n\n".join(collected_texts)
+
async def remove_inline_keyboard(
self,
context: MessageContext,
@@ -625,11 +711,21 @@ class FeishuBot(BaseIMClient):
) -> bool:
"""Remove interactive buttons from a Feishu message.
- Feishu cards must be rebuilt entirely, so *text* should contain
- the desired card body. When *text* is ``None`` the card is
- re-sent with an empty body (callers should pass text explicitly).
+ Feishu cards must be rebuilt entirely. When *text* is not provided,
+ this method first fetches the current message content and extracts
+ card text before updating the card without buttons.
"""
- display_text = text if text is not None else ""
+ display_text = text
+ if display_text is None:
+ card_content = await self._fetch_message_card_content(message_id)
+ if card_content is None:
+ logger.debug("Skip Feishu keyboard removal: unable to fetch card content for %s", message_id)
+ return False
+ display_text = self._extract_text_from_card_content(card_content)
+ if display_text is None:
+ logger.debug("Skip Feishu keyboard removal: unable to extract card text for %s", message_id)
+ return False
+
return await self.edit_message(context, message_id, text=display_text, keyboard=None, parse_mode=parse_mode)
# ------------------------------------------------------------------