The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(weixin): same session-not-ready error on the media leg; cooldown message keeps the raw fields; test + docs
kshitijk4poor5db9f02372c3
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.pyindex 1f1df222f2f..d8c3e835d35 100644--- a/gateway/platforms/weixin.py+++ b/gateway/platforms/weixin.py@@ -74,7 +74,7 @@ def _is_stale_session_ret(ret: "Optional[int]", errcode: "Optional[int]", errmsgdef _is_session_expired(resp: Dict[str, Any], ret: Any, errcode: Any) -> bool:- return SESSION_EXPIRED_ERRCODE in (ret, errcode) or _is_stale_session_ret(ret, errcode, resp.get("errmsg"))+ return SESSION_EXPIRED_ERRCODE in (ret, errcode) or _is_stale_session_ret(ret, errcode, resp.get("errmsg") or resp.get("msg"))def _session_not_ready_error(ret: Any, errcode: Any, errmsg: Any) -> RuntimeError:@@ -981,8 +981,7 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):"""Send one text chunk with retry/backoff under the adapter-wide text gate. A stale-session response (``-14``,or ``-2`` with ``prepare failed``/``unknown error``) is re-sent once *without* ``context_token`` — iLink acceptstokenless sends as a degraded fallback, which keeps cron pushes working when no user message refreshed the- session. A ``-2`` stale-session answer that survives that (or arrives with no token to drop) fails fast with- ``_session_not_ready_error`` instead of entering the retry ladder or the rate-limit breaker (#80125)."""+ session. A ``-2`` that survives that fails fast via ``_session_not_ready_error``."""async with self._send_text_gate:last_error: Optional[Exception] = Noneretried_without_token = False@@ -1012,7 +1011,8 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):last_error = RuntimeError(f"iLink sendmessage rate limited: ret={ret} errcode={errcode} errmsg={errmsg or 'rate limited'}")if self._record_rate_limit_event():last_error = RuntimeError(- f"iLink sendmessage rate limited; cooldown active for {self._rate_limit_cooldown_remaining():.1f}s")+ f"iLink sendmessage rate limited (ret={ret} errcode={errcode} errmsg={errmsg or 'rate limited'}); "+ f"cooldown active for {self._rate_limit_cooldown_remaining():.1f}s")breakif attempt >= self._send_chunk_retries:break@@ -1187,6 +1187,8 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):logger.warning("[%s] session expired for %s; re-sending media without context_token", self.name, _safe_id(chat_id))continueerrmsg = resp.get("errmsg") or resp.get("msg")+ if _is_stale_session_ret(ret, errcode, errmsg):+ raise _session_not_ready_error(ret, errcode, errmsg)raise RuntimeError(f"iLink sendmessage error: ret={ret} errcode={errcode} errmsg={errmsg or 'unknown error'}")return last_message_iddiff --git a/tests/gateway/test_weixin.py b/tests/gateway/test_weixin.pyindex 9e539decd23..9a5575b9aad 100644--- a/tests/gateway/test_weixin.py+++ b/tests/gateway/test_weixin.py@@ -257,13 +257,13 @@ class TestWeixinSendMessageIntegration:class TestWeixinChunkDelivery:- def _connected_adapter(self) -> WeixinAdapter:+ def _connected_adapter(self, context_token="ctx-token") -> WeixinAdapter:adapter = _make_adapter()adapter._session = object()adapter._send_session = adapter._sessionadapter._token = "test-token"adapter._base_url = "https://weixin.example.com"- adapter._token_store.get = lambda account_id, chat_id: "ctx-token"+ adapter._token_store.get = lambda account_id, chat_id: context_tokenreturn adapter@@ -337,6 +337,27 @@ class TestWeixinChunkDelivery:assert [call.kwargs["context_token"] for call in send_message_mock.await_args_list] == ["ctx-token", None]assert adapter._rate_limit_circuit_until == 0.0+ @pytest.mark.parametrize("stored_token", [None, "ctx-token"])+ @patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)+ def test_prepare_failed_without_recovery_is_not_a_rate_limit(self, send_message_mock, stored_token):+ """No token to drop (fresh pairing, #80125) or a tokenless re-send that still fails: the error names the+ real cause and the rate-limit breaker stays closed, instead of "rate limited; cooldown active" for 30s."""+ from gateway.platforms.base import classify_send_error++ adapter = self._connected_adapter(context_token=stored_token)+ adapter._rate_limit_circuit_threshold = 1+ send_message_mock.return_value = {"ret": weixin.RATE_LIMIT_ERRCODE, "errmsg": "prepare failed"}++ result = asyncio.run(adapter.send("wxid_test123", "hello"))++ assert result.success is False+ assert "prepare failed" in (result.error or "") and "cooldown" not in (result.error or "")+ # The platform-neutral classifier must not route it back into the rate-limited redelivery lane either.+ assert classify_send_error(None, result.error or "") != "rate_limited"+ assert adapter._rate_limit_cooldown_remaining() == 0.0+ assert [call.kwargs["context_token"] for call in send_message_mock.await_args_list] == (+ [None] if stored_token is None else ["ctx-token", None])+@patch("gateway.platforms.weixin._send_message", new_callable=AsyncMock)def test_tokenless_resend_does_not_consume_retry_budget(self, send_message_mock):"""With ``send_chunk_retries=0`` the stale-session re-send must still happen: it is a different payload,@@ -364,7 +385,7 @@ class TestWeixinChunkDelivery:result = asyncio.run(adapter.send_document("wxid_test123", str(doc)))assert result.success is False- assert "prepare failed" in (result.error or "")+ assert "session not ready" in (result.error or "") and "prepare failed" in (result.error or "")assert [call.kwargs["context_token"] for call in send_items_mock.await_args_list] == ["ctx-token", None]diff --git a/website/docs/user-guide/messaging/weixin.md b/website/docs/user-guide/messaging/weixin.mdindex 3b7600d73e4..eb23c084262 100644--- a/website/docs/user-guide/messaging/weixin.md+++ b/website/docs/user-guide/messaging/weixin.md@@ -322,7 +322,7 @@ Only one Weixin gateway instance can use a given token at a time. The adapter ac| `Weixin startup failed: WEIXIN_ACCOUNT_ID is required` | Set `WEIXIN_ACCOUNT_ID` in your `.env` or run `hermes gateway setup` || `Another local Hermes gateway is already using this Weixin token` | Stop the other gateway instance first — only one poller per token is allowed || Session expired (`errcode=-14`) | Your login session has expired. Re-run `hermes gateway setup` to scan a new QR code |-| Proactive send (cron / notification) fails with `ret=-2 errmsg=prepare failed` or `unknown error` | The peer's `context_token` went stale (no recent inbound message from them). The adapter treats this as a stale session — not a rate limit — and re-sends once without the token, so the message still arrives. Only other `-2` responses trigger the rate-limit backoff/cooldown |+| Proactive send (cron / notification) fails with `ret=-2 errmsg=prepare failed` or `unknown error` | The peer's `context_token` went stale (no recent inbound message from them). The adapter treats this as a stale session — not a rate limit — and re-sends once without the token, so the message still arrives. If iLink still answers `prepare failed` (or there was no token to drop — a freshly paired bot), the send (text or media) fails with `iLink sendmessage session not ready … the user must send the bot a message first (or re-pair)`; the rate-limit cooldown never opens for it. Only other `-2` responses trigger the rate-limit backoff/cooldown, and that cooldown error carries the raw `ret`/`errcode`/`errmsg` || QR code expired during setup | The QR auto-refreshes up to 3 times. If it keeps expiring, check your network connection || Bot doesn't respond to DMs | Check `WEIXIN_DM_POLICY` — if set to `allowlist`, the sender must be in `WEIXIN_ALLOWED_USERS` || Bot ignores group messages | Group policy defaults to `disabled`. Set `WEIXIN_GROUP_POLICY=open` or `allowlist` — but note that QR-login iLink bot identities (`[email protected]`) typically cannot receive ordinary WeChat group messages at all. If the gateway logs show no raw inbound events for group messages, the limitation is on the iLink side, not in Hermes. |