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.
refactor(platform): copilot-bot cleanup — handler split, shared command policy, AutoGPT branding (#13553)
Bentlyfc8cc4f2962c
diff --git a/autogpt_platform/backend/backend/copilot/bot/README.md b/autogpt_platform/backend/backend/copilot/bot/README.mdindex 13cca61b54..ccb144e818 100644--- a/autogpt_platform/backend/backend/copilot/bot/README.md+++ b/autogpt_platform/backend/backend/copilot/bot/README.md@@ -48,7 +48,11 @@ See `backend/.env.default` for the full list with documentation. Minimum setup:bot/├── app.py # CoPilotChatBridge(AppService), adapter factory, outbound @expose RPC├── config.py # Shared (platform-agnostic) config-├── handler.py # Core logic: routing, linking, batched streaming+├── handler.py # Orchestrator: routing, linking, attachment ingestion, batching+├── turn_stream.py # Streaming one batched turn: chunked sends, artifacts, renames+├── prompt.py # Prompt + thread-name assembly+├── attachments.py # Attachment upload + failure notes+├── command_core.py # Shared /setup + /unlink policy (adapters render it)├── bot_backend.py # Thin facade over PlatformLinkingManagerClient + stream_registry├── text.py # Text splitting + batch formatting├── threads.py # Redis-backed thread subscription trackingdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.pyindex 3af0291026..a855e6e339 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py@@ -12,7 +12,8 @@ from abc import ABC, abstractmethodfrom dataclasses import dataclassfrom typing import Awaitable, Callable, Literal, Optional-from fastapi import FastAPI+from fastapi import FastAPI, Request+from fastapi.responses import PlainTextResponsefrom pydantic import BaseModel# Callback signature: (ctx, adapter) -> awaitable None@@ -196,11 +197,12 @@ class PlatformAdapter(ABC):self, channel_id: str, user_id: str, text: str) -> None: ...- @abstractmethod- async def start_typing(self, channel_id: str) -> None: ...+ async def start_typing(self, channel_id: str) -> None:+ """Show the platform's typing indicator. Default no-op — several+ platforms (Slack bot apps, most webhook platforms) don't expose one."""- @abstractmethod- async def stop_typing(self, channel_id: str) -> None: ...+ async def stop_typing(self, channel_id: str) -> None:+ """Clear the typing indicator. Default no-op (see ``start_typing``)."""@abstractmethodasync def create_thread(@@ -211,10 +213,10 @@ class PlatformAdapter(ABC):"""...- @abstractmethodasync def rename_thread(self, thread_id: str, name: str) -> bool:- """Rename a platform thread/conversation when supported."""- ...+ """Rename a platform thread/conversation. Default: unsupported —+ platforms with unnamed/implicit threads (Slack) simply inherit this."""+ return False@property@abstractmethod@@ -373,3 +375,24 @@ class WebhookAdapter(PlatformAdapter):within the platform's timeout, scheduling the real work off-request."""...+++async def read_verified_webhook_body(+ request: Request, verify: Callable[[Request, bytes], bool]+) -> bytes | None:+ """Read an inbound webhook body and verify its platform signature.++ Returns the raw body when the signature checks out, ``None`` otherwise —+ the route should then return :func:`unauthorized_webhook_response`. Shared+ so every webhook adapter verifies BEFORE parsing, against the same raw+ bytes the platform signed.+ """+ raw = await request.body()+ if not verify(request, raw):+ return None+ return raw+++def unauthorized_webhook_response() -> PlainTextResponse:+ """The uniform 401 for a webhook that failed signature verification."""+ return PlainTextResponse("invalid signature", status_code=401)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 311e827d6d..585f037a08 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@@ -66,7 +66,7 @@ class _AsyncHistory:class TestStripMentions:def test_strips_only_bot_mention(self):adapter, _ = _bare_adapter(bot_id=1000)- bot = _mention(1000, "AutoPilot")+ bot = _mention(1000, "AutoGPT")alice = _mention(2000, "Alice")msg = _message("<@1000> please summarise what <@2000> said",@@ -77,7 +77,7 @@ class TestStripMentions:def test_handles_nickname_style_tokens(self):adapter, _ = _bare_adapter(bot_id=1000)- bot = _mention(1000, "AutoPilot")+ bot = _mention(1000, "AutoGPT")alice = _mention(2000, "Alice")msg = _message("<@!1000> ping <@!2000>", mentions=[bot, alice])@@ -107,7 +107,7 @@ class TestStripMentions:)def test_bot_only_variants(self, content: str, expected: str):adapter, _ = _bare_adapter(bot_id=1000)- bot = _mention(1000, "AutoPilot")+ bot = _mention(1000, "AutoGPT")msg = _message(content, mentions=[bot])assert adapter._strip_mentions(msg) == expected@@ -203,7 +203,7 @@ class TestShouldIgnoreMessage:def test_allows_mentioned_bot_message(self):# Another bot can still reach us by explicitly @mentioning us.adapter, _ = _bare_adapter(bot_id=1000)- msg = _message("hi", [_mention(1000, "AutoPilot")])+ msg = _message("hi", [_mention(1000, "AutoGPT")])msg.author = MagicMock(id=2000, bot=True)msg.guild = MagicMock()@@ -232,13 +232,13 @@ class TestIsMentioned:def test_guild_with_mention_passes(self):adapter, _ = _bare_adapter(bot_id=1000)- msg = _message("hi", [_mention(1000, "AutoPilot")])+ msg = _message("hi", [_mention(1000, "AutoGPT")])msg.guild = MagicMock()assert adapter._is_mentioned(msg) is Truedef test_no_bot_user_treats_guild_mention_as_false(self):adapter, _ = _bare_adapter(bot_id=None)- msg = _message("hi", [_mention(1000, "AutoPilot")])+ msg = _message("hi", [_mention(1000, "AutoGPT")])msg.guild = MagicMock()assert adapter._is_mentioned(msg) is False@@ -256,7 +256,7 @@ class TestIsMentioned:# If they ping the bot AND @everyone, the bot is still in# `message.mentions` and we should reply normally.adapter, _ = _bare_adapter(bot_id=1000)- msg = _message("@everyone and @AutoPilot", [_mention(1000, "AutoPilot")])+ msg = _message("@everyone and @AutoGPT", [_mention(1000, "AutoGPT")])msg.guild = MagicMock()msg.mention_everyone = Trueassert adapter._is_mentioned(msg) is True@@ -449,14 +449,14 @@ class TestThreadHistory:# Discord returns history newest-first; the adapter reverses it back to# chronological order, dropping its own outputs.adapter, _ = _bare_adapter(bot_id=1000)- bot = _mention(1000, "AutoPilot")+ bot = _mention(1000, "AutoGPT")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")+ bot_msg.author = MagicMock(bot=True, id=1000, display_name="AutoGPT")channel = MagicMock(spec=discord.Thread)# newest-first as the Discord API delivers it: Bob, (bot), Alice@@ -636,7 +636,7 @@ class TestCollectMentionableUsers:msg = _message("<@1000> please tell <@2000> something",mentions=[- _mention(1000, "AutoPilot"),+ _mention(1000, "AutoGPT"),_mention(2000, "Sue"),],)@@ -645,7 +645,7 @@ class TestCollectMentionableUsers:def test_returns_empty_when_only_bot_mentioned(self):adapter, _ = _bare_adapter(bot_id=1000)- msg = _message("<@1000> hi", mentions=[_mention(1000, "AutoPilot")])+ msg = _message("<@1000> hi", mentions=[_mention(1000, "AutoGPT")])assert adapter._collect_mentionable_users(msg) == ()@@ -813,7 +813,7 @@ class TestLockedThread:msg.guild = guildmsg.channel = MagicMock(id=555) # a normal channel, not a Threadmsg.content = "<@1000> read https://discord.com/channels/111/222/333"- msg.mentions = [_mention(1000, "AutoPilot")]+ msg.mentions = [_mention(1000, "AutoGPT")]msg.message_snapshots = []await handlers["on_message"](msg)@@ -909,7 +909,7 @@ class TestReplyContext:msg.guild = guildmsg.channel = MagicMock(id=555) # a normal channel, not a Threadmsg.content = "<@1000> can you tell me?"- msg.mentions = [_mention(1000, "AutoPilot")]+ msg.mentions = [_mention(1000, "AutoGPT")]msg.message_snapshots = []msg.reference = MagicMock(resolved=replied)@@ -941,7 +941,7 @@ class TestReplyContext:msg.guild = guildmsg.channel = MagicMock(id=555)msg.content = "<@1000> thanks!" # no link of its own- msg.mentions = [_mention(1000, "AutoPilot")]+ msg.mentions = [_mention(1000, "AutoGPT")]msg.message_snapshots = []msg.reference = MagicMock(resolved=replied)@@ -971,7 +971,7 @@ class TestReplyContext:msg.guild = guildmsg.channel = MagicMock(id=555)msg.content = "<@1000> look at this" # no link of its own- msg.mentions = [_mention(1000, "AutoPilot")]+ msg.mentions = [_mention(1000, "AutoGPT")]msg.message_snapshots = [_snapshot("see https://discord.com/channels/111/222/333")]diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.pyindex 768abbdf81..2dd47e5d49 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/commands.py@@ -13,12 +13,25 @@ from discord import app_commandsfrom backend.copilot.bot import sessions, threadsfrom backend.copilot.bot.bot_backend import BotBackend, ChatSummary-from backend.util.exceptions import LinkAlreadyExistsError-from backend.util.settings import Settings+from backend.copilot.bot.command_core import CommandReply, setup_reply, unlink_replylogger = logging.getLogger(__name__)+def _reply_view(reply: CommandReply) -> discord.ui.View | None:+ if not (reply.button_label and reply.button_url):+ return None+ view = discord.ui.View()+ view.add_item(+ discord.ui.Button(+ style=discord.ButtonStyle.link,+ label=reply.button_label,+ url=reply.button_url,+ )+ )+ return view++def register(tree: app_commands.CommandTree, api: BotBackend) -> None:"""Register all slash commands on the given CommandTree."""@@ -32,14 +45,14 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:@tree.command(name="setup",- description="Link this server to an AutoGPT account for AutoPilot",+ description="Link this server to an AutoGPT account",)@app_commands.default_permissions(manage_guild=True)async def setup_command(interaction: discord.Interaction) -> None:_track(interaction, "setup")await _handle_setup(interaction, api)- @tree.command(name="help", description="Show AutoPilot bot usage info")+ @tree.command(name="help", description="Show AutoGPT bot usage info")async def help_command(interaction: discord.Interaction) -> None:_track(interaction, "help")await _handle_help(interaction)@@ -54,7 +67,7 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:@tree.command(name="new",- description="Start a fresh AutoPilot conversation in this DM or thread",+ description="Start a fresh AutoGPT conversation in this DM or thread",)async def new_command(interaction: discord.Interaction) -> None:_track(interaction, "new")@@ -62,7 +75,7 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:@tree.command(name="resume",- description="Resume one of your past AutoPilot conversations (DMs only)",+ description="Resume one of your past AutoGPT conversations (DMs only)",)async def resume_command(interaction: discord.Interaction) -> None:_track(interaction, "resume")@@ -70,7 +83,7 @@ def register(tree: app_commands.CommandTree, api: BotBackend) -> None:@tree.command(name="leave",- description="Stop AutoPilot from auto-replying in this thread",+ description="Stop AutoGPT from auto-replying in this thread",)async def leave_command(interaction: discord.Interaction) -> None:_track(interaction, "leave")@@ -95,52 +108,26 @@ async def _handle_setup(interaction: discord.Interaction, api: BotBackend) -> Noreturnawait interaction.response.defer(ephemeral=True)- try:- result = await api.create_link_token(- platform="discord",- platform_server_id=str(interaction.guild.id),- platform_user_id=str(interaction.user.id),- platform_username=interaction.user.display_name,- server_name=interaction.guild.name,- channel_id=str(interaction.channel_id or ""),- )- except LinkAlreadyExistsError:- await interaction.followup.send(- "This server is already linked — just mention me!",- ephemeral=True,- )- return- except Exception:- logger.exception("Failed to create link token")- await interaction.followup.send(- "Something went wrong. Try again later.",- ephemeral=True,- )- return-- view = discord.ui.View()- view.add_item(- discord.ui.Button(- style=discord.ButtonStyle.link,- label="Link Server",- url=result.link_url,- )- )- await interaction.followup.send(- f"**Set up AutoPilot for {interaction.guild.name}**\n\n"- "Click the button below to connect this server to your AutoGPT "- "account. Once confirmed, everyone here can mention me to use "- "AutoPilot.\n\n"- "All usage will be billed to your account.\n"- "This link expires in 30 minutes.",- ephemeral=True,- view=view,+ reply = await setup_reply(+ api,+ platform="discord",+ server_noun="server",+ platform_server_id=str(interaction.guild.id),+ platform_user_id=str(interaction.user.id),+ platform_username=interaction.user.display_name,+ server_name=interaction.guild.name,+ channel_id=str(interaction.channel_id or ""),)+ view = _reply_view(reply)+ if view is None:+ await interaction.followup.send(reply.text, ephemeral=True)+ return+ await interaction.followup.send(reply.text, ephemeral=True, view=view)async def _handle_help(interaction: discord.Interaction) -> None:await interaction.response.send_message(- "**AutoPilot Bot**\n\n"+ "**AutoGPT Bot**\n\n""Mention me in a server or DM me directly to chat.\n\n""**Commands:**\n""- `/setup` — Link this server to your AutoGPT account\n"@@ -156,29 +143,12 @@ async def _handle_help(interaction: discord.Interaction) -> None:async def _handle_unlink(interaction: discord.Interaction) -> None:- config = Settings().config- base_url = config.frontend_base_url or config.platform_base_url- message = (- "Unlinking requires authentication, so it has to be done "- "from the web. Click below to manage your linked accounts."- )-- if not base_url:- await interaction.response.send_message(- f"{message}\n\nOpen AutoGPT on the web and go to " "Settings → Bots.",- ephemeral=True,- )+ reply = unlink_reply()+ view = _reply_view(reply)+ if view is None:+ await interaction.response.send_message(reply.text, ephemeral=True)return-- view = discord.ui.View()- view.add_item(- discord.ui.Button(- style=discord.ButtonStyle.link,- label="Open Settings",- url=f"{base_url}/settings/bots",- )- )- await interaction.response.send_message(message, ephemeral=True, view=view)+ await interaction.response.send_message(reply.text, ephemeral=True, view=view)async def _handle_new(interaction: discord.Interaction) -> None: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 112571f78e..7480c9289b 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@@ -93,7 +93,7 @@ class TestHandleSetup:interaction.followup.send.assert_awaited_once()sent = interaction.followup.send.await_args- assert "Set up AutoPilot for Test Guild" in sent.args[0]+ assert "Set up AutoGPT for Test Guild" in sent.args[0]assert sent.kwargs["view"] is not None@pytest.mark.asyncio@@ -143,7 +143,7 @@ class TestHandleUnlink:fake_settings.config.frontend_base_url = "http://localhost:3000"fake_settings.config.platform_base_url = ""with patch(- "backend.copilot.bot.adapters.discord.commands.Settings",+ "backend.copilot.bot.command_core.Settings",return_value=fake_settings,):await _handle_unlink(interaction)@@ -165,7 +165,7 @@ class TestHandleUnlink:fake_settings.config.frontend_base_url = ""fake_settings.config.platform_base_url = "http://other"with patch(- "backend.copilot.bot.adapters.discord.commands.Settings",+ "backend.copilot.bot.command_core.Settings",return_value=fake_settings,):await _handle_unlink(interaction)@@ -184,7 +184,7 @@ class TestHandleUnlink:fake_settings.config.frontend_base_url = ""fake_settings.config.platform_base_url = ""with patch(- "backend.copilot.bot.adapters.discord.commands.Settings",+ "backend.copilot.bot.command_core.Settings",return_value=fake_settings,):await _handle_unlink(interaction)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro.pyindex 8abc6a10f1..0d4fadfee1 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro.py@@ -1,4 +1,4 @@-"""Welcome message posted when AutoPilot is added to a Discord server."""+"""Welcome message posted when the bot is added to a Discord server."""import discord@@ -23,13 +23,15 @@ def pick_intro_channel(guild: discord.Guild) -> discord.TextChannel | None:def intro_message() -> str:return (- "**Hey, I'm AutoPilot — AutoGPT in your Discord.** Thanks for adding me!\n\n"+ "**Hey, I'm AutoGPT.** Thanks for adding me!\n\n""To get started, a server admin runs `/setup` and follows the link ""to connect this server to an AutoGPT account.\n\n""Once linked, mention me anywhere I can read messages "- "(e.g. `@AutoPilot summarise this channel`) and I'll spin up a "+ "(e.g. `@AutoGPT summarise this channel`) and I'll spin up a ""thread for our chat.\n\n""You can also **DM me** to chat 1:1 — send any message and I'll ""walk you through linking your own DMs.\n\n"- "Commands: `/help` `/setup` `/new`"+ "Commands: `/setup` — link this server • `/new` — start fresh • "+ "`/resume` — pick up a past chat • `/leave` — dismiss me from a "+ "thread • `/help` — everything else")diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro_test.pyindex c8d9d48395..377373985d 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/intro_test.py@@ -71,4 +71,4 @@ def test_no_member_returns_none():def test_intro_message_mentions_setup():msg = intro_message()assert "/setup" in msg- assert "AutoPilot" in msg+ assert "AutoGPT" in msgdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.pyindex 01742538d0..e4b5fbdcc4 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py@@ -33,6 +33,8 @@ from backend.copilot.bot.adapters.base import (MessageContext,PostedRef,WebhookAdapter,+ read_verified_webhook_body,+ unauthorized_webhook_response,)from backend.copilot.bot.adapters.shared import InboundFile, collect_attachmentsfrom backend.copilot.bot.bot_backend import BotBackend@@ -173,9 +175,9 @@ class SlackAdapter(WebhookAdapter):# -- Inbound --async def _handle_event_request(self, request: Request) -> Response:- raw = await request.body()- if not _verify_signature(request, raw):- return PlainTextResponse("invalid signature", status_code=401)+ raw = await read_verified_webhook_body(request, _verify_signature)+ if raw is None:+ return unauthorized_webhook_response()payload = json.loads(raw)if payload.get("type") == "url_verification":return JSONResponse({"challenge": payload.get("challenge", "")})@@ -192,9 +194,8 @@ class SlackAdapter(WebhookAdapter):return PlainTextResponse("ok")async def _handle_command_request(self, request: Request) -> Response:- raw = await request.body()- if not _verify_signature(request, raw):- return PlainTextResponse("invalid signature", status_code=401)+ if await read_verified_webhook_body(request, _verify_signature) is None:+ return unauthorized_webhook_response()form_data = await request.form()# Slack slash-command form data is always string-valued; drop anything# else (UploadFile etc.) defensively before passing on.@@ -400,12 +401,6 @@ class SlackAdapter(WebhookAdapter):returnawait client.chat_postEphemeral(channel=channel, user=user_id, text=text)- async def start_typing(self, channel_id: str) -> None:- pass # Slack bot apps don't expose a typing indicator API.-- async def stop_typing(self, channel_id: str) -> None:- pass-async def create_thread(self, channel_id: str, message_id: str, name: str) -> Optional[str]:@@ -414,9 +409,6 @@ class SlackAdapter(WebhookAdapter):team, channel, _ = _decode_target(channel_id)return _encode_target(team, channel, message_id)- async def rename_thread(self, thread_id: str, name: str) -> bool:- return False # Slack threads have no name.-# -- Proactive output --async def list_text_channels(diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yamlindex cef451b36a..29720dd4df 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/app-manifest.yaml@@ -1,22 +1,22 @@-# Slack app manifest for AutoPilot+# Slack app manifest for AutoGPT## Import at https://api.slack.com/apps → Create New App → From an app manifest.# Once the backend is deployed, fill in <BASE_URL> below with the public origin# of the main backend API (e.g. https://dev-server.agpt.co) and re-import.display_information:- name: AutoPilot- description: AutoPilot — your AutoGPT agent in Slack+ name: AutoGPT+ description: AutoGPT — your AutoGPT agent in Slackbackground_color: "#1a1a1a"long_description: |- AutoPilot brings your AutoGPT account into Slack. Mention @AutoPilot in a+ AutoGPT brings your AutoGPT account into Slack. Mention @AutoGPT in achannel or DM the app to chat with your AutoGPT agent. Run /setup in achannel to link the workspace to your AutoGPT account; DM the app to linkyour own DMs as a personal account.features:bot_user:- display_name: AutoPilot+ display_name: AutoGPTalways_online: trueapp_home:home_tab_enabled: false@@ -29,7 +29,7 @@ features:should_escape: false- command: /helpurl: <BASE_URL>/api/copilot-webhooks/slack/commands- description: How to use AutoPilot in Slack+ description: How to use AutoGPT in Slackshould_escape: false- command: /unlinkurl: <BASE_URL>/api/copilot-webhooks/slack/commands@@ -43,7 +43,7 @@ oauth_config:- <BASE_URL>/api/copilot-webhooks/slack/oauth/callbackscopes:bot:- - app_mentions:read # @AutoPilot in any channel the app is in+ - app_mentions:read # @AutoGPT in any channel the app is in- channels:history # read messages in public channels (for thread follow-ups)- channels:read # list public channels for proactive posting- chat:write # post messages as the botdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.pyindex ca8aa177de..8701872a86 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands.py@@ -1,4 +1,9 @@-"""Slack slash-command handlers — /setup, /help, /unlink."""+"""Slack slash-command handlers — /setup, /help, /unlink.++Policy (link-token minting, already-linked handling, unlink destination) is+shared with every platform via ``command_core``; this module owns only Slack's+transport: form parsing and block-kit rendering.+"""import loggingfrom typing import Any@@ -7,8 +12,9 @@ from fastapi import Responsefrom fastapi.responses import JSONResponsefrom backend.copilot.bot.bot_backend import BotBackend-from backend.util.exceptions import LinkAlreadyExistsError-from backend.util.settings import Settings+from backend.copilot.bot.command_core import CommandReply, setup_reply, unlink_reply++from .text import to_mrkdwnlogger = logging.getLogger(__name__)@@ -20,75 +26,47 @@ async def handle(api: BotBackend, form: dict[str, str]) -> Response:if command == "/help":return _help()if command == "/unlink":- return _unlink()+ return _render(unlink_reply())return _ephemeral(f"Unknown command: {command}")async def _setup(api: BotBackend, form: dict[str, str]) -> Response:team_id = form.get("team_id", "")user_id = form.get("user_id", "")- user_name = form.get("user_name", "")- team_domain = form.get("team_domain", "")- channel_id = form.get("channel_id", "")if not team_id or not user_id:return _ephemeral("Slack didn't send the workspace/user info. Try the command again.")- try:- result = await api.create_link_token(- platform="slack",- platform_server_id=team_id,- platform_user_id=user_id,- platform_username=user_name,- server_name=team_domain,- channel_id=channel_id,- )- except LinkAlreadyExistsError:- return _ephemeral(- "This workspace is already linked to an AutoGPT account — just "- "mention me or DM me to chat. Run /unlink to manage the link."- )- except Exception:- logger.exception("Slack /setup link token creation failed")- return _ephemeral(- "Something went wrong creating the setup link. Try again in a moment."- )-- return _link_response(- text=(- "*Set up AutoPilot for this workspace*\n\n"- "Click the button below to link this workspace to your AutoGPT "- "account. The link expires in 30 minutes."- ),- label="Link Workspace",- url=result.link_url,+ reply = await setup_reply(+ api,+ platform="slack",+ server_noun="workspace",+ platform_server_id=team_id,+ platform_user_id=user_id,+ platform_username=form.get("user_name", ""),+ server_name=form.get("team_domain", ""),+ channel_id=form.get("channel_id", ""),)+ return _render(reply)def _help() -> Response:return _ephemeral(- "*AutoPilot for Slack*\n"+ "*AutoGPT for Slack*\n""• Run `/setup` in this workspace to link it to an AutoGPT account.\n"- "• Mention `@AutoPilot` in a channel to start a conversation in a thread.\n"- "• DM `@AutoPilot` to chat with your personal AutoPilot account.\n"+ "• Mention `@AutoGPT` in a channel to start a conversation in a thread.\n"+ "• DM `@AutoGPT` to chat with your personal AutoGPT account.\n""• Run `/unlink` to manage your linked workspace and DM.")-def _unlink() -> Response:- cfg = Settings().config- base_url = (cfg.frontend_base_url or cfg.platform_base_url).rstrip("/")- if not base_url:- return _ephemeral(- "Settings page isn't configured — ask an admin to set FRONTEND_BASE_URL."- )- return _link_response(- text="Manage your workspace and DM links from your AutoGPT settings.",- label="Open Settings",- url=f"{base_url}/profile/settings",- )+def _render(reply: CommandReply) -> Response:+ text = to_mrkdwn(reply.text)+ if reply.button_label and reply.button_url:+ return _link_response(text=text, label=reply.button_label, url=reply.button_url)+ return _ephemeral(text)def _ephemeral(text: str) -> Response:diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.pyindex 0b1b361cc6..2c16a83198 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/commands_test.py@@ -71,13 +71,11 @@ async def test_unlink_points_at_settings():settings = MagicMock()settings.config.frontend_base_url = "https://app.example"settings.config.platform_base_url = ""- with patch(- "backend.copilot.bot.adapters.slack.commands.Settings", return_value=settings- ):+ with patch("backend.copilot.bot.command_core.Settings", return_value=settings):resp = await commands.handle(MagicMock(), {"command": "/unlink"})assert (_body(resp)["blocks"][1]["elements"][0]["url"]- == "https://app.example/profile/settings"+ == "https://app.example/settings/bots")@@ -86,11 +84,9 @@ async def test_unlink_without_base_url_returns_error():settings = MagicMock()settings.config.frontend_base_url = ""settings.config.platform_base_url = ""- with patch(- "backend.copilot.bot.adapters.slack.commands.Settings", return_value=settings- ):+ with patch("backend.copilot.bot.command_core.Settings", return_value=settings):resp = await commands.handle(MagicMock(), {"command": "/unlink"})- assert "FRONTEND_BASE_URL" in _body(resp)["text"]+ assert "Settings → Bots" in _body(resp)["text"]@pytest.mark.asynciodiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.pyindex 817e33f5e5..fa927f933d 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/oauth.py@@ -154,7 +154,7 @@ def _done(*, ok: bool, detail: str) -> Response:return RedirectResponse(f"{base}/settings/bots?{flag}=1", status_code=302)if ok:return PlainTextResponse(- f"AutoPilot was added to {detail}. You can close this tab and run "+ f"AutoGPT was added to {detail}. You can close this tab and run ""/setup in Slack to link your account.")return PlainTextResponse(f"Slack install failed: {detail}", status_code=400)diff --git a/autogpt_platform/backend/backend/copilot/bot/attachments.py b/autogpt_platform/backend/backend/copilot/bot/attachments.pynew file mode 100644index 0000000000..c548b7eaac--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/attachments.py@@ -0,0 +1,73 @@+"""Inbound attachment upload + user/model-facing failure notes.++The adapter already downloaded the platform files (bounded by its caps); this+uploads them into the turn's workspace session and turns per-file failures into+the two notes every platform shares: one telling the user, one telling the+model which files it does NOT have.+"""++import logging++from .adapters.base import MessageContext+from .bot_backend import BotBackend++logger = logging.getLogger(__name__)++_UPLOAD_ERROR_TEXT: dict[str, str] = {+ "virus_detected": "failed a virus scan",+ "scan_unavailable": "couldn't be virus-scanned right now — try again shortly",+ "rejected": "was too large or would exceed your storage limit",+ "upload_failed": "couldn't be uploaded",+}+++async def upload_attachments(+ api: BotBackend, ctx: MessageContext, session_id: str | None = None+) -> tuple[list[str], list[tuple[str, str]]]:+ """Upload the user's attachments to the workspace.++ ``session_id`` scopes the files to the turn's session so AutoPilot can+ read them. Returns ``(file_ids, problems)`` — the IDs that succeeded,+ and ``(filename, reason)`` for the ones that were rejected — so the+ caller can attach the successes and surface the failures.+ """+ if not ctx.attachments:+ return [], []+ try:+ results = await api.upload_workspace_files(+ platform=ctx.platform,+ platform_user_id=ctx.user_id,+ platform_server_id=ctx.server_id,+ attachments=ctx.attachments,+ session_id=session_id,+ )+ except Exception:+ # The upload path itself failed (not a per-file rejection). Don't+ # drop the message — surface it and let any text still go through.+ logger.exception("Attachment upload failed for user %s", ctx.user_id)+ return [], [(a.filename, "couldn't be uploaded") for a in ctx.attachments]+ file_ids = [r.file_id for r in results if r.file_id]+ problems = [+ (r.filename, _UPLOAD_ERROR_TEXT.get(r.error or "", "couldn't be uploaded"))+ for r in results+ if not r.file_id+ ]+ return file_ids, problems+++def format_attachment_problems(problems: list[tuple[str, str]]) -> str:+ """User-facing note listing attachments that couldn't be attached and why."""+ lines = ["⚠️ Some files couldn't be attached:"]+ for filename, reason in problems:+ lines.append(f"• `{filename}` {reason}")+ return "\n".join(lines)+++def model_attachment_note(problems: list[tuple[str, str]]) -> str:+ """Note injected into the turn so AutoPilot knows which files it does NOT+ have, instead of assuming a dropped attachment was read."""+ listed = ", ".join(f"{filename} ({reason})" for filename, reason in problems)+ return (+ f"[Note: the following attachment(s) could NOT be attached and are "+ f"unavailable to you — do not claim to have read them: {listed}]"+ )diff --git a/autogpt_platform/backend/backend/copilot/bot/command_core.py b/autogpt_platform/backend/backend/copilot/bot/command_core.pynew file mode 100644index 0000000000..3e2e39aecd--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/command_core.py@@ -0,0 +1,108 @@+"""Shared slash-command policy — /setup and /unlink, platform-neutral.++Each adapter owns its transport (Discord interactions, Slack form POSTs) and+its rendering (View buttons vs block kit), but the *policy* — how a link token+is minted, what happens when the server is already linked, where unlink points+— must not drift between platforms. Adapters call these and render the+returned ``CommandReply`` in their own markup.+"""++import logging++from pydantic import BaseModel++from backend.util.exceptions import LinkAlreadyExistsError+from backend.util.settings import Settings++from .bot_backend import BotBackend++logger = logging.getLogger(__name__)+++class CommandReply(BaseModel):+ """A transport-neutral ephemeral reply: text plus an optional link button."""++ text: str+ button_label: str | None = None+ button_url: str | None = None+++async def setup_reply(+ api: BotBackend,+ *,+ platform: str,+ server_noun: str,+ platform_server_id: str,+ platform_user_id: str,+ platform_username: str,+ server_name: str,+ channel_id: str,+) -> CommandReply:+ """Mint a server link token and describe the outcome.++ ``server_noun`` is the platform's word for a server ("server",+ "workspace") so the shared copy reads natively everywhere.+ """+ try:+ result = await api.create_link_token(+ platform=platform,+ platform_server_id=platform_server_id,+ platform_user_id=platform_user_id,+ platform_username=platform_username,+ server_name=server_name,+ channel_id=channel_id,+ )+ except LinkAlreadyExistsError:+ return CommandReply(+ text=(+ f"This {server_noun} is already linked to an AutoGPT account — "+ "just mention me or DM me to chat. Run /unlink to manage the "+ "link."+ )+ )+ except Exception:+ logger.exception("%s /setup link token creation failed", platform)+ return CommandReply(+ text=(+ "Something went wrong creating the setup link. Try again in a "+ "moment."+ )+ )++ display_name = server_name or f"this {server_noun}"+ return CommandReply(+ text=(+ f"**Set up AutoGPT for {display_name}**\n\n"+ f"Click the button below to connect this {server_noun} to your "+ "AutoGPT account. Once confirmed, everyone here can mention me to "+ "use AutoGPT.\n\n"+ "All usage will be billed to your account.\n"+ "This link expires in 30 minutes."+ ),+ button_label=f"Link {server_noun.capitalize()}",+ button_url=result.link_url,+ )+++def unlink_reply() -> CommandReply:+ """Point the user at the Bots settings page — unlinking needs web auth."""+ message = (+ "Unlinking requires authentication, so it has to be done from the "+ "web. Click below to manage your linked accounts."+ )+ base_url = _base_url()+ if not base_url:+ return CommandReply(+ text=f"{message}\n\nOpen AutoGPT on the web and go to Settings → Bots."+ )+ return CommandReply(+ text=message,+ button_label="Open Settings",+ button_url=f"{base_url}/settings/bots",+ )+++def _base_url() -> str | None:+ config = Settings().config+ base_url = (config.frontend_base_url or config.platform_base_url).rstrip("/")+ return base_url or Nonediff --git a/autogpt_platform/backend/backend/copilot/bot/command_core_test.py b/autogpt_platform/backend/backend/copilot/bot/command_core_test.pynew file mode 100644index 0000000000..a8c29743c6--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/command_core_test.py@@ -0,0 +1,80 @@+"""Tests for the shared slash-command policy."""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.util.exceptions import LinkAlreadyExistsError++from .command_core import setup_reply, unlink_reply++_CORE = "backend.copilot.bot.command_core"+++def _api(**overrides) -> MagicMock:+ api = MagicMock()+ api.create_link_token = AsyncMock(+ return_value=MagicMock(link_url="https://x/link/tok"), **overrides+ )+ return api+++async def _setup(api) -> object:+ return await setup_reply(+ api,+ platform="slack",+ server_noun="workspace",+ platform_server_id="T1",+ platform_user_id="U1",+ platform_username="bently",+ server_name="acme",+ channel_id="C1",+ )+++async def test_setup_success_returns_link_button():+ reply = await _setup(_api())+ assert reply.button_url == "https://x/link/tok"+ assert reply.button_label == "Link Workspace"+ assert "Set up AutoGPT for acme" in reply.text+ assert "expires in 30 minutes" in reply.text+++async def test_setup_already_linked_is_friendly_not_error():+ api = _api()+ api.create_link_token = AsyncMock(side_effect=LinkAlreadyExistsError("dup"))+ reply = await _setup(api)+ assert reply.button_url is None+ assert "already linked" in reply.text+ assert "workspace" in reply.text # platform's own noun+++async def test_setup_failure_returns_generic_message():+ api = _api()+ api.create_link_token = AsyncMock(side_effect=RuntimeError("boom"))+ reply = await _setup(api)+ assert reply.button_url is None+ assert "went wrong" in reply.text.lower()+++def test_unlink_points_at_settings_bots():+ fake = MagicMock()+ fake.config.frontend_base_url = "https://app.example"+ fake.config.platform_base_url = ""+ with patch(f"{_CORE}.Settings", return_value=fake):+ reply = unlink_reply()+ assert reply.button_url == "https://app.example/settings/bots"+ assert reply.button_label == "Open Settings"+++def test_unlink_without_base_url_falls_back_to_text():+ fake = MagicMock()+ fake.config.frontend_base_url = ""+ fake.config.platform_base_url = ""+ with patch(f"{_CORE}.Settings", return_value=fake):+ reply = unlink_reply()+ assert reply.button_url is None+ assert "Settings → Bots" in reply.textdiff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.pyindex ff5fd38092..d6ec78feb1 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py@@ -1,46 +1,32 @@"""Platform-agnostic message handler.-Receives a MessageContext from any adapter and drives the full AutoPilot-interaction: link resolution, thread routing, batched streaming with a-persistent typing indicator.+Receives a MessageContext from any adapter and orchestrates the turn: link+resolution, thread routing, attachment ingestion, then batched streaming.+The streaming machinery itself lives in ``turn_stream``; prompt assembly in+``prompt``; attachment upload + failure notes in ``attachments``."""import asyncioimport logging-import time-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.data.sharing.workspace_refs import (- WorkspaceArtifactLink,- extract_artifact_links,-)++from pydantic import BaseModel, Field+from backend.platform_linking.models import TurnDenial-from backend.util.exceptions import (- DuplicateChatMessageError,- LinkAlreadyExistsError,- NotFoundError,-)-from backend.util.settings import Settings+from backend.util.exceptions import LinkAlreadyExistsErrorfrom . import sessions, threads-from .adapters.base import (- FileAttachment,- MessageContext,- MessageHistoryEntry,- PlatformAdapter,+from .adapters.base import MessageContext, PlatformAdapter+from .attachments import (+ format_attachment_problems,+ model_attachment_note,+ upload_attachments,)-from .bot_backend import BotBackend, BotStreamError, ChatTurnDeniedError-from .config import SESSION_TTL-from .text import format_batch, split_at_boundary+from .bot_backend import BotBackend+from .prompt import build_message_text, build_thread_name+from .turn_stream import TurnStreamer, send_deniallogger = logging.getLogger(__name__)-THREAD_NAME_PREFIX = "AutoPilot: "-TITLE_RENAME_ATTEMPTS = 5-TITLE_RENAME_INTERVAL_SECONDS = 1.0# Cap on file IDs carried into a single turn — must stay <= the# ``BotChatRequest.file_ids`` ``max_length``. Batching several file-heavy# messages can accumulate more than that; cap so the turn runs (with a log)@@ -48,8 +34,7 @@ TITLE_RENAME_INTERVAL_SECONDS = 1.0MAX_TURN_FILE_IDS = 20-@dataclass-class TargetState:+class TargetState(BaseModel):"""Per-target streaming state.A "target" is wherever the bot replies — a thread ID, a DM channel ID.@@ -58,11 +43,11 @@ class TargetState:"""processing: bool = False- pending: list[tuple[str, str, str]] = field(default_factory=list)# Each entry: (username, user_id, text)+ pending: list[tuple[str, str, str]] = Field(default_factory=list)# Workspace file IDs uploaded for messages in `pending`, drained together# with them so a batched turn carries every attached file.- pending_file_ids: list[str] = field(default_factory=list)+ pending_file_ids: list[str] = Field(default_factory=list)# Session the pending attachments were uploaded to, carried straight to the# turn so it uses the same session (not a separate Redis read that could# diverge). None for text-only batches, which resolve the session normally.@@ -72,82 +57,12 @@ class TargetState:class MessageHandler:def __init__(self, api: BotBackend):self._api = api+ self._streamer = TurnStreamer(api)self._targets: dict[str, TargetState] = {}# Per-target lock serialising session resolution, so two attachment# messages racing on a fresh target converge on ONE session instead of# each creating its own and splitting the files across them.self._session_locks: dict[str, asyncio.Lock] = {}- # Strong-ref set so the GC doesn't drop fire-and-forget rename tasks.- self._rename_tasks: set[asyncio.Task[None]] = set()-- def _session_lock(self, target_id: str) -> asyncio.Lock:- lock = self._session_locks.get(target_id)- if lock is None:- lock = asyncio.Lock()- self._session_locks[target_id] = lock- return lock-- async def _resolve_session_for_attachments(- self, ctx: MessageContext, target_id: str- ) -> tuple[str | None, TurnDenial | None]:- """Resolve (or create) the session this message's attachments upload- into, so they land where the turn will read them (``/sessions/<id>/``).-- Serialised per target so concurrent attachment messages converge on one- session instead of splitting the files. Returns ``(session_id, None)``- on success, ``(None, denial)`` when the turn gate refused the user- (the caller renders the denial and skips the upload + turn), and- ``(None, None)`` on failure — the caller then reports the files as- un-attachable rather than uploading them somewhere AutoPilot can't see.- """- async with self._session_lock(target_id):- try:- result = await self._api.ensure_session(- platform=ctx.platform,- platform_user_id=ctx.user_id,- platform_server_id=ctx.server_id,- session_id=await sessions.get_session(ctx.platform, target_id),- )- if result.denial is not None:- return None, result.denial- if result.session_id:- await sessions.set_session(- ctx.platform, target_id, result.session_id- )- return result.session_id, None- except Exception:- logger.exception(- "Failed to resolve session for uploads (user %s)", ctx.user_id- )- return None, None-- async def _send_denial(- self,- ctx: MessageContext,- adapter: PlatformAdapter,- target_id: str,- denial: TurnDenial,- ) -> None:- """Render a turn denial: message plus CTA button when configured."""- logger.info("Turn denied (%s) for target %s", denial.reason, target_id)- self._api.track_event(- platform=ctx.platform,- event_type="turn_denied",- server_id=ctx.server_id,- channel_type=ctx.channel_type,- error_kind=denial.reason,- )- if denial.button_url and denial.button_label:- await adapter.send_link(- target_id,- denial.message,- link_label=denial.button_label,- link_url=denial.button_url,- )- else:- await adapter.send_message(- target_id, denial.message, mentionable_users=ctx.mentionable_users- )async def handle(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:if not ctx.text.strip() and not ctx.attachments:@@ -170,7 +85,7 @@ class MessageHandler:if not ctx.bot_mentioned:return# First time we're @-ed into this thread — pull the recent- # thread history into the prompt so AutoPilot has context,+ # thread history into the prompt so AutoGPT has context,# but DON'T subscribe. Future messages here need another @.include_thread_history = True@@ -190,7 +105,7 @@ class MessageHandler:)# Attachments must be written into the turn's session folder so- # AutoPilot can read them (same as a web upload), and the turn must run+ # AutoGPT can read them (same as a web upload), and the turn must run# in that same session — resolve it up front and thread it through.session_id: str | None = Nonefile_ids: list[str]@@ -203,29 +118,29 @@ class MessageHandler:# The turn gate refused the user before anything was uploaded —# render the denial and stop; no file is scanned or stored and# no turn runs.- await self._send_denial(ctx, adapter, target_id, denial)+ await send_denial(self._api, ctx, adapter, target_id, denial)returnif session_id is None:# Without a session the files can't be made readable to- # AutoPilot, so report them as failed rather than uploading+ # AutoGPT, so report them as failed rather than uploading# them somewhere it can't see.file_ids = []upload_problems = [(a.filename, "couldn't be uploaded") for a in ctx.attachments]else:- file_ids, upload_problems = await self._upload_attachments(- ctx, session_id+ file_ids, upload_problems = await upload_attachments(+ self._api, ctx, session_id)else:- file_ids, upload_problems = await self._upload_attachments(ctx)+ file_ids, upload_problems = await upload_attachments(self._api, ctx)# Files that didn't make it: adapter-stage (too large / failed download)# plus upload-stage (virus / quota). Tell the user AND, below, the model# — so neither assumes a dropped file was actually read.problems = list(ctx.skipped_attachments) + upload_problemsif problems:- await adapter.send_message(target_id, _format_attachment_problems(problems))+ await adapter.send_message(target_id, format_attachment_problems(problems))# Decide on NEW input only — typed text or a usable upload. Thread# history (folded into the prompt below) is context, not a reason to@@ -238,50 +153,58 @@ class MessageHandler:await threads.unsubscribe(ctx.platform, target_id)return- # A file-only message gets a nudge so AutoPilot looks at the uploads+ # A file-only message gets a nudge so AutoGPT looks at the uploads# instead of seeing an empty "[Current message]".current_text = ctx.text if ctx.text.strip() else "(see the attached file(s))"message_text = self._message_text(ctx, include_thread_history, current_text)if problems:- message_text += "\n\n" + _model_attachment_note(problems)+ message_text += "\n\n" + model_attachment_note(problems)await self._enqueue_and_process(ctx, adapter, target_id, message_text, file_ids, session_id)- async def _upload_attachments(- self, ctx: MessageContext, session_id: str | None = None- ) -> tuple[list[str], list[tuple[str, str]]]:- """Upload the user's attachments to the workspace.+ # -- Session + target resolution --- ``session_id`` scopes the files to the turn's session so AutoPilot can- read them. Returns ``(file_ids, problems)`` — the IDs that succeeded,- and ``(filename, reason)`` for the ones that were rejected — so the- caller can attach the successes and surface the failures.+ def _session_lock(self, target_id: str) -> asyncio.Lock:+ lock = self._session_locks.get(target_id)+ if lock is None:+ lock = asyncio.Lock()+ self._session_locks[target_id] = lock+ return lock++ async def _resolve_session_for_attachments(+ self, ctx: MessageContext, target_id: str+ ) -> tuple[str | None, TurnDenial | None]:+ """Resolve (or create) the session this message's attachments upload+ into, so they land where the turn will read them (``/sessions/<id>/``).++ Serialised per target so concurrent attachment messages converge on one+ session instead of splitting the files. Returns ``(session_id, None)``+ on success, ``(None, denial)`` when the turn gate refused the user+ (the caller renders the denial and skips the upload + turn), and+ ``(None, None)`` on failure — the caller then reports the files as+ un-attachable rather than uploading them somewhere AutoGPT can't see."""- if not ctx.attachments:- return [], []- try:- results = await self._api.upload_workspace_files(- platform=ctx.platform,- platform_user_id=ctx.user_id,- platform_server_id=ctx.server_id,- attachments=ctx.attachments,- session_id=session_id,- )- except Exception:- # The upload path itself failed (not a per-file rejection). Don't- # drop the message — surface it and let any text still go through.- logger.exception("Attachment upload failed for user %s", ctx.user_id)- return [], [(a.filename, "couldn't be uploaded") for a in ctx.attachments]- file_ids = [r.file_id for r in results if r.file_id]- problems = [- (r.filename, _UPLOAD_ERROR_TEXT.get(r.error or "", "couldn't be uploaded"))- for r in results- if not r.file_id- ]- return file_ids, problems-- # -- Target resolution --+ async with self._session_lock(target_id):+ try:+ result = await self._api.ensure_session(+ platform=ctx.platform,+ platform_user_id=ctx.user_id,+ platform_server_id=ctx.server_id,+ session_id=await sessions.get_session(ctx.platform, target_id),+ )+ if result.denial is not None:+ return None, result.denial+ if result.session_id:+ await sessions.set_session(+ ctx.platform, target_id, result.session_id+ )+ return result.session_id, None+ except Exception:+ logger.exception(+ "Failed to resolve session for uploads (user %s)", ctx.user_id+ )+ return None, Noneasync def _resolve_target(self, ctx: MessageContext, adapter: PlatformAdapter@@ -305,7 +228,7 @@ class MessageHandler:await threads.subscribe(ctx.platform, thread_id)return thread_id- # -- Batched streaming --+ # -- Batching --def _message_text(self,@@ -313,50 +236,20 @@ class MessageHandler:include_thread_history: bool,current_text: str | None = None,) -> str:- # ``current_text`` overrides ``ctx.text`` as the "current message" body- # (e.g. a nudge for a file-only message); defaults to the raw text.- text = ctx.text if current_text is None else current_text- # Referenced conversations (links/@-mentions the user pasted) are always- # surfaced — that's the whole point of fetching them. Thread history is- # only included on the first @-into a thread we don't own; a subscribed- # thread's prior turns already live in the session.- thread_history = ctx.thread_history if include_thread_history else ()- if not thread_history and not ctx.referenced_conversations:- return text-- platform_display = ctx.platform.capitalize()- lines: list[str] = []- if ctx.referenced_conversations:- # The user pointed at other channels/threads; their content is- # already fetched and inlined below. Lead with a firm instruction so- # the model answers from it instead of fixating on the link and- # claiming it can't access the platform.- lines.append(- f"[The {platform_display} channel(s) the user referenced have "- f"already been read for you — their full content is included "- f"below under each #name. Answer directly from it. Do NOT say you "- f"can't open links or access {platform_display}; you already have "- f"the content.]"- )- for convo in ctx.referenced_conversations:- lines.append(f"\n[Content of #{convo.title}]")- for entry in convo.messages:- lines.append(self._format_history_entry(entry, platform_display))- if thread_history:- lines.append("\n[Recent thread context before this message]")- for entry in thread_history:- lines.append(self._format_history_entry(entry, platform_display))- lines.append(f"\n[Current message]\n{text}")- return "\n".join(lines)-- @staticmethod- def _format_history_entry(entry: MessageHistoryEntry, platform_display: str) -> str:- user = (- f"{entry.username} ({platform_display} user ID: {entry.user_id})"- if entry.user_id- else entry.username+ return build_message_text(ctx, include_thread_history, current_text)++ async def _stream_batch(+ self,+ batch: list[tuple[str, str, str]],+ ctx: MessageContext,+ adapter: PlatformAdapter,+ target_id: str,+ file_ids: list[str] | None = None,+ session_id: str | None = None,+ ) -> None:+ await self._streamer.stream_batch(+ batch, ctx, adapter, target_id, file_ids=file_ids, session_id=session_id)- return f"\n[From {user}]\n{entry.text}"async def _enqueue_and_process(self,@@ -412,373 +305,6 @@ class MessageHandler:if not state.pending:self._targets.pop(target_id, None)- async def _send_text_and_artifacts(- self,- adapter: PlatformAdapter,- target_id: str,- text: str,- ctx: MessageContext,- session_id: str | None,- ) -> bool:- """Send a finished chunk of text, then any workspace artifacts it- referenced. Returns True if anything was sent to the channel.-- Each artifact gets its own platform message — files attach inline- when small enough, otherwise we drop a link button pointing at the- chat on the platform so the user can grab it from there.- """- stripped, artifacts = extract_artifact_links(text)- sent_any = False- if stripped:- await adapter.send_message(- target_id, stripped, mentionable_users=ctx.mentionable_users- )- sent_any = True- for artifact in artifacts:- sent = await self._deliver_artifact(- adapter, target_id, artifact, session_id- )- sent_any = sent_any or sent- return sent_any-- async def _deliver_artifact(- self,- adapter: PlatformAdapter,- target_id: str,- artifact: WorkspaceArtifactLink,- session_id: str | None,- ) -> bool:- """Attach the file inline when possible; otherwise drop a link to- the chat on the platform. Returns whether anything was sent."""- if session_id is None:- # Can't fetch or build a link button without a session id. Surface- # the artifact name as plain text so the user knows something was- # produced, even if they can't grab it from here.- logger.warning(- "Workspace artifact %s referenced before session id known",- artifact.file_id,- )- await self._send_artifact_note(adapter, target_id, artifact)- return True- if await self._attach_artifact(adapter, target_id, artifact, session_id):- return True- await self._send_artifact_fallback(adapter, target_id, artifact, session_id)- return True-- async def _attach_artifact(- self,- adapter: PlatformAdapter,- target_id: str,- artifact: WorkspaceArtifactLink,- session_id: str,- ) -> bool:- """Fetch and inline-attach the file. Returns False when it's missing,- unowned, too large, or the fetch errored."""- try:- fetched = await self._api.fetch_workspace_artifact(- session_id=session_id,- file_id=artifact.file_id,- max_bytes=adapter.max_attachment_bytes,- )- except Exception:- logger.exception("Failed to fetch workspace artifact %s", artifact.file_id)- return False- if fetched is None:- return False- await adapter.send_file(- target_id,- text="",- file=FileAttachment(- filename=artifact.display_name or fetched.filename,- mime_type=fetched.mime_type,- content=fetched.content,- ),- )- return True-- async def _send_artifact_fallback(- self,- adapter: PlatformAdapter,- target_id: str,- artifact: WorkspaceArtifactLink,- session_id: str,- ) -> None:- """Link the user to the chat when the file can't be attached here —- covers missing, unavailable, errored and too-large cases alike."""- session_url = _copilot_session_url(session_id)- if session_url is None:- logger.warning(- "No base URL configured; can't render fallback link for %s",- artifact.file_id,- )- await self._send_artifact_note(adapter, target_id, artifact)- return- await adapter.send_link(- target_id,- f"Open AutoGPT to download `{artifact.display_name}`.",- link_label="Open in AutoGPT",- link_url=session_url,- )-- async def _send_artifact_note(- self,- adapter: PlatformAdapter,- target_id: str,- artifact: WorkspaceArtifactLink,- ) -> None:- await adapter.send_message(- target_id,- f"_(produced `{artifact.display_name}` — open the chat to download)_",- )-- async def _stream_batch(- self,- batch: list[tuple[str, str, str]],- ctx: MessageContext,- adapter: PlatformAdapter,- target_id: str,- file_ids: list[str] | None = None,- session_id: str | None = None,- ) -> None:- prefixed = format_batch(batch, ctx.platform)-- redis = await get_redis_async()- cache_key = sessions.session_cache_key(ctx.platform, target_id)- if session_id is not None:- # Attachments were already uploaded to this session — use it- # directly so the turn can't diverge from where the files went.- active_session_id: str | None = session_id- else:- 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:- logger.warning("Failed to cache session id for target %s", target_id)-- 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 active_session_id, buffer, sent_any_content, setup_prompt_sent- if setup_prompt_sent:- return- setup_prompt_sent = True- # This callback carries the authoritative session id — adopt it so- # buffered workspace artifacts resolve instead of falling back to- # the "no session" plain-text note.- active_session_id = session_id- # Drain any pending text first so the link button doesn't render- # ahead of the message it belongs to.- if buffer.strip():- if await self._send_text_and_artifacts(- adapter, target_id, buffer, ctx, session_id- ):- sent_any_content = True- 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,- )-- async def _on_setup_dropped(- session_id: str,- _tool_name: str | None,- ) -> None:- nonlocal active_session_id, buffer, sent_any_content- active_session_id = session_id- # Drain pending text first so the notice doesn't jump ahead of the- # message it follows.- if buffer.strip():- if await self._send_text_and_artifacts(- adapter, target_id, buffer, ctx, session_id- ):- sent_any_content = True- buffer = ""- sent_any_content = True- await adapter.send_message(- target_id,- _setup_dropped_message(),- mentionable_users=ctx.mentionable_users,- )-- started_at = time.monotonic()- reply_chars = 0- typing_task = asyncio.create_task(_keep_typing(adapter, target_id))- try:- async for chunk in self._api.stream_chat(- platform=ctx.platform,- platform_user_id=ctx.user_id,- message=prefixed,- session_id=active_session_id,- platform_server_id=ctx.server_id,- file_ids=file_ids,- on_session_id=_on_session_id,- on_setup_required=_on_setup_required,- on_setup_dropped=_on_setup_dropped,- ):- buffer += chunk- reply_chars += len(chunk)- if len(buffer) >= flush_at:- post, buffer = split_at_boundary(buffer, flush_at)- if post and post.strip():- if await self._send_text_and_artifacts(- adapter, target_id, post, ctx, active_session_id- ):- sent_any_content = True- except ChatTurnDeniedError as exc:- # Refused before running (paywall / rate limit). Show the message- # and, when present, a CTA button (Subscribe / Upgrade).- await self._send_denial(ctx, adapter, target_id, exc.denial)- return- except DuplicateChatMessageError:- # Another in-flight turn is already processing this exact message —- # stay quiet so the user doesn't get a double response.- logger.info("Duplicate message dropped for target %s", target_id)- return- except BotStreamError as exc:- # Stream couldn't complete (timeout, subscribe fail, backend stream- # error). Track the specific kind, surface a generic message, and- # do NOT fire reply_sent below.- logger.warning(- "Stream failed for target %s: %s (%s)",- target_id,- exc,- exc.error_kind,- )- self._track_stream_error(ctx, exc.error_kind)- await adapter.send_message(- target_id,- "AutoPilot ran into an error. Try again in a moment.",- )- return- except NotFoundError:- logger.exception("Chat turn rejected")- self._track_stream_error(ctx, "chat_turn_rejected")- await adapter.send_message(- target_id, "AutoPilot ran into an error. Try again later."- )- return- except Exception:- logger.exception(- "Unexpected error during streaming for target %s", target_id- )- self._track_stream_error(ctx, "stream_exception")- await adapter.send_message(- target_id,- "Something went wrong. Try again in a moment.",- )- return- finally:- typing_task.cancel()- try:- await typing_task- except asyncio.CancelledError:- pass- await adapter.stop_typing(target_id)-- if buffer.strip():- if await self._send_text_and_artifacts(- adapter, target_id, buffer, ctx, active_session_id- ):- sent_any_content = True-- if not sent_any_content:- await adapter.send_message(- target_id,- "AutoPilot didn't produce a response. Try rephrasing your question.",- )- self._track_stream_error(ctx, "empty_reply")- return-- self._api.track_event(- platform=ctx.platform,- event_type="reply_sent",- server_id=ctx.server_id,- channel_type=ctx.channel_type,- char_count=reply_chars,- duration_ms=int((time.monotonic() - started_at) * 1000),- )-- 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, adapter.max_thread_name_length)- )- return- if attempt < TITLE_RENAME_ATTEMPTS - 1:- await asyncio.sleep(TITLE_RENAME_INTERVAL_SECONDS)-- def _track_stream_error(self, ctx: MessageContext, error_kind: str) -> None:- self._api.track_event(- platform=ctx.platform,- event_type="stream_error",- server_id=ctx.server_id,- channel_type=ctx.channel_type,- error_kind=error_kind,- )-# -- Linking --async def _ensure_linked(@@ -833,7 +359,7 @@ class MessageHandler:ctx.channel_id,f"Your {platform_display} DMs aren't linked to an AutoGPT ""account yet. Click below to connect — once linked, you can "- "chat with AutoPilot right here.",+ "chat with AutoGPT right here.",link_label="Link Account",link_url=result.link_url,)@@ -854,98 +380,3 @@ class MessageHandler:ctx.channel_id,"Something went wrong setting up the link. Try again later.",)---async def _keep_typing(adapter: PlatformAdapter, target_id: str) -> None:- """Re-fire the typing indicator so it doesn't expire mid-stream.-- Cadence is the adapter's ``typing_refresh_interval`` — platform indicators- auto-expire at different rates.- """- try:- while True:- await adapter.start_typing(target_id)- await asyncio.sleep(adapter.typing_refresh_interval)- except asyncio.CancelledError:- raise- except Exception:- logger.debug("Typing loop error", exc_info=True)---_UPLOAD_ERROR_TEXT: dict[str, str] = {- "virus_detected": "failed a virus scan",- "scan_unavailable": "couldn't be virus-scanned right now — try again shortly",- "rejected": "was too large or would exceed your storage limit",- "upload_failed": "couldn't be uploaded",-}---def _format_attachment_problems(problems: list[tuple[str, str]]) -> str:- """User-facing note listing attachments that couldn't be attached and why."""- lines = ["⚠️ Some files couldn't be attached:"]- for filename, reason in problems:- lines.append(f"• `{filename}` {reason}")- return "\n".join(lines)---def _model_attachment_note(problems: list[tuple[str, str]]) -> str:- """Note injected into the turn so AutoPilot knows which files it does NOT- have, instead of assuming a dropped attachment was read."""- listed = ", ".join(f"{filename} ({reason})" for filename, reason in problems)- return (- f"[Note: the following attachment(s) could NOT be attached and are "- f"unavailable to you — do not claim to have read them: {listed}]"- )---def build_thread_name(text: str, username: str, max_length: int) -> str:- """Build a thread name from the user's first prompt, clamped to the- platform's ``max_length``."""- cleaned = " ".join(text.split())- if not cleaned:- cleaned = f"{username} with AutoPilot"- return clamp_thread_name(f"{THREAD_NAME_PREFIX}{cleaned}", max_length)---def clamp_thread_name(name: str, max_length: int) -> str:- cleaned = " ".join(name.split()) or "AutoPilot Chat"- if len(cleaned) <= max_length:- return cleaned- # Below the ellipsis width a tiny adapter cap can't fit "…", and a- # negative slice index would overrun the limit — hard-cut instead.- ellipsis = "..."- if max_length <= len(ellipsis):- return cleaned[:max_length]- return cleaned[: max_length - len(ellipsis)].rstrip() + ellipsis---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_dropped_message() -> str:- return (- "⚠️ AutoPilot tried to send you a sign-in link, but the data arrived "- "corrupted so the button couldn't be shown. Please ask it to try that "- "step again."- )---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.pyindex 594059ffb3..fb80e66f9d 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py@@ -22,13 +22,8 @@ from .adapters.base import (ReferencedConversation,)from .bot_backend import ChatTurnDeniedError, LinkTokenResult, ResolveResult-from .handler import (- MAX_TURN_FILE_IDS,- MessageHandler,- TargetState,- build_thread_name,- clamp_thread_name,-)+from .handler import MAX_TURN_FILE_IDS, MessageHandler, TargetState+from .prompt import build_thread_name, clamp_thread_namedef _ctx(@@ -121,7 +116,7 @@ def _capture_handler_tasks():return taskwith patch(- "backend.copilot.bot.handler.asyncio.create_task",+ "backend.copilot.bot.turn_stream.asyncio.create_task",side_effect=_capturing,):yield tasks@@ -255,7 +250,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"+ assert adapter.create_thread.await_args.args[2] == "AutoGPT: hello bot"@pytest.mark.asyncioasync def test_channel_falls_back_to_parent_when_thread_creation_fails(self):@@ -273,7 +268,7 @@ class TestThreadAdoption:# turn so the user gets an answer, but DON'T subscribe — future# messages here need another @ to wake it back up. This keeps the# bot from hijacking ongoing team conversations. The reply should- # carry the thread history so AutoPilot has context.+ # carry the thread history so AutoGPT has context.handler = MessageHandler(_api())adapter = _adapter()enqueue = AsyncMock()@@ -471,7 +466,7 @@ class TestBatching:adapter = _adapter()with patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),):await handler._stream_batch(@@ -505,10 +500,12 @@ class TestBatching:with (patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),),- patch("backend.copilot.bot.handler.Settings", return_value=fake_settings),+ patch(+ "backend.copilot.bot.turn_stream.Settings", return_value=fake_settings+ ),):await handler._stream_batch([("Bently", "u1", "hi")], _ctx(), adapter, "target-1"@@ -551,10 +548,12 @@ class TestBatching:with (patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),),- patch("backend.copilot.bot.handler.Settings", return_value=fake_settings),+ patch(+ "backend.copilot.bot.turn_stream.Settings", return_value=fake_settings+ ),):await handler._stream_batch([("Bently", "u1", "hi")], _ctx(), adapter, "target-1"@@ -579,7 +578,7 @@ class TestBatching:with (patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=redis),),patch(@@ -619,7 +618,7 @@ class TestBatching:with (patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=redis),),patch(@@ -659,7 +658,7 @@ class TestBatching:with (patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=redis),),patch(@@ -682,14 +681,14 @@ class TestBatching:class TestStreamFallback:"""Covers the empty-response fallback, including the boundary-flush bug- where prior code posted 'AutoPilot didn't produce a response' even though+ where prior code posted 'AutoGPT didn't produce a response' even thoughcontent had already been flushed mid-stream."""@staticmethoddef _redis_patch():return patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),)@@ -767,13 +766,13 @@ class TestThreadNames:def test_build_thread_name_from_prompt(self):assert (build_thread_name(" tell me\nabout space ", "Bently", 100)- == "AutoPilot: tell me about space"+ == "AutoGPT: tell me about space")def test_build_thread_name_truncates_to_platform_limit(self):name = build_thread_name("x" * 200, "Bently", 100)assert len(name) <= 100- assert name.startswith("AutoPilot: ")+ assert name.startswith("AutoGPT: ")assert name.endswith("...")def test_build_thread_name_respects_a_larger_limit(self):@@ -787,7 +786,7 @@ class TestThreadNames:)def test_clamp_thread_name_falls_back_when_blank(self):- assert clamp_thread_name(" ", 100) == "AutoPilot Chat"+ assert clamp_thread_name(" ", 100) == "AutoGPT Chat"def test_clamp_thread_name_never_overruns_a_tiny_cap(self):# A tiny adapter cap must not make the slice index go negative.@@ -813,7 +812,7 @@ class TestDeliverArtifact:)text = "Here is your result: [chart.png](workspace://abc#image/png)"- await handler._send_text_and_artifacts(+ await handler._streamer._send_text_and_artifacts(adapter, "target-1", text, _ctx(), "sess-1")@@ -841,8 +840,10 @@ class TestDeliverArtifact:fake_settings.config.frontend_base_url = "https://app.example.com"fake_settings.config.platform_base_url = ""- with patch("backend.copilot.bot.handler.Settings", return_value=fake_settings):- await handler._send_text_and_artifacts(+ with patch(+ "backend.copilot.bot.turn_stream.Settings", return_value=fake_settings+ ):+ await handler._streamer._send_text_and_artifacts(adapter,"target-1","[big.zip](workspace://big)",@@ -876,8 +877,10 @@ class TestDeliverArtifact:fake_settings.config.frontend_base_url = "https://app.example.com"fake_settings.config.platform_base_url = ""- with patch("backend.copilot.bot.handler.Settings", return_value=fake_settings):- await handler._send_text_and_artifacts(+ with patch(+ "backend.copilot.bot.turn_stream.Settings", return_value=fake_settings+ ):+ await handler._streamer._send_text_and_artifacts(adapter, "target-1", "[x.png](workspace://x)", _ctx(), "sess-1")@@ -896,7 +899,7 @@ class TestDeliverArtifact:handler = MessageHandler(_api())adapter = _adapter()- await handler._send_text_and_artifacts(+ await handler._streamer._send_text_and_artifacts(adapter, "target-1", "[x.png](workspace://x)", _ctx(), None)@@ -975,7 +978,7 @@ class TestAttachments:),patch("backend.copilot.bot.handler.sessions.set_session", new=AsyncMock()),patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=redis),),):@@ -1053,7 +1056,7 @@ class TestAttachments:await handler.handle(self._dm_ctx("look", [("a.png", "image/png")]), adapter)- # Files are NOT uploaded sessionless (where AutoPilot couldn't read+ # Files are NOT uploaded sessionless (where AutoGPT couldn't read# them); the user is told they couldn't be attached and no file_ids# reach the turn.api.upload_workspace_files.assert_not_awaited()@@ -1326,7 +1329,7 @@ class TestTurnDenied:raise ChatTurnDeniedError(TurnDenial(reason="paywalled",- message="AutoPilot needs an active subscription.",+ message="AutoGPT needs an active subscription.",button_label="Subscribe",button_url="https://app.example/settings/billing",)@@ -1338,7 +1341,7 @@ class TestTurnDenied:adapter = _adapter()with patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),):await handler._stream_batch(@@ -1365,7 +1368,7 @@ class TestTurnDenied:adapter = _adapter()with patch(- "backend.copilot.bot.handler.get_redis_async",+ "backend.copilot.bot.turn_stream.get_redis_async",new=AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=None))),):await handler._stream_batch(diff --git a/autogpt_platform/backend/backend/copilot/bot/prompt.py b/autogpt_platform/backend/backend/copilot/bot/prompt.pynew file mode 100644index 0000000000..172ed68125--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/prompt.py@@ -0,0 +1,85 @@+"""Prompt and thread-name assembly for bot turns.++Pure text-building: how a platform message (plus optional thread history and+referenced conversations) becomes the model's prompt, and how thread names are+derived and clamped to a platform's cap. No I/O.+"""++from .adapters.base import MessageContext, MessageHistoryEntry++THREAD_NAME_PREFIX = "AutoGPT: "+++def build_message_text(+ ctx: MessageContext,+ include_thread_history: bool,+ current_text: str | None = None,+) -> str:+ """Assemble the turn's prompt from the current message plus any context.++ ``current_text`` overrides ``ctx.text`` as the "current message" body+ (e.g. a nudge for a file-only message); defaults to the raw text.+ Referenced conversations (links/@-mentions the user pasted) are always+ surfaced — that's the whole point of fetching them. Thread history is+ only included on the first @-into a thread we don't own; a subscribed+ thread's prior turns already live in the session.+ """+ text = ctx.text if current_text is None else current_text+ thread_history = ctx.thread_history if include_thread_history else ()+ if not thread_history and not ctx.referenced_conversations:+ return text++ platform_display = ctx.platform.capitalize()+ lines: list[str] = []+ if ctx.referenced_conversations:+ # The user pointed at other channels/threads; their content is+ # already fetched and inlined below. Lead with a firm instruction so+ # the model answers from it instead of fixating on the link and+ # claiming it can't access the platform.+ lines.append(+ f"[The {platform_display} channel(s) the user referenced have "+ f"already been read for you — their full content is included "+ f"below under each #name. Answer directly from it. Do NOT say you "+ f"can't open links or access {platform_display}; you already have "+ f"the content.]"+ )+ for convo in ctx.referenced_conversations:+ lines.append(f"\n[Content of #{convo.title}]")+ for entry in convo.messages:+ lines.append(format_history_entry(entry, platform_display))+ if thread_history:+ lines.append("\n[Recent thread context before this message]")+ for entry in thread_history:+ lines.append(format_history_entry(entry, platform_display))+ lines.append(f"\n[Current message]\n{text}")+ return "\n".join(lines)+++def format_history_entry(entry: MessageHistoryEntry, platform_display: str) -> str:+ user = (+ f"{entry.username} ({platform_display} user ID: {entry.user_id})"+ if entry.user_id+ else entry.username+ )+ return f"\n[From {user}]\n{entry.text}"+++def build_thread_name(text: str, username: str, max_length: int) -> str:+ """Build a thread name from the user's first prompt, clamped to the+ platform's ``max_length``."""+ cleaned = " ".join(text.split())+ if not cleaned:+ cleaned = f"{username} with AutoGPT"+ return clamp_thread_name(f"{THREAD_NAME_PREFIX}{cleaned}", max_length)+++def clamp_thread_name(name: str, max_length: int) -> str:+ cleaned = " ".join(name.split()) or "AutoGPT Chat"+ if len(cleaned) <= max_length:+ return cleaned+ # Below the ellipsis width a tiny adapter cap can't fit "…", and a+ # negative slice index would overrun the limit — hard-cut instead.+ ellipsis = "..."+ if max_length <= len(ellipsis):+ return cleaned[:max_length]+ return cleaned[: max_length - len(ellipsis)].rstrip() + ellipsisdiff --git a/autogpt_platform/backend/backend/copilot/bot/turn_stream.py b/autogpt_platform/backend/backend/copilot/bot/turn_stream.pynew file mode 100644index 0000000000..59015df512--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/turn_stream.py@@ -0,0 +1,490 @@+"""Streaming one batched turn to a platform target.++Owns everything between "a batch of messages is ready" and "the reply is fully+delivered": the AutoGPT stream, chunked sends with a persistent typing+indicator, workspace-artifact delivery, setup-required prompts, error surfaces,+and the post-turn thread rename. The orchestration (batching, linking, target+resolution) stays in ``handler``.+"""++import asyncio+import logging+import time+from typing import Any+from urllib.parse import quote++from backend.data.redis_client import get_redis_async+from backend.data.sharing.workspace_refs import (+ WorkspaceArtifactLink,+ extract_artifact_links,+)+from backend.platform_linking.models import TurnDenial+from backend.util.exceptions import DuplicateChatMessageError, NotFoundError+from backend.util.settings import Settings++from . import sessions+from .adapters.base import FileAttachment, MessageContext, PlatformAdapter+from .bot_backend import BotBackend, BotStreamError, ChatTurnDeniedError+from .config import SESSION_TTL+from .prompt import clamp_thread_name+from .text import format_batch, split_at_boundary++logger = logging.getLogger(__name__)++TITLE_RENAME_ATTEMPTS = 5+TITLE_RENAME_INTERVAL_SECONDS = 1.0+++async def send_denial(+ api: BotBackend,+ ctx: MessageContext,+ adapter: PlatformAdapter,+ target_id: str,+ denial: TurnDenial,+) -> None:+ """Render a turn denial: message plus CTA button when configured."""+ logger.info("Turn denied (%s) for target %s", denial.reason, target_id)+ api.track_event(+ platform=ctx.platform,+ event_type="turn_denied",+ server_id=ctx.server_id,+ channel_type=ctx.channel_type,+ error_kind=denial.reason,+ )+ if denial.button_url and denial.button_label:+ await adapter.send_link(+ target_id,+ denial.message,+ link_label=denial.button_label,+ link_url=denial.button_url,+ )+ else:+ await adapter.send_message(+ target_id, denial.message, mentionable_users=ctx.mentionable_users+ )+++class TurnStreamer:+ def __init__(self, api: BotBackend):+ self._api = api+ # Strong-ref set so the GC doesn't drop fire-and-forget rename tasks.+ self._rename_tasks: set[asyncio.Task[None]] = set()++ async def stream_batch(+ self,+ batch: list[tuple[str, str, str]],+ ctx: MessageContext,+ adapter: PlatformAdapter,+ target_id: str,+ file_ids: list[str] | None = None,+ session_id: str | None = None,+ ) -> None:+ prefixed = format_batch(batch, ctx.platform)++ redis = await get_redis_async()+ cache_key = sessions.session_cache_key(ctx.platform, target_id)+ if session_id is not None:+ # Attachments were already uploaded to this session — use it+ # directly so the turn can't diverge from where the files went.+ active_session_id: str | None = session_id+ else:+ 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:+ logger.warning("Failed to cache session id for target %s", target_id)++ 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 active_session_id, buffer, sent_any_content, setup_prompt_sent+ if setup_prompt_sent:+ return+ setup_prompt_sent = True+ # This callback carries the authoritative session id — adopt it so+ # buffered workspace artifacts resolve instead of falling back to+ # the "no session" plain-text note.+ active_session_id = session_id+ # Drain any pending text first so the link button doesn't render+ # ahead of the message it belongs to.+ if buffer.strip():+ if await self._send_text_and_artifacts(+ adapter, target_id, buffer, ctx, session_id+ ):+ sent_any_content = True+ 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,+ )++ async def _on_setup_dropped(+ session_id: str,+ _tool_name: str | None,+ ) -> None:+ nonlocal active_session_id, buffer, sent_any_content+ active_session_id = session_id+ # Drain pending text first so the notice doesn't jump ahead of the+ # message it follows.+ if buffer.strip():+ if await self._send_text_and_artifacts(+ adapter, target_id, buffer, ctx, session_id+ ):+ sent_any_content = True+ buffer = ""+ sent_any_content = True+ await adapter.send_message(+ target_id,+ _setup_dropped_message(),+ mentionable_users=ctx.mentionable_users,+ )++ started_at = time.monotonic()+ reply_chars = 0+ typing_task = asyncio.create_task(_keep_typing(adapter, target_id))+ try:+ async for chunk in self._api.stream_chat(+ platform=ctx.platform,+ platform_user_id=ctx.user_id,+ message=prefixed,+ session_id=active_session_id,+ platform_server_id=ctx.server_id,+ file_ids=file_ids,+ on_session_id=_on_session_id,+ on_setup_required=_on_setup_required,+ on_setup_dropped=_on_setup_dropped,+ ):+ buffer += chunk+ reply_chars += len(chunk)+ if len(buffer) >= flush_at:+ post, buffer = split_at_boundary(buffer, flush_at)+ if post and post.strip():+ if await self._send_text_and_artifacts(+ adapter, target_id, post, ctx, active_session_id+ ):+ sent_any_content = True+ except ChatTurnDeniedError as exc:+ # Refused before running (paywall / rate limit). Show the message+ # and, when present, a CTA button (Subscribe / Upgrade).+ await send_denial(self._api, ctx, adapter, target_id, exc.denial)+ return+ except DuplicateChatMessageError:+ # Another in-flight turn is already processing this exact message —+ # stay quiet so the user doesn't get a double response.+ logger.info("Duplicate message dropped for target %s", target_id)+ return+ except BotStreamError as exc:+ # Stream couldn't complete (timeout, subscribe fail, backend stream+ # error). Track the specific kind, surface a generic message, and+ # do NOT fire reply_sent below.+ logger.warning(+ "Stream failed for target %s: %s (%s)",+ target_id,+ exc,+ exc.error_kind,+ )+ self._track_stream_error(ctx, exc.error_kind)+ await adapter.send_message(+ target_id,+ "AutoGPT ran into an error. Try again in a moment.",+ )+ return+ except NotFoundError:+ logger.exception("Chat turn rejected")+ self._track_stream_error(ctx, "chat_turn_rejected")+ await adapter.send_message(+ target_id, "AutoGPT ran into an error. Try again later."+ )+ return+ except Exception:+ logger.exception(+ "Unexpected error during streaming for target %s", target_id+ )+ self._track_stream_error(ctx, "stream_exception")+ await adapter.send_message(+ target_id,+ "Something went wrong. Try again in a moment.",+ )+ return+ finally:+ typing_task.cancel()+ try:+ await typing_task+ except asyncio.CancelledError:+ pass+ await adapter.stop_typing(target_id)++ if buffer.strip():+ if await self._send_text_and_artifacts(+ adapter, target_id, buffer, ctx, active_session_id+ ):+ sent_any_content = True++ if not sent_any_content:+ await adapter.send_message(+ target_id,+ "AutoGPT didn't produce a response. Try rephrasing your question.",+ )+ self._track_stream_error(ctx, "empty_reply")+ return++ self._api.track_event(+ platform=ctx.platform,+ event_type="reply_sent",+ server_id=ctx.server_id,+ channel_type=ctx.channel_type,+ char_count=reply_chars,+ duration_ms=int((time.monotonic() - started_at) * 1000),+ )++ 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)++ # -- Artifact delivery --++ async def _send_text_and_artifacts(+ self,+ adapter: PlatformAdapter,+ target_id: str,+ text: str,+ ctx: MessageContext,+ session_id: str | None,+ ) -> bool:+ """Send a finished chunk of text, then any workspace artifacts it+ referenced. Returns True if anything was sent to the channel.++ Each artifact gets its own platform message — files attach inline+ when small enough, otherwise we drop a link button pointing at the+ chat on the platform so the user can grab it from there.+ """+ stripped, artifacts = extract_artifact_links(text)+ sent_any = False+ if stripped:+ await adapter.send_message(+ target_id, stripped, mentionable_users=ctx.mentionable_users+ )+ sent_any = True+ for artifact in artifacts:+ sent = await self._deliver_artifact(+ adapter, target_id, artifact, session_id+ )+ sent_any = sent_any or sent+ return sent_any++ async def _deliver_artifact(+ self,+ adapter: PlatformAdapter,+ target_id: str,+ artifact: WorkspaceArtifactLink,+ session_id: str | None,+ ) -> bool:+ """Attach the file inline when possible; otherwise drop a link to+ the chat on the platform. Returns whether anything was sent."""+ if session_id is None:+ # Can't fetch or build a link button without a session id. Surface+ # the artifact name as plain text so the user knows something was+ # produced, even if they can't grab it from here.+ logger.warning(+ "Workspace artifact %s referenced before session id known",+ artifact.file_id,+ )+ await self._send_artifact_note(adapter, target_id, artifact)+ return True+ if await self._attach_artifact(adapter, target_id, artifact, session_id):+ return True+ await self._send_artifact_fallback(adapter, target_id, artifact, session_id)+ return True++ async def _attach_artifact(+ self,+ adapter: PlatformAdapter,+ target_id: str,+ artifact: WorkspaceArtifactLink,+ session_id: str,+ ) -> bool:+ """Fetch and inline-attach the file. Returns False when it's missing,+ unowned, too large, or the fetch errored."""+ try:+ fetched = await self._api.fetch_workspace_artifact(+ session_id=session_id,+ file_id=artifact.file_id,+ max_bytes=adapter.max_attachment_bytes,+ )+ except Exception:+ logger.exception("Failed to fetch workspace artifact %s", artifact.file_id)+ return False+ if fetched is None:+ return False+ await adapter.send_file(+ target_id,+ text="",+ file=FileAttachment(+ filename=artifact.display_name or fetched.filename,+ mime_type=fetched.mime_type,+ content=fetched.content,+ ),+ )+ return True++ async def _send_artifact_fallback(+ self,+ adapter: PlatformAdapter,+ target_id: str,+ artifact: WorkspaceArtifactLink,+ session_id: str,+ ) -> None:+ """Link the user to the chat when the file can't be attached here —+ covers missing, unavailable, errored and too-large cases alike."""+ session_url = copilot_session_url(session_id)+ if session_url is None:+ logger.warning(+ "No base URL configured; can't render fallback link for %s",+ artifact.file_id,+ )+ await self._send_artifact_note(adapter, target_id, artifact)+ return+ await adapter.send_link(+ target_id,+ f"Open AutoGPT to download `{artifact.display_name}`.",+ link_label="Open in AutoGPT",+ link_url=session_url,+ )++ async def _send_artifact_note(+ self,+ adapter: PlatformAdapter,+ target_id: str,+ artifact: WorkspaceArtifactLink,+ ) -> None:+ await adapter.send_message(+ target_id,+ f"_(produced `{artifact.display_name}` — open the chat to download)_",+ )++ # -- Post-turn --++ 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, adapter.max_thread_name_length)+ )+ return+ if attempt < TITLE_RENAME_ATTEMPTS - 1:+ await asyncio.sleep(TITLE_RENAME_INTERVAL_SECONDS)++ def _track_stream_error(self, ctx: MessageContext, error_kind: str) -> None:+ self._api.track_event(+ platform=ctx.platform,+ event_type="stream_error",+ server_id=ctx.server_id,+ channel_type=ctx.channel_type,+ error_kind=error_kind,+ )+++async def _keep_typing(adapter: PlatformAdapter, target_id: str) -> None:+ """Re-fire the typing indicator so it doesn't expire mid-stream.++ Cadence is the adapter's ``typing_refresh_interval`` — platform indicators+ auto-expire at different rates.+ """+ try:+ while True:+ await adapter.start_typing(target_id)+ await asyncio.sleep(adapter.typing_refresh_interval)+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.debug("Typing loop error", exc_info=True)+++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_dropped_message() -> str:+ return (+ "⚠️ AutoGPT tried to send you a sign-in link, but the data arrived "+ "corrupted so the button couldn't be shown. Please ask it to try that "+ "step again."+ )+++def _setup_required_message(setup_output: dict[str, Any]) -> str:+ message = str(setup_output.get("message") or "").strip()+ if not message:+ message = (+ "AutoGPT 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/util/architecture_test.py b/autogpt_platform/backend/backend/util/architecture_test.pyindex 0a68969098..cffb2e4873 100644--- a/autogpt_platform/backend/backend/util/architecture_test.py+++ b/autogpt_platform/backend/backend/util/architecture_test.py@@ -126,7 +126,6 @@ _DATACLASS_KNOWN_OFFENDERS = frozenset("copilot/baseline/service.py","copilot/bot/adapters/base.py","copilot/bot/bot_backend.py",- "copilot/bot/handler.py","copilot/sdk/compaction.py","copilot/sdk/file_ref.py","copilot/sdk/service.py",diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsxindex c4f36c4fa1..eff3e51422 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/__tests__/page.test.tsx@@ -146,7 +146,7 @@ describe("PlatformLinkPage", () => {expect(await screen.findByRole("heading", {- name: /set up autopilot for builders guild/i,+ name: /set up autogpt for builders guild/i,}),).toBeDefined();expect(screen.getByText(/signed in as [email protected]/i)).toBeDefined();@@ -156,11 +156,29 @@ describe("PlatformLinkPage", () => {);expect(- await screen.findByRole("heading", { name: /autopilot is ready/i }),+ await screen.findByRole("heading", { name: /autogpt is ready/i }),).toBeDefined();expect(screen.getByText(/builders guild/i)).toBeDefined();});+ test("falls back to a generic title when the server has no name", async () => {+ server.use(+ getGetPlatformLinkingGetDisplayInfoForALinkTokenMockHandler200({+ platform: "DISCORD",+ link_type: LinkType.SERVER,+ server_name: null,+ }),+ );++ render(<PlatformLinkPage />);++ expect(+ await screen.findByRole("heading", {+ name: /set up autogpt for this discord server/i,+ }),+ ).toBeDefined();+ });+test("loads user link details and confirms the user link endpoint", async () => {let serverConfirmCalls = 0;let userConfirmCalls = 0;@@ -206,7 +224,7 @@ describe("PlatformLinkPage", () => {);expect(- await screen.findByRole("heading", { name: /autopilot is ready/i }),+ await screen.findByRole("heading", { name: /autogpt is ready/i }),).toBeDefined();expect(userConfirmCalls).toBe(1);expect(serverConfirmCalls).toBe(0);diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsxindex 6e30901e3f..02d02cf92e 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/LoadingView.tsx@@ -8,7 +8,7 @@ interface Props {}export function LoadingView({- title = "Setting up AutoPilot",+ title = "Setting up AutoGPT",message = "Loading...",}: Props) {return (diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsxindex 24d161b88b..4b5a2ccefc 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/NotAuthenticatedView.tsx@@ -15,7 +15,7 @@ export function NotAuthenticatedView({ token, loginRedirect }: Props) {variant="body-medium"className="text-center text-muted-foreground">- Sign in to your AutoGPT account to finish setting up AutoPilot.+ Sign in to your AutoGPT account to finish setting up AutoGPT.</Text><Button as="NextLink" href={loginRedirect} className="w-full">Sign indiff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsxindex d1cac69e6a..2eb3189295 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/ReadyView.tsx@@ -39,16 +39,20 @@ export function ReadyView({{forUser ? (<ul className="mt-3 space-y-2 text-sm text-muted-foreground"><li>{contextLabel} will be linked to your AutoGPT account</li>- <li>DMs with the bot run as your personal AutoPilot</li>+ <li>DMs with the bot run as your own private AutoGPT chat</li><li>All usage from those DMs is billed to your account</li></ul>) : (<ul className="mt-3 space-y-2 text-sm text-muted-foreground"><li>{contextLabel} will be connected to your AutoGPT account</li>- <li>Everyone in the server can chat with AutoPilot</li>- <li>Each person gets their own private conversation</li>+ <li>Anyone in the server can give AutoGPT tasks</li><li>- All usage from the server is billed to your AutoGPT account+ Server conversations are shared — for private 1:1 work, DM the+ bot and link your own AutoGPT account+ </li>+ <li>+ Uses the tools and integrations connected to your AutoGPT+ account</li></ul>)}@@ -56,8 +60,8 @@ export function ReadyView({<div className="w-full rounded-xl border border-border bg-muted p-4"><Text variant="small" className="text-muted-foreground">- Usage from {contextLabel} will be billed to your AutoGPT account.- You can unlink at any time from your account settings.+ Usage from {contextLabel} is billed to your AutoGPT account. You can+ unlink at any time in Settings → Bots.</Text></div>@@ -98,6 +102,6 @@ function buildTitle(args: {serverName: string | null;}): string {if (args.forUser) return `Link your ${args.platform} DMs`;- if (args.serverName) return `Set up AutoPilot for ${args.serverName}`;- return `Set up AutoPilot for this ${args.platform} server`;+ if (args.serverName) return `Set up AutoGPT for ${args.serverName}`;+ return `Set up AutoGPT for this ${args.platform} server`;}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsxindex 02b7afc6fe..b096037057 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/link/[token]/components/SuccessView.tsx@@ -15,11 +15,11 @@ export function SuccessView({ linkType, platform, serverName }: Props) {const label =forUser || !serverName ? `your ${platform} account` : serverName;const detail = forUser- ? `You can now chat with AutoPilot in your ${platform} DMs.`- : `Everyone in the server can start using AutoPilot right away.`;+ ? `You can now chat with AutoGPT in your ${platform} DMs.`+ : `Everyone in the server can start using AutoGPT right away.`;return (- <AuthCard title="AutoPilot is ready!">+ <AuthCard title="AutoGPT is ready!"><div className="flex w-full flex-col items-center gap-6"><div className="flex h-16 w-16 items-center justify-center rounded-full bg-green-100"><CheckCircle size={40} weight="fill" className="text-green-600" />diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsxindex 3ccfa9e702..f7a0faba21 100644--- a/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/settings/bots/components/BotCard/BotCardServerList.tsx@@ -27,7 +27,8 @@ export function BotCardServerList({<div className="rounded-large border border-dashed border-zinc-200 px-4 py-3"><Text variant="small" as="span" className="text-zinc-500">No servers linked yet. Use "Add bot to {platformName}" to- invite the bot.+ invite the bot — already added it? Run <code>/setup</code> there to+ finish connecting.</Text></div>);