Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(backend/copilot): keep linked server names fresh from bot gateway events (#13221)

Bently7e2154c31fd5
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
index ac841d791d..92971d580e 100644
--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py
@@ -176,6 +176,11 @@ class DiscordAdapter(PlatformAdapter):
@self._client.event
async def on_ready() -> None:
logger.info(f"Discord bot connected as {self._client.user}")
+ # Refresh display names for every guild we're currently in — keeps
+ # the Bots settings page in sync with renames and backfills any
+ # rows that pre-date name capture. Cheap: in-memory cache only,
+ # no Discord API calls.
+ await self._refresh_known_server_names()
# Sync slash commands once per process — on_ready fires on every
# gateway reconnect, but the command tree only needs uploading once.
if self._commands_synced:
@@ -189,6 +194,7 @@ class DiscordAdapter(PlatformAdapter):
@self._client.event
async def on_guild_join(guild: discord.Guild) -> None:
+ await self._refresh_server_name(guild)
channel = intro.pick_intro_channel(guild)
if channel is None:
logger.info(
@@ -204,6 +210,11 @@ class DiscordAdapter(PlatformAdapter):
except discord.HTTPException:
logger.exception("Failed to post intro message in guild %s", guild.id)
+ @self._client.event
+ async def on_guild_update(before: discord.Guild, after: discord.Guild) -> None:
+ if before.name != after.name:
+ await self._refresh_server_name(after)
+
@self._client.event
async def on_message(message: discord.Message) -> None:
if self._should_ignore_message(message):
@@ -238,6 +249,23 @@ class DiscordAdapter(PlatformAdapter):
)
await self._on_message_callback(ctx, self)
+ async def _refresh_known_server_names(self) -> None:
+ """Push current display names for every guild the bot is in."""
+ for guild in self._client.guilds:
+ await self._refresh_server_name(guild)
+
+ async def _refresh_server_name(self, guild: discord.Guild) -> None:
+ if not guild.name:
+ return
+ try:
+ await self._api.refresh_server_name(
+ platform="discord",
+ platform_server_id=str(guild.id),
+ server_name=guild.name,
+ )
+ except Exception:
+ logger.exception("Failed to refresh display name for guild %s", guild.id)
+
def _should_ignore_message(self, message: discord.Message) -> bool:
if self._client.user is not None and message.author.id == self._client.user.id:
return True
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter_test.py
index 91f54f6acf..d55f9e4c3c 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
@@ -471,3 +471,46 @@ class TestCollectMentionableUsers:
adapter, _ = _bare_adapter(bot_id=1000)
msg = _message("<@1000> hi", mentions=[_mention(1000, "AutoPilot")])
assert adapter._collect_mentionable_users(msg) == ()
+
+
+def _bare_adapter_with_api() -> tuple[DiscordAdapter, MagicMock, MagicMock]:
+ adapter, client = _bare_adapter(bot_id=1000)
+ api = MagicMock()
+ api.refresh_server_name = AsyncMock()
+ adapter._api = api
+ return adapter, client, api
+
+
+def _guild(guild_id: int, name: str | None) -> MagicMock:
+ g = MagicMock()
+ g.id = guild_id
+ g.name = name
+ return g
+
+
+class TestRefreshServerNames:
+ @pytest.mark.asyncio
+ async def test_pushes_every_guild_to_the_backend(self):
+ adapter, client, api = _bare_adapter_with_api()
+ client.guilds = [_guild(1, "Server One"), _guild(2, "Server Two")]
+ await adapter._refresh_known_server_names()
+ assert api.refresh_server_name.await_count == 2
+ api.refresh_server_name.assert_any_await(
+ platform="discord", platform_server_id="1", server_name="Server One"
+ )
+ api.refresh_server_name.assert_any_await(
+ platform="discord", platform_server_id="2", server_name="Server Two"
+ )
+
+ @pytest.mark.asyncio
+ async def test_skips_guild_with_blank_name(self):
+ adapter, _, api = _bare_adapter_with_api()
+ await adapter._refresh_server_name(_guild(99, ""))
+ api.refresh_server_name.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_swallows_backend_errors(self):
+ adapter, _, api = _bare_adapter_with_api()
+ api.refresh_server_name.side_effect = RuntimeError("rpc down")
+ # Must not raise — refreshing names is never critical-path.
+ await adapter._refresh_server_name(_guild(1, "Server One"))
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
index edf3d198e6..faa8f6eee9 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -105,6 +105,25 @@ class BotBackend:
)
return ResolveResult(linked=resp.linked)
+ async def refresh_server_name(
+ self, platform: str, platform_server_id: str, server_name: str
+ ) -> None:
+ """Push the bot's authoritative display name for a server into the DB.
+
+ Called by adapters whenever they learn or re-learn a server's name —
+ e.g. Discord's on_ready and on_guild_join. The Bots settings page
+ renders whatever is in the DB, so this keeps stale or missing names
+ in sync with what the bot is actually connected to. Best-effort:
+ failures are logged on the manager side, never raised.
+ """
+ if not server_name:
+ return
+ await self._client.refresh_server_link_name(
+ platform=Platform(platform.upper()),
+ platform_server_id=platform_server_id,
+ server_name=server_name,
+ )
+
async def create_link_token(
self,
platform: str,
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
index 063707e922..d998494309 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py
@@ -15,6 +15,7 @@ from backend.copilot.response_model import (
from backend.platform_linking.models import (
ChatTurnHandle,
LinkTokenResponse,
+ Platform,
ResolveResponse,
)
from backend.util.exceptions import (
@@ -55,6 +56,24 @@ class TestResolve:
assert result.linked is False
+class TestRefreshServerName:
+ @pytest.mark.asyncio
+ async def test_forwards_uppercased_platform(self, api: BotBackend):
+ api._client.refresh_server_link_name = AsyncMock()
+ await api.refresh_server_name("discord", "g1", "AutoGPT HQ")
+ api._client.refresh_server_link_name.assert_awaited_once_with(
+ platform=Platform.DISCORD,
+ platform_server_id="g1",
+ server_name="AutoGPT HQ",
+ )
+
+ @pytest.mark.asyncio
+ async def test_skips_call_when_server_name_is_empty(self, api: BotBackend):
+ api._client.refresh_server_link_name = AsyncMock()
+ await api.refresh_server_name("discord", "g1", "")
+ api._client.refresh_server_link_name.assert_not_awaited()
+
+
class TestCreateLinkTokens:
@pytest.mark.asyncio
async def test_create_server_link_token(self, api: BotBackend):
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 294b2e1c02..c71f0589b8 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -383,6 +383,7 @@ class DatabaseManager(AppService):
confirm_user_link = _(platform_linking_db.confirm_user_link)
list_server_links = _(platform_linking_db.list_server_links)
list_user_links = _(platform_linking_db.list_user_links)
+ refresh_server_link_name = _(platform_linking_db.refresh_server_link_name)
delete_server_link = _(platform_linking_db.delete_server_link)
delete_user_link = _(platform_linking_db.delete_user_link)
cleanup_expired_platform_link_tokens = _(
@@ -627,6 +628,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
confirm_user_link = d.confirm_user_link
list_server_links = d.list_server_links
list_user_links = d.list_user_links
+ refresh_server_link_name = d.refresh_server_link_name
delete_server_link = d.delete_server_link
delete_user_link = d.delete_user_link
cleanup_expired_platform_link_tokens = d.cleanup_expired_platform_link_tokens
diff --git a/autogpt_platform/backend/backend/platform_linking/db.py b/autogpt_platform/backend/backend/platform_linking/db.py
index cdc6bc6247..f5c5972bc8 100644
--- a/autogpt_platform/backend/backend/platform_linking/db.py
+++ b/autogpt_platform/backend/backend/platform_linking/db.py
@@ -396,6 +396,50 @@ async def list_user_links(user_id: str) -> list[PlatformUserLinkInfo]:
]
+# ── Backfill ──────────────────────────────────────────────────────────
+
+
+async def refresh_server_link_name(
+ platform: str, platform_server_id: str, server_name: str
+) -> None:
+ """Update the display name on a PlatformLink row, keyed by platform + server ID.
+
+ Called by chat-bot adapters when they learn (or re-learn) a server's
+ display name — e.g. Discord's on_ready / on_guild_join events. The bot
+ only knows the platform-side identifiers, not the AutoGPT PlatformLink
+ UUID, so we key off (platform, platform_server_id), which is unique.
+
+ No-ops if no matching link exists (the bot is in a server the user
+ never linked) or the row's name already matches. Best-effort: DB errors
+ are logged but not raised — refreshing a display name is never
+ critical-path.
+ """
+ if not server_name:
+ return
+ try:
+ # `serverName: {"not": ...}` excludes NULL rows in SQL (`NULL != 'x'`
+ # is NULL, not true), so we OR in the explicit NULL case to make
+ # sure first-time backfills land for legacy links.
+ await PlatformLink.prisma().update_many(
+ where={
+ "platform": platform,
+ "platformServerId": platform_server_id,
+ "OR": [
+ {"serverName": None},
+ {"serverName": {"not": server_name}},
+ ],
+ },
+ data={"serverName": server_name},
+ )
+ except Exception as exc:
+ logger.warning(
+ "Failed to refresh server_name for %s server %s: %s",
+ platform,
+ platform_server_id,
+ exc,
+ )
+
+
# ── Deletion ──────────────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/platform_linking/db_test.py b/autogpt_platform/backend/backend/platform_linking/db_test.py
index 6bc260d611..70d79b40d3 100644
--- a/autogpt_platform/backend/backend/platform_linking/db_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/db_test.py
@@ -25,6 +25,7 @@ from .db import (
delete_user_link,
get_link_token_info,
get_link_token_status,
+ refresh_server_link_name,
resolve_server_link,
resolve_user_link,
)
@@ -511,3 +512,45 @@ class TestCleanupExpired:
mock_model.prisma.return_value.delete_many = AsyncMock(return_value=0)
count = await cleanup_expired_platform_link_tokens()
assert count == 0
+
+
+# ── Refresh server-link display name ───────────────────────────────────
+
+
+class TestRefreshServerLinkName:
+ @pytest.mark.asyncio
+ async def test_no_op_when_name_blank(self):
+ with patch("backend.platform_linking.db.PlatformLink") as mock_model:
+ mock_model.prisma.return_value.update_many = AsyncMock()
+ await refresh_server_link_name("DISCORD", "g1", "")
+ mock_model.prisma.return_value.update_many.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_filter_matches_null_rows_and_differing_rows(self):
+ """The filter MUST include both NULL serverName rows and rows whose
+ serverName differs. `{not: 'x'}` alone excludes NULLs (SQL: NULL != 'x'
+ is NULL, not true), which was leaving legacy backfills stuck. The
+ bug surfaced as servers showing as their ID forever on the Bots page."""
+ with patch("backend.platform_linking.db.PlatformLink") as mock_model:
+ mock_model.prisma.return_value.update_many = AsyncMock()
+ await refresh_server_link_name("DISCORD", "g1", "AutoGPT HQ")
+
+ update_many = mock_model.prisma.return_value.update_many
+ update_many.assert_awaited_once()
+ await_args = update_many.await_args
+ assert await_args is not None
+ where = await_args.kwargs["where"]
+ assert where["platform"] == "DISCORD"
+ assert where["platformServerId"] == "g1"
+ # OR clause must cover the NULL case explicitly.
+ assert {"serverName": None} in where["OR"]
+ assert {"serverName": {"not": "AutoGPT HQ"}} in where["OR"]
+
+ @pytest.mark.asyncio
+ async def test_swallows_db_errors(self):
+ with patch("backend.platform_linking.db.PlatformLink") as mock_model:
+ mock_model.prisma.return_value.update_many = AsyncMock(
+ side_effect=RuntimeError("db down")
+ )
+ # Must not raise.
+ await refresh_server_link_name("DISCORD", "g1", "x")
diff --git a/autogpt_platform/backend/backend/platform_linking/manager.py b/autogpt_platform/backend/backend/platform_linking/manager.py
index 44048b4fff..3ac849d976 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager.py
@@ -63,6 +63,14 @@ class PlatformLinkingManager(AppService):
async def start_chat_turn(self, request: BotChatRequest) -> ChatTurnHandle:
return await start_chat_turn(request)
+ @expose
+ async def refresh_server_link_name(
+ self, platform: Platform, platform_server_id: str, server_name: str
+ ) -> None:
+ await platform_linking_db().refresh_server_link_name(
+ platform.value, platform_server_id, server_name
+ )
+
@expose
async def list_user_chats(
self,
@@ -91,4 +99,7 @@ class PlatformLinkingManagerClient(AppServiceClient):
PlatformLinkingManager.get_link_token_status
)
start_chat_turn = endpoint_to_async(PlatformLinkingManager.start_chat_turn)
+ refresh_server_link_name = endpoint_to_async(
+ PlatformLinkingManager.refresh_server_link_name
+ )
list_user_chats = endpoint_to_async(PlatformLinkingManager.list_user_chats)
diff --git a/autogpt_platform/backend/backend/platform_linking/manager_test.py b/autogpt_platform/backend/backend/platform_linking/manager_test.py
index a768c08dac..1ae306762b 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager_test.py
@@ -156,6 +156,20 @@ class TestManagerWiring:
stub.assert_awaited_once_with(req)
assert result is fake_response
+ @pytest.mark.asyncio
+ async def test_refresh_server_link_name_delegates(self):
+ manager = PlatformLinkingManager()
+ db_mock = MagicMock()
+ db_mock.refresh_server_link_name = AsyncMock()
+ with patch(
+ "backend.platform_linking.manager.platform_linking_db",
+ return_value=db_mock,
+ ):
+ await manager.refresh_server_link_name(Platform.DISCORD, "g1", "AutoGPT HQ")
+ db_mock.refresh_server_link_name.assert_awaited_once_with(
+ "DISCORD", "g1", "AutoGPT HQ"
+ )
+
class TestAdversarialConfirmRace:
"""Concurrent confirm of one token: exactly one winner via ``update_many``