AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend): let AutoPilot edit its own chat-platform messages (#14436)
Bently28d332fb3604
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.pyindex 9e899454d4..32e9a5389c 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py@@ -107,16 +107,50 @@ class ChannelInfo(BaseModel):server_name: Optional[str] = None+class EditOutcome(Enum):+ """Result of a proactive edit — see ``PlatformAdapter.edit_channel_message``.++ Distinct from a bool so the caller can surface *why* an edit didn't land:+ the platform never supports edits at all (``UNSUPPORTED``), the target+ message is gone or too old to touch (``NOT_FOUND``), or the platform+ rejected the call for another reason — wrong author, no permission, body+ too long (``FAILED``).+ """++ OK = "ok"+ UNSUPPORTED = "unsupported"+ NOT_FOUND = "not_found"+ FAILED = "failed"++class PostedRef(BaseModel):"""Pointer to something the bot just created on the platform.``url`` is a best-effort permalink (Discord ``jump_url``) so callers cansurface a clickable link in their confirmation; platforms withoutpermalinks leave it ``None``.++ ``id`` is always a *message* reference — the thing ``edit_channel_message``+ takes. ``channel_id`` is where that message lives when it differs from the+ channel the caller posted to: creating a thread posts the body inside the+ new thread, so an edit has to target the thread, not its parent. Follow-up+ posts use it too, so a thread stays one conversation. ``None`` means "the+ channel you posted to".++ ``chunk_count`` and ``editable`` describe what ``id`` can still be done+ to. A post split across the platform's message cap has ``id`` pointing at+ the *first* chunk only, so editing it would rewrite the opening and leave+ the rest stale. ``editable=False`` marks a ref with no message behind it+ at all — a thread that was created but whose body failed to post — which+ is surfaced so the caller doesn't retry into a duplicate thread, but+ cannot be edited. Both are refused rather than half-applied."""id: strurl: Optional[str] = None+ channel_id: Optional[str] = None+ chunk_count: int = 1+ editable: bool = True@dataclass@@ -454,6 +488,20 @@ class PlatformAdapter(ABC):"""...+ async def edit_channel_message(+ self, channel_id: str, ref_id: str, text: str+ ) -> EditOutcome:+ """Edit a message this bot previously posted via ``post_channel_message``.++ ``channel_id``/``ref_id`` are exactly what that call (or+ ``create_channel_thread``) returned — adapters that encode extra state+ into those ids (Slack) must decode the same way as their send path.+ Default: unsupported — platforms without a wired edit call (or not yet+ implemented) simply inherit this rather than every caller special-casing+ ``NotImplementedError``.+ """+ return EditOutcome.UNSUPPORTED+class SocketAdapter(PlatformAdapter):"""Adapter that owns a long-lived connection (Discord Gateway, Slack Socketdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.pyindex 327a3cdd04..1fc4374007 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py@@ -28,6 +28,7 @@ from backend.copilot.bot.text import iter_chunks, resolve_mentionsfrom ..base import (ChannelInfo,ChannelType,+ EditOutcome,FileAttachment,InboundAttachment,MessageCallback,@@ -157,12 +158,22 @@ class DiscordAdapter(SocketAdapter):``Client.get_channel`` only reads the in-memory cache, so it missesthreads the bot hasn't seen since its last restart. Fall back to``fetch_channel`` (REST) so long-lived threads keep working.++ ``channel_id`` reaches here as a caller-supplied string (a model-chosen+ edit target, a raw proactive-post ID) that was never guaranteed to look+ like a snowflake, so the ``int()`` conversion is inside the guarded+ block rather than raising ``ValueError`` straight out to the RPC layer."""- channel = self._client.get_channel(int(channel_id))+ try:+ numeric_id = int(channel_id)+ except ValueError:+ logger.warning("Channel id %r is not a valid snowflake", channel_id)+ return None+ channel = self._client.get_channel(numeric_id)if channel is not None:return channeltry:- return await self._client.fetch_channel(int(channel_id))+ return await self._client.fetch_channel(numeric_id)except (discord.NotFound, discord.Forbidden, discord.HTTPException):logger.warning("Channel %s not found or inaccessible", channel_id)return None@@ -353,13 +364,13 @@ class DiscordAdapter(SocketAdapter):logger.warning("Cannot post to non-messageable channel %s", channel_id)return Nonetry:- first = await self._send_chunked(channel, text)+ first, sent = await self._send_chunked(channel, text)except discord.HTTPException:logger.exception("Failed to post message to channel %s", channel_id)return Noneif first is None:return None- return PostedRef(id=str(first.id), url=first.jump_url)+ return PostedRef(id=str(first.id), url=first.jump_url, chunk_count=sent)async def create_channel_thread(self, channel_id: str, name: str, text: str@@ -379,20 +390,67 @@ class DiscordAdapter(SocketAdapter):# The thread now exists on Discord. Surface its ref even if posting the# body fails, so the caller reports partial success and doesn't retry# into a duplicate thread.+ first: Optional[discord.Message] = None+ sent = 0try:- await self._send_chunked(thread, text)+ first, sent = await self._send_chunked(thread, text)except discord.HTTPException:logger.exception("Thread %s created but posting its content failed", thread.id)- return PostedRef(id=str(thread.id), url=thread.jump_url)+ if first is None:+ # A thread with no body: there is no message to edit, but the+ # thread id still has to reach the caller.+ return PostedRef(+ id=str(thread.id),+ url=thread.jump_url,+ channel_id=str(thread.id),+ editable=False,+ )+ # `id` is the body message so it can be edited; `channel_id` is the+ # thread, both because that is where the message lives and because+ # follow-up posts belong in the thread rather than its parent.+ return PostedRef(+ id=str(first.id),+ url=first.jump_url,+ channel_id=str(thread.id),+ chunk_count=sent,+ )++ async def edit_channel_message(+ self, channel_id: str, ref_id: str, text: str+ ) -> EditOutcome:+ channel = await self._resolve_channel(channel_id)+ if channel is None or not isinstance(channel, discord.abc.Messageable):+ return EditOutcome.NOT_FOUND+ try:+ message = await channel.fetch_message(int(ref_id))+ except ValueError:+ return EditOutcome.NOT_FOUND+ except discord.NotFound:+ return EditOutcome.NOT_FOUND+ except discord.HTTPException:+ logger.exception("Failed to fetch message %s for edit", ref_id)+ return EditOutcome.FAILED+ rendered, allowed = _resolve_mentions(+ text, await self._mentionables_for(channel, text, ())+ )+ try:+ await message.edit(content=rendered, allowed_mentions=allowed)+ except discord.HTTPException:+ # Covers both a rejected edit (message too old/foreign author) and+ # a body over Discord's cap — either way the edit did not land.+ logger.exception("Failed to edit message %s", ref_id)+ return EditOutcome.FAILED+ return EditOutcome.OKasync def _send_chunked(self, channel: discord.abc.Messageable, text: str- ) -> Optional[discord.Message]:+ ) -> tuple[Optional[discord.Message], int]:"""Send ``text`` to ``channel``, splitting at natural boundaries to stayunder Discord's per-message cap. Returns the first message sent (the one- callers permalink to), or ``None`` if there was nothing to send.+ callers permalink to) and how many chunks actually landed, or+ ``(None, 0)`` if there was nothing to send.Raises only if the *first* chunk fails — once anything is delivered, alater-chunk failure stops the send and keeps the partial result rather@@ -402,6 +460,7 @@ class DiscordAdapter(SocketAdapter):text, await self._mentionables_for(channel, text, ()))first: Optional[discord.Message] = None+ sent = 0for chunk in iter_chunks(rendered, config.CHUNK_FLUSH_AT):try:msg = await channel.send(chunk, tts=False, allowed_mentions=allowed)@@ -410,9 +469,10 @@ class DiscordAdapter(SocketAdapter):raiselogger.exception("Dropping trailing chunk after partial send")break+ sent += 1if first is None:first = msg- return first+ return first, sent# -- Internal --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 957880fd61..512f0bd831 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@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport discordimport pytest-from backend.copilot.bot.adapters.base import FileAttachment+from backend.copilot.bot.adapters.base import EditOutcome, FileAttachmentfrom backend.copilot.bot.adapters.discord.adapter import (MAX_INBOUND_ATTACHMENTS,THREAD_HISTORY_CHAR_BUDGET,@@ -1479,6 +1479,16 @@ class TestProactiveOutput:)assert await adapter.get_channel_server_id("10") is None+ @pytest.mark.asyncio+ async def test_get_channel_server_id_none_for_non_numeric_id(self):+ # A non-snowflake channel_id (a caller-chosen edit target, not+ # necessarily one that passed the numeric-ID grammar check first)+ # must resolve to None rather than raise ValueError out of int().+ adapter, client = _bare_adapter()++ assert await adapter.get_channel_server_id("not-a-snowflake") is None+ client.get_channel.assert_not_called()+@pytest.mark.asyncioasync def test_post_channel_message_returns_ref_with_url(self):adapter, client = _bare_adapter()@@ -1500,14 +1510,21 @@ class TestProactiveOutput:thread = MagicMock(spec=discord.Thread)thread.id = 555thread.jump_url = "https://discord.com/channels/1/555"- thread.send = AsyncMock()+ body = MagicMock()+ body.id = 901+ body.jump_url = "https://discord.com/channels/1/555/901"+ thread.send = AsyncMock(return_value=body)channel.create_thread = AsyncMock(return_value=thread)client.get_channel.return_value = channelref = await adapter.create_channel_thread("10", "Monday update", "body")assert ref is not None- assert ref.id == "555"+ # `id` addresses the body message so it can be edited; `channel_id`+ # is the thread, where the message lives and where follow-ups go.+ assert ref.id == "901"+ assert ref.channel_id == "555"+ assert ref.editable is Truechannel.create_thread.assert_awaited_once()thread.send.assert_awaited()@@ -1583,7 +1600,91 @@ class TestProactiveOutput:ref = await adapter.create_channel_thread("10", "Monday", "body")assert ref is not None+ # The thread exists, so its id must reach the caller (a retry would+ # duplicate it), but there is no body message to edit.assert ref.id == "777"+ assert ref.channel_id == "777"+ assert ref.editable is False++ @pytest.mark.asyncio+ async def test_edit_channel_message_edits_in_place(self):+ adapter, client = _bare_adapter()+ channel = MagicMock(spec=discord.TextChannel)+ message = MagicMock()+ message.edit = AsyncMock()+ channel.fetch_message = AsyncMock(return_value=message)+ client.get_channel.return_value = channel++ outcome = await adapter.edit_channel_message("10", "999", "updated text")++ assert outcome == EditOutcome.OK+ message.edit.assert_awaited_once()+ assert message.edit.call_args.kwargs["content"] == "updated text"+ # An edit carries model-authored content, so it must pass the same+ # mention suppressor as a send — without it, "@everyone" in an edit+ # pings the server.+ allowed = message.edit.call_args.kwargs["allowed_mentions"]+ assert allowed.everyone is False+ assert allowed.roles is False++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found_when_message_missing(self):+ adapter, client = _bare_adapter()+ channel = MagicMock(spec=discord.TextChannel)+ channel.fetch_message = AsyncMock(+ side_effect=discord.NotFound(MagicMock(status=404), "gone")+ )+ client.get_channel.return_value = channel++ outcome = await adapter.edit_channel_message("10", "999", "updated text")++ assert outcome == EditOutcome.NOT_FOUND++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found_for_bad_ref_id(self):+ adapter, client = _bare_adapter()+ channel = MagicMock(spec=discord.TextChannel)+ client.get_channel.return_value = channel++ outcome = await adapter.edit_channel_message("10", "not-a-number", "x")++ assert outcome == EditOutcome.NOT_FOUND++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found_for_non_numeric_channel_id(self):+ adapter, client = _bare_adapter()++ outcome = await adapter.edit_channel_message("not-a-snowflake", "999", "x")++ assert outcome == EditOutcome.NOT_FOUND+ client.get_channel.assert_not_called()++ @pytest.mark.asyncio+ async def test_edit_channel_message_failed_when_platform_rejects(self):+ adapter, client = _bare_adapter()+ channel = MagicMock(spec=discord.TextChannel)+ message = MagicMock()+ message.edit = AsyncMock(+ side_effect=discord.HTTPException(MagicMock(status=403), "forbidden")+ )+ channel.fetch_message = AsyncMock(return_value=message)+ client.get_channel.return_value = channel++ outcome = await adapter.edit_channel_message("10", "999", "updated text")++ assert outcome == EditOutcome.FAILED++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found_for_non_messageable_channel(self):+ adapter, client = _bare_adapter()+ client.get_channel.return_value = None+ client.fetch_channel = AsyncMock(+ side_effect=discord.NotFound(MagicMock(status=404), "gone")+ )++ outcome = await adapter.edit_channel_message("10", "999", "x")++ assert outcome == EditOutcome.NOT_FOUND# ── Referenced-conversation fetch ──────────────────────────────────────diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.pyindex b91fbfb714..f86ccda804 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py@@ -24,12 +24,14 @@ from typing import Any, Optionalimport httpxfrom fastapi import FastAPI, Request, Responsefrom fastapi.responses import JSONResponse, PlainTextResponse+from slack_sdk.errors import SlackApiErrorfrom slack_sdk.web.async_client import AsyncWebClientfrom backend.copilot.bot import choices, threadsfrom backend.copilot.bot.adapters.base import (ChannelInfo,ChannelType,+ EditOutcome,FileAttachment,MessageCallback,MessageContext,@@ -739,11 +741,15 @@ class SlackAdapter(WebhookAdapter):self, channel_id: str, text: str) -> Optional[PostedRef]:team, channel, thread_ts = _decode_target(channel_id)- first_ts = await self._post_chunked(team, channel, text, thread_ts=thread_ts)+ first_ts, sent = await self._post_chunked(+ team, channel, text, thread_ts=thread_ts+ )if first_ts is None:return Nonereturn PostedRef(- id=first_ts, url=await self._permalink(team, channel, first_ts)+ id=first_ts,+ url=await self._permalink(team, channel, first_ts),+ chunk_count=sent,)async def create_channel_thread(@@ -752,18 +758,54 @@ class SlackAdapter(WebhookAdapter):# Slack threads are implicit + unnamed: post text as the root message;# the returned ref threads subsequent sends off it.team, channel, _ = _decode_target(channel_id)- root_ts = await self._post_chunked(team, channel, text)+ root_ts, sent = await self._post_chunked(team, channel, text)if root_ts is None:return None+ # `id` is the root message's ts so it can be edited; `channel_id`+ # carries the encoded target whose thread_ts keeps follow-up sends+ # threaded under it.return PostedRef(- id=_encode_target(team, channel, root_ts),+ id=root_ts,url=await self._permalink(team, channel, root_ts),+ channel_id=_encode_target(team, channel, root_ts),+ chunk_count=sent,)+ async def edit_channel_message(+ self, channel_id: str, ref_id: str, text: str+ ) -> EditOutcome:+ team, channel, _ = _decode_target(channel_id)+ client = await self._client_for(team)+ if client is None:+ return EditOutcome.FAILED+ try:+ # `blocks=[]` is required, not cosmetic: chat.update keeps the+ # message's existing blocks when the field is omitted, so editing+ # a block message (every `send_link` card) would change nothing+ # visible while still reporting success.+ await client.chat_update(+ channel=channel,+ ts=ref_id,+ text=self.localize_markup(text),+ blocks=[],+ )+ except SlackApiError as e:+ if e.response.get("error") == "message_not_found":+ return EditOutcome.NOT_FOUND+ logger.warning(+ "Slack chat.update rejected edit: %s", e.response.get("error")+ )+ return EditOutcome.FAILED+ except Exception:+ logger.exception("Failed to edit Slack message %s", ref_id)+ return EditOutcome.FAILED+ return EditOutcome.OK+async def _post_chunked(self, team_id: str, channel: str, text: str, thread_ts: Optional[str] = None- ) -> Optional[str]:- """Post ``text`` chunked under the message cap; return the first ts.+ ) -> tuple[Optional[str], int]:+ """Post ``text`` chunked under the message cap; return the first ts+ and how many chunks landed.Later chunks thread off the first so a long post stays one conversation.@@ -776,8 +818,9 @@ class SlackAdapter(WebhookAdapter):"""client = await self._client_for(team_id)if client is None:- return None+ return None, 0first_ts = thread_ts+ sent = 0posted = Falsefor rendered in self._localized_chunks(text, config.CHUNK_FLUSH_AT):try:@@ -792,9 +835,10 @@ class SlackAdapter(WebhookAdapter):logger.exception("Dropping trailing Slack chunk after partial send")breakposted = True+ sent += 1if first_ts is None:first_ts = resp.get("ts")- return first_ts+ return first_ts, sentdef _localized_chunks(self, text: str, flush_at: int) -> Iterator[str]:"""Chunk the canonical markdown, then localize each chunk, so a cutdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.pyindex bf6a576988..bd2f9eab0f 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter_test.py@@ -7,7 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom slack_sdk.errors import SlackApiError-from backend.copilot.bot.adapters.base import FileAttachment+from backend.copilot.bot.adapters.base import EditOutcome, FileAttachmentfrom backend.copilot.bot.choices import ResolvedChoicefrom backend.copilot.bot.turn_stream import _clarification_messagefrom backend.data.bot_installs import BotInstallCredentials@@ -35,8 +35,8 @@ def _mock_client() -> MagicMock:client = MagicMock()client.token = "xoxb-test"client.chat_postMessage = AsyncMock(return_value={"ts": "111.222"})+ client.chat_update = AsyncMock(return_value={"ok": True})client.chat_postEphemeral = AsyncMock()- client.chat_update = AsyncMock()client.chat_getPermalink = AsyncMock(return_value={"permalink": "https://x/p"})client.files_upload_v2 = AsyncMock()client.conversations_info = AsyncMock(return_value={"ok": True})@@ -767,6 +767,56 @@ class TestOutbound:async def test_rename_thread_is_noop(self, adapter):assert await adapter.rename_thread("T1|C1|9.9", "x") is False+ @pytest.mark.asyncio+ async def test_edit_channel_message_calls_chat_update(self, adapter):+ outcome = await adapter.edit_channel_message("T1|C1|", "111.222", "updated")++ assert outcome == EditOutcome.OK+ call = adapter._clients["T1"].chat_update.await_args.kwargs+ assert call["channel"] == "C1"+ assert call["ts"] == "111.222"+ assert call["text"] == "updated"+ # chat.update keeps a message's existing blocks when `blocks` is+ # omitted, so a block message would silently not change.+ assert call["blocks"] == []++ @pytest.mark.asyncio+ async def test_edit_channel_message_escapes_like_the_send_path(self, adapter):+ # Edit content is model-authored, so it must go through the same+ # mrkdwn escaping as a send. Dropping `localize_markup` from the edit+ # path has to fail here.+ await adapter.edit_channel_message(+ "T1|C1|", "111.222", "**bold** <!channel> & <https://x>"+ )++ call = adapter._clients["T1"].chat_update.await_args.kwargs+ assert call["text"] == adapter.localize_markup(+ "**bold** <!channel> & <https://x>"+ )+ assert "**bold**" not in call["text"]++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found(self, adapter):+ adapter._clients["T1"].chat_update = AsyncMock(+ side_effect=SlackApiError("not found", {"error": "message_not_found"})+ )++ outcome = await adapter.edit_channel_message("T1|C1|", "111.222", "updated")++ assert outcome == EditOutcome.NOT_FOUND++ @pytest.mark.asyncio+ async def test_edit_channel_message_failed_on_other_slack_error(self, adapter):+ adapter._clients["T1"].chat_update = AsyncMock(+ side_effect=SlackApiError(+ "edit forbidden", {"error": "cant_update_message"}+ )+ )++ outcome = await adapter.edit_channel_message("T1|C1|", "111.222", "updated")++ assert outcome == EditOutcome.FAILED+class TestChannelIdGrammar:def test_slack_ids_match(self, adapter):diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.pyindex ce1b271891..ae09b45040 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py@@ -32,6 +32,7 @@ from backend.copilot.bot import choicesfrom backend.copilot.bot.adapters.base import (ChannelInfo,ChannelType,+ EditOutcome,FileAttachment,MessageCallback,MessageContext,@@ -517,8 +518,8 @@ class TeamsAdapter(WebhookAdapter):async def post_channel_message(self, channel_id: str, text: str) -> Optional[PostedRef]:- first_id = await self._send_chunked(channel_id, text, ())- return PostedRef(id=first_id) if first_id else None+ first_id, sent = await self._send_chunked(channel_id, text, ())+ return PostedRef(id=first_id, chunk_count=sent) if first_id else Noneasync def create_channel_thread(self, channel_id: str, name: str, text: str@@ -528,6 +529,25 @@ class TeamsAdapter(WebhookAdapter):body = f"**{name}**\n\n{text}" if name else textreturn await self.post_channel_message(channel_id, body)+ async def edit_channel_message(+ self, channel_id: str, ref_id: str, text: str+ ) -> EditOutcome:+ activity = {+ "type": "message",+ "text": self.localize_markup(text),+ "textFormat": "markdown",+ }+ try:+ await self._client.update_activity(+ self._service_url_for(channel_id), channel_id, ref_id, activity+ )+ except TeamsApiError as e:+ logger.exception("Failed to edit Teams activity %s", ref_id)+ if e.status_code == 404:+ return EditOutcome.NOT_FOUND+ return EditOutcome.FAILED+ return EditOutcome.OK+async def open_dm_channel(self, platform_user_id: str) -> Optional[str]:"""Create (or fetch) the bot's 1:1 conversation with a user.@@ -555,13 +575,15 @@ class TeamsAdapter(WebhookAdapter):channel_id: str,text: str,mentionable_users: tuple[tuple[str, str], ...],- ) -> Optional[str]:- """Post ``text`` in message-sized chunks; return the first activity id.+ ) -> tuple[Optional[str], int]:+ """Post ``text`` in message-sized chunks; return the first activity id+ and how many chunks landed.Chunks are awaited in sequence: Teams does not guarantee ordering formessages posted in quick succession."""first_id: Optional[str] = None+ sent = 0for chunk in iter_chunks(self.localize_markup(text), config.CHUNK_FLUSH_AT):rendered, pinged = resolve_mentions(chunk, mentionable_users, mention_token)activity: dict[str, Any] = {@@ -573,8 +595,10 @@ class TeamsAdapter(WebhookAdapter):if entities:activity["entities"] = entitiesactivity_id = await self._post(channel_id, activity)+ if activity_id:+ sent += 1first_id = first_id or activity_id- return first_id+ return first_id, sentasync def _post(self, channel_id: str, activity: dict[str, Any]) -> Optional[str]:return await self._client.send_activity(diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.pyindex f3991649c3..d5aa637cab 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter_test.py@@ -596,6 +596,54 @@ async def test_send_link_uses_an_adaptive_card_button(app_id):assert card["content"]["actions"][0]["url"] == "https://example.com/link"+async def test_edit_channel_message_updates_activity(app_id):+ from backend.copilot.bot.adapters.base import EditOutcome++ adapter = TeamsAdapter(MagicMock())+ adapter._client.update_activity = AsyncMock(return_value=None)++ outcome = await adapter.edit_channel_message("a:chat", "activity-9", "updated text")++ assert outcome == EditOutcome.OK+ args = adapter._client.update_activity.await_args.args+ assert args[1] == "a:chat"+ assert args[2] == "activity-9"+ activity = args[3]+ assert activity["type"] == "message"+ assert activity["text"] == "updated text"+++async def test_edit_channel_message_failed_on_connector_error(app_id):+ from backend.copilot.bot.adapters.base import EditOutcome+ from backend.copilot.bot.adapters.teams.api_client import TeamsApiError++ adapter = TeamsAdapter(MagicMock())+ adapter._client.update_activity = AsyncMock(+ side_effect=TeamsApiError("boom", status_code=500)+ )++ outcome = await adapter.edit_channel_message("a:chat", "activity-9", "updated text")++ assert outcome == EditOutcome.FAILED+++async def test_edit_channel_message_not_found_on_404(app_id):+ from backend.copilot.bot.adapters.base import EditOutcome+ from backend.copilot.bot.adapters.teams.api_client import TeamsApiError++ adapter = TeamsAdapter(MagicMock())+ adapter._client.update_activity = AsyncMock(+ side_effect=TeamsApiError("not found", status_code=404)+ )++ outcome = await adapter.edit_channel_message("a:chat", "activity-9", "updated text")++ assert outcome == EditOutcome.NOT_FOUND++@pytest.mark.asyncioasync def test_non_image_file_degrades_to_a_note(app_id):from backend.copilot.bot.adapters.base import FileAttachmentdiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.pyindex a464deb908..07169b3095 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client.py@@ -11,6 +11,7 @@ import asyncioimport loggingimport timefrom typing import Any+from urllib.parse import quoteimport httpx@@ -25,8 +26,34 @@ _HTTP_TIMEOUT_SECONDS = 30.0_TOKEN_REFRESH_MARGIN_SECONDS = 300+def _path_segment(value: str) -> str:+ """Encode ``value`` as a single, inert URL path segment.++ For a value with no id grammar of its own — an AutoPilot-tool-supplied+ ``ref_id``, not a Connector-issued id — quoting every reserved character+ (``/``, ``?``, ``#``, …) stops it from splicing extra path segments into+ the request, and rejecting a bare ``.``/``..`` stops a same-length+ dot-segment from being normalized away by the HTTP client, either of+ which could otherwise redirect the call to a different+ conversation/activity than the one that was authorized.+ """+ if value in (".", ".."):+ raise TeamsApiError(f"invalid path segment {value!r}")+ return quote(value, safe="")++class TeamsApiError(Exception):- """A Bot Connector call failed."""+ """A Bot Connector call failed.++ ``status_code`` is the HTTP status the Connector responded with, or+ ``None`` for errors raised before a response arrived (e.g. an untrusted+ ``serviceUrl``) — callers that need to distinguish "not found" from other+ rejections (edit outcomes) branch on this rather than parsing the message.+ """++ def __init__(self, message: str, status_code: int | None = None) -> None:+ super().__init__(message)+ self.status_code = status_codeclass TeamsClient:@@ -50,6 +77,30 @@ class TeamsClient:activity,)+ async def update_activity(+ self,+ service_url: str,+ conversation_id: str,+ activity_id: str,+ activity: dict[str, Any],+ ) -> None:+ """Replace a previously sent activity's content in place.++ Unlike ``conversation_id`` (always a real Teams-issued id the caller+ re-derived and matched before getting here — see+ ``outbound.edit_message``'s DM authorization), ``activity_id`` is an+ AutoPilot-tool-supplied ``ref_id`` with no such constraint, so it's+ the one encoded as an inert path segment here: unescaped, a `/`+ or a `..` segment in it could redirect this PUT to a different+ conversation/activity than the one that was authorized.+ """+ await self._request(+ "PUT",+ service_url,+ f"v3/conversations/{conversation_id}/activities/{_path_segment(activity_id)}",+ activity,+ )+async def create_conversation(self, service_url: str, payload: dict[str, Any]) -> str | None:@@ -98,7 +149,8 @@ class TeamsClient:response = await self._http.request(method, url, json=payload, headers=headers)if response.status_code >= 400:raise TeamsApiError(- f"{method} {path} failed ({response.status_code}): {response.text[:300]}"+ f"{method} {path} failed ({response.status_code}): {response.text[:300]}",+ status_code=response.status_code,)if not response.content:return Nonediff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.pyindex 1a28ffa372..6a0e8d8db6 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/api_client_test.py@@ -166,3 +166,67 @@ async def test_the_playground_sends_no_bearer():client = TeamsClient()with patch(f"{_CONFIG_PATH}.allow_unverified_requests", return_value=True):assert await client.bearer_headers() == {}+++def _ok_response():+ response = MagicMock()+ response.status_code = 200+ response.content = b"{}"+ response.json.return_value = {}+ return response+++def _authed_client() -> TeamsClient:+ client = TeamsClient()+ client._http = MagicMock()+ client._token = "tok"+ client._token_expires_at = time.monotonic() + 600+ return client+++async def test_update_activity_builds_the_expected_url():+ client = _authed_client()+ client._http.request = AsyncMock(return_value=_ok_response())+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ await client.update_activity(_ALLOWED, "19:conv", "act-1", {"type": "message"})++ method, url = client._http.request.await_args.args+ assert method == "PUT"+ assert url == f"{_ALLOWED.rstrip('/')}/v3/conversations/19:conv/activities/act-1"+++async def test_update_activity_encodes_a_slash_in_activity_id():+ # activity_id is an AutoPilot-tool-supplied ref_id with no id grammar of+ # its own — a raw "/" must not be able to splice in an extra path segment+ # and redirect the PUT to a different (unauthorized) conversation.+ client = _authed_client()+ client._http.request = AsyncMock(return_value=_ok_response())+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified:+ await client.update_activity(+ _ALLOWED, "19:conv", "../../conversations/other/activities/x", {}+ )++ _, url = client._http.request.await_args.args+ # The malicious segment is fully percent-encoded, so it stays one inert+ # path component instead of being normalized into a different path.+ assert url.startswith(+ f"{_ALLOWED.rstrip('/')}/v3/conversations/19:conv/activities/"+ )+ assert "/conversations/other/" not in url+ assert "%2F" in url++[email protected]("activity_id", [".", ".."])+async def test_update_activity_rejects_bare_dot_segments(activity_id):+ client = _authed_client()+ client._http.request = AsyncMock(return_value=_ok_response())+ app_id, password, tenant, unverified = _creds()+ with app_id, password, tenant, unverified, pytest.raises(TeamsApiError):+ await client.update_activity(_ALLOWED, "19:conv", activity_id, {})++ client._http.request.assert_not_awaited()diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.pyindex 5597dcd973..17f3efb4c5 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py@@ -27,6 +27,7 @@ from backend.copilot.bot import choicesfrom backend.copilot.bot.adapters.base import (ChannelInfo,ChannelType,+ EditOutcome,FileAttachment,MessageCallback,MessageContext,@@ -42,7 +43,7 @@ from backend.copilot.bot.config import MAX_INBOUND_ATTACHMENTSfrom backend.copilot.bot.text import iter_chunks, resolve_mentionsfrom . import choice_ui, commands, config-from .api_client import TelegramClient+from .api_client import TelegramAPIError, TelegramClientfrom .targets import decode_target as _decode_targetfrom .targets import encode_target as _encode_targetfrom .text import to_html@@ -604,6 +605,7 @@ class TelegramAdapter(WebhookAdapter):# caller's retry would repost the chunks already delivered (mirrors# Discord's ``_send_chunked``).posted = False+ sent = 0for chunk in iter_chunks(text, config.CHUNK_FLUSH_AT):try:result = await self._client.call(@@ -621,11 +623,12 @@ class TelegramAdapter(WebhookAdapter):logger.exception("Dropping trailing Telegram chunk after partial send")breakposted = True+ sent += 1if first_id is None:first_id = str(result.get("message_id", ""))if first_id is None:return None- return PostedRef(id=first_id, url=None)+ return PostedRef(id=first_id, url=None, chunk_count=sent)async def create_channel_thread(self, channel_id: str, name: str, text: str@@ -635,7 +638,49 @@ class TelegramAdapter(WebhookAdapter):posted = await self.post_channel_message(channel_id, f"**{name}**\n\n{text}")if posted is None:return None- return PostedRef(id=channel_id, url=posted.url)+ # `id` stays the posted message so it can be edited; `channel_id`+ # carries the chat/topic target that keeps follow-up sends in place.+ return PostedRef(+ id=posted.id,+ url=posted.url,+ channel_id=channel_id,+ chunk_count=posted.chunk_count,+ )++ async def edit_channel_message(+ self, channel_id: str, ref_id: str, text: str+ ) -> EditOutcome:+ chat_id, _ = _decode_target(channel_id)+ try:+ message_id = int(ref_id)+ except ValueError:+ return EditOutcome.NOT_FOUND+ try:+ await self._client.call(+ "editMessageText",+ chat_id=chat_id,+ message_id=message_id,+ text=self.localize_markup(text),+ parse_mode="HTML",+ )+ except TelegramAPIError as e:+ detail = str(e).lower()+ # Telegram answers "message is not modified" when the new text is+ # byte-identical. The edit is already in the requested state, so+ # reporting failure only makes the model retry forever.+ if "not modified" in detail:+ return EditOutcome.OK+ # "message to edit not found" and "message can't be edited" (past+ # the 48h window) are both NOT_FOUND's documented meaning: gone or+ # too old to touch.+ if "not found" in detail or "can't be edited" in detail:+ return EditOutcome.NOT_FOUND+ logger.warning("Telegram editMessageText rejected edit: %s", e)+ return EditOutcome.FAILED+ except Exception:+ logger.exception("Failed to edit Telegram message %s", ref_id)+ return EditOutcome.FAILED+ return EditOutcome.OK# -- Helpers --diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.pyindex b6cc52018f..937f759423 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter_test.py@@ -6,7 +6,11 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from backend.copilot.bot.adapters.base import FileAttachment, StreamDraftOutcome+from backend.copilot.bot.adapters.base import (+ EditOutcome,+ FileAttachment,+ StreamDraftOutcome,+)from backend.copilot.bot.adapters.telegram.api_client import TelegramAPIErrorfrom backend.copilot.bot.choices import ResolvedChoicefrom backend.copilot.bot.turn_stream import _clarification_message@@ -541,6 +545,94 @@ class TestProactiveChunking:assert joined.count("Tom") == 200 # nothing dropped across the chunks+class TestEditChannelMessage:+ @pytest.mark.asyncio+ async def test_edit_channel_message_calls_edit_message_text(self):+ a = _adapter()++ outcome = await a.edit_channel_message("123", "77", "updated text")++ assert outcome == EditOutcome.OK+ assert a._client.call.call_args.args == ("editMessageText",)+ kwargs = a._client.call.call_args.kwargs+ assert kwargs["chat_id"] == "123"+ assert kwargs["message_id"] == 77+ assert kwargs["text"] == "updated text"++ @pytest.mark.asyncio+ async def test_edit_channel_message_escapes_like_the_send_path(self):+ a = _adapter()+ a._client.call = AsyncMock(return_value={})++ await a.edit_channel_message("123", "77", "<b>raw</b> & **bold**")++ kwargs = a._client.call.call_args.kwargs+ assert kwargs["text"] == a.localize_markup("<b>raw</b> & **bold**")+ assert kwargs["parse_mode"] == "HTML"++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_modified_is_ok(self):+ # Telegram answers this when the text is byte-identical. The message+ # is already in the requested state, so reporting failure only makes+ # the model retry forever.+ a = _adapter()+ a._client.call = AsyncMock(+ side_effect=TelegramAPIError(+ "editMessageText failed: message is not modified"+ )+ )++ outcome = await a.edit_channel_message("123", "77", "same")++ assert outcome == EditOutcome.OK++ @pytest.mark.asyncio+ async def test_edit_channel_message_too_old_is_not_found(self):+ a = _adapter()+ a._client.call = AsyncMock(+ side_effect=TelegramAPIError(+ "editMessageText failed: message can't be edited"+ )+ )++ outcome = await a.edit_channel_message("123", "77", "updated")++ assert outcome == EditOutcome.NOT_FOUND++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found(self):+ a = _adapter()+ a._client.call = AsyncMock(+ side_effect=TelegramAPIError(+ "editMessageText failed: message to edit not found"+ )+ )++ outcome = await a.edit_channel_message("123", "77", "updated text")++ assert outcome == EditOutcome.NOT_FOUND++ @pytest.mark.asyncio+ async def test_edit_channel_message_failed_on_other_error(self):+ a = _adapter()+ a._client.call = AsyncMock(+ side_effect=TelegramAPIError("editMessageText failed: message is too old")+ )++ outcome = await a.edit_channel_message("123", "77", "updated text")++ assert outcome == EditOutcome.FAILED++ @pytest.mark.asyncio+ async def test_edit_channel_message_not_found_for_bad_ref_id(self):+ a = _adapter()++ outcome = await a.edit_channel_message("123", "not-a-number", "updated text")++ assert outcome == EditOutcome.NOT_FOUND+ a._client.call.assert_not_awaited()++class TestChoiceCallbackQuery:@pytest.mark.asyncioasync def test_click_resolves_updates_message_and_dispatches(self):diff --git a/autogpt_platform/backend/backend/copilot/bot/app.py b/autogpt_platform/backend/backend/copilot/bot/app.pyindex 79dae482ec..f4960bf4a5 100644--- a/autogpt_platform/backend/backend/copilot/bot/app.py+++ b/autogpt_platform/backend/backend/copilot/bot/app.py@@ -6,6 +6,7 @@ other services to push messages into chat platforms.import asyncioimport loggingfrom concurrent.futures import Future+from typing import Literalfrom backend.platform_linking.models import Platformfrom backend.util.service import (@@ -23,7 +24,7 @@ from .adapters.discord import config as discord_configfrom .adapters.discord.adapter import DiscordAdapterfrom .bot_backend import BotBackendfrom .handler import MessageHandler-from .outbound import DeliveryResult+from .outbound import DeliveryResult, EditResultfrom .webhook_routes import build_webhook_adapterslogger = logging.getLogger(__name__)@@ -200,6 +201,28 @@ class CoPilotChatBridge(AppService):adapter, api, platform.value, user_id, channel, thread_name, content)+ @expose+ async def edit_message_in_channel(+ self,+ platform: Platform,+ user_id: str,+ target: Literal["channel", "dm"],+ channel_id: str,+ ref_id: str,+ content: str,+ ) -> EditResult:+ """Edit a message ``user_id`` previously posted via ``send_message_to_channel``+ / ``send_dm_to_user`` / ``create_thread_in_channel``.++ ``channel_id``/``ref_id`` must be exactly what that earlier call+ returned — authorization re-derives the expected channel from the+ user's links rather than trusting the caller's ``channel_id``.+ """+ adapter, api = self._require(platform)+ return await outbound.edit_message(+ adapter, api, platform.value, user_id, target, channel_id, ref_id, content+ )+class CoPilotChatBridgeClient(AppServiceClient):@classmethod@@ -214,6 +237,9 @@ class CoPilotChatBridgeClient(AppServiceClient):create_thread_in_channel = endpoint_to_async(CoPilotChatBridge.create_thread_in_channel)+ edit_message_in_channel = endpoint_to_async(+ CoPilotChatBridge.edit_message_in_channel+ )def _build_socket_adapters(api: BotBackend) -> list[SocketAdapter]:diff --git a/autogpt_platform/backend/backend/copilot/bot/outbound.py b/autogpt_platform/backend/backend/copilot/bot/outbound.pyindex b0d5713dbf..e836780af3 100644--- a/autogpt_platform/backend/backend/copilot/bot/outbound.py+++ b/autogpt_platform/backend/backend/copilot/bot/outbound.py@@ -6,7 +6,10 @@ adapter calls. Two concerns live here, both platform-agnostic:- **Authorization** — a user may only post into channels that belong to aserver they've linked (``BotBackend.list_linked_server_ids``). Channelresolution is funneled through that allowlist so an unauthorized target can- never be reached, whether referenced by ID or by name.+ never be reached, whether referenced by ID or by name. Editing needs a+ second, stronger fact: the channel allowlist is shared by everyone linked+ to that server, so an edit additionally requires an authorship record+ (``sent_messages``) proving *this* account had the bot post that message.- **Resolution** — a human channel reference (``#announcements``, a barename, or a raw snowflake ID) is mapped to a concrete channel ID.@@ -19,11 +22,19 @@ from typing import Literal, Optionalfrom pydantic import BaseModel-from backend.copilot.bot.adapters.base import ChannelInfo, PlatformAdapter+from backend.copilot.bot.adapters.base import ChannelInfo, EditOutcome, PlatformAdapterfrom backend.copilot.bot.bot_backend import BotBackend+from backend.copilot.bot.sent_messages import record_sent, sender_oflogger = logging.getLogger(__name__)+# Maps an adapter's EditOutcome to the stable error code a tool/LLM can relay.+_EDIT_OUTCOME_ERRORS: dict[EditOutcome, str] = {+ EditOutcome.UNSUPPORTED: "edit_unsupported",+ EditOutcome.NOT_FOUND: "message_not_found",+ EditOutcome.FAILED: "edit_failed",+}+class DeliveryResult(BaseModel):"""Outcome of a proactive post, shaped for a tool/LLM to relay.@@ -41,6 +52,13 @@ class DeliveryResult(BaseModel):error: Optional[str] = None+class EditResult(BaseModel):+ """Outcome of a proactive edit, shaped for a tool/LLM to relay."""++ ok: bool+ error: Optional[str] = None++async def list_channels(adapter: PlatformAdapter,api: BotBackend,@@ -81,6 +99,14 @@ async def deliver_message(return DeliveryResult(ok=False, kind="message", channel_id=channel_id, error="send_failed")+ await record_sent(+ platform,+ channel_id,+ ref.id,+ user_id,+ chunk_count=ref.chunk_count,+ editable=ref.editable,+ )return DeliveryResult(ok=True, kind="message", channel_id=channel_id, ref_id=ref.id, url=ref.url)@@ -112,6 +138,14 @@ async def deliver_dm(return DeliveryResult(ok=False, kind="dm", channel_id=channel_id, error="send_failed")+ await record_sent(+ platform,+ channel_id,+ ref.id,+ user_id,+ chunk_count=ref.chunk_count,+ editable=ref.editable,+ )return DeliveryResult(ok=True, kind="dm", channel_id=channel_id, ref_id=ref.id, url=ref.url)@@ -137,11 +171,99 @@ async def create_thread(return DeliveryResult(ok=False, kind="thread", channel_id=channel_id, error="thread_failed")+ # The body lives inside the new thread, not the channel it was created+ # from, so both the edit target and any follow-up post belong there.+ thread_channel_id = ref.channel_id or channel_id+ await record_sent(+ platform,+ thread_channel_id,+ ref.id,+ user_id,+ chunk_count=ref.chunk_count,+ editable=ref.editable,+ )return DeliveryResult(- ok=True, kind="thread", channel_id=channel_id, ref_id=ref.id, url=ref.url+ ok=True,+ kind="thread",+ channel_id=thread_channel_id,+ ref_id=ref.id,+ url=ref.url,)+async def edit_message(+ adapter: PlatformAdapter,+ api: BotBackend,+ platform: str,+ user_id: str,+ target: Literal["channel", "dm"],+ channel_id: str,+ ref_id: str,+ content: str,+) -> EditResult:+ """Edit a message previously posted via ``deliver_message``/``deliver_dm``.++ Two independent gates, both required:++ 1. **Authorship** — ``sent_messages`` must hold a record that this same+ ``user_id`` had the bot post this ``ref_id``. Without it, "the channel+ is in a server you linked" is the only check, and that is shared by+ every user linked to the server: Alice could rewrite Bob's post, or any+ reply the bot made to a third party. A message the bot sent as+ *conversation* (an inbound reply) is never recorded, so it can never be+ rewritten this way either.+ 2. **Channel** — the channel is still re-derived from the user's links and+ required to match, exactly like ``_resolve_target`` does for a raw id.+ Redundant with (1) by construction, kept as defence in depth so a lost+ or forged record still can't reach an unlinked server.+ """+ if not content or not content.strip():+ return EditResult(ok=False, error="empty_content")++ record = await sender_of(platform, channel_id, ref_id)+ if record is None:+ return EditResult(ok=False, error="not_sender")+ sender_user_id, chunk_count, editable = record+ if sender_user_id != user_id:+ return EditResult(ok=False, error="not_sender")+ if not editable:+ return EditResult(ok=False, error="edit_unsupported_ref")+ if chunk_count > 1:+ # `ref_id` is only the first chunk, so an edit would rewrite the+ # opening and leave the rest of the post stale below it.+ return EditResult(ok=False, error="edit_chunked")++ if target == "dm":+ platform_user_id = await api.get_dm_user_id(platform, user_id)+ if platform_user_id is None:+ return EditResult(ok=False, error="no_dm_link")+ expected_channel_id = await adapter.open_dm_channel(platform_user_id)+ if expected_channel_id is None or expected_channel_id != channel_id:+ return EditResult(ok=False, error="not_authorized")+ else:+ server_ids = tuple(await api.list_linked_server_ids(platform, user_id))+ if not server_ids:+ return EditResult(ok=False, error="no_linked_servers")+ # No `looks_like_channel_id` gate here on purpose. The post path needs+ # it to tell a raw id from a channel *name*; the edit path takes no+ # names, and applying it would reject the encoded `team|channel|`+ # targets `list_text_channels` hands back for name-resolved Slack+ # posts. What keeps the edit path from being wider than the post path+ # is the authorship record above: a channel/ref pair only has one if+ # `_resolve_target` already authorized it for this same user, which is+ # strictly narrower than any id-shape test.+ guild_id = await adapter.get_channel_server_id(channel_id)+ if guild_id is None:+ return EditResult(ok=False, error="channel_not_found")+ if guild_id not in server_ids:+ return EditResult(ok=False, error="not_authorized")++ outcome = await adapter.edit_channel_message(channel_id, ref_id, content)+ if outcome is EditOutcome.OK:+ return EditResult(ok=True)+ return EditResult(ok=False, error=_EDIT_OUTCOME_ERRORS[outcome])++async def _resolve_target(adapter: PlatformAdapter,api: BotBackend,diff --git a/autogpt_platform/backend/backend/copilot/bot/outbound_test.py b/autogpt_platform/backend/backend/copilot/bot/outbound_test.pyindex 86f33da73f..fabff3d80e 100644--- a/autogpt_platform/backend/backend/copilot/bot/outbound_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/outbound_test.py@@ -1,12 +1,56 @@"""Tests for proactive-output authorization + channel resolution."""+import jsonimport re-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.copilot.bot import outbound-from backend.copilot.bot.adapters.base import ChannelInfo, PostedRef+from backend.copilot.bot.adapters.base import ChannelInfo, EditOutcome, PostedRef+from backend.copilot.bot.sent_messages import _key+++class _FakeRedis:+ """Just enough Redis for the authorship record: get/set over a dict."""++ def __init__(self) -> None:+ self.store: dict[str, str] = {}++ async def get(self, key: str) -> str | None:+ return self.store.get(key)++ async def set(self, key: str, value: str, ex: int | None = None) -> None:+ self.store[key] = value++[email protected](autouse=True)+def sent_store():+ """Back `sent_messages` with an in-memory store for every test.++ Autouse because the edit path now refuses anything without an authorship+ record, so a real Redis client would otherwise be reached (and every edit+ test would fail on the record lookup rather than the check it is about).+ """+ fake = _FakeRedis()+ with patch("backend.copilot.bot.sent_messages.get_redis_async", return_value=fake):+ yield fake+++def _seed_sent(+ store: _FakeRedis,+ platform: str,+ channel_id: str,+ ref_id: str,+ user_id: str,+ *,+ chunks: int = 1,+ editable: bool = True,+) -> None:+ """Pretend ``user_id`` already had the bot post ``ref_id`` there."""+ store.store[_key(platform, channel_id, ref_id)] = json.dumps(+ {"user_id": user_id, "chunks": chunks, "editable": editable}+ )def _api(server_ids: list[str]) -> AsyncMock:@@ -22,6 +66,7 @@ def _adapter(posted: PostedRef | None = None,thread: PostedRef | None = None,dm_channel: str | None = None,+ edit_outcome: EditOutcome = EditOutcome.OK,) -> AsyncMock:adapter = AsyncMock()# Sync classifier — mirrors Discord's numeric-snowflake grammar so@@ -34,6 +79,7 @@ def _adapter(adapter.post_channel_message.return_value = postedadapter.create_channel_thread.return_value = threadadapter.open_dm_channel.return_value = dm_channel+ adapter.edit_channel_message.return_value = edit_outcomereturn adapter@@ -266,3 +312,313 @@ async def test_list_channels_drops_unlinked_server_channels():)result = await outbound.list_channels(adapter, _api(["g1"]), "discord", "user-1")assert [c.id for c in result] == ["10"]+++async def test_edit_message_channel_happy_path(sent_store):+ adapter = _adapter(channel_server="g1")+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is True+ assert result.error is None+ adapter.edit_channel_message.assert_awaited_once_with("42", "100", "updated")+++async def test_edit_message_channel_in_unlinked_server_is_rejected(sent_store):+ adapter = _adapter(channel_server="other-guild")+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "not_authorized"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_channel_unknown_id_is_not_found(sent_store):+ adapter = _adapter(channel_server=None)+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "channel_not_found"+++async def test_edit_message_channel_no_linked_servers(sent_store):+ adapter = _adapter()+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api([]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "no_linked_servers"+ adapter.get_channel_server_id.assert_not_awaited()+++async def test_edit_message_dm_happy_path(sent_store):+ adapter = _adapter(dm_channel="dm-42")+ _seed_sent(sent_store, "discord", "dm-42", "100", "u1")+ result = await outbound.edit_message(+ adapter, _dm_api("pu1"), "discord", "u1", "dm", "dm-42", "100", "updated"+ )+ assert result.ok is True+ adapter.open_dm_channel.assert_awaited_once_with("pu1")+ adapter.edit_channel_message.assert_awaited_once_with("dm-42", "100", "updated")+++async def test_edit_message_dm_without_link_is_rejected(sent_store):+ adapter = _adapter(dm_channel="dm-42")+ _seed_sent(sent_store, "discord", "dm-42", "100", "u1")+ result = await outbound.edit_message(+ adapter, _dm_api(None), "discord", "u1", "dm", "dm-42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "no_dm_link"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_dm_channel_id_mismatch_is_rejected(sent_store):+ # A caller-supplied channel_id that doesn't match this user's own DM+ # channel must never be trusted, even though it "looks like" a DM id —+ # this is the authorization check the caller-supplied id can't skip.+ adapter = _adapter(dm_channel="dm-42")+ # Seeded, so the authorship gate passes and the DM-channel check is the+ # one under test: the two gates are independent, not one behind the other.+ _seed_sent(sent_store, "discord", "someone-elses-dm", "100", "u1")+ result = await outbound.edit_message(+ adapter, _dm_api("pu1"), "discord", "u1", "dm", "someone-elses-dm", "100", "x"+ )+ assert result.ok is False+ assert result.error == "not_authorized"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_empty_content_is_distinct_error():+ adapter = _adapter(channel_server="g1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", " "+ )+ assert result.ok is False+ assert result.error == "empty_content"+ adapter.get_channel_server_id.assert_not_awaited()+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_unsupported_platform_is_surfaced(sent_store):+ adapter = _adapter(channel_server="g1", edit_outcome=EditOutcome.UNSUPPORTED)+ _seed_sent(sent_store, "teams", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "teams", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "edit_unsupported"+++async def test_edit_message_not_found_is_surfaced(sent_store):+ adapter = _adapter(channel_server="g1", edit_outcome=EditOutcome.NOT_FOUND)+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "message_not_found"+++async def test_edit_message_failed_is_surfaced(sent_store):+ adapter = _adapter(channel_server="g1", edit_outcome=EditOutcome.FAILED)+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "edit_failed"+++# -- Authorship: an edit needs proof *this* account had the bot post it --+++async def test_edit_message_without_authorship_record_is_refused():+ # The whole point: channel authorization alone used to be enough, and it+ # is shared by everyone linked to the server.+ adapter = _adapter(channel_server="g1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "not_sender"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_by_another_linked_user_is_refused(sent_store):+ # Bob posted it; Alice is linked to the same guild, so every channel check+ # in this function passes for her. Only the record stops the rewrite.+ _seed_sent(sent_store, "discord", "42", "100", "bob")+ adapter = _adapter(channel_server="g1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "alice", "channel", "42", "100", "hijacked"+ )+ assert result.ok is False+ assert result.error == "not_sender"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_dm_of_another_user_is_refused(sent_store):+ _seed_sent(sent_store, "discord", "dm-42", "100", "bob")+ adapter = _adapter(dm_channel="dm-42")+ result = await outbound.edit_message(+ adapter, _dm_api("pu1"), "discord", "alice", "dm", "dm-42", "100", "hijacked"+ )+ assert result.ok is False+ assert result.error == "not_sender"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_chunked_post_is_refused(sent_store):+ # ref_id is the first chunk only, so editing would leave chunks 2..n stale+ # underneath a rewritten opening while reporting success.+ _seed_sent(sent_store, "discord", "42", "100", "user-1", chunks=3)+ adapter = _adapter(channel_server="g1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "edit_chunked"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_edit_message_thread_ref_is_refused(sent_store):+ # Discord/Telegram hand back a thread or chat id, which no edit call takes.+ _seed_sent(sent_store, "discord", "42", "100", "user-1", editable=False)+ adapter = _adapter(channel_server="g1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "42", "100", "updated"+ )+ assert result.ok is False+ assert result.error == "edit_unsupported_ref"+ adapter.edit_channel_message.assert_not_awaited()+++async def test_deliver_message_records_authorship_so_the_sender_can_edit(sent_store):+ adapter = _adapter(channel_server="g1", posted=PostedRef(id="100"))+ posted = await outbound.deliver_message(+ adapter, _api(["g1"]), "discord", "user-1", "999888777666555444", "hi"+ )+ assert posted.ok is True++ edited = await outbound.edit_message(+ adapter,+ _api(["g1"]),+ "discord",+ "user-1",+ "channel",+ "999888777666555444",+ "100",+ "updated",+ )+ assert edited.ok is True+++async def test_deliver_message_records_chunk_count_from_the_adapter(sent_store):+ adapter = _adapter(channel_server="g1", posted=PostedRef(id="100", chunk_count=2))+ await outbound.deliver_message(+ adapter, _api(["g1"]), "discord", "user-1", "999888777666555444", "hi"+ )+ result = await outbound.edit_message(+ adapter,+ _api(["g1"]),+ "discord",+ "user-1",+ "channel",+ "999888777666555444",+ "100",+ "updated",+ )+ assert result.error == "edit_chunked"+++async def test_create_thread_records_the_adapters_editable_flag(sent_store):+ # A thread whose body never posted: the thread id still reaches the+ # caller so a retry can't duplicate it, but there is nothing to edit.+ adapter = _adapter(+ channel_server="g1",+ thread=PostedRef(id="t1", channel_id="t1", editable=False),+ )+ await outbound.create_thread(+ adapter, _api(["g1"]), "discord", "user-1", "999888777666555444", "n", "hi"+ )+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "discord", "user-1", "channel", "t1", "t1", "updated"+ )+ assert result.error == "edit_unsupported_ref"+++async def test_thread_body_is_editable_inside_the_new_thread(sent_store):+ # The body lives in the thread, not the channel it was created from, so+ # the edit target has to be the thread.+ adapter = _adapter(+ channel_server="g1", thread=PostedRef(id="body-1", channel_id="thread-9")+ )+ posted = await outbound.create_thread(+ adapter, _api(["g1"]), "discord", "user-1", "999888777666555444", "n", "hi"+ )+ assert posted.ok is True+ assert posted.channel_id == "thread-9"+ assert posted.ref_id == "body-1"++ edited = await outbound.edit_message(+ adapter,+ _api(["g1"]),+ "discord",+ "user-1",+ "channel",+ "thread-9",+ "body-1",+ "updated",+ )+ assert edited.ok is True+ adapter.edit_channel_message.assert_awaited_once_with(+ "thread-9", "body-1", "updated"+ )+++async def test_thread_without_its_own_channel_falls_back_to_the_parent(sent_store):+ # Teams delegates thread creation to a plain post, so its ref carries no+ # separate channel; the channel posted to is still the right one.+ adapter = _adapter(channel_server="g1", thread=PostedRef(id="m1"))+ posted = await outbound.create_thread(+ adapter, _api(["g1"]), "teams", "user-1", "999888777666555444", "n", "hi"+ )+ assert posted.channel_id == "999888777666555444"+++async def test_authorship_is_scoped_per_platform(sent_store):+ _seed_sent(sent_store, "discord", "42", "100", "user-1")+ adapter = _adapter(channel_server="g1")+ result = await outbound.edit_message(+ adapter, _api(["g1"]), "slack", "user-1", "channel", "42", "100", "updated"+ )+ assert result.error == "not_sender"diff --git a/autogpt_platform/backend/backend/copilot/bot/sent_messages.py b/autogpt_platform/backend/backend/copilot/bot/sent_messages.pynew file mode 100644index 0000000000..e724bd38b0--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/sent_messages.py@@ -0,0 +1,110 @@+"""Authorship record for messages the bot posted proactively.++``edit_message`` may only touch a message *this account* asked the bot to+post. Channel authorization alone can't establish that: two users linked to+the same server both pass a "is this channel in a server you linked?" check,+so without a record of who sent what, either could rewrite the other's post —+or any reply the bot made to a third party, turning the bot's own history+into something forgeable.++So every proactive send records ``(platform, channel_id, ref_id) -> sender``+here, and the edit path requires a matching record. Inbound replies the+handler makes on a user's behalf are deliberately *not* recorded: they are+conversation, not the caller's post, and nothing should rewrite them.++Records live in Redis with a 30-day TTL. Expiry only ever costs an edit the+model could have made (it gets ``not_sender`` and can post afresh); it can+never grant one.+"""++import hashlib+import json+import logging++from backend.data.redis_client import get_redis_async++logger = logging.getLogger(__name__)++SENT_MESSAGE_TTL = 30 * 86400 # 30 days+++def _key(platform: str, channel_id: str, ref_id: str) -> str:+ # Hash the pair rather than joining it: Teams ids contain ':', so a joined+ # key could let two different (channel, message) pairs share one record.+ pair = json.dumps([channel_id, ref_id]).encode()+ return f"copilot-bot:sent:{platform}:{hashlib.sha256(pair).hexdigest()}"+++async def record_sent(+ platform: str,+ channel_id: str,+ ref_id: str,+ user_id: str,+ *,+ chunk_count: int = 1,+ editable: bool = True,+) -> None:+ """Record that ``user_id`` had the bot post ``ref_id`` in ``channel_id``.++ ``chunk_count``/``editable`` come off the adapter's ``PostedRef`` and are+ stored so the edit path can refuse the cases it cannot honour rather than+ silently half-applying them.++ Never raises: a proactive post that already landed must not be reported as+ failed because Redis was briefly unreachable. The cost of a lost record is+ a refused edit, which is the safe direction.+ """+ try:+ redis = await get_redis_async()+ await redis.set(+ _key(platform, channel_id, ref_id),+ json.dumps(+ {"user_id": user_id, "chunks": chunk_count, "editable": editable}+ ),+ ex=SENT_MESSAGE_TTL,+ )+ except Exception:+ logger.exception(+ "Failed to record sent message %s/%s on %s; edits to it will be refused",+ channel_id,+ ref_id,+ platform,+ )+++async def sender_of(+ platform: str, channel_id: str, ref_id: str+) -> tuple[str, int, bool] | None:+ """``(user_id, chunk_count, editable)`` for a recorded post, else ``None``.++ ``None`` means "not a message this bot posted proactively, or the record+ aged out" — both of which must refuse an edit.+ """+ try:+ redis = await get_redis_async()+ raw = await redis.get(_key(platform, channel_id, ref_id))+ except Exception:+ logger.exception(+ "Failed to read sent-message record %s/%s on %s",+ channel_id,+ ref_id,+ platform,+ )+ return None+ if not raw:+ return None+ try:+ record = json.loads(raw)+ return (+ str(record["user_id"]),+ int(record.get("chunks", 1)),+ bool(record.get("editable", True)),+ )+ except (ValueError, TypeError, KeyError):+ logger.warning(+ "Malformed sent-message record for %s/%s on %s",+ channel_id,+ ref_id,+ platform,+ )+ return Nonediff --git a/autogpt_platform/backend/backend/copilot/bot/sent_messages_test.py b/autogpt_platform/backend/backend/copilot/bot/sent_messages_test.pynew file mode 100644index 0000000000..9408be8902--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/sent_messages_test.py@@ -0,0 +1,12 @@+from backend.copilot.bot.sent_messages import _key+++def test_key_keeps_colon_ids_apart():+ # Teams channel and message ids both contain ':'. Joined naively, these two+ # different messages would collapse onto the same authorship record.+ assert _key("teams", "a:b", "c") != _key("teams", "a", "b:c")+++def test_key_is_stable_and_scoped_by_platform():+ assert _key("discord", "1", "2") == _key("discord", "1", "2")+ assert _key("discord", "1", "2") != _key("slack", "1", "2")diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.pyindex 1e7863ebee..19a45ce5aa 100644--- a/autogpt_platform/backend/backend/copilot/permissions.py+++ b/autogpt_platform/backend/backend/copilot/permissions.py@@ -39,6 +39,11 @@ are allowed.``blocks_exclude`` follows the same pattern for ``blocks``.+Denying a capability denies the tools that extend it (see+``_IMPLIED_DENIALS``). A blacklist is written against the tools that exist+when it is written, so a later tool that reaches the same resource would+otherwise be silently regained by every existing blacklist.+Recursion inheritance---------------------:meth:`CopilotPermissions.merged_with_parent` produces a new instance that@@ -93,6 +98,7 @@ ToolName = Literal["delete_skill","delete_workspace_file","edit_agent",+ "edit_chat_platform_message","enter_agent_building_mode","expert_onboarding","find_agent",@@ -200,6 +206,25 @@ _FULL_UUID_RE = re.compile(_PARTIAL_UUID_RE = re.compile(r"^[0-9a-f]{8}$", re.IGNORECASE)+# Tools that a blacklist entry must deny alongside the capability named.+#+# A blacklist is written against the tools that existed when it was written,+# so a tool added later that reaches the same resource is silently regained+# by every blacklist already out there. An operator who revoked proactive+# posting to their chat platforms should not find the agent able to rewrite+# everything the bot has already said in them.+_IMPLIED_DENIALS: dict[str, tuple[str, ...]] = {+ "post_to_chat_platform": ("edit_chat_platform_message",),+}+++def _with_implied_denials(denied: frozenset[str]) -> frozenset[str]:+ """Expand a deny set with the tools its entries imply."""+ return denied.union(+ implied for name in denied for implied in _IMPLIED_DENIALS.get(name, ())+ )++# ---------------------------------------------------------------------------# Helper — block identifier matching# ---------------------------------------------------------------------------@@ -263,7 +288,7 @@ class CopilotPermissions(BaseModel):return frozenset(all_tools)tool_set = frozenset(self.tools)if self.tools_exclude:- return all_tools - tool_set+ return all_tools - _with_implied_denials(tool_set)return all_tools & tool_set# ------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/copilot/permissions_test.py b/autogpt_platform/backend/backend/copilot/permissions_test.pyindex 53d3ff7141..c3bab4af4b 100644--- a/autogpt_platform/backend/backend/copilot/permissions_test.py+++ b/autogpt_platform/backend/backend/copilot/permissions_test.py@@ -106,6 +106,34 @@ class TestEffectiveAllowedTools:result = perms.effective_allowed_tools(ALL_TOOLS)assert result == ALL_TOOLS+ def test_denying_a_capability_also_denies_what_extends_it(self):+ # A blacklist is written against the tools that exist at the time, so+ # an operator who revoked proactive posting never listed the edit+ # tool — and would otherwise silently regain the ability to rewrite+ # everything the bot has already said in their servers.+ chat_tools = frozenset(+ ["post_to_chat_platform", "edit_chat_platform_message", "run_block"]+ )+ perms = CopilotPermissions(tools=["post_to_chat_platform"], tools_exclude=True)++ result = perms.effective_allowed_tools(chat_tools)++ assert result == frozenset(["run_block"])++ def test_an_implied_denial_does_not_leak_into_a_whitelist(self):+ # Whitelists are explicit: listing the edit tool means it is wanted,+ # and the implication table must not second-guess that.+ chat_tools = frozenset(+ ["post_to_chat_platform", "edit_chat_platform_message", "run_block"]+ )+ perms = CopilotPermissions(+ tools=["edit_chat_platform_message"], tools_exclude=False+ )++ result = perms.effective_allowed_tools(chat_tools)++ assert result == frozenset(["edit_chat_platform_message"])+# ---------------------------------------------------------------------------# CopilotPermissions.is_block_alloweddiff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.pyindex 1887600cbe..f250f6ae19 100644--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py@@ -15,7 +15,11 @@ from .agent_output import AgentOutputToolfrom .ask_question import AskQuestionToolfrom .base import BaseToolfrom .bash_exec import BashExecTool-from .chat_platform import ListChatPlatformChannelsTool, PostToChatPlatformTool+from .chat_platform import (+ EditChatPlatformMessageTool,+ ListChatPlatformChannelsTool,+ PostToChatPlatformTool,+)from .confirm_expert_change import ConfirmExpertChangeToolfrom .connect_integration import ConnectIntegrationToolfrom .continue_run_block import ContinueRunBlockTool@@ -129,6 +133,7 @@ TOOL_REGISTRY: dict[str, BaseTool] = {"schedule_followup": ScheduleFollowupTool(),# Proactive chat-platform output (post message / open thread on user's behalf)"post_to_chat_platform": PostToChatPlatformTool(),+ "edit_chat_platform_message": EditChatPlatformMessageTool(),"list_chat_platform_channels": ListChatPlatformChannelsTool(),# Trigger management (parent agent → its triggers)"list_agent_triggers": ListAgentTriggersTool(),diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform.pyindex 2c4ec50ead..f79f79eef2 100644--- a/autogpt_platform/backend/backend/copilot/tools/chat_platform.py+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform.py@@ -21,7 +21,7 @@ bot via their DM link — enforced bridge-side.import loggingfrom functools import lru_cache-from typing import Any+from typing import Any, Literal, castfrom backend.copilot.model import ChatSessionfrom backend.platform_linking.models import Platform@@ -32,6 +32,7 @@ from .base import BaseToolfrom .models import (ChatPlatformChannelListResponse,ChatPlatformChannelSummary,+ ChatPlatformEditedResponse,ChatPlatformPostedResponse,ErrorResponse,ToolResponseBase,@@ -93,6 +94,32 @@ _ERROR_MESSAGES: dict[str, str] = {"dm_unavailable": ("The bot couldn't open a DM with the user's linked account on that " "platform."),+ "edit_unsupported": (+ "This platform doesn't support editing a message after it's " "posted."+ ),+ "message_not_found": (+ "That message could not be found — it may have been deleted or is too "+ "old to edit."+ ),+ "edit_failed": (+ "The platform rejected the edit — the bot may lack permission, or the "+ "message wasn't posted by the bot."+ ),+ "not_sender": (+ "That message isn't one this account had the bot post, so it can't be "+ "edited. Only a message from an earlier post_to_chat_platform call in "+ "this account can be edited, and only for 30 days. Post a new message "+ "instead."+ ),+ "edit_chunked": (+ "That post was too long for one message and was split across several, "+ "so editing it would rewrite only the first part and leave the rest "+ "stale. Post a shorter replacement instead."+ ),+ "edit_unsupported_ref": (+ "That thread was created but its opening message never posted, so "+ "there is nothing to edit. Post into the thread instead."+ ),}@@ -203,7 +230,11 @@ class PostToChatPlatformTool(BaseTool):"target='dm' only; its channels cannot be posted to yet. Pair ""with schedule_followup for recurring posts; call ""list_chat_platform_channels if a Discord/Slack channel won't "- "resolve."+ "resolve. Whatever this posts can later be changed with "+ "edit_chat_platform_message using the channel_id and ref_id it "+ "returns — for mode='thread' those address the body message "+ "inside the new thread, so posting again with that channel_id "+ "continues the thread.")@property@@ -385,6 +416,166 @@ class PostToChatPlatformTool(BaseTool):)+class EditChatPlatformMessageTool(BaseTool):+ """Edit a message the bot previously posted via ``post_to_chat_platform``."""++ @property+ def name(self) -> str:+ return "edit_chat_platform_message"++ @property+ def description(self) -> str:+ return (+ "Edit a message the bot previously sent with post_to_chat_platform "+ "on Discord, Slack, Telegram or Microsoft Teams. Pass the same "+ "`channel_id` and `ref_id` that call returned (and the same "+ "`target`/`platform` it used) along with the new `content` — the "+ "old content is replaced entirely. Only a message this account "+ "itself had the bot post is editable, and only for 30 days — not "+ "the bot's replies to anyone, not another user's posts, and not a "+ "long post that was split across several messages. A failure "+ "(message too old, deleted, not yours, or the platform rejecting "+ "the edit) is always reported, never silent."+ )++ @property+ def requires_auth(self) -> bool:+ return True++ @property+ def is_available(self) -> bool:+ return _any_chat_platform_configured()++ @property+ def parameters(self) -> dict[str, Any]:+ return {+ "type": "object",+ "properties": {+ "platform": _platform_param(),+ "target": {+ "type": "string",+ "enum": ["channel", "dm"],+ "description": (+ "Must match the `target` used in the original "+ "post_to_chat_platform call."+ ),+ },+ "channel_id": {+ "type": "string",+ "description": (+ "The `channel_id` post_to_chat_platform returned for "+ "the message being edited."+ ),+ },+ "ref_id": {+ "type": "string",+ "description": (+ "The `ref_id` post_to_chat_platform returned for the "+ "message being edited."+ ),+ },+ "content": {+ "type": "string",+ "description": "New message body, replacing the original content.",+ },+ },+ "required": ["channel_id", "ref_id", "content"],+ }++ @staticmethod+ def _validate_params(session_id: str | None, **kwargs) -> ErrorResponse | None:+ _platform, platform_name = _resolve_platform(kwargs.get("platform"))+ if _platform is None:+ return ErrorResponse(+ message=f"Unsupported platform '{platform_name}'.",+ error="unsupported_platform",+ session_id=session_id,+ )+ target: str = kwargs.get("target") or _default_target(platform_name)+ if target not in ("channel", "dm"):+ return ErrorResponse(+ message="`target` must be 'channel' or 'dm'.",+ error="invalid_target",+ session_id=session_id,+ )+ channel_id = kwargs.get("channel_id")+ if not channel_id or not str(channel_id).strip():+ return ErrorResponse(+ message="`channel_id` is required.",+ error="missing_channel_id",+ session_id=session_id,+ )+ ref_id = kwargs.get("ref_id")+ if not ref_id or not str(ref_id).strip():+ return ErrorResponse(+ message="`ref_id` is required.",+ error="missing_ref_id",+ session_id=session_id,+ )+ content = kwargs.get("content")+ if not content or not content.strip():+ return ErrorResponse(+ message="`content` is required.",+ error="missing_content",+ session_id=session_id,+ )+ return None++ async def _execute(+ self,+ user_id: str | None,+ session: ChatSession,+ **kwargs,+ ) -> ToolResponseBase:+ session_id = session.session_id if session else None+ if not user_id:+ return ErrorResponse(+ message="Authentication required.",+ error="auth_required",+ session_id=session_id,+ )+ invalid = self._validate_params(session_id, **kwargs)+ if invalid is not None:+ return invalid++ platform, platform_name = _resolve_platform(kwargs.get("platform"))+ if platform is None: # already validated; narrows the type+ return ErrorResponse(+ message=f"Unsupported platform '{platform_name}'.",+ error="unsupported_platform",+ session_id=session_id,+ )+ target_value: str = kwargs.get("target") or _default_target(platform_name)+ # Already validated to be one of these two literals above.+ target = cast(Literal["channel", "dm"], target_value)+ channel_id = str(kwargs["channel_id"])+ ref_id = str(kwargs["ref_id"])+ content: str = kwargs["content"]++ client = get_copilot_chat_bridge_client()+ result = await client.edit_message_in_channel(+ platform=platform,+ user_id=user_id,+ target=target,+ channel_id=channel_id,+ ref_id=ref_id,+ content=content,+ )+ if not result.ok:+ return ErrorResponse(+ message=_error_message(result.error, platform_name),+ error=result.error or "chat_platform_edit_failed",+ session_id=session_id,+ )+ return ChatPlatformEditedResponse(+ message=f"Edited the message on {platform_name}.",+ platform=platform_name,+ channel_id=channel_id,+ ref_id=ref_id,+ session_id=session_id,+ )++class ListChatPlatformChannelsTool(BaseTool):"""List channels the bot can post to across the user's linked servers."""diff --git a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.pyindex c29e020f55..90ffd8c9fc 100644--- a/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/chat_platform_test.py@@ -5,14 +5,16 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.copilot.bot.adapters.base import ChannelInfo-from backend.copilot.bot.outbound import DeliveryResult+from backend.copilot.bot.outbound import DeliveryResult, EditResultfrom backend.copilot.tools.chat_platform import (+ EditChatPlatformMessageTool,ListChatPlatformChannelsTool,PostToChatPlatformTool,_any_chat_platform_configured,)from backend.copilot.tools.models import (ChatPlatformChannelListResponse,+ ChatPlatformEditedResponse,ChatPlatformPostedResponse,ErrorResponse,)@@ -34,6 +36,7 @@ def _bridge() -> MagicMock:bridge.create_thread_in_channel = AsyncMock()bridge.send_dm_to_user = AsyncMock()bridge.list_channels = AsyncMock()+ bridge.edit_message_in_channel = AsyncMock()return bridge@@ -315,6 +318,151 @@ async def test_post_unavailable_without_token():assert PostToChatPlatformTool().is_available is True+# ── EditChatPlatformMessageTool ─────────────────────────────────────+++async def test_edit_requires_auth(session):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=None, session=session, channel_id="42", ref_id="100", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "auth_required"+++async def test_edit_missing_channel_id(session):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER, session=session, channel_id=" ", ref_id="100", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_channel_id"+++async def test_edit_missing_ref_id(session):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER, session=session, channel_id="42", ref_id="", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_ref_id"+++async def test_edit_missing_content(session):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER, session=session, channel_id="42", ref_id="100", content=" "+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "missing_content"+++async def test_edit_unsupported_platform(session):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER,+ session=session,+ platform="myspace",+ channel_id="42",+ ref_id="100",+ content="hi",+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "unsupported_platform"+++async def test_edit_happy_path_defaults_to_discord(session):+ bridge = _bridge()+ bridge.edit_message_in_channel.return_value = EditResult(ok=True)+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER,+ session=session,+ channel_id="42",+ ref_id="100",+ content="updated",+ )+ assert isinstance(result, ChatPlatformEditedResponse)+ assert result.platform == "discord"+ assert result.channel_id == "42"+ assert result.ref_id == "100"+ call = bridge.edit_message_in_channel.await_args.kwargs+ assert call["platform"].value == "DISCORD"+ assert call["target"] == "channel"+ assert call["channel_id"] == "42"+ assert call["ref_id"] == "100"+ assert call["content"] == "updated"+++async def test_edit_dm_defaults_target_for_teams(session):+ bridge = _bridge()+ bridge.edit_message_in_channel.return_value = EditResult(ok=True)+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER,+ session=session,+ platform="teams",+ channel_id="a:chat",+ ref_id="activity-9",+ content="updated",+ )+ assert isinstance(result, ChatPlatformEditedResponse)+ assert bridge.edit_message_in_channel.await_args.kwargs["target"] == "dm"+++async def test_edit_maps_not_authorized_error(session):+ bridge = _bridge()+ bridge.edit_message_in_channel.return_value = EditResult(+ ok=False, error="not_authorized"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER, session=session, channel_id="999", ref_id="100", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "not_authorized"+++async def test_edit_maps_message_not_found_error(session):+ bridge = _bridge()+ bridge.edit_message_in_channel.return_value = EditResult(+ ok=False, error="message_not_found"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER, session=session, channel_id="42", ref_id="100", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "message_not_found"+ assert "deleted" in result.message+++async def test_edit_maps_edit_unsupported_error(session):+ bridge = _bridge()+ bridge.edit_message_in_channel.return_value = EditResult(+ ok=False, error="edit_unsupported"+ )+ with patch(f"{_PATH}.get_copilot_chat_bridge_client", return_value=bridge):+ result = await EditChatPlatformMessageTool()._execute(+ user_id=_USER, session=session, channel_id="42", ref_id="100", content="hi"+ )+ assert isinstance(result, ErrorResponse)+ assert result.error == "edit_unsupported"+++async def test_edit_unavailable_without_token():+ with patch(f"{_PATH}._any_chat_platform_configured", return_value=False):+ assert EditChatPlatformMessageTool().is_available is False+ with patch(f"{_PATH}._any_chat_platform_configured", return_value=True):+ assert EditChatPlatformMessageTool().is_available is True++# ── ListChatPlatformChannelsTool ───────────────────────────────────diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex 8797d2d067..7066059592 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -120,9 +120,10 @@ class ResponseType(str, Enum):# Platform infoPLATFORM_INFO = "platform_info"- # Chat-platform proactive output (post message / create thread)+ # Chat-platform proactive output (post message / create thread / edit)CHAT_PLATFORM_CHANNEL_LIST = "chat_platform_channel_list"CHAT_PLATFORM_POSTED = "chat_platform_posted"+ CHAT_PLATFORM_EDITED = "chat_platform_edited"# Skills (self-distilled procedure registry)SKILL_STORED = "skill_stored"@@ -1355,3 +1356,12 @@ class ChatPlatformPostedResponse(ToolResponseBase):channel_id: strref_id: str | None = Noneurl: str | None = None+++class ChatPlatformEditedResponse(ToolResponseBase):+ """Response after the bot edits a message it previously posted."""++ type: ResponseType = ResponseType.CHAT_PLATFORM_EDITED+ platform: str+ channel_id: str+ ref_id: strdiff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.pyindex f7da1c3116..568fe1cef5 100644--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py@@ -165,7 +165,11 @@ from backend.copilot.tools import TOOL_REGISTRY# counts against this ceiling. The tip reads 68,235 and `refs/pull/14416/merge`# 68,237 — dev widened raise_expert by two characters after this line was first# set, which reddened three interpreters on a branch that had added nothing.-_CHAR_BUDGET = 69_056+# Bumped 69_056 -> 70_771 for SECRT-2605: edit_chat_platform_message (mirroring+# post_to_chat_platform's platform/target enums plus channel_id/ref_id/content)+# measures 1,460, and the line in post_to_chat_platform's description pointing+# at it 255. Measured on the branch merged with dev: 70,770, plus one.+_CHAR_BUDGET = 70_771@pytest.fixture(scope="module")diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 4ad6f39242..844bfd382d 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -27813,6 +27813,7 @@"platform_info","chat_platform_channel_list","chat_platform_posted",+ "chat_platform_edited","skill_stored","skill_loaded","skill_deleted",diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.mdindex 336d26fc3a..6e1d0d3bce 100644--- a/docs/integrations/block-integrations/misc.md+++ b/docs/integrations/block-integrations/misc.md@@ -96,7 +96,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run| transport | Run on platform credits, or on your connected ChatGPT subscription if supported by your plan. | "platform" \| "codex_app_server" | No || session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No || max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "start_desktop" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "pause_schedule" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "resume_schedule" \| "revoke_expert_credential" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "ask_question" \| "bash_exec" \| "start_desktop" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "confirm_expert_change" \| "confirm_expert_soul_update" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delegate_to_expert" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "edit_chat_platform_message" \| "enter_agent_building_mode" \| "expert_onboarding" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "grant_expert_credential" \| "handoff_to_expert" \| "hire_expert" \| "install_expert_workflow" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_expert_chats" \| "list_expert_credentials" \| "list_expert_workflows" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_team" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "pause_schedule" \| "post_to_chat_platform" \| "raise_expert" \| "read_expert_chat" \| "read_skill" \| "read_workspace_file" \| "remove_expert_workflow" \| "request_credential_grant" \| "resume_schedule" \| "revoke_expert_credential" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_expert" \| "update_expert_soul" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No || tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No || blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No || blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |