Skip to content

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.

fix(backend/copilot-bot): exit threads on /leave or kick (#13268)

Bently833246e4a104
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
index 0d63ed4c68..3485860b42 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -12,6 +12,7 @@ from typing import Optional
import discord
from discord import app_commands
+from backend.copilot.bot import threads
from backend.copilot.bot.bot_backend import BotBackend
from ..base import (
@@ -215,6 +216,21 @@ class DiscordAdapter(PlatformAdapter):
if before.name != after.name:
await self._refresh_server_name(after)
+ @self._client.event
+ async def on_thread_remove(thread: discord.Thread) -> None:
+ # Fires when a thread is removed from the client's cache — the
+ # typical path is the bot being kicked or the thread being made
+ # private without us in it. Drop the auto-reply subscription so a
+ # subsequent re-add by @mention starts in the @-only mode again.
+ # Unlike on_thread_member_remove, this event only requires the
+ # default Intents.guilds and not the privileged members intent.
+ try:
+ await threads.unsubscribe("discord", str(thread.id))
+ except Exception:
+ logger.exception(
+ f"Failed to unsubscribe thread {thread.id} after removal"
+ )
+
@self._client.event
async def on_message(message: discord.Message) -> None:
if self._should_ignore_message(message):
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.py
index 3abddc4afa..ca4163748a 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
@@ -1,7 +1,7 @@
"""Tests for DiscordAdapter helpers that don't need a live gateway."""
from typing import cast
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import AsyncMock, MagicMock, patch
import discord
import pytest
@@ -529,3 +529,57 @@ class TestRefreshServerNames:
api.refresh_server_name.side_effect = RuntimeError("rpc down")
# Must not raise — refreshing names is never critical-path.
await adapter._refresh_server_name(_guild(1, "Server One"))
+
+
+# ── on_thread_remove ────────────────────────────────────────────────────
+
+
+def _thread(thread_id: int) -> MagicMock:
+ thread = MagicMock(spec=discord.Thread)
+ thread.id = thread_id
+ return thread
+
+
+def _register_events_with_mocked_decorator(adapter: DiscordAdapter) -> dict:
+ """Capture the @client.event handlers without actually attaching to
+ discord.py. Returns a name→coroutine map for direct invocation."""
+ handlers: dict = {}
+
+ def _event(coro):
+ handlers[coro.__name__] = coro
+ return coro
+
+ adapter._client.event = _event # type: ignore[assignment]
+ adapter._register_events()
+ return handlers
+
+
+class TestOnThreadRemove:
+ @pytest.mark.asyncio
+ async def test_removal_unsubscribes_thread(self):
+ # We use on_thread_remove instead of on_thread_member_remove so we
+ # don't need the privileged `members` intent. The trade-off is that
+ # this only tells us the bot lost access — which is exactly when we
+ # want to drop the subscription, so the trade-off is free.
+ adapter, _ = _bare_adapter(bot_id=1000)
+ handlers = _register_events_with_mocked_decorator(adapter)
+
+ with patch(
+ "backend.copilot.bot.threads.unsubscribe",
+ new=AsyncMock(),
+ ) as mock_unsub:
+ await handlers["on_thread_remove"](_thread(555))
+
+ mock_unsub.assert_awaited_once_with("discord", "555")
+
+ @pytest.mark.asyncio
+ async def test_swallows_redis_failures(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ handlers = _register_events_with_mocked_decorator(adapter)
+
+ with patch(
+ "backend.copilot.bot.threads.unsubscribe",
+ new=AsyncMock(side_effect=RuntimeError("redis down")),
+ ):
+ # Must not raise — cleanup is never critical-path.
+ await handlers["on_thread_remove"](_thread(555))
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
index 3c7c879ac8..1c35f1bcb1 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
@@ -11,7 +11,7 @@ from datetime import datetime
import discord
from discord import app_commands
-from backend.copilot.bot import sessions
+from backend.copilot.bot import sessions, threads
from backend.copilot.bot.bot_backend import BotBackend, ChatSummary
from backend.util.exceptions import LinkAlreadyExistsError
from backend.util.settings import Settings
@@ -55,6 +55,13 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:
async def resume_command(interaction: discord.Interaction) -> None:
await _handle_resume(interaction, api)
+ @tree.command(
+ name="leave",
+ description="Stop AutoPilot from auto-replying in this thread",
+ )
+ async def leave_command(interaction: discord.Interaction) -> None:
+ await _handle_leave(interaction)
+
async def _handle_setup(interaction: discord.Interaction, api: BotBackend) -> None:
if interaction.guild is None:
@@ -187,6 +194,31 @@ async def _handle_new(interaction: discord.Interaction) -> None:
)
+async def _handle_leave(interaction: discord.Interaction) -> None:
+ if not isinstance(interaction.channel, discord.Thread):
+ await interaction.response.send_message(
+ "Use `/leave` inside a thread. I only auto-reply in threads I'm "
+ "subscribed to.",
+ ephemeral=True,
+ )
+ return
+
+ try:
+ await threads.unsubscribe("discord", str(interaction.channel.id))
+ except Exception:
+ logger.exception("Failed to unsubscribe thread for /leave")
+ await interaction.response.send_message(
+ "Couldn't step out of this thread right now. Please try again in a moment.",
+ ephemeral=True,
+ )
+ return
+
+ await interaction.response.send_message(
+ "Going quiet in this thread. @mention me to bring me back.",
+ ephemeral=True,
+ )
+
+
async def _handle_resume(interaction: discord.Interaction, api: BotBackend) -> None:
if interaction.guild is not None:
await interaction.response.send_message(
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py
index dc79e837d9..112571f78e 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands_test.py
@@ -15,6 +15,7 @@ from backend.util.exceptions import LinkAlreadyExistsError
from ...bot_backend import ChatSummary, LinkTokenResult
from .commands import (
_handle_help,
+ _handle_leave,
_handle_new,
_handle_resume,
_handle_setup,
@@ -254,6 +255,69 @@ class TestHandleNew:
assert "try again" in sent.args[0].lower()
+class TestHandleLeave:
+ @pytest.mark.asyncio
+ async def test_thread_unsubscribes(self):
+ interaction = _interaction()
+ interaction.channel = MagicMock(spec=discord.Thread)
+ interaction.channel.id = 777
+ with patch(
+ "backend.copilot.bot.threads.unsubscribe",
+ new=AsyncMock(),
+ ) as mock_unsub:
+ await _handle_leave(interaction)
+
+ mock_unsub.assert_awaited_once_with("discord", "777")
+ interaction.response.send_message.assert_awaited_once()
+ sent = interaction.response.send_message.await_args
+ assert sent.kwargs["ephemeral"] is True
+ assert "quiet" in sent.args[0].lower()
+
+ @pytest.mark.asyncio
+ async def test_plain_channel_is_rejected(self):
+ # Channels aren't subscribed in the first place — /leave only makes
+ # sense in a thread we'd otherwise auto-reply in.
+ interaction = _interaction()
+ interaction.channel = MagicMock()
+ with patch(
+ "backend.copilot.bot.threads.unsubscribe",
+ new=AsyncMock(),
+ ) as mock_unsub:
+ await _handle_leave(interaction)
+
+ mock_unsub.assert_not_awaited()
+ interaction.response.send_message.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_dm_is_rejected(self):
+ interaction = _interaction(guild=False)
+ interaction.channel = MagicMock()
+ with patch(
+ "backend.copilot.bot.threads.unsubscribe",
+ new=AsyncMock(),
+ ) as mock_unsub:
+ await _handle_leave(interaction)
+
+ mock_unsub.assert_not_awaited()
+ interaction.response.send_message.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_redis_failure_sends_fallback_message(self):
+ interaction = _interaction()
+ interaction.channel = MagicMock(spec=discord.Thread)
+ interaction.channel.id = 777
+ with patch(
+ "backend.copilot.bot.threads.unsubscribe",
+ new=AsyncMock(side_effect=RuntimeError("redis down")),
+ ):
+ await _handle_leave(interaction)
+
+ interaction.response.send_message.assert_awaited_once()
+ sent = interaction.response.send_message.await_args
+ assert sent.kwargs["ephemeral"] is True
+ assert "try again" in sent.args[0].lower()
+
+
def _chat(session_id: str, title: str | None = "A chat") -> ChatSummary:
return ChatSummary(
session_id=session_id,
diff --git a/autogpt_platform/backend/backend/copilot/bot/threads.py b/autogpt_platform/backend/backend/copilot/bot/threads.py
index f42a708570..78427c10e1 100644
--- a/autogpt_platform/backend/backend/copilot/bot/threads.py
+++ b/autogpt_platform/backend/backend/copilot/bot/threads.py
@@ -23,3 +23,10 @@ async def is_subscribed(platform: str, thread_id: str) -> bool:
async def subscribe(platform: str, thread_id: str) -> None:
redis = await get_redis_async()
await redis.set(_key(platform, thread_id), "1", ex=THREAD_SUBSCRIPTION_TTL)
+
+
+async def unsubscribe(platform: str, thread_id: str) -> None:
+ """Drop the auto-reply subscription for a thread — used when the user
+ runs `/leave` or when the bot is kicked from the thread."""
+ redis = await get_redis_async()
+ await redis.delete(_key(platform, thread_id))
diff --git a/autogpt_platform/backend/backend/copilot/bot/threads_test.py b/autogpt_platform/backend/backend/copilot/bot/threads_test.py
index d1f041c4a9..67f0152c6b 100644
--- a/autogpt_platform/backend/backend/copilot/bot/threads_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/threads_test.py
@@ -12,6 +12,7 @@ def redis_mock():
mock = AsyncMock()
mock.get = AsyncMock()
mock.set = AsyncMock()
+ mock.delete = AsyncMock()
with patch("backend.copilot.bot.threads.get_redis_async", return_value=mock):
yield mock
@@ -53,3 +54,20 @@ class TestIsSubscribed:
read_key = redis_mock.get.await_args.args[0]
write_key = redis_mock.set.await_args.args[0]
assert read_key == write_key
+
+
+class TestUnsubscribe:
+ @pytest.mark.asyncio
+ async def test_deletes_the_key(self, redis_mock):
+ await threads.unsubscribe("discord", "thread-1")
+ redis_mock.delete.assert_awaited_once_with(
+ "copilot-bot:thread:discord:thread-1"
+ )
+
+ @pytest.mark.asyncio
+ async def test_uses_same_key_as_subscribe(self, redis_mock):
+ await threads.unsubscribe("discord", "thread-1")
+ await threads.subscribe("discord", "thread-1")
+ del_key = redis_mock.delete.await_args.args[0]
+ write_key = redis_mock.set.await_args.args[0]
+ assert del_key == write_key