From 59c44e94ca2f2c167e84fce083f7168b03189a01 Mon Sep 17 00:00:00 2001 From: OpenBot Date: Sat, 24 Oct 2026 09:18:19 +0800 Subject: [PATCH] fix(wecom): degrade stream replies to proactive msg when callback req_id stale Turns that outlive the WeCom callback req_id window (e.g. approval round-trips >5min) had their delta/finish frames silently rejected by the gateway, so the user saw 'clicked approve, nothing happened' while the agent kept working. Track req_id recv time; past a 240s TTL, stream updates fall back to proactive aibot_send_msg. Also log non-zero errcode ack frames so future gateway rejections are visible. --- src/agenthub/channels/wecom.py | 56 +++++++++++++++++++++++----------- tests/test_channels.py | 16 ++++++++-- tests/test_finish_overflow.py | 4 +-- 3 files changed, 55 insertions(+), 21 deletions(-) diff --git a/src/agenthub/channels/wecom.py b/src/agenthub/channels/wecom.py index a6a2931..677bee9 100644 --- a/src/agenthub/channels/wecom.py +++ b/src/agenthub/channels/wecom.py @@ -57,9 +57,9 @@ class WecomAibotChannel: self._ws = None # current socket (set by _connect_and_serve) self.connection_state = "idle" self.connection_error: str = "" - # chat -> streaming state; chat -> last callback req_id (respond must reuse it) + # chat -> streaming state; chat -> (last callback req_id, recv time) self._streams: dict[str, dict] = {} - self._req_ids: dict[str, str] = {} + self._req_ids: dict[str, tuple[str, float]] = {} self._stream_lock = threading.Lock() # media upload acks: req_id -> {event, msg} self._pending_acks: dict[str, dict] = {} @@ -165,6 +165,8 @@ class WecomAibotChannel: cmd = msg.get("cmd", "") if msg.get("errcode") is not None and not cmd: # ack/pong frame — route to a waiting media-upload _request() if any + if msg.get("errcode") != 0: + self._logger.warning(f"[wecom] gateway rejected frame: errcode={msg.get('errcode')} errmsg={msg.get('errmsg')} req_id={(msg.get('headers') or {}).get('req_id', '')}") self._deliver_ack(msg) return req_id = (msg.get("headers") or {}).get("req_id", "") @@ -216,7 +218,7 @@ class WecomAibotChannel: # remember req_id for streaming replies keyed by chat if req_id: with self._stream_lock: - self._req_ids[chat_id] = req_id + self._req_ids[chat_id] = (req_id, time.time()) text = clean_control_chars(text, max_len=100000).strip() if text else "" # group chat: only respond when @mentioned is handled by WeCom itself if not text and not images and not files: @@ -469,23 +471,43 @@ class WecomAibotChannel: for chunk in overflow: self.reply(chat_id, chunk) + # The inbound callback's req_id is only accepted by the WeCom gateway for a + # limited window (~minutes). After an approval round-trip the turn can + # outlive that window; frames reusing the stale req_id are silently + # rejected, so the user sees "clicked approve, nothing happened". Past the + # TTL, stream updates degrade to proactive aibot_send_msg messages. + _CALLBACK_REQ_TTL_S = 240.0 + def _reply_stream(self, chat_id: str, st: dict, text: str, finished: bool) -> None: - # official: reuse the CALLBACK's req_id in headers; stream.id identifies the bubble - req_id = self._req_ids.get(chat_id, "") - self._send( - { - "cmd": "aibot_respond_msg", - "headers": {"req_id": req_id}, - "body": { - "msgtype": "stream", - "stream": {"id": st["req_id"], "finish": finished, "content": text}, - }, - } - ) + entry = self._req_ids.get(chat_id) + req_id = "" + stale = True + if entry: + req_id, ts = entry + stale = (time.time() - ts) > self._CALLBACK_REQ_TTL_S + if req_id and not stale: + self._send( + { + "cmd": "aibot_respond_msg", + "headers": {"req_id": req_id}, + "body": { + "msgtype": "stream", + "stream": {"id": st["req_id"], "finish": finished, "content": text}, + }, + } + ) + if finished: + st["sent"] = True + with self._stream_lock: + self._req_ids.pop(chat_id, None) + return + # no live callback req_id: fall back to a proactive message + self.reply(chat_id, text) if text else None if finished: st["sent"] = True - # proactive follow-ups after the stream need aibot_send_msg - self._req_ids.pop(chat_id, None) + with self._stream_lock: + self._req_ids.pop(chat_id, None) + self._logger.info(f"[wecom] stream finished via proactive message (callback req_id stale or absent) chat={chat_id}") def _send(self, obj: dict) -> None: raw = json.dumps(obj, ensure_ascii=False) diff --git a/tests/test_channels.py b/tests/test_channels.py index ca7738b..d540f27 100644 --- a/tests/test_channels.py +++ b/tests/test_channels.py @@ -77,7 +77,7 @@ def test_wecom_dispatch_text_and_permission(): "from": {"userid": "u1"}, "text": {"content": "hello\u200b"}}} ch._dispatch(frame, ws) assert len(got) == 1 and got[0].text == "hello" and got[0].chat_id == "c1" - assert ch._req_ids["c1"] == "r1" # captured for the streaming reply + assert ch._req_ids["c1"][0] == "r1" # captured for the streaming reply def test_wecom_allowed_users_drops_others(): @@ -91,7 +91,8 @@ def test_wecom_allowed_users_drops_others(): def test_wecom_streaming_delta_coalesce_and_final(): ch, ws = _make_wecom() ch._ws = ws # pretend connected (stream sends go through the socket) - ch._req_ids["c1"] = "req-9" # as set by an inbound callback + ch._req_ids["c1"] = ("req-9", __import__("time").time()) # fresh inbound callback + ch._req_ids["stale"] = ("req-old", __import__("time").time() - 600) # expired callback ch.push_event("c1", "delta", {"text": "hello "}) ch.push_event("c1", "delta", {"text": "world"}) ch.push_event("c1", "final", {"text": "hello world"}) @@ -171,3 +172,14 @@ def test_weixin_no_edit_deltas_dropped_final_sent(): assert not http.posts ch.push_event("u", "final", {"text": "full text"}) assert http.posts[-1][1]["text"]["content"] == "full text" + + +def test_wecom_stream_falls_back_when_callback_req_stale(): + ch, ws = _make_wecom() + ch._ws = ws + ch._req_ids["c1"] = ("req-old", __import__("time").time() - 600) # beyond TTL + ch.push_event("c1", "final", {"text": "late answer"}) + respond = [m for m in ws.sent if m["cmd"] == "aibot_respond_msg"] + send = [m for m in ws.sent if m["cmd"] == "aibot_send_msg"] + assert respond == [] # stale req_id must NOT be reused + assert send and "late answer" in json.dumps(send[-1]) diff --git a/tests/test_finish_overflow.py b/tests/test_finish_overflow.py index 8be85b9..f99085b 100644 --- a/tests/test_finish_overflow.py +++ b/tests/test_finish_overflow.py @@ -37,7 +37,7 @@ def _channel() -> tuple[WecomAibotChannel, MockWS]: def test_small_final_single_stream_frame(): ch, ws = _channel() - ch._req_ids["c1"] = "r1" + ch._req_ids["c1"] = ("r1", __import__("time").time()) ch._stream_close("c1", "hello") streams = [m for m in ws.sent if m.get("cmd") == "aibot_respond_msg"] assert len(streams) == 1 @@ -47,7 +47,7 @@ def test_small_final_single_stream_frame(): def test_large_final_splits_into_stream_plus_markdown(): ch, ws = _channel() - ch._req_ids["c1"] = "r1" + ch._req_ids["c1"] = ("r1", __import__("time").time()) big = "字" * 12000 # 3 bytes/char -> 36000 bytes > 19000 limit ch._stream_close("c1", big) streams = [m for m in ws.sent if m.get("cmd") == "aibot_respond_msg"]