"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(channels): reuse one wecom stream id across each streamed reply (#1929)
Lanre Shittu8c0d6435f4f2
diff --git a/agent/src/channels/wecom.py b/agent/src/channels/wecom.pyindex 4850b5de7..775b7d799 100644--- a/agent/src/channels/wecom.py+++ b/agent/src/channels/wecom.py@@ -99,6 +99,11 @@ class WecomChannel(BaseChannel):self._generate_req_id = None# Store frame headers for each chat to enable repliesself._chat_frames: dict[str, Any] = {}+ # WeCom requires one stable stream_id reused across every reply_stream+ # call of the same logical reply, finished only by the last one.+ # Keyed by chat_id as a fallback for callers that never set the+ # channel-wide "_stream_id" metadata (base.py's streaming contract).+ self._stream_ids: dict[str, str] = {}async def start(self) -> None:"""Start the WeCom bot with WebSocket long connection."""@@ -531,13 +536,26 @@ class WecomChannel(BaseChannel):# Both progress and final messages must use reply_stream (cmd="aibot_respond_msg").# The plain reply() uses cmd="reply" which does not support "text" msgtype# and causes errcode=40008 from WeCom API.- stream_id = self._generate_req_id("stream")+ #+ # reply_stream requires the SAME stream_id across every chunk+ # of one logical reply, finished only by the last call -- a+ # fresh id per call makes WeCom treat each progress update and+ # the final answer as unrelated streams instead of one+ # progressively updating message.+ stream_id = (+ str(msg.metadata.get("_stream_id") or "")+ or self._stream_ids.get(msg.chat_id)+ or self._generate_req_id("stream")+ )+ self._stream_ids[msg.chat_id] = stream_idawait self._client.reply_stream(frame,stream_id,content,finish=not is_progress,)+ if not is_progress:+ self._stream_ids.pop(msg.chat_id, None)self.logger.debug("%s sent to %s","progress" if is_progress else "message",diff --git a/agent/tests/test_wecom_stream_id_continuity.py b/agent/tests/test_wecom_stream_id_continuity.pynew file mode 100644index 000000000..5b6bd5535--- /dev/null+++ b/agent/tests/test_wecom_stream_id_continuity.py@@ -0,0 +1,109 @@+"""Regression: WeCom must reuse one stream_id across one logical reply."""++from __future__ import annotations++import asyncio+import itertools++from src.channels.bus.events import OutboundMessage+from src.channels.wecom import WecomChannel+++def _make_channel() -> WecomChannel:+ channel = WecomChannel({"enabled": True, "bot_id": "x", "secret": "y"}, bus=None)+ channel._chat_frames["user123"] = {"headers": {"req_id": "abc"}}+ counter = itertools.count()+ channel._generate_req_id = lambda prefix: f"{prefix}_{next(counter)}"+ return channel+++class _FakeClient:+ def __init__(self) -> None:+ self.calls: list[tuple[str, str, bool]] = []++ async def reply_stream(self, frame, stream_id, content, finish): # noqa: ANN001+ self.calls.append((stream_id, content, finish))+++class TestWecomStreamIdContinuity:+ """Progress chunks and the final answer of one turn must share a stream_id,+ otherwise WeCom treats each chunk as an unrelated message instead of one+ progressively updating reply.+ """++ def test_progress_and_final_share_the_injected_stream_id(self) -> None:+ channel = _make_channel()+ client = _FakeClient()+ channel._client = client+ attempt_id = "attempt-42"++ async def run() -> None:+ await channel.send(+ OutboundMessage(+ channel="wecom", chat_id="user123", content="Thinking",+ metadata={"_progress": True, "_stream_id": attempt_id},+ )+ )+ await channel.send(+ OutboundMessage(+ channel="wecom", chat_id="user123", content="Still thinking",+ metadata={"_progress": True, "_stream_id": attempt_id},+ )+ )+ await channel.send(+ OutboundMessage(+ channel="wecom", chat_id="user123", content="Final answer",+ metadata={"_stream_id": attempt_id},+ )+ )++ asyncio.run(run())++ stream_ids = [c[0] for c in client.calls]+ assert stream_ids == [attempt_id, attempt_id, attempt_id]+ assert [c[2] for c in client.calls] == [False, False, True]+ assert channel._stream_ids == {}++ def test_falls_back_to_a_stable_per_chat_id_when_no_stream_id_injected(self) -> None:+ channel = _make_channel()+ client = _FakeClient()+ channel._client = client++ async def run() -> None:+ await channel.send(+ OutboundMessage(+ channel="wecom", chat_id="user123", content="Thinking",+ metadata={"_progress": True},+ )+ )+ await channel.send(+ OutboundMessage(+ channel="wecom", chat_id="user123", content="Final answer",+ metadata={},+ )+ )++ asyncio.run(run())++ stream_ids = [c[0] for c in client.calls]+ assert stream_ids[0] == stream_ids[1]+ assert channel._stream_ids == {}++ def test_separate_chats_never_share_a_stream_id(self) -> None:+ channel = _make_channel()+ channel._chat_frames["user456"] = {"headers": {"req_id": "def"}}+ client = _FakeClient()+ channel._client = client++ async def run() -> None:+ await channel.send(+ OutboundMessage(channel="wecom", chat_id="user123", content="A", metadata={"_progress": True})+ )+ await channel.send(+ OutboundMessage(channel="wecom", chat_id="user456", content="B", metadata={"_progress": True})+ )++ asyncio.run(run())++ stream_ids = [c[0] for c in client.calls]+ assert stream_ids[0] != stream_ids[1]