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(slack): resolve bound DM channel so reaction ack stops downgrading (#1233)

Qi Qi1ac3e35a39c9
diff --git a/core/internal_server.py b/core/internal_server.py
index 782b4c139..b63befb7b 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1737,6 +1737,17 @@ def _build_session_context(
resolved_user_id = user_id or (
target_info.session_key.scope_id if is_dm else "workbench"
)
+ if not channel_id and is_dm and resolved_platform != "avibe":
+ # A DM Session's scope_id is the USER id, which is not a channel. Every
+ # other resolver (``running_agents._resolve_session_key_context``,
+ # ``ScheduledTasks._resolve_target_context``) swaps in the bound
+ # ``dm_chat_id``; this builder must too. Slack's ``chat.postMessage``
+ # silently tolerates a user id (it opens the DM for you) so sending kept
+ # working, but ``reactions.add`` rejects it with ``channel_not_found`` —
+ # the reaction ack then failed and silently downgraded to an ack message.
+ bound_dm_channel_id = _lookup_dm_channel_id(resolved_platform, str(resolved_user_id))
+ if bound_dm_channel_id:
+ resolved_channel_id = bound_dm_channel_id
platform_specific: dict[str, Any] = {
"agent_session_id": session_id,
"platform": resolved_platform,
@@ -1782,6 +1793,39 @@ def _build_session_context(
)
+def _lookup_dm_channel_id(platform: str, user_id: str) -> Optional[str]:
+ """Return the bound DM channel id for ``user_id`` on ``platform``.
+
+ Reads the persisted user scope settings directly (no controller / settings
+ manager in scope here). Returns ``None`` when the user is unbound or has no
+ recorded ``dm_chat_id`` — callers then keep the scope_id fallback.
+ """
+
+ if not platform or not user_id:
+ return None
+ try:
+ from sqlalchemy import select
+
+ from storage.models import scope_settings
+ from storage.settings_service import make_scope_id
+
+ scope_id = make_scope_id(platform, "user", user_id)
+ engine = get_cached_sqlite_engine()
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(scope_settings.c.settings_json).where(scope_settings.c.scope_id == scope_id)
+ ).first()
+ if row is None or not row[0]:
+ return None
+ payload = json.loads(row[0])
+ except Exception:
+ logger.debug("internal_server: failed to resolve dm_chat_id for %s/%s", platform, user_id, exc_info=True)
+ return None
+ if not isinstance(payload, dict):
+ return None
+ return str(payload.get("dm_chat_id") or "").strip() or None
+
+
def _lookup_session(session_id: str) -> Optional[dict[str, Any]]:
"""Load the workbench session row for routing metadata.
diff --git a/core/processing_indicator.py b/core/processing_indicator.py
index 23d8549f8..0a097b776 100644
--- a/core/processing_indicator.py
+++ b/core/processing_indicator.py
@@ -600,9 +600,35 @@ class ProcessingIndicatorService:
if self._mode_supported(capabilities, "typing", handle.context):
fell_back = await self._start_typing_indicator(handle)
if not fell_back and self._mode_supported(capabilities, "message", handle.context):
- await self._start_message_indicator(handle, agent_name or "")
+ fell_back = await self._start_message_indicator(handle, agent_name or "")
+ if fell_back:
+ self._warn_ack_mode_downgraded(
+ handle.context,
+ "typing" if handle.typing_indicator_active else "message",
+ )
self._sync_reaction_to_request(handle, request)
+ def _warn_ack_mode_downgraded(self, context: MessageContext, applied_mode: str) -> None:
+ """Report that the configured ack mode failed and a lower one was used.
+
+ The fallback ladder is deliberately silent about *which* mode won, so a
+ user who picked ``reaction`` and keeps seeing an ack message has nothing
+ to go on. Warn once per downgraded turn, naming the channel — a DM whose
+ channel_id is a user id is the usual cause.
+ """
+
+ configured = str(getattr(self.config, "ack_mode", "typing") or "typing")
+ if configured != "reaction":
+ return
+ logger.warning(
+ "Ack mode 'reaction' failed for %s channel=%s; downgraded to '%s'. "
+ "Check that the bot can react in this conversation (reactions:write, membership, "
+ "and a real channel id — a DM context must not carry the user id).",
+ context.platform or "unknown",
+ context.channel_id,
+ applied_mode,
+ )
+
@staticmethod
def _turn_tokens(context: MessageContext) -> set[str]:
payload = context.platform_specific or {}
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 9d5e5e6ff..d7e147eaa 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -394,6 +394,11 @@ class SlackBot(BaseIMClient):
def _is_dm_context(self, context: MessageContext) -> bool:
if bool((context.platform_specific or {}).get("is_dm", False)):
return True
+ if context.channel_id and context.channel_id == context.user_id:
+ # A DM context whose channel_id was left as the USER id. Slack has no
+ # channel with a ``U``/``W`` id, so this shape only ever arises from a
+ # DM scope that never resolved its bound dm_chat_id.
+ return True
return self._channel_looks_like_dm(context.channel_id)
def _is_own_bot_message(self, event: Dict[str, Any], bot_user_id: Optional[str]) -> bool:
@@ -492,6 +497,36 @@ class SlackBot(BaseIMClient):
context.thread_id = None
return await self._chat_post_message(**kwargs)
+ async def _recover_dm_channel_id(self, context: MessageContext, failed_channel_id: Optional[str]) -> Optional[str]:
+ """Resolve the real ``D...`` channel for a DM context that lost it.
+
+ Mirrors ``_post_message_with_dm_recovery`` for endpoints that do NOT
+ tolerate a user id as ``channel`` (``reactions.add`` / ``reactions.remove``
+ answer ``channel_not_found``). Repairs the context in place and persists the
+ resolved id as the user's ``dm_chat_id`` so the next turn starts correct.
+ """
+ if not self._is_dm_context(context) or not context.user_id:
+ return None
+ try:
+ recovered_channel_id = await self._open_dm_channel(context.user_id)
+ except Exception as exc:
+ logger.warning("Failed to recover Slack DM channel for user %s: %s", context.user_id, exc)
+ return None
+ if not recovered_channel_id or recovered_channel_id == failed_channel_id:
+ return None
+
+ logger.warning(
+ "Recovered Slack DM channel %s for user %s (context carried %s)",
+ recovered_channel_id,
+ context.user_id,
+ failed_channel_id,
+ )
+ context.channel_id = recovered_channel_id
+ record = self._get_bound_user_record(context.user_id)
+ if record is not None:
+ self._persist_bound_dm_channel(context.user_id, record, recovered_channel_id)
+ return recovered_channel_id
+
@staticmethod
def _find_text_split_index(text: str, max_chars: int) -> int:
minimum_boundary = max_chars // 2
@@ -1416,6 +1451,25 @@ class SlackBot(BaseIMClient):
except Exception:
pass
+ if error_code == "channel_not_found":
+ recovered_channel_id = await self._recover_dm_channel_id(context, context.channel_id)
+ if recovered_channel_id:
+ try:
+ await self.web_client.reactions_add(
+ channel=recovered_channel_id,
+ timestamp=message_id,
+ name=name,
+ )
+ return True
+ except SlackApiError as retry_err:
+ retry_error_code = (
+ retry_err.response.get("error") if getattr(retry_err, "response", None) else None
+ )
+ if retry_error_code == "already_reacted":
+ return True
+ logger.warning("Slack reaction add failed after DM recovery: %s", retry_error_code or retry_err)
+ return False
+
# 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}")
@@ -1442,6 +1496,20 @@ class SlackBot(BaseIMClient):
)
return True
except SlackApiError as err:
+ error_code = err.response.get("error") if getattr(err, "response", None) else None
+ if error_code == "channel_not_found":
+ recovered_channel_id = await self._recover_dm_channel_id(context, context.channel_id)
+ if recovered_channel_id:
+ try:
+ await self.web_client.reactions_remove(
+ channel=recovered_channel_id,
+ timestamp=message_id,
+ name=name,
+ )
+ return True
+ except SlackApiError as retry_err:
+ logger.warning("Slack reaction remove failed after DM recovery: %s", retry_err)
+ return False
logger.debug(f"Failed to remove Slack reaction: {err}")
return False
except Exception as err:
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index eff960329..1a3352771 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -5732,3 +5732,109 @@ def test_boot_publishes_app_then_waits_for_controller_recovery(
asyncio.run(_run())
assert calls == ["app", "serve", "close"]
+
+
+def _seed_slack_dm_session(conn, tmp_path, *, dm_chat_id: str, user_id: str = "U_DM"):
+ """Create a Slack DM Session whose scope_id is the USER id, like production."""
+
+ import json as _json
+
+ from core.services import sessions as sessions_service
+ from storage.models import scope_settings
+ from storage.settings_service import upsert_scope
+
+ now = "2026-08-09T00:00:00Z"
+ scope_id = upsert_scope(
+ conn,
+ platform="slack",
+ scope_type="user",
+ native_id=user_id,
+ now=now,
+ )
+ payload = {"bound_at": now}
+ if dm_chat_id:
+ payload["dm_chat_id"] = dm_chat_id
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=scope_id,
+ enabled=1,
+ role=None,
+ workdir=str(tmp_path),
+ agent_name=None,
+ agent_backend=None,
+ agent_variant=None,
+ model=None,
+ reasoning_effort=None,
+ require_mention=None,
+ settings_version=1,
+ settings_json=_json.dumps(payload),
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ return sessions_service.create_session(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="claude",
+ )
+
+
+def test_build_session_context_uses_bound_dm_channel_for_dm_scope(monkeypatch, tmp_path):
+ """A DM Session's scope_id is the USER id, which is not a channel.
+
+ Slack's ``chat.postMessage`` tolerates a user id (it opens the DM), so sending
+ kept working — but ``reactions.add`` answers ``channel_not_found``, so the
+ reaction ack failed and silently downgraded to the ack message. The builder
+ must swap in the bound ``dm_chat_id`` like every other resolver does.
+ """
+
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = _seed_slack_dm_session(conn, tmp_path, dm_chat_id="D_REAL")
+
+ context = internal_server._build_session_context(session["id"])
+
+ assert context.platform == "slack"
+ assert context.user_id == "U_DM"
+ assert context.channel_id == "D_REAL"
+ assert context.platform_specific["is_dm"] is True
+
+
+def test_build_session_context_falls_back_to_scope_id_without_dm_binding(monkeypatch, tmp_path):
+ """No recorded dm_chat_id -> keep the old behaviour rather than inventing one."""
+
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = _seed_slack_dm_session(conn, tmp_path, dm_chat_id="", user_id="U_UNBOUND")
+
+ context = internal_server._build_session_context(session["id"])
+
+ assert context.channel_id == "U_UNBOUND"
+
+
+def test_build_session_context_respects_explicit_channel_override(monkeypatch, tmp_path):
+ """An explicit channel_id (Delivery hydration) still wins over the binding."""
+
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ session = _seed_slack_dm_session(conn, tmp_path, dm_chat_id="D_REAL", user_id="U_OVERRIDE")
+
+ context = internal_server._build_session_context(session["id"], channel_id="D_EXPLICIT")
+
+ assert context.channel_id == "D_EXPLICIT"
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index c3e1d90cd..1de80c4db 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -1858,5 +1858,119 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
)
+class SlackReactionDmRecoveryTests(unittest.IsolatedAsyncioTestCase):
+ """``reactions.add``/``remove`` reject a user id as ``channel``.
+
+ ``chat.postMessage`` silently accepts one (it opens the DM for you), so a DM
+ context that carried the user id kept *sending* fine while every reaction ack
+ failed with ``channel_not_found`` and silently downgraded to an ack message.
+ """
+
+ @staticmethod
+ def _slack_api_error(error: str):
+ return sys.modules["slack_sdk.errors"].SlackApiError(error, response={"error": error})
+
+ def _bot_with_store(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ record = SimpleNamespace(dm_chat_id="")
+ updates = []
+
+ class _Store:
+ def get_user(self, user_id, platform=None):
+ return record
+
+ def update_user(self, user_id, settings, platform=None):
+ updates.append((user_id, settings.dm_chat_id))
+
+ slack.settings_manager = SimpleNamespace(get_store=lambda: _Store(), reload_from_disk=lambda: None)
+ return slack, record, updates
+
+ async def test_add_reaction_recovers_dm_channel_when_context_carries_user_id(self):
+ slack, record, updates = self._bot_with_store()
+ calls = []
+
+ class _WebClient:
+ async def reactions_add(self, **kwargs):
+ calls.append(kwargs["channel"])
+ if kwargs["channel"] != "D999":
+ raise SlackReactionDmRecoveryTests._slack_api_error("channel_not_found")
+ return {"ok": True}
+
+ async def conversations_open(self, users):
+ return {"ok": True, "channel": {"id": "D999"}}
+
+ slack.web_client = _WebClient()
+ # The broken shape: a DM whose channel_id was left as the user id.
+ context = MessageContext(user_id="U123", channel_id="U123", platform_specific={"is_dm": True})
+
+ ok = await slack.add_reaction(context, "1710000000.000010", "👀")
+
+ self.assertTrue(ok)
+ self.assertEqual(calls, ["U123", "D999"])
+ self.assertEqual(context.channel_id, "D999")
+ self.assertEqual(record.dm_chat_id, "D999")
+ self.assertEqual(updates, [("U123", "D999")])
+
+ async def test_add_reaction_treats_channel_equal_to_user_as_dm_without_is_dm_flag(self):
+ slack, _record, _updates = self._bot_with_store()
+ calls = []
+
+ class _WebClient:
+ async def reactions_add(self, **kwargs):
+ calls.append(kwargs["channel"])
+ if kwargs["channel"] != "D999":
+ raise SlackReactionDmRecoveryTests._slack_api_error("channel_not_found")
+ return {"ok": True}
+
+ async def conversations_open(self, users):
+ return {"ok": True, "channel": {"id": "D999"}}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="U123")
+
+ self.assertTrue(await slack.add_reaction(context, "1710000000.000010", "👀"))
+ self.assertEqual(calls, ["U123", "D999"])
+
+ async def test_add_reaction_does_not_recover_for_real_channel(self):
+ slack, _record, _updates = self._bot_with_store()
+ opened = []
+
+ class _WebClient:
+ async def reactions_add(self, **kwargs):
+ raise SlackReactionDmRecoveryTests._slack_api_error("channel_not_found")
+
+ async def conversations_open(self, users):
+ opened.append(users)
+ return {"ok": True, "channel": {"id": "D999"}}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ self.assertFalse(await slack.add_reaction(context, "1710000000.000010", "👀"))
+ self.assertEqual(opened, [])
+ self.assertEqual(context.channel_id, "C123")
+
+ async def test_remove_reaction_recovers_dm_channel(self):
+ slack, _record, _updates = self._bot_with_store()
+ calls = []
+
+ class _WebClient:
+ async def reactions_remove(self, **kwargs):
+ calls.append(kwargs["channel"])
+ if kwargs["channel"] != "D999":
+ raise SlackReactionDmRecoveryTests._slack_api_error("channel_not_found")
+ return {"ok": True}
+
+ async def conversations_open(self, users):
+ return {"ok": True, "channel": {"id": "D999"}}
+
+ slack.web_client = _WebClient()
+ context = MessageContext(user_id="U123", channel_id="U123", platform_specific={"is_dm": True})
+
+ self.assertTrue(await slack.remove_reaction(context, "1710000000.000010", "👌"))
+ self.assertEqual(calls, ["U123", "D999"])
+ self.assertEqual(context.channel_id, "D999")
+
+
if __name__ == "__main__":
unittest.main()