Skip to content

The agent that grows with you

fix(discord): capture the voice binding when a poll batch is collected

John Paul Solivafb49ef18f550
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 41c6ec8f393..152f3528714 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -3873,9 +3873,10 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAd
if listen_task:
listen_task.cancel()
guild = self._client.get_guild(guild_id) if self._client is not None else None
+ captured_for = self._voice_text_channels.get(guild_id)
for user_id, pcm_data in pending_inputs:
if self._is_allowed_user(str(user_id), guild=guild, is_dm=False):
- await self._process_voice_input(guild_id, user_id, pcm_data)
+ await self._process_voice_input(guild_id, user_id, pcm_data, captured_for)
# Tear down the mixer (stops the continuous outgoing stream).
if getattr(self, "_voice_mixers", None) is not None:
self._voice_mixers.pop(guild_id, None)
@@ -4099,6 +4100,9 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAd
except Exception:
pass
completed = receiver.check_silence()
+ # Utterances in one batch are transcribed serially; each must keep the binding it was
+ # spoken under, not one a /voice join set during an earlier utterance's STT.
+ captured_for = self._voice_text_channels.get(guild_id)
# Pass guild so role checks stay guild-scoped.
_vc_guild = self._client.get_guild(guild_id) if self._client is not None else None
for user_id, pcm_data in completed:
@@ -4106,18 +4110,21 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAd
continue
# User speech is activity too; keeps active listeners connected.
self._reset_voice_timeout(guild_id)
- await self._process_voice_input(guild_id, user_id, pcm_data)
+ await self._process_voice_input(guild_id, user_id, pcm_data, captured_for)
except asyncio.CancelledError:
pass
except Exception as e:
logger.error("Voice listen loop error: %s", e, exc_info=True)
- async def _process_voice_input(self, guild_id: int, user_id: int, pcm_data: bytes):
- """Convert PCM -> WAV -> STT -> callback."""
+ async def _process_voice_input(self, guild_id: int, user_id: int, pcm_data: bytes,
+ captured_for: int | None):
+ """Convert PCM -> WAV -> STT -> callback.
+
+ ``captured_for`` is the text-channel binding when the utterance was collected. The callback
+ routes by the binding as it is when it runs; a /voice join elsewhere in between would hand
+ this utterance to that other conversation, so stale work is dropped.
+ """
from tools.voice_mode_transcript import is_whisper_hallucination
- # The callback routes by the binding as it is when it runs; a /voice join elsewhere during
- # STT would hand this utterance to that other conversation, so stale work is dropped.
- captured_for = self._voice_text_channels.get(guild_id)
tmp_f = tempfile.NamedTemporaryFile(suffix=".wav", prefix="vc_listen_", delete=False)
wav_path = tmp_f.name
tmp_f.close()
@@ -4131,7 +4138,7 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, BasePlatformAd
if not transcript or is_whisper_hallucination(transcript):
return
logger.info("Voice input from user %d: %s", user_id, transcript[:100])
- if self._voice_text_channels.get(guild_id) != captured_for:
+ if getattr(self, "_voice_text_channels", {}).get(guild_id) != captured_for:
logger.info("Dropping voice input from user %d: the voice binding moved during transcription",
user_id)
return
diff --git a/tests/gateway/test_discord_voice_stale_binding.py b/tests/gateway/test_discord_voice_stale_binding.py
index d7af0d84eb2..917e6c00269 100644
--- a/tests/gateway/test_discord_voice_stale_binding.py
+++ b/tests/gateway/test_discord_voice_stale_binding.py
@@ -3,7 +3,8 @@
``_process_voice_input`` awaits WAV conversion and STT, then the gateway callback reads the guild's
binding as it is at that moment. A ``/voice join`` from another text channel during transcription
rewrote the binding, and the old utterance became a turn in the new conversation, with its prompt,
-skills and replies.
+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.
"""
import asyncio
@@ -18,15 +19,29 @@ from plugins.platforms.discord.adapter import DiscordAdapter
_GUILD, _USER = 1, 42
+class _OneBatchReceiver:
+ """One check_silence() batch of two utterances, both completed while bound to channel 700."""
+
+ def __init__(self):
+ self._running = True
+
+ def check_silence(self):
+ self._running = False
+ return [(_USER, b"\x00" * 9600), (_USER + 1, b"\x00" * 9600)]
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("bound_after,dispatched", [
- (700, 1), # unchanged binding (also leave + rejoin from the same channel)
- (800, 0), # /voice join from another text channel while transcribing
+ (700, 2), # unchanged binding (also leave + rejoin from the same channel)
+ (800, 0), # /voice join from another text channel during the first utterance's STT
])
async def test_transcribed_utterance_keeps_its_captured_binding(bound_after, dispatched):
adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fake"))
adapter._voice_text_channels = {_GUILD: 700}
+ adapter._voice_receivers[_GUILD] = _OneBatchReceiver()
adapter._voice_input_callback = callback = AsyncMock()
+ adapter._is_allowed_user = lambda *a, **k: True
+ adapter._reset_voice_timeout = lambda *a: None
started, release = threading.Event(), threading.Event()
def transcribe(_path):
@@ -36,7 +51,7 @@ async def test_transcribed_utterance_keeps_its_captured_binding(bound_after, dis
with patch("plugins.platforms.discord.adapter.VoiceReceiver.pcm_to_wav"), \
patch("tools.transcription_tools.transcribe_audio", side_effect=transcribe):
- task = asyncio.ensure_future(adapter._process_voice_input(_GUILD, _USER, b"\x00" * 9600))
+ task = asyncio.ensure_future(adapter._voice_listen_loop(_GUILD))
while not started.is_set():
await asyncio.sleep(0.01)
adapter._voice_text_channels[_GUILD] = bound_after
diff --git a/tests/gateway/test_voice_command.py b/tests/gateway/test_voice_command.py
index 8950e43d9af..e970a2c2c5e 100644
--- a/tests/gateway/test_voice_command.py
+++ b/tests/gateway/test_voice_command.py
@@ -697,7 +697,7 @@ class TestDiscordVoiceChannelMethods:
adapter._voice_listen_tasks[111] = MagicMock()
adapter._is_allowed_user = MagicMock(return_value=True)
- async def process(guild_id, user_id, pcm_data):
+ async def process(guild_id, user_id, pcm_data, captured_for):
events.append("process")
adapter._process_voice_input = process
@@ -817,7 +817,7 @@ class TestDiscordVoiceChannelMethods:
patch("tools.transcription_tools.transcribe_audio",
return_value={"success": True, "transcript": "Hello"}), \
patch("tools.voice_mode_transcript.is_whisper_hallucination", return_value=False):
- await adapter._process_voice_input(111, 42, pcm_data)
+ await adapter._process_voice_input(111, 42, pcm_data, None)
callback.assert_called_once_with(guild_id=111, user_id=42, transcript="Hello")
diff --git a/website/docs/user-guide/features/voice-mode.md b/website/docs/user-guide/features/voice-mode.md
index 9d58e2dc582..82791b48d68 100644
--- a/website/docs/user-guide/features/voice-mode.md
+++ b/website/docs/user-guide/features/voice-mode.md
@@ -431,7 +431,7 @@ When the bot is in a voice channel:
- Transcripts appear in the text channel: `[Voice] @user: what you said`
- Agent responses are sent as text in the channel AND spoken in the VC
- The text channel is the one where `/voice join` was issued
-- Running `/voice join` from another text channel moves the binding there; an utterance still being transcribed at that moment is dropped, not posted to the new channel
+- Running `/voice join` from another text channel moves the binding there; utterances still being transcribed or queued at that moment are dropped, not posted to the new channel
### Echo Prevention
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/voice-mode.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/voice-mode.md
index 549b871ba83..3ad9bca9b75 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/voice-mode.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/voice-mode.md
@@ -353,7 +353,7 @@ Bot 在语音频道中时:
- 转录内容会出现在文字频道中:`[Voice] @user: 您说的内容`
- Agent 回复同时以文字发送到频道并在语音频道中朗读
- 文字频道为发出 `/voice join` 命令的那个频道
-- 在另一个文字频道再次运行 `/voice join` 会把绑定移到那里;此时仍在转录中的语音会被丢弃,不会发到新频道
+- 在另一个文字频道再次运行 `/voice join` 会把绑定移到那里;此时仍在转录或排队中的语音会被丢弃,不会发到新频道
### 回声消除