Skip to content

The agent that grows with you

fix(discord): a programmatic voice join binds the requested text channel on every path

unsupportedpastelsa036b13793a2
diff --git a/gateway/run_voice.py b/gateway/run_voice.py
index 128dbddde46..45b92b4458e 100644
--- a/gateway/run_voice.py
+++ b/gateway/run_voice.py
@@ -256,6 +256,7 @@ class GatewayVoiceMixin:
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 None
+ channel = client.get_channel(int(text_ch_id)) if client else None
if source_data := getattr(adapter, "_voice_sources", {}).get(guild_id):
source = SessionSource.from_dict(source_data)
# get_member() is cache-only: on a miss the /voice join invoker keeps the name bound at
@@ -268,14 +269,19 @@ class GatewayVoiceMixin:
# (run.py exports it as HERMES_SESSION_MESSAGE_ID for reply anchoring).
source.message_id = None
else:
+ # A programmatic join binds no source: build the one a typed message in that channel carries
+ # (group, or thread under its parent, with the guild), else the turn keys another session.
user_name = user_name or GatewayVoiceMixin._cached_user_display_name(client, user_id)
- source = SessionSource(
- platform=Platform.DISCORD, chat_id=str(text_ch_id), user_id=str(user_id),
- user_name=user_name or str(user_id), chat_type="channel",
- profile=getattr(adapter, "_owner_profile", None))
+ thread_id = None
+ if channel is not None and callable(split := getattr(adapter, "_thread_id_and_chat_for_channel", None)):
+ thread_id, _ = split(channel)
+ parent_id = adapter._get_parent_channel_id(channel) if thread_id else None
+ source = adapter.build_source(
+ chat_id=str(text_ch_id), chat_type="thread" if thread_id else "group", user_id=str(user_id),
+ user_name=user_name or str(user_id), thread_id=thread_id, guild_id=str(guild_id),
+ parent_chat_id=parent_id)
# The stored source is a join-time copy; a typed message reads the channel's current name and
# topic, so a rename or topic edit would otherwise flip the pinned prompt on every switch.
- channel = client.get_channel(int(text_ch_id)) if client else None
if channel is not None and callable(labels := getattr(adapter, "_guild_channel_labels", None)):
if isinstance(current := labels(channel), tuple):
source.chat_name, source.chat_topic = current
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 482df1141df..94dca131e85 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -3840,19 +3840,15 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn
async with self._voice_locks.setdefault(guild_id, asyncio.Lock()):
existing = self._voice_clients.get(guild_id)
if existing and existing.is_connected():
- if existing.channel.id == channel.id:
- self._reset_voice_timeout(guild_id)
- return True
- await existing.move_to(channel)
+ if existing.channel.id != channel.id:
+ await existing.move_to(channel)
self._reset_voice_timeout(guild_id)
+ self._bind_voice_text_channel(guild_id, text_channel_id, source)
return True
vc = await channel.connect()
self._voice_clients[guild_id] = vc
self._reset_voice_timeout(guild_id)
- if text_channel_id is not None:
- self._voice_text_channels[guild_id] = text_channel_id
- if source is not None:
- self._voice_sources[guild_id] = source
+ self._bind_voice_text_channel(guild_id, text_channel_id, source)
try:
receiver = VoiceReceiver(vc, allowed_user_ids=self._allowed_user_ids)
receiver.start()
diff --git a/plugins/platforms/discord/adapter_voice_info.py b/plugins/platforms/discord/adapter_voice_info.py
index 284cdfe6e83..ace04485e11 100644
--- a/plugins/platforms/discord/adapter_voice_info.py
+++ b/plugins/platforms/discord/adapter_voice_info.py
@@ -8,7 +8,26 @@ from typing import Any, Dict, Optional
class DiscordVoiceInfoMixin:
_voice_clients: dict[int, Any]
_voice_receivers: dict[int, Any]
+ _voice_text_channels: dict[int, Any]
+ _voice_sources: dict[int, Dict[str, Any]]
_client: Any
+ discard_pending_voice_input: Any
+
+ def _bind_voice_text_channel(self, guild_id: int, text_channel_id: Any, source: Optional[dict]) -> None:
+ """A programmatic join's transcription binding, on every path: cold join, same voice channel and
+ move. The already-connected paths returned before writing it, so a successful join to another
+ text channel kept answering in the old one. Moving to another text channel drops speech captured
+ for the old one (as ``/voice join`` does) and, unless a new source is given, the old channel's
+ bound source, whose chat would otherwise keep routing turns into the old conversation."""
+ if text_channel_id is not None:
+ previous = self._voice_text_channels.get(guild_id)
+ if previous is not None and previous != text_channel_id:
+ self.discard_pending_voice_input(guild_id)
+ if source is None:
+ self._voice_sources.pop(guild_id, None)
+ self._voice_text_channels[guild_id] = text_channel_id
+ if source is not None:
+ self._voice_sources[guild_id] = source
def get_voice_channel_info(self, guild_id: int) -> Optional[Dict[str, Any]]:
"""Return voice channel info (name, members, count, speaking user IDs) or None if not connected."""
diff --git a/tests/gateway/test_discord_turn_prompt_parity.py b/tests/gateway/test_discord_turn_prompt_parity.py
index 2a03097ec96..b7c57e53422 100644
--- a/tests/gateway/test_discord_turn_prompt_parity.py
+++ b/tests/gateway/test_discord_turn_prompt_parity.py
@@ -6,7 +6,8 @@ another chat label (DM: none; thread: without its parent channel), another topic
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.
Voice rebuilds its source from a ``/voice join`` copy, so it must also see the parent's bindings from a
-thread and the channel's current name and topic.
+thread and the channel's current name and topic. A programmatic join binds no copy: the voice turn then
+builds the source a typed message in that channel carries, or it keys another session.
"""
from __future__ import annotations
@@ -21,7 +22,7 @@ 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 gateway.session import build_session_context, build_session_key
from plugins.platforms.discord.adapter import DiscordAdapter
@@ -120,10 +121,11 @@ async def test_slash_and_thread_starter_turns_match_a_message_turn(
@pytest.mark.asyncio
[email protected]("case", ["channel", "thread-under-bound-parent", "renamed-after-join", "speaker-uncached"])
[email protected]("case", ["channel", "thread-under-bound-parent", "renamed-after-join", "speaker-uncached",
+ "programmatic-join", "programmatic-join-thread"])
async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch: pytest.MonkeyPatch, case: str) -> None:
parent = _parent()
- channel = _Thread(800, parent) if case == "thread-under-bound-parent" else parent
+ channel = _Thread(800, parent) if case.endswith("thread") or case.startswith("thread") else parent
adapter = _adapter(monkeypatch, parent.id)
join = adapter._build_slash_event(
SimpleNamespace(channel=channel, channel_id=channel.id, guild=parent.guild, guild_id=1, user=_USER),
@@ -132,6 +134,8 @@ async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch: pytest.Monke
# A typed `/voice join` binds that message's source, id included; a voice turn must not inherit it
# as its own trigger.
adapter._voice_sources = {1: {**join.source.to_dict(), "message_id": "1554000000000000000"}}
+ if case.startswith("programmatic-join"):
+ adapter._voice_sources = {} # join_voice_channel(..., text_channel_id=...) without a source
adapter._client.get_channel = {channel.id: channel}.get
if case == "renamed-after-join":
channel.name, channel.topic = "renamed", "New topic"
@@ -153,6 +157,7 @@ async def test_voice_channel_turn_matches_a_typed_turn(monkeypatch: pytest.Monke
spoken = adapter.handle_message.await_args.args[0]
assert spoken is not typed
_assert_same_prompt_inputs(typed, spoken)
+ assert build_session_key(spoken.source) == build_session_key(typed.source)
assert spoken.source.message_id is None
# The join-time name belongs to the joiner only; another uncached speaker never borrows it, and
# gets their cached user name (global name, no server nickname) rather than a bare id.
diff --git a/tests/gateway/test_discord_voice_stale_binding.py b/tests/gateway/test_discord_voice_stale_binding.py
index 11059dd3a8a..97e2840a6b4 100644
--- a/tests/gateway/test_discord_voice_stale_binding.py
+++ b/tests/gateway/test_discord_voice_stale_binding.py
@@ -6,7 +6,8 @@ rewrote the binding, and the old utterance became a turn in the new conversation
skills and replies. The listen loop transcribes a poll batch serially, so a later utterance of the
same batch must keep the binding of the batch, not one set during an earlier utterance's STT.
Speech the receiver still buffers when the binding moves is dropped too: a poll or leave flush
-after the move must not stamp it with the new binding.
+after the move must not stamp it with the new binding. A programmatic ``join_voice_channel`` while
+already connected applies the requested binding the same way, rather than keeping the old one.
"""
from __future__ import annotations
@@ -178,3 +179,37 @@ async def test_leave_after_a_rebind_does_not_flush_old_speech_into_the_new_chann
_speak(receiver, 0.6) # still speaking: the leave flush, not silence, emits it
await _voice_join_from(adapter, join_from, tmp_path)
assert await _transcribed_pcm(adapter, lambda: adapter.leave_voice_channel(_GUILD)) == (len(reaching), reaching)
+
+
+class _ConnectedVoiceClient:
+ def __init__(self, channel_id: int) -> None:
+ self.channel = SimpleNamespace(id=channel_id)
+ self.move_to = AsyncMock(side_effect=lambda channel: setattr(self, "channel", channel))
+
+ def is_connected(self) -> bool:
+ return True
+
+
[email protected]("voice_channel,text_channel,source,bound_source,reaching", [
+ (900, 800, None, None, []), # same voice channel, other text channel
+ (901, 800, None, None, []), # move, other text channel
+ (901, 800, {"chat_id": "800"}, {"chat_id": "800"}, []), # move with the new channel's source
+ (900, 700, None, {"chat_id": "700"}, [int(0.6 * _BYTES_PER_SECOND)]), # same text channel keeps all
+], ids=["same-voice-channel", "move", "move-with-source", "same-text-channel"])
+async def test_a_programmatic_join_while_connected_applies_the_requested_binding(
+ voice_channel: int, text_channel: int, source: dict | None, bound_source: dict | None, reaching: list[int],
+) -> None:
+ adapter, receiver = _listening_adapter()
+ adapter._client = MagicMock()
+ adapter._voice_clients[_GUILD] = vc = _ConnectedVoiceClient(900)
+ adapter._voice_sources[_GUILD] = {"chat_id": "700"}
+ _speak(receiver, 0.6)
+ target = SimpleNamespace(id=voice_channel, guild=SimpleNamespace(id=_GUILD))
+ with patch("plugins.platforms.discord.adapter.DISCORD_AVAILABLE", True):
+ assert await adapter.join_voice_channel(target, text_channel_id=text_channel, source=source)
+ assert vc.move_to.await_count == (voice_channel != 900)
+ assert adapter._voice_text_channels[_GUILD] == text_channel
+ assert adapter._voice_sources.get(_GUILD) == bound_source
+ _fall_silent(receiver)
+ assert await _transcribed_pcm(adapter, lambda: _one_poll(adapter, receiver)) == (len(reaching), reaching)
diff --git a/tests/gateway/test_voice_command.py b/tests/gateway/test_voice_command.py
index e970a2c2c5e..42dad830820 100644
--- a/tests/gateway/test_voice_command.py
+++ b/tests/gateway/test_voice_command.py
@@ -55,6 +55,18 @@ from gateway.platforms.base import SessionSource
from gateway.platforms.event import MessageEvent, MessageType
+def _unbound_voice_adapter() -> AsyncMock:
+ """A Discord adapter bound to text channel 123 with no join source (a programmatic join)."""
+ from gateway.config import Platform
+ adapter = AsyncMock()
+ adapter._voice_text_channels, adapter._voice_sources = {111: 123}, {}
+ adapter._client = MagicMock()
+ adapter.handle_message = AsyncMock()
+ adapter._thread_id_and_chat_for_channel = MagicMock(return_value=(None, "123"))
+ adapter.build_source = MagicMock(side_effect=lambda **kw: SessionSource(platform=Platform.DISCORD, **kw))
+ return adapter
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -525,13 +537,9 @@ class TestVoiceChannelCommands:
async def test_input_creates_event_and_dispatches(self, runner):
"""Voice input creates synthetic event and calls handle_message."""
from gateway.config import Platform
- mock_adapter = AsyncMock()
- mock_adapter._voice_text_channels = {111: 123}
- mock_adapter._voice_sources = {}
+ mock_adapter = _unbound_voice_adapter()
mock_channel = AsyncMock()
- mock_adapter._client = MagicMock()
mock_adapter._client.get_channel = MagicMock(return_value=mock_channel)
- mock_adapter.handle_message = AsyncMock()
runner.adapters[Platform.DISCORD] = mock_adapter
await runner._handle_voice_channel_input(111, 42, "Hello from VC")
mock_adapter.handle_message.assert_called_once()
@@ -539,7 +547,8 @@ class TestVoiceChannelCommands:
assert event.text == "Hello from VC"
assert event.message_type == MessageType.VOICE
assert event.source.chat_id == "123"
- assert event.source.chat_type == "channel"
+ # A typed message in a guild text channel is a "group" turn; voice keys the same session.
+ assert (event.source.chat_type, event.source.guild_id) == ("group", "111")
@pytest.mark.asyncio
async def test_input_reroutes_speaker_without_changing_transport_owner(self, runner, monkeypatch):
@@ -583,12 +592,8 @@ class TestVoiceChannelCommands:
async def test_input_resolves_channel_prompt(self, runner):
"""Voice input must carry the bound text channel's channel_prompt (#50149)."""
from gateway.config import Platform
- mock_adapter = AsyncMock()
- mock_adapter._voice_text_channels = {111: 123}
- mock_adapter._voice_sources = {}
- mock_adapter._client = MagicMock()
+ mock_adapter = _unbound_voice_adapter()
mock_adapter._client.get_channel = MagicMock(return_value=AsyncMock())
- mock_adapter.handle_message = AsyncMock()
mock_adapter._resolve_channel_prompt = MagicMock(return_value="Be terse in #dev.")
runner.adapters[Platform.DISCORD] = mock_adapter
await runner._handle_voice_channel_input(111, 42, "Hello from VC")
diff --git a/tests/gateway/test_voice_transcript_dedup_scope.py b/tests/gateway/test_voice_transcript_dedup_scope.py
index 206d5e0bbfd..b5919c46c12 100644
--- a/tests/gateway/test_voice_transcript_dedup_scope.py
+++ b/tests/gateway/test_voice_transcript_dedup_scope.py
@@ -13,6 +13,7 @@ import pytest
import gateway.run as gateway_run
from gateway.config import Platform
+from gateway.session import SessionSource
_GUILD, _USER = 1, 42
@@ -26,6 +27,9 @@ class _Bot:
self._client = SimpleNamespace(get_channel=lambda _id: None, get_guild=lambda _id: None)
self.handle_message = AsyncMock()
+ def build_source(self, **fields) -> SessionSource:
+ return SessionSource(platform=Platform.DISCORD, profile=self._owner_profile, **fields)
+
@pytest.mark.asyncio
async def test_dedup_is_scoped_to_the_receiving_bot_and_its_binding() -> None: