AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend/copilot): adopt mentioned Discord threads (#12995)
Bently1d862f75c6e8
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.pyindex 658c883130..4d2bd64b48 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py@@ -19,6 +19,15 @@ MessageCallback = Callable[["MessageContext", "PlatformAdapter"], Awaitable[NoneChannelType = Literal["dm", "channel", "thread"]+@dataclass+class MessageHistoryEntry:+ """A prior platform message included as context for the current turn."""++ username: str+ user_id: Optional[str]+ text: str++@dataclassclass MessageContext:"""Everything the core handler needs to know about an incoming message."""@@ -31,6 +40,8 @@ class MessageContext:user_id: strusername: strtext: str # with bot mentions stripped+ bot_mentioned: bool = False+ thread_history: tuple[MessageHistoryEntry, ...] = ()@propertydef is_dm(self) -> bool:diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.pyindex 739fa9f524..a4c20ac258 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py@@ -13,10 +13,17 @@ from discord import app_commandsfrom backend.copilot.bot.bot_backend import BotBackend-from ..base import ChannelType, MessageCallback, MessageContext, PlatformAdapter+from ..base import (+ ChannelType,+ MessageCallback,+ MessageContext,+ MessageHistoryEntry,+ PlatformAdapter,+)from . import commands, configlogger = logging.getLogger(__name__)+THREAD_HISTORY_LIMIT = 20class DiscordAdapter(PlatformAdapter):@@ -164,12 +171,17 @@ class DiscordAdapter(PlatformAdapter):returnchannel_type = self._channel_type(message)+ bot_mentioned = self._is_mentioned(message)# Channels require an explicit @mention; DMs and threads always forward# (handler checks thread subscription).- if channel_type == "channel" and not self._is_mentioned(message):+ if channel_type == "channel" and not bot_mentioned:return+ thread_history = ()+ if channel_type == "thread" and bot_mentioned:+ thread_history = await self._thread_history(message)+ctx = MessageContext(platform="discord",channel_type=channel_type,@@ -179,6 +191,8 @@ class DiscordAdapter(PlatformAdapter):user_id=str(message.author.id),username=message.author.display_name,text=self._strip_mentions(message),+ bot_mentioned=bot_mentioned,+ thread_history=thread_history,)await self._on_message_callback(ctx, self)@@ -207,3 +221,34 @@ class DiscordAdapter(PlatformAdapter):for token in raw_tokens:text = text.replace(token, replacement)return text.strip()++ async def _thread_history(+ self, message: discord.Message+ ) -> tuple[MessageHistoryEntry, ...]:+ if not isinstance(message.channel, discord.Thread):+ return ()++ entries: list[MessageHistoryEntry] = []+ try:+ async for prior in message.channel.history(+ limit=THREAD_HISTORY_LIMIT,+ before=message,+ oldest_first=True,+ ):+ if prior.author.bot:+ continue+ text = self._strip_mentions(prior)+ if not text:+ continue+ entries.append(+ MessageHistoryEntry(+ username=prior.author.display_name,+ user_id=str(prior.author.id),+ text=text,+ )+ )+ except (discord.Forbidden, discord.HTTPException):+ logger.warning("Could not fetch Discord thread history", exc_info=True)+ return ()++ return tuple(entries)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.pyindex 9f58e178d3..ff3954269c 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py@@ -6,7 +6,10 @@ from unittest.mock import AsyncMock, MagicMockimport discordimport pytest-from backend.copilot.bot.adapters.discord.adapter import DiscordAdapter+from backend.copilot.bot.adapters.discord.adapter import (+ THREAD_HISTORY_LIMIT,+ DiscordAdapter,+)def _bare_adapter(bot_id: int | None = 1000) -> tuple[DiscordAdapter, MagicMock]:@@ -38,6 +41,21 @@ def _message(content: str, mentions: list[MagicMock]) -> MagicMock:return msg+class _AsyncHistory:+ def __init__(self, messages: list[MagicMock]):+ self._messages = messages++ def __aiter__(self):+ self._iter = iter(self._messages)+ return self++ async def __anext__(self):+ try:+ return next(self._iter)+ except StopIteration:+ raise StopAsyncIteration++# ── _strip_mentions ────────────────────────────────────────────────────@@ -249,6 +267,39 @@ class TestSendMethods:# ── properties ─────────────────────────────────────────────────────────+class TestThreadHistory:+ @pytest.mark.asyncio+ async def test_fetches_user_thread_history_oldest_first(self):+ adapter, _ = _bare_adapter(bot_id=1000)+ bot = _mention(1000, "AutoPilot")++ prior_1 = _message("first idea", [])+ prior_1.author = MagicMock(bot=False, id=2000, display_name="Alice")+ prior_2 = _message("<@1000> can ignore old bot ping", [bot])+ prior_2.author = MagicMock(bot=False, id=3000, display_name="Bob")+ bot_msg = _message("old bot output", [])+ bot_msg.author = MagicMock(bot=True, id=1000, display_name="AutoPilot")++ channel = MagicMock(spec=discord.Thread)+ channel.history.return_value = _AsyncHistory([prior_1, bot_msg, prior_2])+ message = _message("<@1000> help", [bot])+ message.channel = channel++ history = await adapter._thread_history(message)++ channel.history.assert_called_once_with(+ limit=THREAD_HISTORY_LIMIT,+ before=message,+ oldest_first=True,+ )+ assert [entry.username for entry in history] == ["Alice", "Bob"]+ assert [entry.user_id for entry in history] == ["2000", "3000"]+ assert [entry.text for entry in history] == [+ "first idea",+ "can ignore old bot ping",+ ]++class TestProperties:def test_platform_name_is_discord(self):adapter, _ = _bare_adapter()diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.pyindex af36fabf3f..55c57aa80e 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py@@ -54,10 +54,13 @@ class MessageHandler:)return- if ctx.channel_type == "thread" and not await threads.is_subscribed(- ctx.platform, ctx.channel_id- ):- return+ should_subscribe_thread = False+ if ctx.channel_type == "thread":+ is_subscribed = await threads.is_subscribed(ctx.platform, ctx.channel_id)+ if not is_subscribed:+ if not ctx.bot_mentioned:+ return+ should_subscribe_thread = Trueif not await self._ensure_linked(ctx, adapter):return@@ -66,7 +69,11 @@ class MessageHandler:if not target_id:return # Thread not subscribed, ignore silently- await self._enqueue_and_process(ctx, adapter, target_id)+ if should_subscribe_thread:+ await threads.subscribe(ctx.platform, ctx.channel_id)++ message_text = self._message_text(ctx) if should_subscribe_thread else ctx.text+ await self._enqueue_and_process(ctx, adapter, target_id, message_text)# -- Target resolution --@@ -92,11 +99,31 @@ class MessageHandler:# -- Batched streaming --+ def _message_text(self, ctx: MessageContext) -> str:+ if not ctx.thread_history:+ return ctx.text++ platform_display = ctx.platform.capitalize()+ lines = ["[Recent thread context before this message]"]+ for entry in ctx.thread_history:+ user = (+ f"{entry.username} ({platform_display} user ID: {entry.user_id})"+ if entry.user_id+ else entry.username+ )+ lines.append(f"\n[From {user}]\n{entry.text}")+ lines.append(f"\n[Current message]\n{ctx.text}")+ return "\n".join(lines)+async def _enqueue_and_process(- self, ctx: MessageContext, adapter: PlatformAdapter, target_id: str+ self,+ ctx: MessageContext,+ adapter: PlatformAdapter,+ target_id: str,+ message_text: str | None = None,) -> None:state = self._targets.setdefault(target_id, TargetState())- state.pending.append((ctx.username, ctx.user_id, ctx.text))+ state.pending.append((ctx.username, ctx.user_id, message_text or ctx.text))if state.processing:# Another invocation is streaming for this target — it will pickdiff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.pyindex ae0a133ca9..34c0db80a8 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py@@ -6,7 +6,7 @@ import pytestfrom backend.util.exceptions import DuplicateChatMessageError, NotFoundError-from .adapters.base import ChannelType, MessageContext+from .adapters.base import ChannelType, MessageContext, MessageHistoryEntryfrom .bot_backend import LinkTokenResult, ResolveResultfrom .handler import MessageHandler, TargetState@@ -20,6 +20,8 @@ def _ctx(user_id: str = "user-1",username: str = "Bently",text: str = "hello bot",+ bot_mentioned: bool = False,+ thread_history: tuple[MessageHistoryEntry, ...] = (),) -> MessageContext:return MessageContext(platform="discord",@@ -30,6 +32,8 @@ def _ctx(user_id=user_id,username=username,text=text,+ bot_mentioned=bot_mentioned,+ thread_history=thread_history,)@@ -107,6 +111,28 @@ class TestEnsureLinked:api.resolve_server.assert_not_awaited()adapter.send_message.assert_not_awaited()+ @pytest.mark.asyncio+ async def test_unlinked_mentioned_thread_tells_user_to_setup(self):+ api = _api(server_linked=False)+ handler = MessageHandler(api)+ adapter = _adapter()+ with (+ patch(+ "backend.copilot.bot.handler.threads.is_subscribed",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "backend.copilot.bot.handler.threads.subscribe", new=AsyncMock()+ ) as subscribe,+ ):+ await handler.handle(+ _ctx(channel_type="thread", bot_mentioned=True), adapter+ )++ subscribe.assert_not_awaited()+ adapter.send_message.assert_awaited_once()+ assert "/setup" in adapter.send_message.await_args.args[1]+@pytest.mark.asyncioasync def test_unlinked_dm_prompts_link_flow(self):handler = MessageHandler(_api(user_linked=False))@@ -181,6 +207,55 @@ class TestResolveTarget:assert result == "parent-chan"+class TestThreadAdoption:+ @pytest.mark.asyncio+ async def test_mentioned_unsubscribed_thread_is_subscribed(self):+ handler = MessageHandler(_api())+ adapter = _adapter()+ enqueue = AsyncMock()++ with (+ patch.object(handler, "_enqueue_and_process", new=enqueue),+ patch(+ "backend.copilot.bot.handler.threads.is_subscribed",+ new=AsyncMock(return_value=False),+ ),+ patch(+ "backend.copilot.bot.handler.threads.subscribe", new=AsyncMock()+ ) as subscribe,+ ):+ await handler.handle(+ _ctx(+ channel_type="thread",+ channel_id="thread-existing",+ bot_mentioned=True,+ ),+ adapter,+ )++ subscribe.assert_awaited_once_with("discord", "thread-existing")+ enqueue.assert_awaited_once()++ def test_thread_history_is_included_in_message_text(self):+ handler = MessageHandler(_api())+ text = handler._message_text(+ _ctx(+ channel_type="thread",+ text="what should we do?",+ thread_history=(+ MessageHistoryEntry("Alice", "u-1", "I think option A"),+ MessageHistoryEntry("Bob", "u-2", "Option B is safer"),+ ),+ )+ )++ assert "Recent thread context" in text+ assert "Alice (Discord user ID: u-1)" in text+ assert "I think option A" in text+ assert "Current message" in text+ assert "what should we do?" in text++class TestBatching:@pytest.mark.asyncioasync def test_concurrent_message_queues_when_processing(self):