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.

refactor: Implement robust formatter architecture for cross-platform markdown

cyhhao6de8fc129f42
diff --git a/core/controller.py b/core/controller.py
index 55aa42162..b19733be1 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -194,8 +194,8 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
)
else:
# For non-Slack platforms
- # Need to escape special chars for MarkdownV2
- confirmation_text = f"⏳ Processing\\.\\.\\."
+ formatter = self.im_client.formatter
+ confirmation_text = f"⏳ {formatter.format_text('Processing...')}"
await self.im_client.send_message(
target_context,
confirmation_text,
@@ -246,8 +246,9 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
except Exception as e:
logger.error(f"Error handling message: {e}")
- # Escape for MarkdownV2 if needed
- error_msg = "Error processing message\\." if self.config.platform == "telegram" else "Error processing message."
+ # Format error message using formatter
+ formatter = self.im_client.formatter
+ error_msg = formatter.format_error("Error processing message")
await self.im_client.send_message(context, error_msg)
async def _session_message_receiver(self, session_id: str, client: ClaudeSDKClient, context: MessageContext, thread_id: Optional[str]):
@@ -312,8 +313,9 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
if session:
session.session_active[session_id] = False
- # Escape special chars for MarkdownV2 if needed
- ready_msg = "✅ Ready for next message\\!" if self.config.platform == "telegram" else "✅ Ready for next message!"
+ # Format ready message using formatter
+ formatter = self.im_client.formatter
+ ready_msg = formatter.format_success("Ready for next message!")
await self.im_client.send_message(
target_context,
ready_msg,
@@ -327,14 +329,10 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
logger.error(f"Error in message receiver for session {session_id}: {e}")
# Notify user of error
try:
- if self.config.platform == "telegram":
- # Escape for MarkdownV2
- from telegram.helpers import escape_markdown
- escaped_error = escape_markdown(str(e), version=2)
- # Escape the static text parts properly for MarkdownV2
- error_msg = f"❌ Session error: {escaped_error}\nPlease use /clear to reset\\."
- else:
- error_msg = f"❌ Session error: {str(e)}\nPlease use /clear to reset."
+ formatter = self.im_client.formatter
+ error_text = formatter.format_text(f"Session error: {str(e)}")
+ instruction = formatter.format_text("Please use /clear to reset.")
+ error_msg = f"❌ {error_text}\n{instruction}"
await self.im_client.send_message(
target_context,
@@ -368,14 +366,10 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
# Notify user
target_context = self._get_target_context(context)
- if self.config.platform == "telegram":
- # Escape for MarkdownV2
- from telegram.helpers import escape_markdown
- escaped_error = escape_markdown(str(e), version=2)
- # Escape the static text parts properly for MarkdownV2
- error_msg = f"❌ Error: {escaped_error}\nPlease try again or use /clear to reset\\."
- else:
- error_msg = f"❌ Error: {str(e)}\nPlease try again or use /clear to reset."
+ formatter = self.im_client.formatter
+ error_text = formatter.format_text(f"Error: {str(e)}")
+ instruction = formatter.format_text("Please try again or use /clear to reset.")
+ error_msg = f"❌ {error_text}\n{instruction}"
await self.im_client.send_message(
target_context,
@@ -386,13 +380,8 @@ Use the buttons below to manage your Claude Code sessions, or simply type any me
except Exception as e:
logger.error(f"Error in process_message_immediately: {e}")
target_context = self._get_target_context(context)
- if self.config.platform == "telegram":
- # Escape for MarkdownV2
- from telegram.helpers import escape_markdown
- escaped_error = escape_markdown(str(e), version=2)
- error_msg = f"❌ Unexpected error: {escaped_error}"
- else:
- error_msg = f"❌ Unexpected error: {str(e)}"
+ formatter = self.im_client.formatter
+ error_msg = formatter.format_error(f"Unexpected error: {str(e)}")
await self.im_client.send_message(
target_context,
@@ -863,38 +852,20 @@ _Tip: All commands work in DMs, channels, and threads!_"""
logger.info(f"Handling info_msg_types callback for user {context.user_id}")
try:
- # Initialize info_text early to avoid unbound variable error
- info_text = ""
-
formatter = self.im_client.formatter
- # Build info text using formatter to handle escaping properly
- if self.config.platform == "telegram":
- # For Telegram, need to escape special characters in MarkdownV2
- lines = [
- f"📋 {formatter.format_bold('Message Types Info:')}",
- "",
- f"• {formatter.format_bold('System')} \\- System initialization and status messages",
- f"• {formatter.format_bold('Response')} \\- Tool execution responses and results",
- f"• {formatter.format_bold('Assistant')} \\- Claude's messages and explanations",
- f"• {formatter.format_bold('Result')} \\- Final execution results and summaries",
- "",
- "Hidden messages won't be sent to your IM platform\\."
- ]
- else:
- # For Slack, no escaping needed for dashes
- lines = [
- f"📋 {formatter.format_bold('Message Types Info:')}",
- "",
- f"• {formatter.format_bold('System')} - System initialization and status messages",
- f"• {formatter.format_bold('Response')} - Tool execution responses and results",
- f"• {formatter.format_bold('Assistant')} - Claude's messages and explanations",
- f"• {formatter.format_bold('Result')} - Final execution results and summaries",
- "",
- "Hidden messages won't be sent to your IM platform."
- ]
-
- info_text = "\n".join(lines)
+ # Use the new format_info_message method for clean, platform-agnostic formatting
+ info_text = formatter.format_info_message(
+ title="Message Types Info:",
+ emoji="📋",
+ items=[
+ ("System", "System initialization and status messages"),
+ ("Response", "Tool execution responses and results"),
+ ("Assistant", "Claude's messages and explanations"),
+ ("Result", "Final execution results and summaries")
+ ],
+ footer="Hidden messages won't be sent to your IM platform."
+ )
# Send as new message
parse_mode = 'MarkdownV2' if self.config.platform == "telegram" else 'markdown'
diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.py
index f64f0a949..40d9c8df3 100644
--- a/modules/im/formatters/base_formatter.py
+++ b/modules/im/formatters/base_formatter.py
@@ -38,6 +38,25 @@ class BaseMarkdownFormatter(ABC):
"""Format horizontal rule"""
return "---"
+ # Core text formatting method
+ def format_text(self, text: str, safe: bool = False) -> str:
+ """Format plain text with automatic escaping
+
+ Args:
+ text: The text to format
+ safe: If True, text is already escaped/formatted and won't be escaped again
+
+ Returns:
+ Formatted text with special characters escaped
+ """
+ if safe:
+ return text
+ return self.escape_special_chars(text)
+
+ def format_plain(self, text: str) -> str:
+ """Alias for format_text - formats plain text with escaping"""
+ return self.format_text(text)
+
# Platform-specific abstract methods
@abstractmethod
def format_bold(self, text: str) -> str:
@@ -64,6 +83,92 @@ class BaseMarkdownFormatter(ABC):
"""Escape platform-specific special characters"""
pass
+ # High-level message composition methods
+ def format_message(self, *lines) -> str:
+ """Compose a message from multiple lines
+
+ Args:
+ *lines: Variable number of lines to compose
+
+ Returns:
+ Formatted message with proper line breaks
+ """
+ return "\n".join(str(line) for line in lines if line)
+
+ def format_bullet_list(self, items: List[str], escape: bool = True) -> List[str]:
+ """Format a list of items as bullet points
+
+ Args:
+ items: List of items to format
+ escape: Whether to escape special characters in items
+
+ Returns:
+ List of formatted bullet points
+ """
+ formatted = []
+ for item in items:
+ if escape:
+ item = self.format_text(item)
+ formatted.append(f"• {item}")
+ return formatted
+
+ def format_definition_list(self, items: List[Tuple[str, str]], bold_key: bool = True) -> List[str]:
+ """Format a list of key-value pairs
+
+ Args:
+ items: List of (key, value) tuples
+ bold_key: Whether to make keys bold
+
+ Returns:
+ List of formatted definition items
+ """
+ formatted = []
+ for key, value in items:
+ if bold_key:
+ key_part = self.format_bold(key)
+ else:
+ key_part = self.format_text(key)
+ value_part = self.format_text(value)
+ formatted.append(f"• {key_part} - {value_part}")
+ return formatted
+
+ def format_info_message(self, title: str, emoji: str = "", items: List[Tuple[str, str]] = None, footer: str = "") -> str:
+ """Format a complete info message with title, items, and optional footer
+
+ Args:
+ title: Message title
+ emoji: Optional emoji for title
+ items: Optional list of (label, description) tuples
+ footer: Optional footer text
+
+ Returns:
+ Formatted info message
+ """
+ lines = []
+
+ # Add header
+ if emoji:
+ lines.append(f"{emoji} {self.format_bold(title)}")
+ else:
+ lines.append(self.format_bold(title))
+
+ # Add blank line after header
+ if items or footer:
+ lines.append("")
+
+ # Add items
+ if items:
+ for label, description in items:
+ lines.append(f"• {self.format_bold(label)} - {self.format_text(description)}")
+
+ # Add footer
+ if footer:
+ if items:
+ lines.append("")
+ lines.append(self.format_text(footer))
+
+ return self.format_message(*lines)
+
# Convenience methods that combine formatting
def format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:
"""Format tool name with emoji and styling"""
diff --git a/modules/im/formatters/telegram_formatter.py b/modules/im/formatters/telegram_formatter.py
index 6c1767aad..6dd5506d2 100644
--- a/modules/im/formatters/telegram_formatter.py
+++ b/modules/im/formatters/telegram_formatter.py
@@ -11,19 +11,18 @@ class TelegramFormatter(BaseMarkdownFormatter):
def format_bold(self, text: str) -> str:
"""Format bold text using double asterisks"""
- # Text needs to be escaped first
- escaped_text = self.escape_special_chars(text)
- return f"*{escaped_text}*"
+ # Don't double-escape - text should be plain text
+ return f"*{text}*"
def format_italic(self, text: str) -> str:
"""Format italic text using underscores"""
- escaped_text = self.escape_special_chars(text)
- return f"_{escaped_text}_"
+ # Don't double-escape - text should be plain text
+ return f"_{text}_"
def format_strikethrough(self, text: str) -> str:
"""Format strikethrough text using tildes"""
- escaped_text = self.escape_special_chars(text)
- return f"~{escaped_text}~"
+ # Don't double-escape - text should be plain text
+ return f"~{text}~"
def format_link(self, text: str, url: str) -> str:
"""Format hyperlink in Telegram style"""