The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(discord): slash, /thread and voice turns carry a message turn's prompt inputs
John Paul Soliva7c3a3bfc0690
diff --git a/gateway/run_voice.py b/gateway/run_voice.pyindex 36c04400486..f5e6537fa40 100644--- a/gateway/run_voice.py+++ b/gateway/run_voice.py@@ -233,13 +233,19 @@ class GatewayVoiceMixin:def _voice_input_source(adapter, guild_id: int, user_id: int, text_ch_id) -> SessionSource:"""Bound text channel's own source when available (voice shares the text conversation'ssession), else a synthetic one."""+ # The speaker's display name, as their typed messages carry it: the pinned session-context+ # prompt renders it, so a bare id here re-rendered it on every spoken/typed switch.+ guild = getattr(adapter, "_client", None) and adapter._client.get_guild(guild_id)+ member = guild.get_member(int(user_id)) if guild else None+ display_name = getattr(member, "display_name", None)+ user_name = display_name if isinstance(display_name, str) and display_name else str(user_id)if source_data := getattr(adapter, "_voice_sources", {}).get(guild_id):source = SessionSource.from_dict(source_data)- source.user_id = source.user_name = str(user_id)+ source.user_id, source.user_name = str(user_id), user_nameelse:source = SessionSource(platform=Platform.DISCORD, chat_id=str(text_ch_id), user_id=str(user_id),- user_name=str(user_id), chat_type="channel",+ user_name=user_name, chat_type="channel",profile=getattr(adapter, "_owner_profile", None))# Serialization drops transport provenance; auth must still follow the receiving bot.source._transport_adapter_ref = weakref.ref(adapter)@@ -281,18 +287,22 @@ class GatewayVoiceMixin:safe_text = transcript[:2000].replace("@everyone", "@\u200beveryone")safe_text = safe_text.replace("@here", "@\u200bhere")await channel.send(t("gateway.voice.transcript_echo", user=user_id, text=safe_text))- # Bound text channel's channel_prompt: voice input gets the same per-channel context.- channel_prompt = None+ # Bound text channel's channel_prompt and skills: voice input gets the same per-channel+ # context, and a first spoken turn opens the session, the only point skills load.+ channel_prompt = auto_skill = Noneif callable(resolver := getattr(adapter, "_resolve_channel_prompt", None)):with suppress(Exception):resolved = resolver(str(text_ch_id))channel_prompt = resolved if isinstance(resolved, str) else None+ if callable(skills := getattr(adapter, "_resolve_channel_skills", None)):+ bound = skills(str(text_ch_id))+ auto_skill = bound if isinstance(bound, list) else None# Synthetic MessageEvent for the normal pipeline; the SimpleNamespace raw_message lets# _get_guild_id() extract guild_id so _send_voice_reply() plays audio in the voice channel.event = MessageEvent(source=source, text=transcript, message_type=MessageType.VOICE,raw_message=SimpleNamespace(guild_id=guild_id, guild=None),- channel_prompt=channel_prompt)+ channel_prompt=channel_prompt, auto_skill=auto_skill)await adapter.handle_message(event)def _should_send_voice_reply(diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 837567a6d4e..802c7411afb 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -4733,8 +4733,14 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAdthread_id = str(interaction.channel_id)else:chat_type = "group"+ # A slash turn re-pins the session-context prompt, so it names the chat exactly as a message+ # there does; any other label re-renders the pinned prompt on every switch between the two.chat_name = ""- if not is_dm and hasattr(interaction.channel, "name"):+ if is_dm:+ chat_name = interaction.user.name+ elif is_thread:+ chat_name = self._format_thread_chat_name(interaction.channel)+ elif hasattr(interaction.channel, "name"):chat_name = interaction.channel.nameif hasattr(interaction.channel, "guild") and interaction.channel.guild:chat_name = f"{interaction.channel.guild.name} / #{chat_name}"@@ -4756,6 +4762,8 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAdreturn MessageEvent(text=text, message_type=msg_type, source=source, raw_message=interaction,channel_prompt=self._resolve_channel_prompt(channel_id, parent_id or None),+ # Bound skills load only when a session starts, and "/skill x" or "/queue" can start one.+ auto_skill=self._resolve_channel_skills(channel_id, parent_id or None),)# --- Thread creation helpers ---@@ -4790,25 +4798,18 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAdawait self._threads.mark_async(thread_id)starter = (message or "").strip()if starter and thread_id:- await self._dispatch_thread_session(interaction, thread_id, thread_name, starter)+ await self._dispatch_thread_session(interaction, result["thread"], starter)- async def _dispatch_thread_session(- self, interaction: discord.Interaction, thread_id: str, thread_name: str, text: str,- ) -> None:+ async def _dispatch_thread_session(self, interaction: discord.Interaction, thread: Any, text: str) -> None:"""Build a MessageEvent pointing at a thread and send it through handle_message."""- guild_name = ""- if hasattr(interaction, "guild") and interaction.guild:- guild_name = interaction.guild.name- chat_name = f"{guild_name} / {thread_name}" if guild_name else thread_name- # Inherit forum topic when the thread was created inside a forum channel.- _chan = getattr(interaction, "channel", None)- chat_topic = self._get_effective_topic(_chan, is_thread=True) if _chan else None- _parent_channel = self._thread_parent_channel(getattr(interaction, "channel", None))- _parent_id = str(getattr(_parent_channel, "id", "") or "")+ # Name, topic and parent come from the thread itself, as for a message posted in it: this+ # turn opens the session and pins its context prompt, which the thread's messages then reuse.+ thread_id = str(thread.id)+ _parent_id = self._get_parent_channel_id(thread) or ""source = self.build_source(- chat_id=thread_id, chat_name=chat_name, chat_type="thread",+ chat_id=thread_id, chat_name=self._format_thread_chat_name(thread), chat_type="thread",user_id=str(interaction.user.id), user_name=interaction.user.display_name,- thread_id=thread_id, chat_topic=chat_topic,+ thread_id=thread_id, chat_topic=self._get_effective_topic(thread, is_thread=True),guild_id=self._interaction_guild_id(interaction), parent_chat_id=_parent_id or None,)_skills = self._resolve_channel_skills(thread_id, _parent_id or None)@@ -5353,7 +5354,8 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAd@staticmethoddef _thread_created(thread: Any, name: str) -> Dict[str, Any]:- return {"success": True, "thread_id": str(thread.id), "thread_name": getattr(thread, "name", None) or name}+ return {"success": True, "thread_id": str(thread.id), "thread_name": getattr(thread, "name", None) or name,+ "thread": thread}# ------------------------------------------------------------------# Auto-thread helpersdiff --git a/tests/gateway/test_discord_slash_commands.py b/tests/gateway/test_discord_slash_commands.pyindex e636901a708..c4cf6737ffa 100644--- a/tests/gateway/test_discord_slash_commands.py+++ b/tests/gateway/test_discord_slash_commands.py@@ -366,7 +366,9 @@ async def test_dispatch_thread_session_builds_thread_event(adapter):adapter.handle_message = capture_handle- await adapter._dispatch_thread_session(interaction, "555", "Planning", "Hello!")+ thread = SimpleNamespace(id=555, name="Planning", guild=interaction.guild, topic=None,+ parent=SimpleNamespace(id=100, name="general", guild=interaction.guild))+ await adapter._dispatch_thread_session(interaction, thread, "Hello!")assert len(captured_events) == 1event = captured_events[0]diff --git a/tests/gateway/test_discord_turn_prompt_parity.py b/tests/gateway/test_discord_turn_prompt_parity.pynew file mode 100644index 00000000000..3312d31680a--- /dev/null+++ b/tests/gateway/test_discord_turn_prompt_parity.py@@ -0,0 +1,132 @@+"""Discord turns built outside on_message carry the same prompt inputs as a message in that chat.++Native slash commands (``/skill``, ``/queue``, ``/plan``), the ``/thread`` starter and voice-channel+input are human turns: each re-pins the session-context prompt and the channel prompt. Built with+another chat label (DM: none; thread: without its parent channel), another topic or a bare user id,+they re-rendered the pinned prompt, and the next typed message rendered it back: a prompt-cache miss+each way. Built without ``auto_skill``, a session they opened never loaded the channel's bound skill.+"""++from datetime import datetime, timezone+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++import gateway.run as gateway_run+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+++class _DM:+ def __init__(self, channel_id):+ self.id, self.name = channel_id, "dm"+++class _Text:+ def __init__(self, channel_id, name="ops", topic="Incident triage"):+ self.id, self.name, self.topic = channel_id, name, topic+ self.guild = SimpleNamespace(id=1, name="Hermes Server")+++class _Thread:+ def __init__(self, channel_id, parent, name="incident-42"):+ self.id, self.name, self.parent, self.parent_id = channel_id, name, parent, parent.id+ self.guild, self.topic = parent.guild, None+++_USER = SimpleNamespace(id=42, display_name="Alice", name="alice")+++def _adapter(monkeypatch, bound_id) -> DiscordAdapter:+ monkeypatch.setattr(discord_platform.discord, "DMChannel", _DM, raising=False)+ monkeypatch.setattr(discord_platform.discord, "Thread", _Thread, raising=False)+ monkeypatch.setenv("DISCORD_REQUIRE_MENTION", "false")+ monkeypatch.setenv("DISCORD_AUTO_THREAD", "false")+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fake", extra={+ "channel_prompts": {str(bound_id): "Answer in haiku."},+ "channel_skill_bindings": [{"id": str(bound_id), "skill": "triage"}]}))+ adapter._client = SimpleNamespace(+ user=SimpleNamespace(id=999), get_channel=lambda _id: None,+ get_guild=lambda _id: SimpleNamespace(get_member=lambda _uid: _USER))+ adapter._text_batch_delay_seconds = 0+ adapter._discord_history_backfill = lambda: False+ adapter.handle_message = AsyncMock()+ return adapter+++async def _typed(adapter, channel):+ await adapter._handle_message(SimpleNamespace(+ id=123, content="what broke?", mentions=[], attachments=[], reference=None,+ created_at=datetime.now(timezone.utc), channel=channel, author=_USER))+ return adapter.handle_message.await_args.args[0]+++def _assert_same_prompt_inputs(typed, other):+ """typed -> other -> typed through the real pins leaves one context prompt and one channel prompt."""+ runner = object.__new__(gateway_run.GatewayRunner)+ config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")})+ pinned = []+ for event in (typed, other, typed):+ context = build_session_context(event.source, config)+ channel_prompt, _ = runner._pinned_channel_inputs(+ "k", event.channel_prompt, event.source, internal=False)+ pinned.append((runner._pinned_session_context_prompt(context, False, "k"), channel_prompt))+ assert typed.channel_prompt == "Answer in haiku."+ assert len(set(pinned)) == 1, (pinned[0][0], pinned[1][0])+ assert other.auto_skill == typed.auto_skill == ["triage"]+++def _parent():+ return _Text(700)+++def _interaction(channel):+ return SimpleNamespace(+ channel=channel, channel_id=channel.id, guild=getattr(channel, "guild", None), guild_id=None,+ user=_USER, response=SimpleNamespace(defer=AsyncMock()), followup=SimpleNamespace(send=AsyncMock()),+ delete_original_response=AsyncMock())++[email protected]("case", ["dm", "channel", "thread", "thread-starter"])+async def test_slash_and_thread_starter_turns_match_a_message_turn(monkeypatch, case):+ parent = _parent()+ channel = {"dm": _DM(500), "channel": parent}.get(case) or _Thread(800, parent)+ adapter = _adapter(monkeypatch, channel.id)+ adapter._check_slash_authorization = AsyncMock(return_value=True)+ typed = await _typed(adapter, channel)+ if case == "thread-starter":+ channel.send = AsyncMock()+ parent.create_thread = AsyncMock(return_value=channel)+ await adapter._handle_thread_create_slash(_interaction(parent), channel.name, "what broke?")+ else:+ await adapter._run_simple_slash(_interaction(channel), "/skill triage what broke?")+ assert adapter.handle_message.await_count == 2+ _assert_same_prompt_inputs(typed, adapter.handle_message.await_args.args[0])+++async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch):+ parent = _parent()+ adapter = _adapter(monkeypatch, parent.id)+ typed = await _typed(adapter, parent)+ join = adapter._build_slash_event(+ SimpleNamespace(channel=parent, channel_id=parent.id, guild=parent.guild, guild_id=1, user=_USER),+ "/voice join")+ adapter._voice_text_channels = {1: parent.id}+ adapter._voice_sources = {1: join.source.to_dict()}+ runner = object.__new__(gateway_run.GatewayRunner)+ runner.adapters = {Platform.DISCORD: adapter}+ runner._voice_mode = {}+ runner._session_db = None+ runner.session_store = MagicMock()+ runner._is_user_authorized = lambda source: True++ await runner._handle_voice_channel_input(1, _USER.id, "what broke?", adapter=adapter)++ spoken = adapter.handle_message.await_args.args[0]+ assert spoken is not typed+ _assert_same_prompt_inputs(typed, spoken)