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 /resume to pick and resume a past chat (#13219)
Bently5ac3fe29a452
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.pyindex 82d53663ba..93b7a1a4fb 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py@@ -6,12 +6,13 @@ URLs private."""import logging+from datetime import datetimeimport discordfrom discord import app_commandsfrom backend.copilot.bot import sessions-from backend.copilot.bot.bot_backend import BotBackend+from backend.copilot.bot.bot_backend import BotBackend, ChatSummaryfrom backend.util.exceptions import LinkAlreadyExistsErrorfrom backend.util.settings import Settings@@ -47,6 +48,13 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:async def new_command(interaction: discord.Interaction) -> None:await _handle_new(interaction)+ @tree.command(+ name="resume",+ description="Resume one of your past AutoPilot conversations (DMs only)",+ )+ async def resume_command(interaction: discord.Interaction) -> None:+ await _handle_resume(interaction, api)+async def _handle_setup(interaction: discord.Interaction, api: BotBackend) -> None:if interaction.guild is None:@@ -116,6 +124,7 @@ async def _handle_help(interaction: discord.Interaction) -> None:"**Commands:**\n""- `/setup` — Link this server to your AutoGPT account\n""- `/new` — Start a fresh conversation (DMs & threads)\n"+ "- `/resume` — Resume a past conversation (DMs only)\n""- `/help` — Show this message\n""- `/unlink` — Manage linked accounts\n\n""**How it works:**\n"@@ -177,3 +186,106 @@ async def _handle_new(interaction: discord.Interaction) -> None:"Started a fresh conversation — send a message to begin.",ephemeral=True,)+++async def _handle_resume(interaction: discord.Interaction, api: BotBackend) -> None:+ if interaction.guild is not None:+ await interaction.response.send_message(+ "`/resume` only works in my DMs — your conversations are private "+ "to you. Send me a direct message to use it.",+ ephemeral=True,+ )+ return++ # Defer immediately — the linking-manager RPC can blow past Discord's+ # 3-second ack window on a cold cache, which 404s the interaction.+ await interaction.response.defer(ephemeral=True)++ try:+ chats = await api.list_user_chats("discord", str(interaction.user.id))+ except ValueError:+ # NotFoundError (DMs not linked) crosses RPC as its ValueError base.+ await interaction.followup.send(+ "Your DMs aren't linked to an AutoGPT account yet — send me a "+ "message to get started.",+ ephemeral=True,+ )+ return+ except Exception:+ logger.exception("Failed to list chats for /resume")+ await interaction.followup.send(+ "Something went wrong loading your conversations. Try again later.",+ ephemeral=True,+ )+ return++ if not chats:+ await interaction.followup.send(+ "You don't have any conversations yet — send me a message to start one.",+ ephemeral=True,+ )+ return++ await interaction.followup.send(+ "Pick a conversation to resume:",+ view=_ResumeView(chats),+ ephemeral=True,+ )+++class _ResumeView(discord.ui.View):+ def __init__(self, chats: list[ChatSummary]) -> None:+ super().__init__(timeout=180)+ self.add_item(_ResumeSelect(chats))+++class _ResumeSelect(discord.ui.Select):+ # Discord caps select menus at 25 options — silently breaks the picker+ # past that. _handle_resume already requests at most that many chats, but+ # we re-slice here so any future caller is safe.+ DISCORD_SELECT_OPTION_LIMIT = 25++ def __init__(self, chats: list[ChatSummary]) -> None:+ capped_chats = chats[: self.DISCORD_SELECT_OPTION_LIMIT]+ options = [+ discord.SelectOption(+ label=(chat.title or "Untitled conversation")[:100],+ value=chat.session_id,+ description=f"Last active {_relative_time(chat.updated_at)}"[:100],+ )+ for chat in capped_chats+ ]+ super().__init__(placeholder="Choose a conversation to resume", options=options)++ async def callback(self, interaction: discord.Interaction) -> None:+ await _resume_to_session(interaction, self.values[0])+++async def _resume_to_session(interaction: discord.Interaction, session_id: str) -> None:+ # In a DM, discord.py types interaction.channel_id as Optional[int]; an+ # unset value would silently route the session into the wrong cache key.+ # Bail with an ephemeral error instead of corrupting state.+ if interaction.channel_id is None:+ logger.warning("/resume callback fired without channel_id; cannot resume")+ await interaction.response.send_message(+ "Couldn't resume that conversation right now. Please try `/resume` again.",+ ephemeral=True,+ )+ return++ await sessions.set_session("discord", str(interaction.channel_id), session_id)+ await interaction.response.send_message(+ "Resumed that conversation — send a message to continue it.",+ ephemeral=True,+ )+++def _relative_time(when: datetime) -> str:+ seconds = max(0, int((datetime.now(when.tzinfo) - when).total_seconds()))+ if seconds < 60:+ return "just now"+ if seconds < 3600:+ return f"{seconds // 60}m ago"+ if seconds < 86400:+ return f"{seconds // 3600}h ago"+ return f"{seconds // 86400}d ago"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.pyindex fba8ffab74..a549fea0cf 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@@ -4,6 +4,7 @@ Targets the ``_handle_*`` functions directly — sidesteps ``CommandTree``registration since it requires a live ``discord.Client``."""+from datetime import datetime, timezonefrom unittest.mock import AsyncMock, MagicMock, patchimport discord@@ -11,8 +12,15 @@ import pytestfrom backend.util.exceptions import LinkAlreadyExistsError-from ...bot_backend import LinkTokenResult-from .commands import _handle_help, _handle_new, _handle_setup, _handle_unlink+from ...bot_backend import ChatSummary, LinkTokenResult+from .commands import (+ _handle_help,+ _handle_new,+ _handle_resume,+ _handle_setup,+ _handle_unlink,+ _resume_to_session,+)def _interaction(*, guild: bool = True, manage_guild: bool = True) -> MagicMock:@@ -239,3 +247,100 @@ class TestHandleNew:sent = interaction.response.send_message.await_argsassert sent.kwargs["ephemeral"] is Trueassert "try again" in sent.args[0].lower()+++def _chat(session_id: str, title: str | None = "A chat") -> ChatSummary:+ return ChatSummary(+ session_id=session_id,+ title=title,+ updated_at=datetime.now(timezone.utc),+ )+++class TestHandleResume:+ @pytest.mark.asyncio+ async def test_rejected_in_a_server(self):+ interaction = _interaction()+ api = MagicMock()+ api.list_user_chats = AsyncMock()+ await _handle_resume(interaction, api)++ interaction.response.send_message.assert_awaited_once()+ api.list_user_chats.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_no_chats_shows_message(self):+ interaction = _interaction(guild=False)+ api = MagicMock()+ api.list_user_chats = AsyncMock(return_value=[])+ await _handle_resume(interaction, api)++ interaction.response.defer.assert_awaited_once()+ sent = interaction.followup.send.await_args+ assert "view" not in sent.kwargs or sent.kwargs.get("view") is None+ assert "conversations" in sent.args[0]++ @pytest.mark.asyncio+ async def test_lists_chats_in_a_picker(self):+ interaction = _interaction(guild=False)+ api = MagicMock()+ api.list_user_chats = AsyncMock(return_value=[_chat("s1"), _chat("s2")])+ await _handle_resume(interaction, api)++ interaction.response.defer.assert_awaited_once()+ api.list_user_chats.assert_awaited_once_with("discord", "456")+ sent = interaction.followup.send.await_args+ assert sent.kwargs["view"] is not None+ assert sent.kwargs["ephemeral"] is True++ @pytest.mark.asyncio+ async def test_unlinked_user_gets_guidance(self):+ interaction = _interaction(guild=False)+ api = MagicMock()+ api.list_user_chats = AsyncMock(side_effect=ValueError("not linked"))+ await _handle_resume(interaction, api)++ interaction.response.defer.assert_awaited_once()+ sent = interaction.followup.send.await_args+ assert "linked" in sent.args[0].lower()++ @pytest.mark.asyncio+ async def test_resume_to_session_sets_the_dm_session_cache(self):+ interaction = _interaction(guild=False)+ interaction.channel_id = 999+ with patch(+ "backend.copilot.bot.sessions.set_session",+ new=AsyncMock(),+ ) as mock_set:+ await _resume_to_session(interaction, "sess-pick")++ mock_set.assert_awaited_once_with("discord", "999", "sess-pick")+ interaction.response.send_message.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_resume_to_session_bails_when_channel_id_missing(self):+ """If discord.py hands us a None channel_id, persisting to+ `copilot-bot:session:discord:None` would silently break resume. We+ must refuse the action and tell the user."""+ interaction = _interaction(guild=False)+ interaction.channel_id = None+ with patch(+ "backend.copilot.bot.sessions.set_session",+ new=AsyncMock(),+ ) as mock_set:+ await _resume_to_session(interaction, "sess-pick")++ mock_set.assert_not_awaited()+ interaction.response.send_message.assert_awaited_once()+ sent = interaction.response.send_message.await_args+ assert sent.kwargs["ephemeral"] is True++ def test_resume_select_caps_options_at_discord_limit(self):+ """Discord's select menu hard-caps at 25 options. _ResumeSelect must+ trim its input so a long chat history doesn't break the picker."""+ from .commands import _ResumeSelect++ too_many = [_chat(f"s{i}", f"Chat {i}") for i in range(40)]+ select = _ResumeSelect(too_many)++ assert len(select.options) == _ResumeSelect.DISCORD_SELECT_OPTION_LIMITdiff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.pyindex f49bd838bf..edf3d198e6 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py@@ -10,8 +10,11 @@ import asyncioimport jsonimport loggingfrom dataclasses import dataclass+from datetime import datetimefrom typing import Any, AsyncGenerator, Awaitable, Callable, Optional+from pydantic import BaseModel+from backend.copilot import stream_registryfrom backend.copilot.model import get_chat_sessionfrom backend.copilot.response_model import (@@ -42,6 +45,7 @@ logger = logging.getLogger(__name__)__all__ = ["BotBackend",+ "ChatSummary","DuplicateChatMessageError","LinkAlreadyExistsError","LinkTokenResult",@@ -62,6 +66,12 @@ class LinkTokenResult:expires_at: str+class ChatSummary(BaseModel):+ session_id: str+ title: str | None+ updated_at: datetime++SetupRequiredCallback = Callable[[str, dict[str, Any], str | None],Awaitable[None],@@ -143,6 +153,23 @@ class BotBackend:session = await get_chat_session(session_id)return session.title if session else None+ async def list_user_chats(+ self, platform: str, platform_user_id: str, limit: int = 25+ ) -> list[ChatSummary]:+ resp = await self._client.list_user_chats(+ platform=Platform(platform.upper()),+ platform_user_id=platform_user_id,+ limit=limit,+ )+ return [+ ChatSummary(+ session_id=s.session_id,+ title=s.title,+ updated_at=s.updated_at,+ )+ for s in resp.sessions+ ]+async def stream_chat(self,platform: str,diff --git a/autogpt_platform/backend/backend/copilot/bot/sessions.py b/autogpt_platform/backend/backend/copilot/bot/sessions.pyindex a21cf1f245..b9dbf30acb 100644--- a/autogpt_platform/backend/backend/copilot/bot/sessions.py+++ b/autogpt_platform/backend/backend/copilot/bot/sessions.py@@ -8,11 +8,18 @@ starts a fresh AutoPilot conversation.from backend.data.redis_client import get_redis_async+from .config import SESSION_TTL+def session_cache_key(platform: str, target_id: str) -> str:return f"copilot-bot:session:{platform}:{target_id}"+async def set_session(platform: str, target_id: str, session_id: str) -> None:+ redis = await get_redis_async()+ await redis.set(session_cache_key(platform, target_id), session_id, ex=SESSION_TTL)++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.pyindex af0463a7b9..3ded808943 100644--- a/autogpt_platform/backend/backend/copilot/bot/sessions_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/sessions_test.py@@ -25,3 +25,18 @@ async def test_clear_session_deletes_key():await sessions.clear_session("discord", "123")redis.delete.assert_awaited_once_with("copilot-bot:session:discord:123")+++async def test_set_session_writes_with_ttl():+ redis = MagicMock()+ redis.set = AsyncMock()+ with patch(+ "backend.copilot.bot.sessions.get_redis_async",+ new=AsyncMock(return_value=redis),+ ):+ await sessions.set_session("discord", "123", "sess-9")++ redis.set.assert_awaited_once_with(+ "copilot-bot:session:discord:123", "sess-9", ex=sessions.SESSION_TTL+ )diff --git a/autogpt_platform/backend/backend/platform_linking/chat.py b/autogpt_platform/backend/backend/platform_linking/chat.pyindex c1de9ca880..0a477f38b8 100644--- a/autogpt_platform/backend/backend/platform_linking/chat.py+++ b/autogpt_platform/backend/backend/platform_linking/chat.py@@ -10,11 +10,18 @@ from backend.copilot.model import (append_and_save_message,create_chat_session,get_chat_session,+ get_user_sessions,)from backend.data.db_accessors import platform_linking_dbfrom backend.util.exceptions import DuplicateChatMessageError, NotFoundError-from .models import BotChatRequest, ChatTurnHandle+from .models import (+ BotChatRequest,+ ChatSessionSummary,+ ChatTurnHandle,+ ListUserChatsResponse,+ Platform,+)logger = logging.getLogger(__name__)@@ -116,3 +123,45 @@ async def start_chat_turn(request: BotChatRequest) -> ChatTurnHandle:turn_id=turn_id,user_id=owner_user_id,)+++LIST_USER_CHATS_MAX_LIMIT = 25+++async def list_user_chats(+ platform: Platform,+ platform_user_id: str,+ limit: int = 25,+ offset: int = 0,+) -> ListUserChatsResponse:+ """List a DM-linked user's own copilot chats, most recent first.++ Ownership is resolved server-side from the user's own DM link — never a+ server — so a caller can only ever see their own conversations.+ """+ owner_user_id = await platform_linking_db().find_user_link_owner(+ platform.value, platform_user_id+ )+ if owner_user_id is None:+ raise NotFoundError("Your DMs are not linked to an AutoGPT account.")++ # Clamp pagination — negative values would crash the DB driver, and an+ # unbounded `limit` would fan out into a giant query. The cap also lines+ # up with Discord's 25-option select-menu limit used by /resume.+ safe_limit = max(0, min(limit, LIST_USER_CHATS_MAX_LIMIT))+ safe_offset = max(0, offset)++ sessions, total = await get_user_sessions(+ owner_user_id, limit=safe_limit, offset=safe_offset+ )+ return ListUserChatsResponse(+ sessions=[+ ChatSessionSummary(+ session_id=s.session_id,+ title=s.title,+ updated_at=s.updated_at,+ )+ for s in sessions+ ],+ total=total,+ )diff --git a/autogpt_platform/backend/backend/platform_linking/chat_test.py b/autogpt_platform/backend/backend/platform_linking/chat_test.pyindex 15a01fd884..d00e59b0e9 100644--- a/autogpt_platform/backend/backend/platform_linking/chat_test.py+++ b/autogpt_platform/backend/backend/platform_linking/chat_test.py@@ -1,12 +1,13 @@"""Tests for chat-turn orchestration — esp. the duplicate-message guard."""+from datetime import datetimefrom unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.util.exceptions import DuplicateChatMessageError, NotFoundError-from .chat import start_chat_turn+from .chat import list_user_chats, start_chat_turnfrom .models import BotChatRequest, Platform@@ -149,3 +150,70 @@ class TestStartChatTurn:assert handle.session_id == "sess-fresh"mock_create.assert_awaited_once()+++class TestListUserChats:+ @pytest.mark.asyncio+ async def test_unlinked_dm_raises_not_found(self):+ db_mock = MagicMock()+ db_mock.find_user_link_owner = AsyncMock(return_value=None)+ with patch(+ "backend.platform_linking.chat.platform_linking_db",+ return_value=db_mock,+ ):+ with pytest.raises(NotFoundError):+ await list_user_chats(Platform.DISCORD, "pu1")++ @pytest.mark.asyncio+ async def test_lists_only_the_resolved_owners_sessions(self):+ # Ownership is resolved from the caller's own DM link, and the+ # listing is scoped to exactly that owner — never a server.+ db_mock = MagicMock()+ db_mock.find_user_link_owner = AsyncMock(return_value="owner-1")+ session = MagicMock(+ session_id="sess-1",+ title="My chat",+ updated_at=datetime(2026, 5, 1),+ )++ with (+ patch(+ "backend.platform_linking.chat.platform_linking_db",+ return_value=db_mock,+ ),+ patch(+ "backend.platform_linking.chat.get_user_sessions",+ new=AsyncMock(return_value=([session], 1)),+ ) as mock_get_sessions,+ ):+ result = await list_user_chats(Platform.DISCORD, "pu1")++ db_mock.find_user_link_owner.assert_awaited_once_with("DISCORD", "pu1")+ get_sessions_call = mock_get_sessions.await_args+ assert get_sessions_call is not None+ assert get_sessions_call.args[0] == "owner-1"+ assert result.total == 1+ assert [s.session_id for s in result.sessions] == ["sess-1"]+ assert result.sessions[0].title == "My chat"++ @pytest.mark.asyncio+ async def test_clamps_pagination_inputs(self):+ """Negative or oversized pagination args must be clamped before they+ hit get_user_sessions — guards the DB and lines up with /resume's+ Discord-imposed 25-option select-menu limit."""+ db_mock = MagicMock()+ db_mock.find_user_link_owner = AsyncMock(return_value="owner-1")++ with (+ patch(+ "backend.platform_linking.chat.platform_linking_db",+ return_value=db_mock,+ ),+ patch(+ "backend.platform_linking.chat.get_user_sessions",+ new=AsyncMock(return_value=([], 0)),+ ) as mock_get_sessions,+ ):+ await list_user_chats(Platform.DISCORD, "pu1", limit=10_000, offset=-50)++ mock_get_sessions.assert_awaited_once_with("owner-1", limit=25, offset=0)diff --git a/autogpt_platform/backend/backend/platform_linking/manager.py b/autogpt_platform/backend/backend/platform_linking/manager.pyindex c8c7fdbd3a..44048b4fff 100644--- a/autogpt_platform/backend/backend/platform_linking/manager.py+++ b/autogpt_platform/backend/backend/platform_linking/manager.py@@ -6,7 +6,7 @@ from backend.data.db_accessors import platform_linking_dbfrom backend.util.service import AppService, AppServiceClient, endpoint_to_async, exposefrom backend.util.settings import Settings-from .chat import start_chat_turn+from .chat import list_user_chats, start_chat_turnfrom .models import (BotChatRequest,ChatTurnHandle,@@ -14,6 +14,7 @@ from .models import (CreateUserLinkTokenRequest,LinkTokenResponse,LinkTokenStatusResponse,+ ListUserChatsResponse,Platform,ResolveResponse,)@@ -62,6 +63,16 @@ class PlatformLinkingManager(AppService):async def start_chat_turn(self, request: BotChatRequest) -> ChatTurnHandle:return await start_chat_turn(request)+ @expose+ async def list_user_chats(+ self,+ platform: Platform,+ platform_user_id: str,+ limit: int = 25,+ offset: int = 0,+ ) -> ListUserChatsResponse:+ return await list_user_chats(platform, platform_user_id, limit, offset)+class PlatformLinkingManagerClient(AppServiceClient):@classmethod@@ -80,3 +91,4 @@ class PlatformLinkingManagerClient(AppServiceClient):PlatformLinkingManager.get_link_token_status)start_chat_turn = endpoint_to_async(PlatformLinkingManager.start_chat_turn)+ list_user_chats = endpoint_to_async(PlatformLinkingManager.list_user_chats)diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.pyindex fa17871b7f..4f7f947506 100644--- a/autogpt_platform/backend/backend/platform_linking/models.py+++ b/autogpt_platform/backend/backend/platform_linking/models.py@@ -180,3 +180,16 @@ class ChatTurnHandle(BaseModel):turn_id: struser_id: strsubscribe_from: str = "0-0"+++class ChatSessionSummary(BaseModel):+ """Minimal chat-session fields safe to send to a bot client."""++ session_id: str+ title: str | None = None+ updated_at: datetime+++class ListUserChatsResponse(BaseModel):+ sessions: list[ChatSessionSummary]+ total: int