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(discord,session): fix file upload on wrong event loop and DM model override ignored

cyhhaocfc95f6b9ff1
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 52aecda71..e102c2e47 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -120,9 +120,9 @@ class SessionHandler(BaseHandler):
settings_key = self._get_settings_key(context)
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)
- routing = channel_settings.routing if channel_settings else None
+ # Read routing overrides via get_channel_routing which correctly
+ # resolves DM users from the users store (not the stale channels store).
+ routing = self.settings_manager.get_channel_routing(settings_key)
# Priority: subagent params > channel config > agent frontmatter > global default
# Note: agent frontmatter model is applied later after loading agent file
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 4ed9122e8..d3b0ef84b 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -387,7 +387,13 @@ class DiscordBot(BaseIMClient):
return True
async def add_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
- target = await self._fetch_channel(context.thread_id or context.channel_id)
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
if target is None:
return False
try:
@@ -402,7 +408,13 @@ class DiscordBot(BaseIMClient):
return False
async def remove_reaction(self, context: MessageContext, message_id: str, emoji: str) -> bool:
- target = await self._fetch_channel(context.thread_id or context.channel_id)
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
if target is None:
return False
try:
@@ -423,7 +435,13 @@ class DiscordBot(BaseIMClient):
content: str,
filetype: str = "markdown",
) -> str:
- target = await self._fetch_channel(context.thread_id or context.channel_id)
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
if target is None:
raise RuntimeError("Discord channel not found")
data = (content or "").encode("utf-8")
@@ -442,12 +460,12 @@ class DiscordBot(BaseIMClient):
if target is None:
return False
- trigger = getattr(target, "trigger_typing", None)
- if not callable(trigger):
+ typing_method = getattr(target, "typing", None)
+ if not callable(typing_method):
return False
try:
- await trigger()
+ await typing_method()
return True
except Exception as err:
logger.debug("Failed to trigger Discord typing indicator: %s", err)
@@ -465,7 +483,13 @@ class DiscordBot(BaseIMClient):
title: Optional[str] = None,
) -> str:
"""Upload a local file to the Discord conversation."""
- target = await self._fetch_channel(context.thread_id or context.channel_id)
+ target = None
+ if context.thread_id:
+ target = await self._fetch_channel(context.thread_id)
+ if not isinstance(target, discord.Thread):
+ target = None
+ if target is None:
+ target = await self._fetch_channel(context.channel_id)
if target is None:
raise RuntimeError("Discord channel not found")
diff --git a/modules/im/slack.py b/modules/im/slack.py
index b40b3eafe..e5cc5d366 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -75,6 +75,13 @@ class SlackBot(BaseIMClient):
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._on_ready: Optional[Callable] = None
+ # RTM typing indicator (best-effort, may not work with modern Slack apps)
+ self._rtm_ws: Optional[aiohttp.ClientWebSocketResponse] = None
+ self._rtm_session: Optional[aiohttp.ClientSession] = None
+ self._rtm_available: Optional[bool] = None # None = not yet attempted
+ self._rtm_msg_id: int = 0
+ self._rtm_drain_task: Optional[asyncio.Task] = None
+
def set_settings_manager(self, settings_manager):
"""Set the settings manager for thread tracking"""
self.settings_manager = settings_manager
@@ -735,6 +742,115 @@ class SlackBot(BaseIMClient):
logger.debug(f"Failed to remove Slack reaction: {err}")
return False
+ # ------------------------------------------------------------------
+ # RTM-based typing indicator (best-effort)
+ # ------------------------------------------------------------------
+
+ async def _ensure_rtm_connection(self) -> Optional[aiohttp.ClientWebSocketResponse]:
+ """Lazily establish an RTM WebSocket solely for typing indicator events.
+
+ Returns the WebSocket on success or ``None`` when RTM is unavailable
+ (e.g. modern Slack apps that lack the ``rtm:stream`` scope). A
+ negative result is cached so subsequent calls return immediately.
+ """
+ if self._rtm_available is False:
+ return None
+
+ # Reuse an existing live connection
+ if self._rtm_ws is not None and not self._rtm_ws.closed:
+ return self._rtm_ws
+
+ # Close stale resources before reconnecting
+ await self._close_rtm()
+
+ self._ensure_clients()
+ try:
+ resp = await self.web_client.rtm_connect()
+ if not resp.get("ok"):
+ err_msg = resp.get("error", "unknown")
+ logger.info("Slack RTM unavailable (%s) — typing indicator disabled", err_msg)
+ self._rtm_available = False
+ return None
+
+ wss_url = resp["url"]
+ self._rtm_session = aiohttp.ClientSession()
+ self._rtm_ws = await self._rtm_session.ws_connect(
+ wss_url,
+ heartbeat=30,
+ autoclose=True,
+ )
+ self._rtm_available = True
+ self._rtm_drain_task = asyncio.create_task(self._rtm_drain_loop())
+ logger.info("Slack RTM WebSocket connected for typing indicator")
+ return self._rtm_ws
+ except Exception as exc:
+ logger.info("Slack RTM connect failed: %s — typing indicator disabled", exc)
+ self._rtm_available = False
+ await self._close_rtm()
+ return None
+
+ async def _rtm_drain_loop(self) -> None:
+ """Read and discard incoming RTM messages to prevent buffer buildup."""
+ try:
+ ws = self._rtm_ws
+ if ws is None:
+ return
+ async for _ in ws:
+ pass # discard all incoming RTM events
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ pass # connection lost — handled on next send attempt
+
+ async def _close_rtm(self) -> None:
+ """Tear down RTM WebSocket and its aiohttp session."""
+ if self._rtm_drain_task is not None:
+ self._rtm_drain_task.cancel()
+ try:
+ await self._rtm_drain_task
+ except (asyncio.CancelledError, Exception):
+ pass
+ self._rtm_drain_task = None
+
+ if self._rtm_ws is not None:
+ try:
+ await self._rtm_ws.close()
+ except Exception:
+ pass
+ self._rtm_ws = None
+
+ if self._rtm_session is not None:
+ try:
+ await self._rtm_session.close()
+ except Exception:
+ pass
+ self._rtm_session = None
+
+ async def send_typing_indicator(self, context: MessageContext) -> bool:
+ """Send a typing indicator via RTM WebSocket (best-effort)."""
+ ws = await self._ensure_rtm_connection()
+ if ws is None:
+ return False
+ try:
+ self._rtm_msg_id += 1
+ await ws.send_json(
+ {
+ "id": self._rtm_msg_id,
+ "type": "typing",
+ "channel": context.channel_id,
+ }
+ )
+ return True
+ except Exception as exc:
+ logger.debug("Slack RTM typing send failed: %s", exc)
+ # Connection may be broken; reset so next call reconnects
+ self._rtm_ws = None
+ return False
+
+ async def clear_typing_indicator(self, context: MessageContext) -> bool:
+ """Slack typing indicators auto-expire (~3 s); no explicit clear needed."""
+ return True
+
async def send_message_with_buttons(
self,
context: MessageContext,
@@ -1775,6 +1891,8 @@ class SlackBot(BaseIMClient):
await self._async_close()
async def _async_close(self) -> None:
+ await self._close_rtm()
+
if self.socket_client is not None:
try:
disconnect = getattr(self.socket_client, "disconnect", None)