Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(realtime): reset local transport across restarts (#2740)
wangtao4783e5b2d1e0
diff --git a/src/agentscope/realtime/_transport/_local.py b/src/agentscope/realtime/_transport/_local.pyindex e4f2003cd..5d1db8500 100644--- a/src/agentscope/realtime/_transport/_local.py+++ b/src/agentscope/realtime/_transport/_local.py@@ -75,6 +75,9 @@ class LocalAudioTransport(TransportBase):"""Open both streams."""import sounddevice as sd+ # A fresh queue: the previous session's sentinel and capture must+ # not leak into this one.+ self._in_queue = asyncio.Queue()self._loop = asyncio.get_running_loop()self._in_stream = sd.InputStream(samplerate=self.input_sample_rate,@@ -96,11 +99,18 @@ class LocalAudioTransport(TransportBase):async def close(self) -> None:"""Stop both streams and end :meth:`incoming`."""+ # Detach first so a late callback cannot enqueue behind the sentinel.+ self._loop = Nonefor stream in (self._in_stream, self._out_stream):if stream is not None:stream.stop()stream.close()self._in_stream = self._out_stream = None+ with self._lock:+ self._pending.clear()+ self._item_id = ""+ self._played_samples = 0+ self._first_played_at = Noneself._in_queue.put_nowait(None)# ------------------------------------------------------------------diff --git a/tests/realtime_local_transport_test.py b/tests/realtime_local_transport_test.pyindex 590d15f46..2761ee2ae 100644--- a/tests/realtime_local_transport_test.py+++ b/tests/realtime_local_transport_test.py@@ -3,6 +3,8 @@directly — no sound card is opened."""# pylint: disable=protected-accessimport asyncio+import sys+from unittest.mock import MagicMock, patchfrom unittest.async_case import IsolatedAsyncioTestCaseimport numpy as np@@ -133,6 +135,33 @@ class LocalAudioTransportTest(IsolatedAsyncioTestCase):(transport._max_queued, 3, (transport._max_queued + 2) % 256),)+ async def test_restart_drops_previous_session_audio(self) -> None:+ """A reused transport starts with fresh capture and playout state."""+ transport = LocalAudioTransport()+ transport._enqueue(AudioFrame(pcm=b"stale-input"))+ await transport.send_audio(b"\x01\x00" * 10, "stale-output")+ await transport.close()++ with patch.dict(sys.modules, {"sounddevice": MagicMock()}):+ await transport.start()+ transport._enqueue(AudioFrame(pcm=b"fresh-input"))+ incoming = transport.incoming()++ self.assertEqual(+ (+ (await anext(incoming)).pcm,+ transport.playout().model_dump(),+ bytes(transport._pending),+ ),+ (+ b"fresh-input",+ {"item_id": "", "played_ms": 0, "first_played_at": None},+ b"",+ ),+ )+ await incoming.aclose()+ await transport.close()+async def test_playout_position_shape(self) -> None:"""The position is a plain value object."""self.assertEqual(