Skip to content

The agent that grows with you

fix(discord): retire the auto-thread title mask from raw rename events

unsupportedpastelsea32af9331a5
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index e913ebf1059..e5f1bd46a9e 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -25,7 +25,7 @@ import threading
import time
import traceback
from collections import defaultdict
-from contextlib import suppress
+from contextlib import nullcontext, suppress
from typing import Callable, Dict, List, Optional, Any, Tuple
from urllib.parse import quote, urljoin
@@ -79,6 +79,7 @@ class _Snowflake:
def __init__(self, id: int) -> None: # noqa: A002 - matches discord API
self.id = id
+
VALID_THREAD_AUTO_ARCHIVE_MINUTES = {60, 1440, 4320, 10080}
_DISCORD_COMMAND_SYNC_POLICIES = {"safe", "bulk", "off"}
_DISCORD_COMMAND_SYNC_STATE_SUBDIR = "gateway"
@@ -89,7 +90,6 @@ _DISCORD_COMMAND_SYNC_MUTATION_INTERVAL_SECONDS = 4.5
_DISCORD_COMMAND_SYNC_MAX_RATE_LIMIT_SLEEP_SECONDS = 30.0
# Discord caps global slash commands at 100/app; exceeding it fails the ENTIRE sync (error 30032).
_DISCORD_MAX_APP_COMMANDS = 100
-_SEMANTIC_THREAD_RENAMES_MAX = 2000
# Native slash commands (registered before COMMAND_REGISTRY/plugins so they survive the 100 cap):
# (discord name, description, [(arg, type, default-or-_REQUIRED, arg description,
# [(choice label, value), ...] or None)], command-text template, follow-up message)
@@ -1049,9 +1049,10 @@ def _read_discord_prompt_timeout() -> int:
from plugins.platforms.discord.adapter_media import DiscordMediaMixin
+from plugins.platforms.discord.adapter_thread_titles import DiscordThreadTitlesMixin, SemanticThreadRenames
-class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
+class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAdapter):
"""Discord bot adapter: guild/DM messages, threads, slash commands, button approvals, reactions."""
MAX_MESSAGE_LENGTH = 2000
@@ -1114,9 +1115,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
self._voice_fx_cfg: Dict[str, Any] = self._load_voice_fx_config()
# Threads the bot participated in (no @mention needed there); persisted across restarts.
self._threads = ThreadParticipationTracker("discord")
- # thread id -> (name it replaced, name it set, set name seen yet) for Hermes's own semantic
- # renames; see _format_thread_chat_name. In memory: after a restart the next turn re-renders once.
- self._semantic_thread_renames: Dict[str, Tuple[str, str, bool]] = {}
+ self._semantic_thread_renames = SemanticThreadRenames()
# Persistent typing loops per channel (DMs don't reliably show bot typing events).
self._typing_tasks: Dict[str, asyncio.Task] = {}
self._bot_task: Optional[asyncio.Task] = None
@@ -1378,6 +1377,10 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
async def on_thread_create(thread):
await adapter_self._on_platform_thread_create(thread)
+ @self._client.event
+ async def on_raw_thread_update(payload: Any) -> None:
+ await adapter_self._on_platform_raw_thread_update(payload)
+
@self._client.event
async def on_thread_update(before, after):
await adapter_self._on_platform_thread_update(before, after)
@@ -1713,13 +1716,6 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
async def _on_platform_thread_update(self, before, after) -> None:
"""Normalize ``on_thread_update`` renames into ``thread_renamed``; non-rename updates are dropped."""
- # The event is the only provenance signal: any name other than the one Hermes set came from
- # someone else, even when its text matches the name Hermes replaced (cache lag looks the same).
- thread_key = str(getattr(after, "id", ""))
- renamed = self._semantic_thread_renames.get(thread_key)
- if renamed and getattr(after, "name", None) != renamed[1]:
- self._semantic_thread_renames.pop(thread_key, None)
-
def _build():
old_name = getattr(before, "name", None)
new_name = getattr(after, "name", None)
@@ -5461,14 +5457,14 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
edit = getattr(thread, "edit", None)
if edit is None:
return False
+ # Only the title lane's guarded rename is Hermes's own title (see adapter_thread_titles).
+ attempt = (
+ self._semantic_thread_renames.attempt(str(thread_id_int), only_if_current_name, cleaned)
+ if only_if_current_name is not None else nullcontext()
+ )
try:
- await edit(name=cleaned, reason="Hermes semantic session title")
- if only_if_current_name is not None:
- renames = self._semantic_thread_renames
- renames.pop(str(thread_id_int), None)
- renames[str(thread_id_int)] = (current_name, cleaned, False)
- while len(renames) > _SEMANTIC_THREAD_RENAMES_MAX:
- renames.pop(next(iter(renames)))
+ with attempt:
+ await edit(name=cleaned, reason="Hermes semantic session title")
logger.info(
"[%s] Renamed Discord thread %s from %r to %r",
self.name, thread_id, current_name, cleaned,
@@ -5809,37 +5805,6 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
topic = getattr(parent, "topic", None)
return topic
- def _format_thread_chat_name(self, thread: Any) -> str:
- """Build a readable chat name for thread-like Discord channels, including forum context when available."""
- thread_name = getattr(thread, "name", None) or str(getattr(thread, "id", "thread"))
- # chat_name keys the pinned session-context prompt, and Hermes's own title rename lands
- # between a new thread's first and second turns: keep the name the turns were pinned under.
- # A rename by anyone else no longer matches what Hermes set, so it still re-renders.
- thread_key = str(getattr(thread, "id", ""))
- renamed = self._semantic_thread_renames.get(thread_key)
- if renamed:
- replaced, set_name, set_seen = renamed
- if thread_name == set_name:
- if not set_seen:
- self._semantic_thread_renames[thread_key] = (replaced, set_name, True)
- thread_name = replaced
- elif set_seen or thread_name != replaced:
- # Someone else renamed it (the old name before Hermes's title is first seen is only
- # cache lag). Equal text is not provenance: if they later restore Hermes's title,
- # that is their choice of name and must show as itself.
- self._semantic_thread_renames.pop(thread_key, None)
- parent = getattr(thread, "parent", None)
- guild = getattr(thread, "guild", None) or getattr(parent, "guild", None)
- guild_name = getattr(guild, "name", None)
- parent_name = getattr(parent, "name", None)
- if self._is_forum_parent(parent) and guild_name and parent_name:
- return f"{guild_name} / {parent_name} / {thread_name}"
- if parent_name and guild_name:
- return f"{guild_name} / #{parent_name} / {thread_name}"
- if parent_name:
- return f"{parent_name} / {thread_name}"
- return thread_name
-
# ------------------------------------------------------------------
# Attachment download helpers
# Prefer the authenticated bot session (``att.read()``): CDN URLs increasingly 403 without
diff --git a/plugins/platforms/discord/adapter_thread_titles.py b/plugins/platforms/discord/adapter_thread_titles.py
new file mode 100644
index 00000000000..8f4580209f1
--- /dev/null
+++ b/plugins/platforms/discord/adapter_thread_titles.py
@@ -0,0 +1,98 @@
+"""Keep Hermes's own auto-thread title rename out of the pinned session-context prompt.
+
+``chat_name`` keys the pinned prompt, and the title lane renames a new auto-thread between its
+first and second turns. While the thread carries Hermes's title, its chat name keeps the name the
+title replaced. Any other observed name retires the record: equal text is not edit provenance, so
+a moderator who later restores Hermes's title sees it as itself. Records live in memory; after a
+restart each renamed thread re-renders once.
+"""
+from __future__ import annotations
+
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass
+from typing import Any
+
+_MAX_RECORDS = 2000
+
+
+@dataclass
+class _TitleRename:
+ replaced: str
+ title: str
+ last_event_name: str
+ title_seen: bool = False
+
+
+class SemanticThreadRenames:
+ """Hermes's latest guarded title rename per thread id."""
+
+ def __init__(self) -> None:
+ self._records: dict[str, _TitleRename] = {}
+
+ @contextmanager
+ def attempt(self, thread_id: str, replaced: str, title: str) -> Iterator[None]:
+ """Record a rename before its REST edit, which gateway events can overtake; drop it if the edit fails."""
+ record = _TitleRename(replaced, title, last_event_name=replaced)
+ self._records.pop(thread_id, None) # re-insert last: eviction is oldest first
+ self._records[thread_id] = record
+ while len(self._records) > _MAX_RECORDS:
+ del self._records[next(iter(self._records))]
+ try:
+ yield
+ except BaseException:
+ # Cancellation included. A newer attempt owns a different record and keeps it.
+ if self._records.get(thread_id) is record:
+ del self._records[thread_id]
+ raise
+
+ def observe_event(self, thread_id: str, name: str) -> None:
+ """Apply one gateway rename event; only Hermes's own replaced -> title step keeps the record."""
+ record = self._records.get(thread_id)
+ if record is None or name == record.last_event_name:
+ return
+ if (record.last_event_name, name) == (record.replaced, record.title):
+ record.last_event_name = name
+ else:
+ del self._records[thread_id]
+
+ def display_name(self, thread_id: str, name: str) -> str:
+ """The name to render for a thread currently called *name*."""
+ record = self._records.get(thread_id)
+ if record is None:
+ return name
+ if name == record.title:
+ record.title_seen = True
+ return record.replaced
+ # Until the title has been seen, the replaced name may come from a cache that lags the edit.
+ if record.title_seen or name != record.replaced:
+ del self._records[thread_id]
+ return name
+
+
+class DiscordThreadTitlesMixin:
+ _semantic_thread_renames: SemanticThreadRenames
+ _is_forum_parent: Callable[[Any], bool]
+
+ async def _on_platform_raw_thread_update(self, payload: Any) -> None:
+ # discord.py updates the cached thread before cached callbacks run, so batched updates
+ # would all report the final name; each raw payload keeps its own.
+ name = payload.data.get("name")
+ if isinstance(name, str):
+ self._semantic_thread_renames.observe_event(str(payload.thread_id), name)
+
+ def _format_thread_chat_name(self, thread: Any) -> str:
+ """Build a readable chat name for thread-like Discord channels, including forum context when available."""
+ thread_name = getattr(thread, "name", None) or str(getattr(thread, "id", "thread"))
+ thread_name = self._semantic_thread_renames.display_name(str(getattr(thread, "id", "")), thread_name)
+ parent = getattr(thread, "parent", None)
+ guild = getattr(thread, "guild", None) or getattr(parent, "guild", None)
+ guild_name = getattr(guild, "name", None)
+ parent_name = getattr(parent, "name", None)
+ if self._is_forum_parent(parent) and guild_name and parent_name:
+ return f"{guild_name} / {parent_name} / {thread_name}"
+ if parent_name and guild_name:
+ return f"{guild_name} / #{parent_name} / {thread_name}"
+ if parent_name:
+ return f"{parent_name} / {thread_name}"
+ return thread_name
diff --git a/tests/e2e/core/platforms/test_discord_thread_rename_ordering.py b/tests/e2e/core/platforms/test_discord_thread_rename_ordering.py
new file mode 100644
index 00000000000..31267ef716d
--- /dev/null
+++ b/tests/e2e/core/platforms/test_discord_thread_rename_ordering.py
@@ -0,0 +1,92 @@
+"""Real SDK dispatch must preserve moderator names before cached callbacks run.
+
+Regression for #131614. The messaging E2E lane owns this SDK contract; gateway
+unit tests exercise the same state machine without the optional Discord extra.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import sys
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+import plugins.platforms.discord.adapter as discord_platform
+from gateway.config import PlatformConfig
+
+
+async def test_batched_thread_updates_retire_the_alias_through_connected_bot(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The parent E2E conftest installs SDK mocks. Require the real messaging
+ # extra here: an absent dependency must fail the owning CI lane, never skip.
+ with patch.dict(sys.modules):
+ for name in tuple(sys.modules):
+ if name == "discord" or name.startswith("discord."):
+ del sys.modules[name]
+ discord = importlib.import_module("discord")
+ commands = importlib.import_module("discord.ext.commands")
+ state_type = importlib.import_module("discord.state").ConnectionState
+ monkeypatch.setattr(discord_platform, "discord", discord)
+ monkeypatch.setattr(discord_platform, "commands", commands)
+ monkeypatch.setattr(discord_platform, "Intents", discord.Intents)
+ monkeypatch.setattr(discord_platform, "DISCORD_AVAILABLE", True)
+ monkeypatch.setattr(discord_platform, "_load_opus_codec", lambda: None)
+ adapter = discord_platform.DiscordAdapter(PlatformConfig(
+ enabled=True, token="fake", extra={"slash_commands": False}))
+ monkeypatch.setattr(adapter, "_start_liveness_probe", lambda: None)
+
+ async def start(client: Any, token: str, **kwargs: Any) -> None:
+ await client._async_setup_hook()
+ adapter._ready_event.set()
+ await asyncio.Future() # transport remains open until disconnect
+
+ monkeypatch.setattr(commands.Bot, "start", start)
+ assert await adapter.connect()
+ try:
+ assert not adapter._platform_events_subscribed()
+ parent = SimpleNamespace(id=700, name="ops", guild=SimpleNamespace(name="Hermes Server"))
+
+ class CachedThread:
+ id, parent_id = 800, 700
+ name = "what broke?"
+ guild = parent.guild
+ archived = False
+
+ def _update(self, data: dict[str, Any]) -> None:
+ self.name = data["name"]
+
+ async def edit(self, *, name: str, reason: str | None = None) -> SimpleNamespace:
+ return SimpleNamespace(name=name)
+
+ thread = CachedThread()
+ thread.parent = parent
+ monkeypatch.setattr(adapter._client, "get_channel", lambda _id: thread)
+ first = adapter._format_thread_chat_name(thread)
+ assert await adapter.rename_thread("800", "Database outage", only_if_current_name=thread.name)
+ # Do not call the formatter on Hermes's title before the moderator
+ # roundtrip: its cache-lag fallback would otherwise hide this seam.
+ guild = SimpleNamespace(get_thread=lambda _id: thread)
+ state = SimpleNamespace(_get_guild=lambda _id: guild, dispatch=adapter._client.dispatch)
+ scheduled_before = asyncio.all_tasks()
+ state_type.parse_thread_update(state, {
+ "id": "800", "guild_id": "1", "parent_id": "700", "type": 11, "name": "Database outage",
+ })
+ await asyncio.gather(*(asyncio.all_tasks() - scheduled_before))
+ scheduled_before = asyncio.all_tasks()
+ for name in ("what broke?", "Database outage"):
+ state_type.parse_thread_update(state, {
+ "id": "800", "guild_id": "1", "parent_id": "700", "type": 11, "name": name,
+ })
+ # Both cached callbacks now share the final name. Only raw payloads
+ # retain the intermediate moderator edit, with no hook subscriber.
+ assert thread.name == "Database outage"
+ await asyncio.gather(*(asyncio.all_tasks() - scheduled_before))
+ rendered = adapter._format_thread_chat_name(thread)
+ assert rendered.endswith(" / Database outage")
+ assert rendered != first
+ finally:
+ await adapter.disconnect()
diff --git a/tests/gateway/test_discord_auto_thread_rename_pin.py b/tests/gateway/test_discord_auto_thread_rename_pin.py
index 55b8b2e974e..fdd3ec043bc 100644
--- a/tests/gateway/test_discord_auto_thread_rename_pin.py
+++ b/tests/gateway/test_discord_auto_thread_rename_pin.py
@@ -1,13 +1,12 @@
-"""Hermes's own semantic rename of an auto-created thread keeps the thread's pinned prompt.
-
-``chat_name`` is part of the pinned session-context prompt's key. The title lane renames a new
-auto-thread once the LLM title arrives, normally before the user's second message, so turn 2 read
-the new name and re-rendered the already-sent prompt: a prompt-cache miss on turn 2 of every
-auto-threaded conversation on the default config. A rename by anyone else is a real metadata
-change and still re-renders, including one that later restores Hermes's title: equal text is not
-edit provenance.
+"""Hermes's own auto-thread title rename keeps the pinned session-context prompt.
+
+``chat_name`` keys the pinned prompt, and the title lane renames a new auto-thread between turns 1
+and 2. Any other rename still re-renders, including a later restore of Hermes's title.
"""
+from __future__ import annotations
+import asyncio
+from collections.abc import Awaitable, Callable
from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock
@@ -19,94 +18,123 @@ import plugins.platforms.discord.adapter as discord_platform
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.session import build_session_context
from plugins.platforms.discord.adapter import DiscordAdapter
+from plugins.platforms.discord.adapter_thread_titles import SemanticThreadRenames
-
-class _Text:
- def __init__(self, channel_id, name="ops"):
- self.id, self.name, self.topic = channel_id, name, None
- self.guild = SimpleNamespace(id=1, name="Hermes Server")
+OPENING, TITLE = "what broke?", "Database outage"
class _Thread:
- def __init__(self, channel_id, parent, name):
- self.id, self.name, self.parent, self.parent_id = channel_id, name, parent, parent.id
- self.guild = parent.guild
+ def __init__(self, parent: SimpleNamespace) -> None:
+ self.id, self.name, self.parent, self.parent_id = 800, OPENING, parent, parent.id
+ self.guild, self.owner_id, self.archived = parent.guild, 42, False
- async def edit(self, *, name, reason=None):
+ async def edit(self, *, name: str, reason: str | None = None) -> None:
self.name = name
-_USER = SimpleNamespace(id=42, display_name="Alice", name="alice")
-
+Turn = Callable[[object, int], Awaitable[str]]
+Conversation = tuple[DiscordAdapter, SimpleNamespace, _Thread, Turn]
-def _message(channel, message_id):
- return SimpleNamespace(
- id=message_id, content="what broke?", mentions=[], attachments=[], reference=None,
- created_at=datetime.now(timezone.utc), channel=channel, author=_USER)
-
[email protected]("moderator_name", ["Renamed by a moderator", "what broke?"])
-async def test_hermes_title_rename_keeps_the_pin_and_a_human_rename_does_not(monkeypatch, moderator_name):
+def conversation(monkeypatch: pytest.MonkeyPatch) -> Conversation:
monkeypatch.setattr(discord_platform.discord, "Thread", _Thread, raising=False)
monkeypatch.setattr(discord_platform, "DISCORD_AVAILABLE", True)
monkeypatch.setenv("DISCORD_REQUIRE_MENTION", "false")
monkeypatch.setenv("DISCORD_AUTO_THREAD", "true")
- parent = _Text(700)
- thread = _Thread(800, parent, name="what broke?")
+ parent = SimpleNamespace(id=700, name="ops", topic=None, guild=SimpleNamespace(id=1, name="Hermes Server"))
+ thread = _Thread(parent)
adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fake"))
adapter._client = SimpleNamespace(user=SimpleNamespace(id=999), get_channel=lambda _id: thread)
adapter._text_batch_delay_seconds = 0
adapter._discord_history_backfill = lambda: False
adapter._auto_create_thread = AsyncMock(return_value=thread)
adapter.handle_message = AsyncMock()
-
runner = object.__new__(gateway_run.GatewayRunner)
config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")})
- async def turn(channel, message_id):
- await adapter._handle_message(_message(channel, message_id))
+ async def turn(channel: object, message_id: int) -> str:
+ await adapter._handle_message(SimpleNamespace(
+ id=message_id, content=OPENING, mentions=[], attachments=[], reference=None,
+ created_at=datetime.now(timezone.utc), channel=channel,
+ author=SimpleNamespace(id=42, display_name="Alice", name="alice")))
source = adapter.handle_message.await_args.args[0].source
- assert source.chat_id == "800"
return runner._pinned_session_context_prompt(build_session_context(source, config), False, "k")
+ return adapter, parent, thread, turn
+
+
+async def _raw_rename(adapter: DiscordAdapter, name: str) -> None:
+ await adapter._on_platform_raw_thread_update(SimpleNamespace(thread_id=800, data={"name": name}))
+
+
[email protected]("moderator_name", ["Renamed by a moderator", OPENING])
+async def test_hermes_title_keeps_the_pin_and_a_moderator_rename_does_not(
+ conversation: Conversation, moderator_name: str,
+) -> None:
+ adapter, parent, thread, turn = conversation
first = await turn(parent, 100)
- # The title lane's call, as gateway/run_topics.py makes it for a native auto-thread.
- assert await adapter.rename_thread("800", "Database outage", only_if_current_name="what broke?")
- assert thread.name == "Database outage"
- # A message read through a cache that has not caught up with the edit still sees the old name.
- thread.name = "what broke?"
- assert await turn(thread, 104) == first
- thread.name = "Database outage"
+ # The title lane's call, as gateway/run_topics.py makes it, and its own gateway event.
+ assert await adapter.rename_thread("800", TITLE, only_if_current_name=OPENING)
+ await _raw_rename(adapter, TITLE)
+ thread.name = OPENING # a cache that has not caught up with the edit
assert await turn(thread, 101) == first
+ thread.name = TITLE
+ assert await turn(thread, 102) == first
thread.name = moderator_name
- assert f"Hermes Server / #ops / {moderator_name}" in await turn(thread, 102)
- # The moderator then restores Hermes's title: it shows as itself, not as the opening name.
- thread.name = "Database outage"
- assert "Hermes Server / #ops / Database outage" in await turn(thread, 103)
+ assert f"Hermes Server / #ops / {moderator_name}" in await turn(thread, 103)
+ thread.name = TITLE # the moderator restores Hermes's title: it shows as itself
+ assert f"Hermes Server / #ops / {TITLE}" in await turn(thread, 104)
@pytest.mark.asyncio
-async def test_a_restore_before_any_turn_retires_the_mask_through_the_update_event(monkeypatch):
- # Restoring the opening name before Hermes's title was ever read looks like cache lag to the
- # formatter; only the THREAD_UPDATE says someone else named it, so that event retires the record.
- monkeypatch.setattr(discord_platform.discord, "Thread", _Thread, raising=False)
- monkeypatch.setattr(discord_platform, "DISCORD_AVAILABLE", True)
- monkeypatch.setenv("DISCORD_REQUIRE_MENTION", "false")
- parent = _Text(700)
- thread = _Thread(800, parent, name="what broke?")
- adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fake"))
- adapter._client = SimpleNamespace(user=SimpleNamespace(id=999), get_channel=lambda _id: thread)
-
- async def rename(name):
- before = SimpleNamespace(id=thread.id, name=thread.name)
+async def test_a_moderator_round_trip_during_the_edit_retires_the_record(conversation: Conversation) -> None:
+ adapter, parent, thread, turn = conversation
+ await turn(parent, 100)
+
+ async def edit(*, name: str, reason: str | None = None) -> None:
+ # Gateway events overtake the REST response: Hermes's own, then a moderator's round trip.
+ for event_name in (name, OPENING, name):
+ await _raw_rename(adapter, event_name)
thread.name = name
- await adapter._on_platform_thread_update(before, thread)
-
- assert await adapter.rename_thread("800", "Database outage", only_if_current_name="what broke?")
- await adapter._on_platform_thread_update(SimpleNamespace(id=800, name="what broke?"), thread)
- await rename("what broke?")
- assert adapter._format_thread_chat_name(thread).endswith("what broke?")
- await rename("Database outage")
- assert adapter._format_thread_chat_name(thread) == "Hermes Server / #ops / Database outage"
+
+ thread.edit = edit
+ assert await adapter.rename_thread("800", TITLE, only_if_current_name=OPENING)
+ assert f"Hermes Server / #ops / {TITLE}" in await turn(thread, 101)
+
+
[email protected]("cancel", [False, True], ids=["failed", "cancelled"])
+async def test_an_unfinished_edit_drops_its_record(conversation: Conversation, cancel: bool) -> None:
+ adapter, parent, thread, turn = conversation
+ await turn(parent, 100)
+ started, finish = asyncio.Event(), asyncio.Event()
+
+ async def edit(*, name: str, reason: str | None = None) -> None:
+ started.set()
+ await finish.wait()
+ raise RuntimeError("REST edit failed")
+
+ thread.edit = edit
+ attempt = asyncio.create_task(adapter.rename_thread("800", TITLE, only_if_current_name=OPENING))
+ await started.wait()
+ if cancel:
+ attempt.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await attempt
+ else:
+ finish.set()
+ assert not await attempt
+ thread.name = TITLE # chosen by someone else
+ assert f"Hermes Server / #ops / {TITLE}" in await turn(thread, 101)
+
+
+def test_an_unfinished_attempt_keeps_a_newer_attempts_record() -> None:
+ renames = SemanticThreadRenames()
+ with pytest.raises(RuntimeError), renames.attempt("800", OPENING, TITLE):
+ with renames.attempt("800", OPENING, TITLE):
+ pass
+ raise RuntimeError("REST edit failed")
+ assert renames.display_name("800", TITLE) == OPENING
diff --git a/tests/gateway/test_discord_platform_events.py b/tests/gateway/test_discord_platform_events.py
index 997dd6baf10..b57e7370ee0 100644
--- a/tests/gateway/test_discord_platform_events.py
+++ b/tests/gateway/test_discord_platform_events.py
@@ -83,7 +83,6 @@ def _adapter() -> DiscordAdapter:
a.platform = Platform.DISCORD
a.config = SimpleNamespace(extra={})
a.gateway_runner = None
- a._semantic_thread_renames = {}
return a