The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(discord): a /voice join to another text channel drops speech the receiver still holds for the old one
unsupportedpastels932210ec2ae8
diff --git a/gateway/run_voice.py b/gateway/run_voice.pyindex f04ee0a0f5e..ce5d162ff1c 100644--- a/gateway/run_voice.py+++ b/gateway/run_voice.py@@ -177,7 +177,13 @@ class GatewayVoiceMixin:if not success:adapter._voice_input_callback = Nonereturn t("gateway.voice.channel_join_permissions")- adapter._voice_text_channels[guild_id] = int(event.source.chat_id)+ text_channel_id = int(event.source.chat_id)+ # Moving to another text channel drops speech buffered for the old one (a same-channel rejoin+ # keeps it); nothing awaits between this and the binding write, so no poll sees the gap.+ previous = adapter._voice_text_channels.get(guild_id)+ if previous is not None and previous != text_channel_id and hasattr(adapter, "discard_pending_voice_input"):+ adapter.discard_pending_voice_input(guild_id)+ adapter._voice_text_channels[guild_id] = text_channel_idif hasattr(adapter, "_voice_sources"):adapter._voice_sources[guild_id] = event.source.to_dict()self._apply_voice_mode(adapter, self._voice_key_for_source(event.source),diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 224d8c08aa3..afda496c2bf 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -1172,6 +1172,12 @@ class VoiceReceiver:self._last_packet_time.pop(ssrc, None)return completed+ def discard_pending(self) -> None:+ """Drop buffered PCM that no poll or flush has emitted yet."""+ with self._lock:+ self._buffers.clear()+ self._last_packet_time.clear()+# --- PCM -> WAV conversion (for Whisper STT) ---@staticmethod@@ -4040,6 +4046,13 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIn# UDP keepalive interval; Discord drops the UDP route after ~60s of silence._KEEPALIVE_INTERVAL = 15+ def discard_pending_voice_input(self, guild_id: int) -> None:+ """Drop speech the receiver holds but has not emitted, before the text binding moves: audio+ captured for the old conversation must never be stamped with the new one (#130311)."""+ receiver = self._voice_receivers.get(guild_id)+ if receiver is not None:+ receiver.discard_pending()+async def _voice_listen_loop(self, guild_id: int):"""Periodically check for completed utterances and process them."""receiver = self._voice_receivers.get(guild_id)diff --git a/tests/gateway/test_discord_voice_stale_binding.py b/tests/gateway/test_discord_voice_stale_binding.pyindex 0063ad5ece3..e4b135cf995 100644--- a/tests/gateway/test_discord_voice_stale_binding.py+++ b/tests/gateway/test_discord_voice_stale_binding.py@@ -5,17 +5,25 @@ binding as it is at that moment. A ``/voice join`` from another text channel durrewrote the binding, and the old utterance became a turn in the new conversation, with its prompt,skills and replies. The listen loop transcribes a poll batch serially, so a later utterance of thesame 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."""from __future__ import annotationsimport asyncioimport threading-from unittest.mock import AsyncMock, patch+import time+from collections.abc import Awaitable, Callable+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom gateway.config import PlatformConfig-from plugins.platforms.discord.adapter import DiscordAdapter+from gateway.platforms.base import SessionSource+from gateway.platforms.event import MessageEvent, MessageType+from plugins.platforms.discord.adapter import DiscordAdapter, VoiceReceiver_GUILD, _USER = 1, 42@@ -60,3 +68,112 @@ async def test_transcribed_utterance_keeps_its_captured_binding(bound_after: intawait taskassert callback.await_count == dispatched+++_SSRC, _BYTES_PER_SECOND = 7, 48000 * 2 * 2+++def _speak(receiver: VoiceReceiver, seconds: float) -> None:+ """Decoded PCM arriving for one speaker, as the packet hook appends it."""+ with receiver._lock:+ receiver._buffers[_SSRC].extend(b"\x01\x00" * int(seconds * _BYTES_PER_SECOND / 2))+ receiver._last_packet_time[_SSRC] = time.monotonic()+++def _fall_silent(receiver: VoiceReceiver) -> None:+ receiver._last_packet_time[_SSRC] = time.monotonic() - 2 * receiver.SILENCE_THRESHOLD+++async def _voice_join_from(adapter: DiscordAdapter, chat_id: str, tmp_path: Path) -> None:+ """``/voice join`` through the gateway handler while the bot is already in the voice channel."""+ from gateway.run import GatewayRunner+ runner = object.__new__(GatewayRunner)+ runner.adapters, runner._voice_mode = {}, {}+ runner._VOICE_MODE_PATH = tmp_path / "gateway_voice_mode.json"+ runner._session_db, runner.session_store = None, MagicMock()+ runner._is_user_authorized = MagicMock(return_value=True)+ platform = MagicMock()+ platform.value = "discord"+ source = SessionSource(chat_id=chat_id, user_id="owner", platform=platform)+ source.thread_id = None+ event = MessageEvent(text="/voice join", message_type=MessageType.TEXT, source=source)+ event.raw_message = SimpleNamespace(guild_id=_GUILD, guild=None)+ runner.adapters[platform] = adapter+ adapter.get_user_voice_channel = AsyncMock(return_value=SimpleNamespace(name="General"))+ adapter.join_voice_channel = AsyncMock(return_value=True)+ await runner._handle_voice_channel_join(event)+++def _listening_adapter() -> tuple[DiscordAdapter, VoiceReceiver]:+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token="fake"))+ receiver = VoiceReceiver(SimpleNamespace())+ receiver._ssrc_to_user[_SSRC] = _USER+ adapter._voice_receivers[_GUILD] = receiver+ adapter._voice_text_channels = {_GUILD: 700}+ adapter._is_allowed_user = MagicMock(return_value=True)+ adapter._reset_voice_timeout = MagicMock()+ return adapter, receiver+++async def _transcribed_pcm(adapter: DiscordAdapter, drain: Callable[[], Awaitable[None]]) -> tuple[int, list[int]]:+ """Run *drain* with STT stubbed; return (callback dispatches, PCM length of each converted utterance)."""+ converted: list[int] = []+ adapter._voice_input_callback = callback = AsyncMock()+ with patch("plugins.platforms.discord.adapter.VoiceReceiver.pcm_to_wav",+ side_effect=lambda pcm, path: converted.append(len(pcm))), \+ patch("tools.transcription_tools.transcribe_audio",+ return_value={"success": True, "transcript": "what broke on the ingest box"}):+ await drain()+ return callback.await_count, converted+++async def _one_poll(adapter: DiscordAdapter, receiver: VoiceReceiver) -> None:+ receiver._running = True+ check = receiver.check_silence++ def once() -> list[tuple[int, bytes]]:+ receiver._running = False+ return check()+ receiver.check_silence = MagicMock(side_effect=once)+ await adapter._voice_listen_loop(_GUILD)++[email protected]("join_from,reaching", [+ ("800", []), # another text channel: the buffered speech is dropped+ ("700", [int(0.6 * _BYTES_PER_SECOND)]), # same channel rejoin keeps it+])+async def test_speech_buffered_across_a_rebind_is_not_stamped_with_the_new_binding(+ join_from: str, reaching: list[int], tmp_path: Path,+) -> None:+ adapter, receiver = _listening_adapter()+ _speak(receiver, 0.6)+ await _voice_join_from(adapter, join_from, tmp_path)+ _fall_silent(receiver)+ assert await _transcribed_pcm(adapter, lambda: _one_poll(adapter, receiver)) == (len(reaching), reaching)+++async def test_speech_spanning_a_rebind_reaches_the_new_channel_without_the_earlier_samples(+ tmp_path: Path,+) -> None:+ adapter, receiver = _listening_adapter()+ _speak(receiver, 0.3)+ await _voice_join_from(adapter, "800", tmp_path)+ _speak(receiver, 0.6)+ _fall_silent(receiver)+ assert await _transcribed_pcm(adapter, lambda: _one_poll(adapter, receiver)) == (1, [int(0.6 * _BYTES_PER_SECOND)])++[email protected]("join_from,reaching", [+ ("800", []),+ ("700", [int(0.6 * _BYTES_PER_SECOND)]),+])+async def test_leave_after_a_rebind_does_not_flush_old_speech_into_the_new_channel(+ join_from: str, reaching: list[int], tmp_path: Path,+) -> None:+ adapter, receiver = _listening_adapter()+ _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)diff --git a/website/docs/user-guide/features/voice-mode.md b/website/docs/user-guide/features/voice-mode.mdindex 82791b48d68..a68a37e3d93 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; utterances still being transcribed or queued at that moment are dropped, not posted to the new channel+- Running `/voice join` from another text channel moves the binding there; speech captured before the move, whether still being transcribed or not yet finished, is dropped, not posted to the new channel### Echo Preventiondiff --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.mdindex 3ad9bca9b75..273f25fc71e 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` 会把绑定移到那里;移动前录到的语音(无论仍在转录还是尚未说完)都会被丢弃,不会发到新频道### 回声消除