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.

feat(backend/copilot-bot): add /new to start a fresh conversation (#13199)

Bently4074fdb40ffe
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 5b65994724..82d53663ba 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py
@@ -10,6 +10,7 @@ import logging
import discord
from discord import app_commands
+from backend.copilot.bot import sessions
from backend.copilot.bot.bot_backend import BotBackend
from backend.util.exceptions import LinkAlreadyExistsError
from backend.util.settings import Settings
@@ -39,6 +40,13 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:
async def unlink_command(interaction: discord.Interaction) -> None:
await _handle_unlink(interaction)
+ @tree.command(
+ name="new",
+ description="Start a fresh AutoPilot conversation in this DM or thread",
+ )
+ async def new_command(interaction: discord.Interaction) -> None:
+ await _handle_new(interaction)
+
async def _handle_setup(interaction: discord.Interaction, api: BotBackend) -> None:
if interaction.guild is None:
@@ -107,6 +115,7 @@ async def _handle_help(interaction: discord.Interaction) -> None:
"Mention me in a server or DM me directly to chat.\n\n"
"**Commands:**\n"
"- `/setup` — Link this server to your AutoGPT account\n"
+ "- `/new` — Start a fresh conversation (DMs & threads)\n"
"- `/help` — Show this message\n"
"- `/unlink` — Manage linked accounts\n\n"
"**How it works:**\n"
@@ -141,3 +150,30 @@ async def _handle_unlink(interaction: discord.Interaction) -> None:
)
)
await interaction.response.send_message(message, ephemeral=True, view=view)
+
+
+async def _handle_new(interaction: discord.Interaction) -> None:
+ is_dm = interaction.guild is None
+ is_thread = isinstance(interaction.channel, discord.Thread)
+ if not is_dm and not is_thread:
+ await interaction.response.send_message(
+ "Use `/new` in a DM or a thread. Mentioning me in a channel "
+ "already starts a fresh thread.",
+ ephemeral=True,
+ )
+ return
+
+ try:
+ await sessions.clear_session("discord", str(interaction.channel_id))
+ except Exception:
+ logger.exception("Failed to clear copilot session for /new")
+ await interaction.response.send_message(
+ "Couldn't reset the conversation right now. Please try again in a moment.",
+ ephemeral=True,
+ )
+ return
+
+ await interaction.response.send_message(
+ "Started a fresh conversation — send a message to begin.",
+ ephemeral=True,
+ )
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 12bdc72eae..fba8ffab74 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
@@ -6,12 +6,13 @@ registration since it requires a live ``discord.Client``.
from unittest.mock import AsyncMock, MagicMock, patch
+import discord
import pytest
from backend.util.exceptions import LinkAlreadyExistsError
from ...bot_backend import LinkTokenResult
-from .commands import _handle_help, _handle_setup, _handle_unlink
+from .commands import _handle_help, _handle_new, _handle_setup, _handle_unlink
def _interaction(*, guild: bool = True, manage_guild: bool = True) -> MagicMock:
@@ -120,6 +121,7 @@ class TestHandleHelp:
assert interaction.response.send_message.await_args.kwargs["ephemeral"] is True
body = interaction.response.send_message.await_args.args[0]
assert "/setup" in body
+ assert "/new" in body
assert "/help" in body
assert "/unlink" in body
@@ -176,3 +178,64 @@ class TestHandleUnlink:
sent = interaction.response.send_message.await_args
assert "view" not in sent.kwargs or sent.kwargs.get("view") is None
assert "Profile" in sent.args[0]
+
+
+class TestHandleNew:
+ @pytest.mark.asyncio
+ async def test_dm_clears_session(self):
+ interaction = _interaction(guild=False)
+ interaction.channel = MagicMock()
+ interaction.channel_id = 555
+ with patch(
+ "backend.copilot.bot.sessions.clear_session",
+ new=AsyncMock(),
+ ) as mock_clear:
+ await _handle_new(interaction)
+
+ mock_clear.assert_awaited_once_with("discord", "555")
+ interaction.response.send_message.assert_awaited_once()
+ assert interaction.response.send_message.await_args.kwargs["ephemeral"] is True
+
+ @pytest.mark.asyncio
+ async def test_thread_clears_session(self):
+ interaction = _interaction()
+ interaction.channel = MagicMock(spec=discord.Thread)
+ interaction.channel_id = 777
+ with patch(
+ "backend.copilot.bot.sessions.clear_session",
+ new=AsyncMock(),
+ ) as mock_clear:
+ await _handle_new(interaction)
+
+ mock_clear.assert_awaited_once_with("discord", "777")
+
+ @pytest.mark.asyncio
+ async def test_plain_channel_is_rejected(self):
+ interaction = _interaction()
+ interaction.channel = MagicMock()
+ with patch(
+ "backend.copilot.bot.sessions.clear_session",
+ new=AsyncMock(),
+ ) as mock_clear:
+ await _handle_new(interaction)
+
+ mock_clear.assert_not_awaited()
+ interaction.response.send_message.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_redis_failure_sends_fallback_message(self):
+ """A Redis outage during /new must never leave the interaction
+ hanging. We must send an ephemeral fallback instead of bubbling up."""
+ interaction = _interaction(guild=False)
+ interaction.channel = MagicMock()
+ interaction.channel_id = 999
+ with patch(
+ "backend.copilot.bot.sessions.clear_session",
+ new=AsyncMock(side_effect=RuntimeError("redis down")),
+ ):
+ await _handle_new(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()
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.py
index cb938e1444..1e5aa36b10 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py
@@ -19,7 +19,7 @@ from backend.util.exceptions import (
)
from backend.util.settings import Settings
-from . import threads
+from . import sessions, threads
from .adapters.base import MessageContext, PlatformAdapter
from .bot_backend import BotBackend
from .config import SESSION_TTL
@@ -163,7 +163,7 @@ class MessageHandler:
prefixed = format_batch(batch, ctx.platform)
redis = await get_redis_async()
- cache_key = f"copilot-bot:session:{ctx.platform}:{target_id}"
+ cache_key = sessions.session_cache_key(ctx.platform, target_id)
cached_session_id = await redis.get(cache_key)
active_session_id = (
cached_session_id.decode()
diff --git a/autogpt_platform/backend/backend/copilot/bot/sessions.py b/autogpt_platform/backend/backend/copilot/bot/sessions.py
new file mode 100644
index 0000000000..a21cf1f245
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/sessions.py
@@ -0,0 +1,18 @@
+"""Per-target copilot session cache.
+
+The bot remembers which copilot session a DM or thread is currently talking
+to. The key lives here so the handler and the ``/new`` command stay in sync:
+the handler owns the read/write, and ``/new`` clears it so the next message
+starts a fresh AutoPilot conversation.
+"""
+
+from backend.data.redis_client import get_redis_async
+
+
+def session_cache_key(platform: str, target_id: str) -> str:
+ return f"copilot-bot:session:{platform}:{target_id}"
+
+
+async def clear_session(platform: str, target_id: str) -> None:
+ redis = await get_redis_async()
+ await redis.delete(session_cache_key(platform, target_id))
diff --git a/autogpt_platform/backend/backend/copilot/bot/sessions_test.py b/autogpt_platform/backend/backend/copilot/bot/sessions_test.py
new file mode 100644
index 0000000000..af0463a7b9
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/bot/sessions_test.py
@@ -0,0 +1,27 @@
+"""Tests for the per-target copilot session cache helpers."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.bot import sessions
+
+
+def test_session_cache_key_format():
+ assert (
+ sessions.session_cache_key("discord", "123")
+ == "copilot-bot:session:discord:123"
+ )
+
+
+async def test_clear_session_deletes_key():
+ redis = MagicMock()
+ redis.delete = AsyncMock()
+ with patch(
+ "backend.copilot.bot.sessions.get_redis_async",
+ new=AsyncMock(return_value=redis),
+ ):
+ await sessions.clear_session("discord", "123")
+
+ redis.delete.assert_awaited_once_with("copilot-bot:session:discord:123")