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): smart threads, setup-link button, mention humans, allow bot-to-bot (#13039)

Bently468013a6512f
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
index 4d2bd64b48..2079db256f 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py
@@ -42,6 +42,11 @@ class MessageContext:
text: str # with bot mentions stripped
bot_mentioned: bool = False
thread_history: tuple[MessageHistoryEntry, ...] = ()
+ # Users the bot is allowed to @-mention back in this turn — populated
+ # from the inbound platform message's mentions (excluding the bot itself).
+ # `(display_name, platform_user_id)` pairs. Anyone not in this list won't
+ # get pinged even if the LLM produces `@theirname` in its output.
+ mentionable_users: tuple[tuple[str, str], ...] = ()
@property
def is_dm(self) -> bool:
@@ -65,7 +70,22 @@ class PlatformAdapter(ABC):
async def stop(self) -> None: ...
@abstractmethod
- async def send_message(self, channel_id: str, text: str) -> None: ...
+ async def send_message(
+ self,
+ channel_id: str,
+ text: str,
+ mentionable_users: tuple[tuple[str, str], ...] = (),
+ ) -> None:
+ """Send `text` to `channel_id`.
+
+ `mentionable_users` is the allowlist of `(display_name, user_id)` pairs
+ the bot may ping in this message. Adapters should resolve `@DisplayName`
+ in the text to a real platform mention only for users on this list — a
+ defence against the LLM hallucinating mentions or pinging unrelated
+ users it learned about elsewhere. Default empty = render mentions as
+ plain text.
+ """
+ ...
@abstractmethod
async def send_link(
@@ -80,7 +100,11 @@ class PlatformAdapter(ABC):
@abstractmethod
async def send_reply(
- self, channel_id: str, text: str, reply_to_message_id: str
+ self,
+ channel_id: str,
+ text: str,
+ reply_to_message_id: str,
+ mentionable_users: tuple[tuple[str, str], ...] = (),
) -> None: ...
@abstractmethod
@@ -103,6 +127,11 @@ class PlatformAdapter(ABC):
"""
...
+ @abstractmethod
+ async def rename_thread(self, thread_id: str, name: str) -> bool:
+ """Rename a platform thread/conversation when supported."""
+ ...
+
@property
@abstractmethod
def max_message_length(self) -> int:
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 a4c20ac258..18e14446a1 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -6,6 +6,7 @@ in the core handler. Slash commands live in commands.py.
"""
import logging
+import re
from typing import Optional
import discord
@@ -83,12 +84,18 @@ class DiscordAdapter(PlatformAdapter):
logger.warning("Channel %s not found or inaccessible", channel_id)
return None
- async def send_message(self, channel_id: str, text: str) -> None:
+ async def send_message(
+ self,
+ channel_id: str,
+ text: str,
+ mentionable_users: tuple[tuple[str, str], ...] = (),
+ ) -> None:
channel = await self._resolve_channel(channel_id)
if channel and isinstance(channel, discord.abc.Messageable):
+ rendered, allowed = _resolve_mentions(text, mentionable_users)
# tts=False is the default but we pin it explicitly — AutoPilot
# output is untrusted and should never blast through voice.
- await channel.send(text, tts=False)
+ await channel.send(rendered, tts=False, allowed_mentions=allowed)
async def send_link(
self, channel_id: str, text: str, link_label: str, link_url: str
@@ -107,16 +114,21 @@ class DiscordAdapter(PlatformAdapter):
await channel.send(text, view=view, tts=False)
async def send_reply(
- self, channel_id: str, text: str, reply_to_message_id: str
+ self,
+ channel_id: str,
+ text: str,
+ reply_to_message_id: str,
+ mentionable_users: tuple[tuple[str, str], ...] = (),
) -> None:
channel = await self._resolve_channel(channel_id)
if not channel or not isinstance(channel, discord.abc.Messageable):
return
+ rendered, allowed = _resolve_mentions(text, mentionable_users)
try:
msg = await channel.fetch_message(int(reply_to_message_id))
- await msg.reply(text, tts=False)
+ await msg.reply(rendered, tts=False, allowed_mentions=allowed)
except discord.NotFound:
- await channel.send(text, tts=False)
+ await channel.send(rendered, tts=False, allowed_mentions=allowed)
async def send_ephemeral(self, channel_id: str, user_id: str, text: str) -> None:
# Ephemeral messages are only possible via interaction responses.
@@ -146,6 +158,18 @@ class DiscordAdapter(PlatformAdapter):
logger.exception("Failed to create thread in channel %s", channel_id)
return None
+ async def rename_thread(self, thread_id: str, name: str) -> bool:
+ channel = await self._resolve_channel(thread_id)
+ if channel is None or not isinstance(channel, discord.Thread):
+ logger.warning("Cannot rename non-thread channel %s", thread_id)
+ return False
+ try:
+ await channel.edit(name=name[:100])
+ return True
+ except discord.HTTPException:
+ logger.exception("Failed to rename thread %s", thread_id)
+ return False
+
# -- Internal --
def _register_events(self) -> None:
@@ -165,7 +189,15 @@ class DiscordAdapter(PlatformAdapter):
@self._client.event
async def on_message(message: discord.Message) -> None:
- if message.author.bot:
+ # Always skip our own messages — without this we'd loop forever
+ # answering our own replies. Other bots are fine: in channels
+ # we still require an @mention, in threads we still require an
+ # explicit subscription, so the existing gates already bound the
+ # blast radius of bot-to-bot interactions.
+ if (
+ self._client.user is not None
+ and message.author.id == self._client.user.id
+ ):
return
if self._on_message_callback is None:
return
@@ -193,6 +225,7 @@ class DiscordAdapter(PlatformAdapter):
text=self._strip_mentions(message),
bot_mentioned=bot_mentioned,
thread_history=thread_history,
+ mentionable_users=self._collect_mentionable_users(message),
)
await self._on_message_callback(ctx, self)
@@ -222,6 +255,17 @@ class DiscordAdapter(PlatformAdapter):
text = text.replace(token, replacement)
return text.strip()
+ def _collect_mentionable_users(
+ self, message: discord.Message
+ ) -> tuple[tuple[str, str], ...]:
+ """Users from the inbound message the bot may ping back this turn."""
+ bot_id = self._client.user.id if self._client.user else None
+ return tuple(
+ (user.display_name, str(user.id))
+ for user in message.mentions
+ if user.id != bot_id
+ )
+
async def _thread_history(
self, message: discord.Message
) -> tuple[MessageHistoryEntry, ...]:
@@ -229,13 +273,16 @@ class DiscordAdapter(PlatformAdapter):
return ()
entries: list[MessageHistoryEntry] = []
+ bot_user_id = self._client.user.id if self._client.user else None
try:
async for prior in message.channel.history(
limit=THREAD_HISTORY_LIMIT,
before=message,
oldest_first=True,
):
- if prior.author.bot:
+ # Skip our own outputs — copilot has its own transcript for
+ # that side. Other bots' messages are kept as context.
+ if bot_user_id is not None and prior.author.id == bot_user_id:
continue
text = self._strip_mentions(prior)
if not text:
@@ -252,3 +299,49 @@ class DiscordAdapter(PlatformAdapter):
return ()
return tuple(entries)
+
+
+def _resolve_mentions(
+ text: str,
+ mentionable_users: tuple[tuple[str, str], ...],
+) -> tuple[str, discord.AllowedMentions]:
+ """Substitute `@DisplayName` in `text` with `<@id>` markup for users on
+ the allowlist, and return an AllowedMentions that pings exactly those
+ users (and nobody else).
+
+ Anyone not on the allowlist stays as plain text — even if the LLM produces
+ `@everyone`, `@here`, or `@SomeRandomUser`. This keeps the bot from
+ pinging users it learned about elsewhere or hallucinated entirely.
+ """
+ if not mentionable_users:
+ return text, discord.AllowedMentions.none()
+
+ rendered = text
+ pinged_ids: list[int] = []
+ # Longest names first so e.g. "@John Smith" matches before "@John".
+ for display_name, user_id in sorted(
+ mentionable_users, key=lambda pair: -len(pair[0])
+ ):
+ # Word-bounded so "@Name" inside emails/URLs is left alone.
+ pattern = re.compile(
+ rf"(?<![\w@]){re.escape(f'@{display_name}')}(?!\w)",
+ re.IGNORECASE,
+ )
+ if not pattern.search(rendered):
+ continue
+ # Callable replacement avoids backref interpretation of user_id.
+ rendered = pattern.sub(lambda _m, uid=user_id: f"<@{uid}>", rendered)
+ try:
+ pinged_ids.append(int(user_id))
+ except ValueError:
+ continue
+
+ if not pinged_ids:
+ return rendered, discord.AllowedMentions.none()
+
+ return rendered, discord.AllowedMentions(
+ everyone=False,
+ users=[discord.Object(id=uid) for uid in pinged_ids],
+ roles=False,
+ replied_user=False,
+ )
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 ff3954269c..a3a61a00a7 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
@@ -9,6 +9,7 @@ import pytest
from backend.copilot.bot.adapters.discord.adapter import (
THREAD_HISTORY_LIMIT,
DiscordAdapter,
+ _resolve_mentions,
)
@@ -220,7 +221,12 @@ class TestSendMethods:
await adapter.send_message("123", "hi")
- channel.send.assert_awaited_once_with("hi", tts=False)
+ channel.send.assert_awaited_once()
+ args, kwargs = channel.send.await_args
+ assert args == ("hi",)
+ assert kwargs["tts"] is False
+ # Default empty mentionable_users → AllowedMentions.none()
+ assert isinstance(kwargs["allowed_mentions"], discord.AllowedMentions)
@pytest.mark.asyncio
async def test_send_message_silently_drops_when_channel_missing(self):
@@ -261,7 +267,35 @@ class TestSendMethods:
await adapter.send_reply("123", "hello", "999")
- channel.send.assert_awaited_once_with("hello", tts=False)
+ channel.send.assert_awaited_once()
+ args, kwargs = channel.send.await_args
+ assert args == ("hello",)
+ assert kwargs["tts"] is False
+ assert isinstance(kwargs["allowed_mentions"], discord.AllowedMentions)
+
+
+class TestRenameThread:
+ @pytest.mark.asyncio
+ async def test_renames_resolved_thread(self):
+ adapter, client = _bare_adapter()
+ thread = MagicMock(spec=discord.Thread)
+ thread.edit = AsyncMock()
+ client.get_channel.return_value = thread
+
+ assert await adapter.rename_thread("123", "Generated Web Title") is True
+
+ thread.edit.assert_awaited_once_with(name="Generated Web Title")
+
+ @pytest.mark.asyncio
+ async def test_refuses_non_thread_channel(self):
+ adapter, client = _bare_adapter()
+ channel = MagicMock(spec=discord.TextChannel)
+ channel.edit = AsyncMock()
+ client.get_channel.return_value = channel
+
+ assert await adapter.rename_thread("123", "Generated Web Title") is False
+
+ channel.edit.assert_not_awaited()
# ── properties ─────────────────────────────────────────────────────────
@@ -308,3 +342,95 @@ class TestProperties:
def test_chunk_flush_at_is_under_message_limit(self):
adapter, _ = _bare_adapter()
assert adapter.chunk_flush_at < adapter.max_message_length
+
+
+class TestResolveMentions:
+ def test_empty_allowlist_returns_text_unchanged_and_no_mentions(self):
+ text = "Hello @World, ping @everyone"
+ rendered, allowed = _resolve_mentions(text, ())
+ assert rendered == text
+ assert allowed.everyone is False
+ assert allowed.users is False
+
+ def test_resolves_allowlisted_displayname_to_id_markup(self):
+ rendered, allowed = _resolve_mentions(
+ "Hey @Sue, did you see this?",
+ (("Sue", "12345"),),
+ )
+ assert rendered == "Hey <@12345>, did you see this?"
+ assert isinstance(allowed.users, list)
+ assert [getattr(u, "id", None) for u in allowed.users] == [12345]
+ assert allowed.everyone is False
+
+ def test_leaves_unknown_handles_as_plain_text(self):
+ rendered, allowed = _resolve_mentions(
+ "Hey @Sue and @Random",
+ (("Sue", "12345"),),
+ )
+ assert "<@12345>" in rendered
+ assert "@Random" in rendered # not on allowlist → stays plain
+ assert isinstance(allowed.users, list)
+ assert [getattr(u, "id", None) for u in allowed.users] == [12345]
+
+ def test_longest_name_wins_when_handles_share_a_prefix(self):
+ # "@John Smith" should match before "@John" so the right user pings.
+ rendered, allowed = _resolve_mentions(
+ "Ask @John Smith about it",
+ (("John", "111"), ("John Smith", "222")),
+ )
+ assert "<@222>" in rendered
+ assert "<@111>" not in rendered
+ assert isinstance(allowed.users, list)
+ assert any(getattr(u, "id", None) == 222 for u in allowed.users)
+
+ def test_does_not_ping_everyone_or_here(self):
+ rendered, allowed = _resolve_mentions(
+ "Heads up @everyone and @here",
+ (("everyone", "9"),), # even if a user is named "everyone"…
+ )
+ # "@everyone" gets substituted to <@9> because the user is on the
+ # allowlist, but AllowedMentions.everyone is False so Discord
+ # won't ping the @everyone role. "@here" stays plain text.
+ assert "<@9>" in rendered
+ assert "@here" in rendered
+ assert allowed.everyone is False
+ assert allowed.roles is False
+
+ def test_does_not_match_inside_emails_or_urls(self):
+ # The whole point of word boundaries: a stray "@Sue" inside an
+ # email address must stay an email, not a ping.
+ rendered, allowed = _resolve_mentions(
+ "Email me at [email protected] or visit https://Sue.dev",
+ (("Sue", "12345"),),
+ )
+ assert rendered == (
+ "Email me at [email protected] or visit https://Sue.dev"
+ )
+ assert allowed.everyone is False
+
+ def test_resolves_standalone_mention_alongside_email_in_same_message(self):
+ rendered, _ = _resolve_mentions(
+ "@Sue, can you check [email protected]?",
+ (("Sue", "12345"),),
+ )
+ # Leading "@Sue" resolves; the one inside the email survives intact.
+ assert rendered == "<@12345>, can you check [email protected]?"
+
+
+class TestCollectMentionableUsers:
+ def test_excludes_the_bot_itself(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ msg = _message(
+ "<@1000> please tell <@2000> something",
+ mentions=[
+ _mention(1000, "AutoPilot"),
+ _mention(2000, "Sue"),
+ ],
+ )
+ result = adapter._collect_mentionable_users(msg)
+ assert result == (("Sue", "2000"),)
+
+ def test_returns_empty_when_only_bot_mentioned(self):
+ adapter, _ = _bare_adapter(bot_id=1000)
+ msg = _message("<@1000> hi", mentions=[_mention(1000, "AutoPilot")])
+ assert adapter._collect_mentionable_users(msg) == ()
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
index f2df877041..f49bd838bf 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -7,12 +7,19 @@ discord/telegram/slack code never touches Pyro / Redis Streams plumbing.
"""
import asyncio
+import json
import logging
from dataclasses import dataclass
-from typing import AsyncGenerator, Awaitable, Callable, Optional
+from typing import Any, AsyncGenerator, Awaitable, Callable, Optional
from backend.copilot import stream_registry
-from backend.copilot.response_model import StreamError, StreamFinish, StreamTextDelta
+from backend.copilot.model import get_chat_session
+from backend.copilot.response_model import (
+ StreamError,
+ StreamFinish,
+ StreamTextDelta,
+ StreamToolOutputAvailable,
+)
from backend.platform_linking.models import (
BotChatRequest,
CreateLinkTokenRequest,
@@ -55,6 +62,12 @@ class LinkTokenResult:
expires_at: str
+SetupRequiredCallback = Callable[
+ [str, dict[str, Any], str | None],
+ Awaitable[None],
+]
+
+
class BotBackend:
"""Bot-side linking + chat operations, routed over cluster-internal RPC."""
@@ -126,6 +139,10 @@ class BotBackend:
expires_at=resp.expires_at.isoformat(),
)
+ async def get_session_title(self, session_id: str) -> str | None:
+ session = await get_chat_session(session_id)
+ return session.title if session else None
+
async def stream_chat(
self,
platform: str,
@@ -134,6 +151,7 @@ class BotBackend:
session_id: Optional[str] = None,
platform_server_id: Optional[str] = None,
on_session_id: Optional[Callable[[str], Awaitable[None]]] = None,
+ on_setup_required: SetupRequiredCallback | None = None,
) -> AsyncGenerator[str, None]:
"""Start a copilot turn and yield text deltas from the stream.
@@ -161,6 +179,8 @@ class BotBackend:
yield "\n[Error: failed to subscribe to response stream]"
return
+ setup_notified = False
+
try:
while True:
try:
@@ -178,6 +198,15 @@ class BotBackend:
if isinstance(chunk, StreamTextDelta):
if chunk.delta:
yield chunk.delta
+ elif isinstance(chunk, StreamToolOutputAvailable):
+ setup_output = _extract_setup_requirements(chunk.output)
+ if setup_output and on_setup_required and not setup_notified:
+ setup_notified = True
+ await on_setup_required(
+ handle.session_id,
+ setup_output,
+ chunk.toolName,
+ )
elif isinstance(chunk, StreamFinish):
return
elif isinstance(chunk, StreamError):
@@ -192,3 +221,20 @@ class BotBackend:
session_id=handle.session_id,
subscriber_queue=queue,
)
+
+
+def _extract_setup_requirements(output: str | dict[str, Any]) -> dict[str, Any] | None:
+ """Return setup-requirements payloads from structured tool output."""
+ if isinstance(output, str):
+ try:
+ parsed: Any = json.loads(output)
+ except json.JSONDecodeError:
+ return None
+ else:
+ parsed = output
+
+ if not isinstance(parsed, dict):
+ return None
+ if parsed.get("type") != "setup_requirements":
+ return None
+ return parsed
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
index 24b5df7dee..063707e922 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
@@ -6,7 +6,12 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from backend.copilot.response_model import StreamError, StreamFinish, StreamTextDelta
+from backend.copilot.response_model import (
+ StreamError,
+ StreamFinish,
+ StreamTextDelta,
+ StreamToolOutputAvailable,
+)
from backend.platform_linking.models import (
ChatTurnHandle,
LinkTokenResponse,
@@ -165,6 +170,55 @@ class TestStreamChat:
assert any("executor crashed" in c for c in chunks)
+ @pytest.mark.asyncio
+ async def test_notifies_setup_requirements_tool_output(self, api: BotBackend):
+ handle = ChatTurnHandle(session_id="sess", turn_id="turn", user_id="u1")
+ api._client.start_chat_turn = AsyncMock(return_value=handle)
+
+ queue: asyncio.Queue = asyncio.Queue()
+ await queue.put(
+ StreamToolOutputAvailable(
+ toolCallId="tool-1",
+ toolName="connect_integration",
+ output='{"type":"setup_requirements","message":"Connect GitHub"}',
+ )
+ )
+ await queue.put(StreamTextDelta(id="1", delta="After setup"))
+ await queue.put(StreamFinish())
+
+ setup_calls: list[tuple[str, dict, str | None]] = []
+
+ async def on_setup(session_id: str, output: dict, tool_name: str | None):
+ setup_calls.append((session_id, output, tool_name))
+
+ with (
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",
+ new=AsyncMock(return_value=queue),
+ ),
+ patch(
+ "backend.copilot.bot.bot_backend.stream_registry.unsubscribe_from_session",
+ new=AsyncMock(),
+ ),
+ ):
+ chunks: list[str] = []
+ async for chunk in api.stream_chat(
+ platform="discord",
+ platform_user_id="u1",
+ message="hi",
+ on_setup_required=on_setup,
+ ):
+ chunks.append(chunk)
+
+ assert chunks == ["After setup"]
+ assert setup_calls == [
+ (
+ "sess",
+ {"type": "setup_requirements", "message": "Connect GitHub"},
+ "connect_integration",
+ )
+ ]
+
@pytest.mark.asyncio
async def test_duplicate_message_propagates(self, api: BotBackend):
api._client.start_chat_turn = AsyncMock(
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.py
index 55c57aa80e..cb938e1444 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py
@@ -8,6 +8,8 @@ persistent typing indicator.
import asyncio
import logging
from dataclasses import dataclass, field
+from typing import Any
+from urllib.parse import quote
from backend.data.redis_client import get_redis_async
from backend.util.exceptions import (
@@ -15,6 +17,7 @@ from backend.util.exceptions import (
LinkAlreadyExistsError,
NotFoundError,
)
+from backend.util.settings import Settings
from . import threads
from .adapters.base import MessageContext, PlatformAdapter
@@ -24,6 +27,11 @@ from .text import format_batch, split_at_boundary
logger = logging.getLogger(__name__)
+THREAD_NAME_MAX_LENGTH = 100
+THREAD_NAME_PREFIX = "AutoPilot: "
+TITLE_RENAME_ATTEMPTS = 5
+TITLE_RENAME_INTERVAL_SECONDS = 1.0
+
@dataclass
class TargetState:
@@ -43,6 +51,8 @@ class MessageHandler:
def __init__(self, api: BotBackend):
self._api = api
self._targets: dict[str, TargetState] = {}
+ # Strong-ref set so the GC doesn't drop fire-and-forget rename tasks.
+ self._rename_tasks: set[asyncio.Task[None]] = set()
async def handle(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:
if not ctx.text.strip():
@@ -87,7 +97,7 @@ class MessageHandler:
return ctx.channel_id
# channel_type == "channel" — create a thread and subscribe
- thread_name = f"{ctx.username} × AutoPilot"
+ thread_name = build_thread_name(ctx.text, ctx.username)
thread_id = await adapter.create_thread(
ctx.channel_id, ctx.message_id, thread_name
)
@@ -155,8 +165,15 @@ class MessageHandler:
redis = await get_redis_async()
cache_key = f"copilot-bot:session:{ctx.platform}:{target_id}"
cached_session_id = await redis.get(cache_key)
+ active_session_id = (
+ cached_session_id.decode()
+ if isinstance(cached_session_id, bytes)
+ else cached_session_id
+ )
async def _on_session_id(sid: str) -> None:
+ nonlocal active_session_id
+ active_session_id = sid
try:
await redis.set(cache_key, sid, ex=SESSION_TTL)
except Exception:
@@ -165,6 +182,44 @@ class MessageHandler:
flush_at = adapter.chunk_flush_at
buffer = ""
sent_any_content = False
+ setup_prompt_sent = False
+
+ async def _on_setup_required(
+ session_id: str,
+ setup_output: dict[str, Any],
+ _tool_name: str | None,
+ ) -> None:
+ nonlocal buffer, sent_any_content, setup_prompt_sent
+ if setup_prompt_sent:
+ return
+ setup_prompt_sent = True
+ # Drain any pending text first so the link button doesn't render
+ # ahead of the message it belongs to.
+ if buffer.strip():
+ await adapter.send_message(
+ target_id, buffer, mentionable_users=ctx.mentionable_users
+ )
+ buffer = ""
+ sent_any_content = True
+ session_url = _copilot_session_url(session_id)
+ message = _setup_required_message(setup_output)
+ if session_url is None:
+ # No base URL configured — fall back to plain text since
+ # Discord rejects relative URLs on link buttons.
+ logger.warning(
+ "No frontend/platform base URL configured; "
+ "sending setup-required prompt without a button"
+ )
+ await adapter.send_message(
+ target_id, message, mentionable_users=ctx.mentionable_users
+ )
+ return
+ await adapter.send_link(
+ target_id,
+ message,
+ link_label="Open AutoGPT",
+ link_url=session_url,
+ )
typing_task = asyncio.create_task(_keep_typing(adapter, target_id))
try:
@@ -172,15 +227,20 @@ class MessageHandler:
platform=ctx.platform,
platform_user_id=ctx.user_id,
message=prefixed,
- session_id=cached_session_id,
+ session_id=active_session_id,
platform_server_id=ctx.server_id,
on_session_id=_on_session_id,
+ on_setup_required=_on_setup_required,
):
buffer += chunk
if len(buffer) >= flush_at:
post, buffer = split_at_boundary(buffer, flush_at)
if post:
- await adapter.send_message(target_id, post)
+ await adapter.send_message(
+ target_id,
+ post,
+ mentionable_users=ctx.mentionable_users,
+ )
if post.strip():
sent_any_content = True
except DuplicateChatMessageError:
@@ -212,7 +272,9 @@ class MessageHandler:
await adapter.stop_typing(target_id)
if buffer.strip():
- await adapter.send_message(target_id, buffer)
+ await adapter.send_message(
+ target_id, buffer, mentionable_users=ctx.mentionable_users
+ )
sent_any_content = True
if not sent_any_content:
@@ -221,6 +283,44 @@ class MessageHandler:
"AutoPilot didn't produce a response. Try rephrasing your question.",
)
+ if (
+ ctx.channel_type == "channel"
+ and target_id != ctx.channel_id
+ and active_session_id
+ ):
+ # Fire-and-forget so the rename poll doesn't stall follow-up turns.
+ task = asyncio.create_task(
+ self._rename_thread_from_session_title(
+ adapter, target_id, active_session_id
+ )
+ )
+ self._rename_tasks.add(task)
+ task.add_done_callback(self._rename_tasks.discard)
+
+ async def _rename_thread_from_session_title(
+ self,
+ adapter: PlatformAdapter,
+ thread_id: str,
+ session_id: str,
+ ) -> None:
+ for attempt in range(TITLE_RENAME_ATTEMPTS):
+ try:
+ title = await self._api.get_session_title(session_id)
+ except Exception:
+ logger.warning(
+ "Failed to fetch generated title for %s (attempt %d/%d)",
+ session_id,
+ attempt + 1,
+ TITLE_RENAME_ATTEMPTS,
+ exc_info=True,
+ )
+ title = None
+ if title:
+ await adapter.rename_thread(thread_id, clamp_thread_name(title))
+ return
+ if attempt < TITLE_RENAME_ATTEMPTS - 1:
+ await asyncio.sleep(TITLE_RENAME_INTERVAL_SECONDS)
+
# -- Linking --
async def _ensure_linked(
@@ -308,3 +408,42 @@ async def _keep_typing(adapter: PlatformAdapter, target_id: str) -> None:
raise
except Exception:
logger.debug("Typing loop error", exc_info=True)
+
+
+def build_thread_name(text: str, username: str) -> str:
+ """Build a Discord-safe thread name from the user's first prompt."""
+ cleaned = " ".join(text.split())
+ if not cleaned:
+ cleaned = f"{username} with AutoPilot"
+ return clamp_thread_name(f"{THREAD_NAME_PREFIX}{cleaned}")
+
+
+def clamp_thread_name(name: str) -> str:
+ cleaned = " ".join(name.split()) or "AutoPilot Chat"
+ if len(cleaned) > THREAD_NAME_MAX_LENGTH:
+ return cleaned[: THREAD_NAME_MAX_LENGTH - 3].rstrip() + "..."
+ return cleaned
+
+
+def _copilot_session_url(session_id: str) -> str | None:
+ """Absolute URL to the live copilot session, or None if no base URL set."""
+ config = Settings().config
+ base_url = (config.frontend_base_url or config.platform_base_url).rstrip("/")
+ if not base_url:
+ return None
+ return f"{base_url}/copilot?sessionId={quote(session_id, safe='')}"
+
+
+def _setup_required_message(setup_output: dict[str, Any]) -> str:
+ message = str(setup_output.get("message") or "").strip()
+ if not message:
+ message = (
+ "AutoPilot needs you to sign in or authorize an integration "
+ "before it can continue."
+ )
+
+ return (
+ f"{message}\n\n"
+ "Click the button below to open your AutoGPT chat and finish setup "
+ "there. Reply here when you're done."
+ )
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
index 34c0db80a8..948a07a554 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
@@ -1,5 +1,7 @@
"""Tests for the platform-agnostic message handler."""
+import asyncio
+import contextlib
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -8,7 +10,7 @@ from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
from .adapters.base import ChannelType, MessageContext, MessageHistoryEntry
from .bot_backend import LinkTokenResult, ResolveResult
-from .handler import MessageHandler, TargetState
+from .handler import MessageHandler, TargetState, build_thread_name, clamp_thread_name
def _ctx(
@@ -46,6 +48,7 @@ def _adapter() -> MagicMock:
adapter.start_typing = AsyncMock()
adapter.stop_typing = AsyncMock()
adapter.create_thread = AsyncMock(return_value="thread-new")
+ adapter.rename_thread = AsyncMock(return_value=True)
return adapter
@@ -69,6 +72,28 @@ def _api(*, server_linked: bool = True, user_linked: bool = True) -> MagicMock:
return api
+def _capture_handler_tasks():
+ """Capture handler-spawned tasks at creation time.
+
+ Rename tasks self-discard from `handler._rename_tasks` via a done-
+ callback, so reading that set post-hoc is racy.
+ """
+ tasks: list[asyncio.Task[None]] = []
+ real_create_task = asyncio.create_task
+
+ def _capturing(coro, **kwargs):
+ task = real_create_task(coro, **kwargs)
+ tasks.append(task)
+ return task
+
+ with patch(
+ "backend.copilot.bot.handler.asyncio.create_task",
+ side_effect=_capturing,
+ ):
+ yield tasks
+
+
class TestEmptyMessage:
@pytest.mark.asyncio
async def test_channel_mention_without_text_gets_nudge(self):
@@ -197,6 +222,7 @@ class TestResolveTarget:
result = await handler._resolve_target(_ctx(), adapter)
assert result == "thread-created"
subscribe.assert_awaited_once_with("discord", "thread-created")
+ assert adapter.create_thread.await_args.args[2] == "AutoPilot: hello bot"
@pytest.mark.asyncio
async def test_channel_falls_back_to_parent_when_thread_creation_fails(self):
@@ -335,6 +361,205 @@ class TestBatching:
adapter.send_message.assert_not_awaited()
+ @pytest.mark.asyncio
+ async def test_setup_requirements_sends_web_handoff_link(self):
+ api = _api()
+
+ async def setup_stream(*args, **kwargs):
+ await kwargs["on_setup_required"](
+ "session-1",
+ {
+ "type": "setup_requirements",
+ "message": "Connect GitHub to continue.",
+ },
+ "connect_integration",
+ )
+ yield "Once connected, I can retry."
+
+ api.stream_chat = setup_stream
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ fake_settings = MagicMock()
+ fake_settings.config.frontend_base_url = "https://app.example.com"
+ fake_settings.config.platform_base_url = ""
+
+ with (
+ patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),
+ ),
+ patch("backend.copilot.bot.handler.Settings", return_value=fake_settings),
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ adapter.send_link.assert_awaited_once()
+ assert adapter.send_link.await_args.kwargs["link_label"] == "Open AutoGPT"
+ assert (
+ adapter.send_link.await_args.kwargs["link_url"]
+ == "https://app.example.com/copilot?sessionId=session-1"
+ )
+ assert "Connect GitHub" in adapter.send_link.await_args.args[1]
+ # Trailing yield after on_setup_required still flushes at end-of-stream.
+ adapter.send_message.assert_awaited_once()
+ assert "Once connected, I can retry." in adapter.send_message.await_args.args[1]
+
+ @pytest.mark.asyncio
+ async def test_setup_requirements_without_text_does_not_send_empty_fallback(self):
+ api = _api()
+
+ async def setup_stream(*args, **kwargs):
+ await kwargs["on_setup_required"](
+ "session-1",
+ {
+ "type": "setup_requirements",
+ "message": "Connect GitHub to continue.",
+ },
+ "connect_integration",
+ )
+ if False:
+ yield ""
+
+ api.stream_chat = setup_stream
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ fake_settings = MagicMock()
+ fake_settings.config.frontend_base_url = "https://app.example.com"
+ fake_settings.config.platform_base_url = ""
+
+ with (
+ patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),
+ ),
+ patch("backend.copilot.bot.handler.Settings", return_value=fake_settings),
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")], _ctx(), adapter, "target-1"
+ )
+
+ adapter.send_link.assert_awaited_once()
+ adapter.send_message.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_channel_thread_renames_from_generated_chat_title(self):
+ api = _api()
+
+ async def title_stream(*args, **kwargs):
+ await kwargs["on_session_id"]("session-1")
+ yield "Done"
+
+ api.stream_chat = title_stream
+ api.get_session_title = AsyncMock(return_value="Generated Web Title")
+ handler = MessageHandler(api)
+ adapter = _adapter()
+ redis = AsyncMock(get=AsyncMock(return_value=None), set=AsyncMock())
+
+ with (
+ patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=redis),
+ ),
+ patch(
+ "backend.copilot.bot.handler.asyncio.sleep",
+ new=AsyncMock(),
+ ),
+ _capture_handler_tasks() as captured,
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")],
+ _ctx(channel_type="channel", channel_id="parent-1"),
+ adapter,
+ "thread-1",
+ )
+ await asyncio.gather(*captured, return_exceptions=True)
+
+ api.get_session_title.assert_awaited_once_with("session-1")
+ adapter.rename_thread.assert_awaited_once_with(
+ "thread-1", "Generated Web Title"
+ )
+
+ @pytest.mark.asyncio
+ async def test_thread_rename_retries_when_title_not_ready_yet(self):
+ api = _api()
+
+ async def title_stream(*args, **kwargs):
+ await kwargs["on_session_id"]("session-2")
+ yield "Done"
+
+ api.stream_chat = title_stream
+ # First two polls return None (title not generated yet), third
+ # returns the real title.
+ api.get_session_title = AsyncMock(side_effect=[None, None, "Late Title"])
+ handler = MessageHandler(api)
+ adapter = _adapter()
+ redis = AsyncMock(get=AsyncMock(return_value=None), set=AsyncMock())
+
+ with (
+ patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=redis),
+ ),
+ patch(
+ "backend.copilot.bot.handler.asyncio.sleep",
+ new=AsyncMock(),
+ ),
+ _capture_handler_tasks() as captured,
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")],
+ _ctx(channel_type="channel", channel_id="parent-1"),
+ adapter,
+ "thread-2",
+ )
+ await asyncio.gather(*captured, return_exceptions=True)
+
+ assert api.get_session_title.await_count == 3
+ adapter.rename_thread.assert_awaited_once_with("thread-2", "Late Title")
+
+ @pytest.mark.asyncio
+ async def test_thread_rename_keeps_retrying_after_transient_exception(self):
+ api = _api()
+
+ async def title_stream(*args, **kwargs):
+ await kwargs["on_session_id"]("session-3")
+ yield "Done"
+
+ api.stream_chat = title_stream
+ # Simulate a transient backend error on the first attempt; the
+ # retry should still go through and pick up the title.
+ api.get_session_title = AsyncMock(
+ side_effect=[RuntimeError("transient"), "Recovered Title"]
+ )
+ handler = MessageHandler(api)
+ adapter = _adapter()
+ redis = AsyncMock(get=AsyncMock(return_value=None), set=AsyncMock())
+
+ with (
+ patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=redis),
+ ),
+ patch(
+ "backend.copilot.bot.handler.asyncio.sleep",
+ new=AsyncMock(),
+ ),
+ _capture_handler_tasks() as captured,
+ ):
+ await handler._stream_batch(
+ [("Bently", "u1", "hi")],
+ _ctx(channel_type="channel", channel_id="parent-1"),
+ adapter,
+ "thread-3",
+ )
+ await asyncio.gather(*captured, return_exceptions=True)
+
+ assert api.get_session_title.await_count == 2
+ adapter.rename_thread.assert_awaited_once_with("thread-3", "Recovered Title")
+
class TestStreamFallback:
"""Covers the empty-response fallback, including the boundary-flush bug
@@ -417,3 +642,23 @@ class TestStreamFallback:
msgs = [c.args[1] for c in adapter.send_message.await_args_list]
assert not any("didn't produce a response" in m for m in msgs)
assert msgs == ["x" * 50]
+
+
+class TestThreadNames:
+ def test_build_thread_name_from_prompt(self):
+ assert (
+ build_thread_name(" tell me\nabout space ", "Bently")
+ == "AutoPilot: tell me about space"
+ )
+
+ def test_build_thread_name_truncates_to_discord_limit(self):
+ name = build_thread_name("x" * 200, "Bently")
+ assert len(name) <= 100
+ assert name.startswith("AutoPilot: ")
+ assert name.endswith("...")
+
+ def test_clamp_thread_name_handles_generated_titles(self):
+ assert clamp_thread_name(" Generated\nWeb Title ") == "Generated Web Title"
+
+ def test_clamp_thread_name_falls_back_when_blank(self):
+ assert clamp_thread_name(" ") == "AutoPilot Chat"