AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
refactor(backend/copilot-bot): extract shared adapter helpers (attachments, mentions, history, chunking) (#13506)
Bently9e7204645458
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.pyindex 3677c3d8b5..29019ea1d1 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/adapter.py@@ -14,8 +14,15 @@ import discordfrom discord import app_commandsfrom backend.copilot.bot import threads+from backend.copilot.bot.adapters.shared import (+ InboundFile,+ budget_history,+ collect_attachments,+ should_ignore,+)from backend.copilot.bot.bot_backend import BotBackend-from backend.copilot.bot.text import split_at_boundary+from backend.copilot.bot.config import MAX_INBOUND_ATTACHMENTS+from backend.copilot.bot.text import iter_chunks, resolve_mentionsfrom ..base import (ChannelInfo,@@ -46,7 +53,6 @@ logger = logging.getLogger(__name__)# messages when a thread is very long.THREAD_HISTORY_LIMIT = 1000THREAD_HISTORY_CHAR_BUDGET = 24000-_HISTORY_TRUNCATION_MARKER = "\n… [message truncated]"# When a message links or @-mentions other threads/channels, the bot fetches# their recent content up-front (same guild only) so the model can read it@@ -56,9 +62,6 @@ MAX_REFERENCED_CONVERSATIONS = 3REFERENCED_HISTORY_LIMIT = 200REFERENCED_CHAR_BUDGET = 8000-# Cap how many attachments we pull off a single message into the workspace, so-# a message with dozens of files can't fan out into that many uploads/scans.-MAX_INBOUND_ATTACHMENTS = 10# When a link names a specific message, fetch that message plus a little of the# conversation leading up to it (rather than the channel's latest activity).REFERENCED_MESSAGE_CONTEXT = 15@@ -330,12 +333,8 @@ class DiscordAdapter(SocketAdapter):later-chunk failure stops the send and keeps the partial result ratherthan discarding what already posted (a retry would duplicate it)."""- remaining = text.strip()first: Optional[discord.Message] = None- while remaining:- chunk, remaining = split_at_boundary(remaining, config.CHUNK_FLUSH_AT)- if not chunk:- break+ for chunk in iter_chunks(text, config.CHUNK_FLUSH_AT):try:msg = await channel.send(chunk, tts=False)except discord.HTTPException:@@ -493,30 +492,20 @@ class DiscordAdapter(SocketAdapter):the per-message count, or a failed download) so the handler can tellthe user and the model rather than silently dropping them."""- attachments: list[InboundAttachment] = []- skipped: list[tuple[str, str]] = []- extra = message.attachments[MAX_INBOUND_ATTACHMENTS:]- for attachment in extra:- skipped.append((attachment.filename or "file", "too many files attached"))- for attachment in message.attachments[:MAX_INBOUND_ATTACHMENTS]:- name = attachment.filename or "file"- if attachment.size > self.max_attachment_bytes:- skipped.append((name, "too large"))- continue- try:- content = await attachment.read()- except (discord.HTTPException, discord.NotFound):- logger.warning("Could not download attachment %s", name)- skipped.append((name, "couldn't be downloaded"))- continue- attachments.append(- InboundAttachment(- filename=name,- mime_type=attachment.content_type or "application/octet-stream",- content=content,- )+ files = [+ InboundFile(+ filename=a.filename,+ size=a.size,+ mime_type=a.content_type,+ fetch=a.read,)- return tuple(attachments), tuple(skipped)+ for a in message.attachments+ ]+ return await collect_attachments(+ files,+ max_count=MAX_INBOUND_ATTACHMENTS,+ max_bytes=self.max_attachment_bytes,+ )async def _refresh_known_server_names(self) -> None:"""Push current display names for every guild the bot is in."""@@ -536,13 +525,12 @@ class DiscordAdapter(SocketAdapter):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- # Other bots reach us only by @mentioning us; without this gate two- # bots in a shared thread (our own dev + prod included) loop forever.- if message.author.bot:- return not self._is_mentioned(message)- return False+ me = self._client.user+ return should_ignore(+ is_self=me is not None and message.author.id == me.id,+ author_is_bot=message.author.bot,+ bot_mentioned=self._is_mentioned(message),+ )def _is_mentioned(self, message: discord.Message) -> bool:if message.guild is None:@@ -689,43 +677,29 @@ class DiscordAdapter(SocketAdapter):async def _budgeted_history(self, history, char_budget: int) -> tuple[MessageHistoryEntry, ...]:- """Drain a newest-first message iterator into chronological entries,- capped at ``char_budget`` chars (most-recent kept when over budget).+ """Normalize Discord history into entries, then char-budget them.- Skips the bot's own messages (copilot has its own transcript for those)- but keeps other bots' messages as context.+ The Discord-specific part is the mapping — skip the bot's own messages+ (copilot has its own transcript for those) but keep other bots' as+ context, and strip Discord mention syntax. The budgeting/truncation is+ shared (``budget_history``)."""- entries: list[MessageHistoryEntry] = []- used_chars = 0bot_user_id = self._client.user.id if self._client.user else None- async for prior in history:- if bot_user_id is not None and prior.author.id == bot_user_id:- continue- text = self._strip_mentions(prior)- if not text:- continue- remaining = char_budget - used_chars- if remaining <= 0:- break- oversized = len(text) > remaining- if oversized and entries:- # No room for another whole message — keep what we have.- break- if oversized:- # Lone most-recent message is itself over budget: keep a head.- text = _truncate_to_budget(text, remaining)- used_chars += len(text)- entries.append(- MessageHistoryEntry(++ async def _entries():+ async for prior in history:+ if bot_user_id is not None and prior.author.id == bot_user_id:+ continue+ text = self._strip_mentions(prior)+ if not text:+ continue+ yield MessageHistoryEntry(username=prior.author.display_name,user_id=str(prior.author.id),text=text,)- )- if oversized:- break- entries.reverse() # chronological order for the prompt- return tuple(entries)++ return await budget_history(_entries(), char_budget=char_budget)async def _fetch_referenced_conversations(self, message: discord.Message, text: str@@ -826,57 +800,28 @@ class DiscordAdapter(SocketAdapter):return True-def _truncate_to_budget(text: str, limit: int) -> str:- """Trim ``text`` to at most ``limit`` characters, leaving a visible marker.-- Used only when a single thread message is itself larger than the history- budget — keep a head of it (with context that it was cut) rather than emit- an oversized payload or drop the message entirely.- """- if len(text) <= limit:- return text- keep = max(0, limit - len(_HISTORY_TRUNCATION_MARKER))- return text[:keep].rstrip() + _HISTORY_TRUNCATION_MARKER--def _resolve_mentions(text: str,mentionable_users: tuple[tuple[str, str], ...],) -> tuple[str, discord.AllowedMentions]:- """Substitute `@DisplayName` in `text` with `<@id>` markup for users on- the allowlist, and return an AllowedMentions that pings exactly those- users (and nobody else).+ """Render allowlisted ``@DisplayName`` as Discord ``<@id>`` markup and+ return an ``AllowedMentions`` that pings exactly those users.- Anyone not on the allowlist stays as plain text — even if the LLM produces- `@everyone`, `@here`, or `@SomeRandomUser`. This keeps the bot from- pinging users it learned about elsewhere or hallucinated entirely.+ The allowlist policy (which names match, longest-first, word-bounded) is+ shared in ``text.resolve_mentions``; here we only supply Discord's mention+ token and turn the pinged IDs into Discord's ping-safety object."""- if not mentionable_users:- return text, discord.AllowedMentions.none()-- rendered = text+ rendered, pinged = resolve_mentions(+ text, mentionable_users, lambda _name, uid: f"<@{uid}>"+ )pinged_ids: list[int] = []- # Longest names first so e.g. "@John Smith" matches before "@John".- for display_name, user_id in sorted(- mentionable_users, key=lambda pair: -len(pair[0])- ):- # Word-bounded so "@Name" inside emails/URLs is left alone.- pattern = re.compile(- rf"(?<![\w@]){re.escape(f'@{display_name}')}(?!\w)",- re.IGNORECASE,- )- if not pattern.search(rendered):- continue- # Callable replacement avoids backref interpretation of user_id.- rendered = pattern.sub(lambda _m, uid=user_id: f"<@{uid}>", rendered)+ for uid in pinged:try:- pinged_ids.append(int(user_id))+ pinged_ids.append(int(uid))except ValueError:continue-if not pinged_ids:return rendered, discord.AllowedMentions.none()-return rendered, discord.AllowedMentions(everyone=False,users=[discord.Object(id=uid) for uid in pinged_ids],diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/shared.py b/autogpt_platform/backend/backend/copilot/bot/adapters/shared.pynew file mode 100644index 0000000000..0a1f2b0a1f--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/shared.py@@ -0,0 +1,153 @@+"""Platform-agnostic helpers shared by every adapter.++These capture policy that is identical across chat platforms — inbound+attachment caps + skip bookkeeping, and the bot-loop guard — so each adapter+supplies only the thin platform-specific callback (how to fetch a file's+bytes; whether the author is us/a bot). Keeping the policy here rather than+re-implemented per adapter is what lets a new adapter stay small and keeps the+rules in one place.+"""++import logging+from typing import AsyncIterable, Awaitable, Callable, Sequence++from pydantic import BaseModel++from .base import InboundAttachment, MessageHistoryEntry++logger = logging.getLogger(__name__)++_HISTORY_TRUNCATION_MARKER = "\n… [message truncated]"+++class InboundFile(BaseModel):+ """A platform file an adapter wants to ingest, normalized for+ ``collect_attachments``. ``fetch`` is the only platform-specific part — a+ zero-arg coroutine bound to this file that downloads its bytes.+ """++ filename: str | None+ size: int+ mime_type: str | None+ fetch: Callable[[], Awaitable[bytes]]+++async def collect_attachments(+ files: Sequence[InboundFile],+ *,+ max_count: int,+ max_bytes: int,+) -> tuple[tuple[InboundAttachment, ...], tuple[tuple[str, str], ...]]:+ """Download the user's inbound files under shared caps.++ Returns ``(kept, skipped)`` where ``skipped`` is ``(filename, reason)`` for+ files dropped over the per-message count cap, over the per-file size cap, or+ on a failed download — so the caller can tell the user and the model rather+ than silently losing them. Only ``fetch`` touches the platform; the caps and+ skip bookkeeping are shared policy every adapter reuses.+ """+ kept: list[InboundAttachment] = []+ skipped: list[tuple[str, str]] = []+ for extra in files[max_count:]:+ skipped.append((extra.filename or "file", "too many files attached"))+ for f in files[:max_count]:+ name = f.filename or "file"+ if f.size > max_bytes:+ skipped.append((name, "too large"))+ continue+ try:+ content = await f.fetch()+ except Exception:+ # The collector can't know each platform's download exceptions, so+ # it catches broadly: a fetch failure becomes a per-file skip the+ # user is told about, never a dropped message.+ logger.warning("Could not download attachment %s", name)+ skipped.append((name, "couldn't be downloaded"))+ continue+ kept.append(+ InboundAttachment(+ filename=name,+ mime_type=f.mime_type or "application/octet-stream",+ content=content,+ )+ )+ return tuple(kept), tuple(skipped)+++async def budget_history(+ entries: AsyncIterable[MessageHistoryEntry],+ *,+ char_budget: int,+) -> tuple[MessageHistoryEntry, ...]:+ """Budget a message history down to ``char_budget`` chars, returning it in+ chronological order.++ **Precondition — ``entries`` MUST be yielded newest-first.** Keeping the+ *most recent* messages under budget is only possible by consuming from the+ newest end (a `MessageHistoryEntry` has no timestamp to sort by), so the+ adapter must stream its history newest→oldest; the result is reversed back+ to chronological for the prompt. Passing oldest-first would keep the wrong+ end of the conversation.++ The adapter yields entries already normalized for its platform (its own+ messages skipped, mentions stripped, empties dropped); this owns only the+ budgeting + truncation, which is identical for every platform and is+ currently assembled in two places in the Discord adapter alone. The lone+ most-recent entry, if itself over budget, keeps a truncated head rather+ than being dropped or emitted oversized.+ """+ kept: list[MessageHistoryEntry] = []+ used = 0+ async for entry in entries:+ remaining = char_budget - used+ if remaining <= 0:+ break+ text = entry.text+ oversized = len(text) > remaining+ if oversized and kept:+ # No room for another whole message — keep what we have.+ break+ if oversized:+ # Lone most-recent message is itself over budget: keep a head.+ text = _truncate_to_budget(text, remaining)+ entry = MessageHistoryEntry(+ username=entry.username, user_id=entry.user_id, text=text+ )+ used += len(text)+ kept.append(entry)+ if oversized:+ break+ kept.reverse() # chronological order for the prompt+ return tuple(kept)+++def _truncate_to_budget(text: str, limit: int) -> str:+ """Trim ``text`` to at most ``limit`` chars, leaving a visible marker.++ Used only when a single message is itself larger than the history budget —+ keep a head of it (with a cut marker) rather than emit an oversized payload+ or drop the message entirely.+ """+ if len(text) <= limit:+ return text+ # Below the marker's own width there's no room for a head + marker; hard-cut+ # so the result still respects the budget (matters for adapters that pass a+ # small budget — the marker is ~22 chars).+ if limit <= len(_HISTORY_TRUNCATION_MARKER):+ return text[:limit]+ keep = limit - len(_HISTORY_TRUNCATION_MARKER)+ return text[:keep].rstrip() + _HISTORY_TRUNCATION_MARKER+++def should_ignore(*, is_self: bool, author_is_bot: bool, bot_mentioned: bool) -> bool:+ """Whether to drop an inbound message before doing any work.++ Ignore our own messages always; ignore other bots unless they @-mention us+ — that mention gate is what stops two bots in a shared thread (a dev bot and+ a prod bot included) from replying to each other forever. The adapter+ computes the three booleans from its platform's message; the decision is+ shared so no adapter can forget the loop guard.+ """+ if is_self:+ return True+ return author_is_bot and not bot_mentioneddiff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/shared_test.py b/autogpt_platform/backend/backend/copilot/bot/adapters/shared_test.pynew file mode 100644index 0000000000..b61c17051f--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/shared_test.py@@ -0,0 +1,123 @@+"""Tests for the platform-agnostic adapter helpers."""++import pytest++from .base import MessageHistoryEntry+from .shared import InboundFile, budget_history, collect_attachments, should_ignore+++async def _stream(entries):+ for entry in entries:+ yield entry+++def _entry(text: str, uid: str = "1") -> MessageHistoryEntry:+ return MessageHistoryEntry(username="u", user_id=uid, text=text)+++def _file(name="a.txt", size=10, mime="text/plain", content=b"data", fail=False):+ async def fetch() -> bytes:+ if fail:+ raise RuntimeError("download failed")+ return content++ return InboundFile(filename=name, size=size, mime_type=mime, fetch=fetch)+++class TestCollectAttachments:+ @pytest.mark.asyncio+ async def test_keeps_files_under_caps(self):+ kept, skipped = await collect_attachments(+ [_file(content=b"hello")], max_count=10, max_bytes=1000+ )+ assert skipped == ()+ assert len(kept) == 1+ assert kept[0].filename == "a.txt"+ assert kept[0].content == b"hello"++ @pytest.mark.asyncio+ async def test_over_count_files_are_skipped(self):+ files = [_file(name=f"f{i}.txt") for i in range(12)]+ kept, skipped = await collect_attachments(files, max_count=10, max_bytes=1000)+ assert len(kept) == 10+ assert skipped == (+ ("f10.txt", "too many files attached"),+ ("f11.txt", "too many files attached"),+ )++ @pytest.mark.asyncio+ async def test_oversized_file_is_skipped(self):+ kept, skipped = await collect_attachments(+ [_file(size=2000)], max_count=10, max_bytes=1000+ )+ assert kept == ()+ assert skipped == (("a.txt", "too large"),)++ @pytest.mark.asyncio+ async def test_failed_download_is_skipped_not_fatal(self):+ kept, skipped = await collect_attachments(+ [_file(name="good.txt"), _file(name="bad.txt", fail=True)],+ max_count=10,+ max_bytes=1000,+ )+ assert [k.filename for k in kept] == ["good.txt"]+ assert skipped == (("bad.txt", "couldn't be downloaded"),)++ @pytest.mark.asyncio+ async def test_missing_name_and_mime_get_defaults(self):+ kept, _ = await collect_attachments(+ [_file(name=None, mime=None)], max_count=10, max_bytes=1000+ )+ assert kept[0].filename == "file"+ assert kept[0].mime_type == "application/octet-stream"+++class TestBudgetHistory:+ @pytest.mark.asyncio+ async def test_all_fit_returns_chronological_order(self):+ # Input is newest-first; output is chronological (reversed).+ result = await budget_history(+ _stream([_entry("newest"), _entry("older")]), char_budget=1000+ )+ assert [e.text for e in result] == ["older", "newest"]++ @pytest.mark.asyncio+ async def test_over_budget_keeps_most_recent(self):+ result = await budget_history(+ _stream([_entry("a" * 30), _entry("b" * 30)]), char_budget=40+ )+ assert [e.text for e in result] == ["a" * 30]++ @pytest.mark.asyncio+ async def test_lone_oversized_head_is_truncated_with_marker(self):+ result = await budget_history(_stream([_entry("x" * 100)]), char_budget=30)+ assert len(result) == 1+ assert result[0].text.endswith("… [message truncated]")+ assert len(result[0].text) <= 30++ @pytest.mark.asyncio+ async def test_tiny_budget_below_marker_width_still_respects_budget(self):+ # A budget smaller than the truncation marker must not overrun.+ result = await budget_history(_stream([_entry("x" * 100)]), char_budget=5)+ assert len(result) == 1+ assert len(result[0].text) <= 5++ @pytest.mark.asyncio+ async def test_empty_stream_returns_empty(self):+ assert await budget_history(_stream([]), char_budget=100) == ()+++class TestShouldIgnore:+ def test_own_message_is_ignored(self):+ assert should_ignore(is_self=True, author_is_bot=True, bot_mentioned=True)++ def test_other_bot_without_mention_is_ignored(self):+ assert should_ignore(is_self=False, author_is_bot=True, bot_mentioned=False)++ def test_other_bot_with_mention_is_processed(self):+ assert not should_ignore(is_self=False, author_is_bot=True, bot_mentioned=True)++ def test_human_is_processed(self):+ assert not should_ignore(+ is_self=False, author_is_bot=False, bot_mentioned=False+ )diff --git a/autogpt_platform/backend/backend/copilot/bot/config.py b/autogpt_platform/backend/backend/copilot/bot/config.pyindex 2a0b03dfab..90a8fc7eda 100644--- a/autogpt_platform/backend/backend/copilot/bot/config.py+++ b/autogpt_platform/backend/backend/copilot/bot/config.py@@ -10,3 +10,8 @@# dangerous. Each turn refreshes this TTL, so an active conversation never loses# context within the subscription window.SESSION_TTL = 7 * 86400 # 7 days — matches the thread subscription window++# Cap on how many attachments the bot pulls off a single message into the+# workspace, so a message with dozens of files can't fan out into that many+# uploads/scans. Bot policy (not a platform limit) — shared by every adapter.+MAX_INBOUND_ATTACHMENTS = 10diff --git a/autogpt_platform/backend/backend/copilot/bot/text.py b/autogpt_platform/backend/backend/copilot/bot/text.pyindex e6898a72b6..cfa726f030 100644--- a/autogpt_platform/backend/backend/copilot/bot/text.py+++ b/autogpt_platform/backend/backend/copilot/bot/text.py@@ -1,6 +1,8 @@"""Text formatting helpers — message batching and chunk splitting."""import re+from collections import Counter+from typing import Callable, Iteratorfrom backend.data.sharing.workspace_refs import cut_lands_inside_artifact_link@@ -68,6 +70,78 @@ def split_at_boundary(text: str, flush_at: int) -> tuple[str, str]:return _balance_code_fences(text[:cut], text[cut:])+def iter_chunks(text: str, flush_at: int) -> Iterator[str]:+ """Yield ``text`` split into postable chunks, each under ``flush_at``.++ Wraps the ``split_at_boundary`` drain loop so any adapter sending a whole+ long message at once (proactive posts) shares one splitter instead of+ re-implementing the loop.+ """+ remaining = text.strip()+ while remaining:+ chunk, remaining = split_at_boundary(remaining, flush_at)+ if not chunk:+ break+ yield chunk+++def resolve_mentions(+ text: str,+ mentionable_users: tuple[tuple[str, str], ...],+ render_token: Callable[[str, str], str],+) -> tuple[str, list[str]]:+ """Substitute ``@DisplayName`` with a platform mention token, but only for+ users on ``mentionable_users``. Returns ``(rendered_text, pinged_user_ids)``.++ Security-sensitive shared policy: only allowlisted names are ever+ converted, so the bot never pings a user the LLM invented (``@everyone``,+ ``@here``, a hallucinated or elsewhere-learned name) — those stay plain+ text. Longest names first so ``@John Smith`` matches before ``@John``, and+ the match is word-bounded so ``@Name`` inside an email/URL is left alone.+ ``render_token(display_name, user_id)`` produces the platform's mention+ markup; the adapter turns ``pinged_user_ids`` into its own ping-safety+ object.+ """+ if not mentionable_users:+ return text, []++ # Names that two different allowlisted users share case-insensitively are+ # ambiguous — we can't know which the author meant, so leave them plain+ # rather than ping whichever happens to sort first.+ name_counts = Counter(name.casefold() for name, _ in mentionable_users)+ users_by_name = {+ name.casefold(): (name, user_id)+ for name, user_id in mentionable_users+ if name_counts[name.casefold()] == 1+ }+ if not users_by_name:+ return text, []++ # ONE combined pattern + ONE sub() pass over the original text. re.sub never+ # re-scans replacement output, so a rendered token can't be matched again —+ # e.g. a display name equal to another user's ID inside an emitted <@U123>.+ # Longest alternative first so "@John Smith" wins over "@John"; the same+ # boundaries as before keep emails/URLs and "@John-Smith" prefixes unmatched.+ alternation = "|".join(+ re.escape(name)+ for name, _ in sorted(users_by_name.values(), key=lambda pair: -len(pair[0]))+ )+ pattern = re.compile(+ rf"(?<![\w@])@({alternation})(?![\w-])",+ re.IGNORECASE,+ )++ pinged: list[str] = []++ def _render(match: re.Match[str]) -> str:+ display_name, user_id = users_by_name[match.group(1).casefold()]+ if user_id not in pinged:+ pinged.append(user_id)+ return render_token(display_name, user_id)++ return pattern.sub(_render, text), pinged++def _guarded_cut(text: str, cut: int) -> int:"""Keep a workspace artifact markdown link from being split across chunks.diff --git a/autogpt_platform/backend/backend/copilot/bot/text_test.py b/autogpt_platform/backend/backend/copilot/bot/text_test.pyindex 7b1369dcc7..bdbd317891 100644--- a/autogpt_platform/backend/backend/copilot/bot/text_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/text_test.py@@ -2,7 +2,113 @@from backend.data.sharing.workspace_refs import extract_artifact_links-from .text import _balance_code_fences, format_batch, split_at_boundary+from .text import (+ _balance_code_fences,+ format_batch,+ iter_chunks,+ resolve_mentions,+ split_at_boundary,+)+++def _token(_name: str, uid: str) -> str:+ return f"<@{uid}>"+++class TestResolveMentions:+ def test_allowlisted_name_is_rendered_and_pinged(self):+ rendered, pinged = resolve_mentions(+ "hey @Bently look", (("Bently", "U1"),), _token+ )+ assert rendered == "hey <@U1> look"+ assert pinged == ["U1"]++ def test_non_allowlisted_name_stays_plain_and_unpinged(self):+ # @everyone / a name the LLM invented must never become a real ping.+ rendered, pinged = resolve_mentions(+ "@everyone and @Ghost", (("Bently", "U1"),), _token+ )+ assert rendered == "@everyone and @Ghost"+ assert pinged == []++ def test_longest_name_wins(self):+ rendered, pinged = resolve_mentions(+ "ping @John Smith now",+ (("John", "U1"), ("John Smith", "U2")),+ _token,+ )+ assert rendered == "ping <@U2> now"+ assert pinged == ["U2"]++ def test_name_inside_email_is_not_matched(self):+ rendered, pinged = resolve_mentions(+ "mail [email protected]", (("Bently", "U1"),), _token+ )+ assert rendered == "mail [email protected]"+ assert pinged == []++ def test_partial_name_before_hyphen_is_not_matched(self):+ # "@John" must not ping inside "@John-Smith" when only John is allowlisted.+ rendered, pinged = resolve_mentions(+ "ping @John-Smith please", (("John", "U1"),), _token+ )+ assert rendered == "ping @John-Smith please"+ assert pinged == []++ def test_hyphenated_name_still_matches_fully(self):+ rendered, pinged = resolve_mentions(+ "ping @John-Smith please", (("John-Smith", "U2"),), _token+ )+ assert rendered == "ping <@U2> please"+ assert pinged == ["U2"]++ def test_ambiguous_duplicate_names_stay_plain(self):+ # Two different users share a case-insensitive display name → ping neither.+ rendered, pinged = resolve_mentions(+ "hey @john", (("John", "U1"), ("john", "U2")), _token+ )+ assert rendered == "hey @john"+ assert pinged == []++ def test_rendered_token_is_never_resubstituted(self):+ # A display name equal to another user's ID must not re-match inside an+ # already-rendered token: "@Bently" → "<@U1>", and the second user named+ # "U1" must not turn that into "<@<@U9>>". Single-pass sub guarantees it.+ rendered, pinged = resolve_mentions(+ "hey @Bently", (("Bently", "U1"), ("U1", "U9")), _token+ )+ assert rendered == "hey <@U1>"+ assert pinged == ["U1"]++ def test_repeated_mentions_render_all_but_ping_once(self):+ rendered, pinged = resolve_mentions(+ "@Bently and again @Bently", (("Bently", "U1"),), _token+ )+ assert rendered == "<@U1> and again <@U1>"+ assert pinged == ["U1"]++ def test_empty_allowlist_returns_text_unchanged(self):+ rendered, pinged = resolve_mentions("hi @Bently", (), _token)+ assert rendered == "hi @Bently"+ assert pinged == []+++class TestIterChunks:+ def test_short_text_is_one_chunk(self):+ assert list(iter_chunks("hello", 100)) == ["hello"]++ def test_long_text_splits_into_multiple_chunks_all_under_limit(self):+ text = "\n\n".join(f"paragraph {i} " + "x" * 40 for i in range(10))+ chunks = list(iter_chunks(text, 100))+ assert len(chunks) > 1+ assert all(len(c) <= 100 for c in chunks)+ # Reassembling recovers the content (whitespace at cut points aside).+ assert "".join(chunks).replace("\n", "").replace(" ", "") == text.replace(+ "\n", ""+ ).replace(" ", "")++ def test_blank_text_yields_nothing(self):+ assert list(iter_chunks(" ", 100)) == []class TestFormatBatch: