Skip to content

Your lightweight open-source personal agent.

merge: resolve conflicts with upstream/main, preserve typing indicator

cypggsca68a89ce6a5
diff --cc nanobot/channels/weixin.py
index 9e2caae3f,891cfd099..2266bc9f0
--- a/nanobot/channels/weixin.py
+++ b/nanobot/channels/weixin.py
@@@ -13,7 -13,9 +13,8 @@@ import asynci
import base64
import hashlib
import json
-import mimetypes
import os
+ import random
import re
import time
import uuid
@@@ -123,8 -158,7 +157,8 @@@ class WeixinChannel(BaseChannel)
self._poll_task: asyncio.Task | None = None
self._next_poll_timeout_s: int = DEFAULT_LONG_POLL_TIMEOUT_S
self._session_pause_until: float = 0.0
+ self._typing_tasks: dict[str, asyncio.Task] = {}
- self._typing_tickets: dict[str, str] = {}
+ self._typing_tickets: dict[str, dict[str, Any]] = {}
# ------------------------------------------------------------------
# State persistence
@@@ -159,15 -193,6 +193,15 @@@
}
else:
self._context_tokens = {}
+ typing_tickets = data.get("typing_tickets", {})
+ if isinstance(typing_tickets, dict):
+ self._typing_tickets = {
- str(user_id): str(ticket)
++ str(user_id): ticket
+ for user_id, ticket in typing_tickets.items()
- if str(user_id).strip() and str(ticket).strip()
++ if str(user_id).strip() and isinstance(ticket, dict)
+ }
+ else:
+ self._typing_tickets = {}
base_url = data.get("base_url", "")
if base_url:
self.config.base_url = base_url
@@@ -731,14 -924,9 +945,13 @@@
return
try:
self._assert_session_active()
- except RuntimeError as e:
- logger.warning("WeChat send blocked: {}", e)
+ except RuntimeError:
return
+ is_progress = bool((msg.metadata or {}).get("_progress", False))
+ if not is_progress:
+ await self._stop_typing(msg.chat_id, clear_remote=True)
+
content = msg.content.strip()
ctx_token = self._context_tokens.get(msg.chat_id, "")
if not ctx_token:
@@@ -771,86 -978,21 +1003,77 @@@
except Exception as e:
logger.error("Error sending WeChat message: {}", e)
raise
+ finally:
+ if typing_keepalive_task:
+ typing_keepalive_stop.set()
+ typing_keepalive_task.cancel()
+ try:
+ await typing_keepalive_task
+ except asyncio.CancelledError:
+ pass
- async def _get_typing_ticket(self, user_id: str, context_token: str) -> str:
- """Fetch and cache typing ticket for a user/context pair."""
- if not self._client or not self._token or not user_id or not context_token:
- return ""
- cached = self._typing_tickets.get(user_id, "")
- if cached:
- return cached
- try:
- data = await self._api_post(
- "ilink/bot/getconfig",
- {
- "ilink_user_id": user_id,
- "context_token": context_token,
- },
- )
- except Exception as e:
- logger.debug("WeChat getconfig failed for {}: {}", user_id, e)
- return ""
- ticket = str(data.get("typing_ticket") or "").strip()
- if ticket:
- self._typing_tickets[user_id] = ticket
- self._save_state()
- return ticket
-
- async def _send_typing_status(self, to_user_id: str, typing_ticket: str, status: int) -> None:
- if not typing_ticket:
- return
- await self._api_post(
- "ilink/bot/sendtyping",
- {
- "ilink_user_id": to_user_id,
- "typing_ticket": typing_ticket,
- "status": status,
- },
- )
- if typing_ticket:
++ if typing_ticket and not is_progress:
+ try:
+ await self._send_typing(msg.chat_id, typing_ticket, TYPING_STATUS_CANCEL)
+ except Exception:
+ pass
- async def _start_typing(self, chat_id: str, context_token: str) -> None:
- if not self._client or not self._token or not chat_id or not context_token:
++ async def _start_typing(self, chat_id: str, context_token: str = "") -> None:
++ """Start typing indicator immediately when a message is received."""
++ if not self._client or not self._token or not chat_id:
+ return
+ await self._stop_typing(chat_id, clear_remote=False)
- ticket = await self._get_typing_ticket(chat_id, context_token)
- if not ticket:
- return
+ try:
- await self._send_typing_status(chat_id, ticket, 1)
++ ticket = await self._get_typing_ticket(chat_id, context_token)
++ if not ticket:
++ return
++ await self._send_typing(chat_id, ticket, TYPING_STATUS_TYPING)
+ except Exception as e:
- logger.debug("WeChat typing indicator failed for {}: {}", chat_id, e)
++ logger.debug("WeChat typing indicator start failed for {}: {}", chat_id, e)
+ return
+
- async def typing_loop() -> None:
++ stop_event = asyncio.Event()
++
++ async def keepalive() -> None:
+ try:
- while self._running:
- await asyncio.sleep(5)
- await self._send_typing_status(chat_id, ticket, 1)
- except asyncio.CancelledError:
++ while not stop_event.is_set():
++ await asyncio.sleep(TYPING_KEEPALIVE_INTERVAL_S)
++ if stop_event.is_set():
++ break
++ try:
++ await self._send_typing(chat_id, ticket, TYPING_STATUS_TYPING)
++ except Exception:
++ pass
++ finally:
+ pass
- except Exception as e:
- logger.debug("WeChat typing keepalive stopped for {}: {}", chat_id, e)
+
- self._typing_tasks[chat_id] = asyncio.create_task(typing_loop())
++ task = asyncio.create_task(keepalive())
++ task._typing_stop_event = stop_event # type: ignore[attr-defined]
++ self._typing_tasks[chat_id] = task
+
+ async def _stop_typing(self, chat_id: str, *, clear_remote: bool) -> None:
++ """Stop typing indicator for a chat."""
+ task = self._typing_tasks.pop(chat_id, None)
+ if task and not task.done():
++ stop_event = getattr(task, "_typing_stop_event", None)
++ if stop_event:
++ stop_event.set()
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ if not clear_remote:
+ return
- ticket = self._typing_tickets.get(chat_id, "")
++ entry = self._typing_tickets.get(chat_id)
++ ticket = str(entry.get("ticket", "") or "") if isinstance(entry, dict) else ""
+ if not ticket:
+ return
+ try:
- await self._send_typing_status(chat_id, ticket, 2)
++ await self._send_typing(chat_id, ticket, TYPING_STATUS_CANCEL)
+ except Exception as e:
+ logger.debug("WeChat typing clear failed for {}: {}", chat_id, e)
+
async def _send_text(
self,
to_user_id: str,
diff --cc tests/channels/test_weixin_channel.py
index 35b01db8b,58fc30865..3a847411b
--- a/tests/channels/test_weixin_channel.py
+++ b/tests/channels/test_weixin_channel.py
@@@ -280,75 -572,355 +572,434 @@@ async def test_process_message_skips_bo
assert bus.inbound_size == 0
- async def test_process_message_fetches_typing_ticket_and_starts_typing() -> None:
++async def test_process_message_starts_typing_on_inbound() -> None:
++ """Typing indicator fires immediately when user message arrives."""
+ channel, _bus = _make_channel()
+ channel._running = True
+ channel._client = object()
+ channel._token = "token"
- channel._api_post = AsyncMock(return_value={"typing_ticket": "ticket-1"})
++ channel._start_typing = AsyncMock()
+
+ await channel._process_message(
+ {
+ "message_type": 1,
+ "message_id": "m-typing",
+ "from_user_id": "wx-user",
+ "context_token": "ctx-typing",
+ "item_list": [
+ {"type": ITEM_TEXT, "text_item": {"text": "hello"}},
+ ],
+ }
+ )
+
- assert channel._typing_tickets["wx-user"] == "ticket-1"
- assert "wx-user" in channel._typing_tasks
- await channel._stop_typing("wx-user", clear_remote=False)
++ channel._start_typing.assert_awaited_once_with("wx-user", "ctx-typing")
+
+
+async def test_send_final_message_clears_typing_indicator() -> None:
++ """Non-progress send should cancel typing status."""
+ channel, _bus = _make_channel()
+ channel._client = object()
+ channel._token = "token"
+ channel._context_tokens["wx-user"] = "ctx-2"
- channel._typing_tickets["wx-user"] = "ticket-2"
++ channel._typing_tickets["wx-user"] = {"ticket": "ticket-2", "next_fetch_at": 9999999999}
+ channel._send_text = AsyncMock()
- channel._api_post = AsyncMock(return_value={})
++ channel._api_post = AsyncMock(return_value={"ret": 0})
+
+ await channel.send(
+ type("Msg", (), {"chat_id": "wx-user", "content": "pong", "media": [], "metadata": {}})()
+ )
+
+ channel._send_text.assert_awaited_once_with("wx-user", "pong", "ctx-2")
- channel._api_post.assert_awaited_once()
- endpoint, body = channel._api_post.await_args.args
- assert endpoint == "ilink/bot/sendtyping"
- assert body["status"] == 2
- assert body["typing_ticket"] == "ticket-2"
++ typing_cancel_calls = [
++ c for c in channel._api_post.await_args_list
++ if c.args[0] == "ilink/bot/sendtyping" and c.args[1]["status"] == 2
++ ]
++ assert len(typing_cancel_calls) >= 1
+
+
+async def test_send_progress_message_keeps_typing_indicator() -> None:
++ """Progress messages must not cancel typing status."""
+ channel, _bus = _make_channel()
+ channel._client = object()
+ channel._token = "token"
+ channel._context_tokens["wx-user"] = "ctx-2"
- channel._typing_tickets["wx-user"] = "ticket-2"
++ channel._typing_tickets["wx-user"] = {"ticket": "ticket-2", "next_fetch_at": 9999999999}
+ channel._send_text = AsyncMock()
- channel._api_post = AsyncMock(return_value={})
++ channel._api_post = AsyncMock(return_value={"ret": 0})
+
+ await channel.send(
+ type(
+ "Msg",
+ (),
+ {
+ "chat_id": "wx-user",
+ "content": "thinking",
+ "media": [],
+ "metadata": {"_progress": True},
+ },
+ )()
+ )
+
+ channel._send_text.assert_awaited_once_with("wx-user", "thinking", "ctx-2")
- channel._api_post.assert_not_awaited()
++ typing_cancel_calls = [
++ c for c in channel._api_post.await_args_list
++ if c.args and c.args[0] == "ilink/bot/sendtyping" and c.args[1].get("status") == 2
++ ]
++ assert len(typing_cancel_calls) == 0
++
++
+ class _DummyHttpResponse:
+ def __init__(self, *, headers: dict[str, str] | None = None, status_code: int = 200) -> None:
+ self.headers = headers or {}
+ self.status_code = status_code
+
+ def raise_for_status(self) -> None:
+ return None
+
+
+ @pytest.mark.asyncio
+ async def test_send_media_uses_upload_full_url_when_present(tmp_path) -> None:
+ channel, _bus = _make_channel()
+
+ media_file = tmp_path / "photo.jpg"
+ media_file.write_bytes(b"hello-weixin")
+
+ cdn_post = AsyncMock(return_value=_DummyHttpResponse(headers={"x-encrypted-param": "dl-param"}))
+ channel._client = SimpleNamespace(post=cdn_post)
+ channel._api_post = AsyncMock(
+ side_effect=[
+ {
+ "upload_full_url": "https://upload-full.example.test/path?foo=bar",
+ "upload_param": "should-not-be-used",
+ },
+ {"ret": 0},
+ ]
+ )
+
+ await channel._send_media_file("wx-user", str(media_file), "ctx-1")
+
+ # first POST call is CDN upload
+ cdn_url = cdn_post.await_args_list[0].args[0]
+ assert cdn_url == "https://upload-full.example.test/path?foo=bar"
+
+
+ @pytest.mark.asyncio
+ async def test_send_media_falls_back_to_upload_param_url(tmp_path) -> None:
+ channel, _bus = _make_channel()
+
+ media_file = tmp_path / "photo.jpg"
+ media_file.write_bytes(b"hello-weixin")
+
+ cdn_post = AsyncMock(return_value=_DummyHttpResponse(headers={"x-encrypted-param": "dl-param"}))
+ channel._client = SimpleNamespace(post=cdn_post)
+ channel._api_post = AsyncMock(
+ side_effect=[
+ {"upload_param": "enc-need-fallback"},
+ {"ret": 0},
+ ]
+ )
+
+ await channel._send_media_file("wx-user", str(media_file), "ctx-1")
+
+ cdn_url = cdn_post.await_args_list[0].args[0]
+ assert cdn_url.startswith(f"{channel.config.cdn_base_url}/upload?encrypted_query_param=enc-need-fallback")
+ assert "&filekey=" in cdn_url
+
+
+ @pytest.mark.asyncio
+ async def test_send_media_voice_file_uses_voice_item_and_voice_upload_type(tmp_path) -> None:
+ channel, _bus = _make_channel()
+
+ media_file = tmp_path / "voice.mp3"
+ media_file.write_bytes(b"voice-bytes")
+
+ cdn_post = AsyncMock(return_value=_DummyHttpResponse(headers={"x-encrypted-param": "voice-dl-param"}))
+ channel._client = SimpleNamespace(post=cdn_post)
+ channel._api_post = AsyncMock(
+ side_effect=[
+ {"upload_full_url": "https://upload-full.example.test/voice?foo=bar"},
+ {"ret": 0},
+ ]
+ )
+
+ await channel._send_media_file("wx-user", str(media_file), "ctx-voice")
+
+ getupload_body = channel._api_post.await_args_list[0].args[1]
+ assert getupload_body["media_type"] == 4
+
+ sendmessage_body = channel._api_post.await_args_list[1].args[1]
+ item = sendmessage_body["msg"]["item_list"][0]
+ assert item["type"] == 3
+ assert "voice_item" in item
+ assert "file_item" not in item
+ assert item["voice_item"]["media"]["encrypt_query_param"] == "voice-dl-param"
+
+
+ @pytest.mark.asyncio
+ async def test_send_typing_uses_keepalive_until_send_finishes() -> None:
+ channel, _bus = _make_channel()
+ channel._client = object()
+ channel._token = "token"
+ channel._context_tokens["wx-user"] = "ctx-typing-loop"
+ async def _api_post_side_effect(endpoint: str, _body: dict | None = None, *, auth: bool = True):
+ if endpoint == "ilink/bot/getconfig":
+ return {"ret": 0, "typing_ticket": "ticket-keepalive"}
+ return {"ret": 0}
+
+ channel._api_post = AsyncMock(side_effect=_api_post_side_effect)
+
+ async def _slow_send_text(*_args, **_kwargs) -> None:
+ await asyncio.sleep(0.03)
+
+ channel._send_text = AsyncMock(side_effect=_slow_send_text)
+
+ old_interval = weixin_mod.TYPING_KEEPALIVE_INTERVAL_S
+ weixin_mod.TYPING_KEEPALIVE_INTERVAL_S = 0.01
+ try:
+ await channel.send(
+ type("Msg", (), {"chat_id": "wx-user", "content": "pong", "media": [], "metadata": {}})()
+ )
+ finally:
+ weixin_mod.TYPING_KEEPALIVE_INTERVAL_S = old_interval
+
+ status_calls = [
+ c.args[1]["status"]
+ for c in channel._api_post.await_args_list
+ if c.args and c.args[0] == "ilink/bot/sendtyping"
+ ]
+ assert status_calls.count(1) >= 2
+ assert status_calls[-1] == 2
+
+
+ @pytest.mark.asyncio
+ async def test_get_typing_ticket_failure_uses_backoff_and_cached_ticket(monkeypatch) -> None:
+ channel, _bus = _make_channel()
+ channel._client = object()
+ channel._token = "token"
+
+ now = {"value": 1000.0}
+ monkeypatch.setattr(weixin_mod.time, "time", lambda: now["value"])
+ monkeypatch.setattr(weixin_mod.random, "random", lambda: 0.5)
+
+ channel._api_post = AsyncMock(return_value={"ret": 0, "typing_ticket": "ticket-ok"})
+ first = await channel._get_typing_ticket("wx-user", "ctx-1")
+ assert first == "ticket-ok"
+
+ # force refresh window reached
+ now["value"] = now["value"] + (12 * 60 * 60) + 1
+ channel._api_post = AsyncMock(return_value={"ret": 1, "errmsg": "temporary failure"})
+
+ # On refresh failure, should still return cached ticket and apply backoff.
+ second = await channel._get_typing_ticket("wx-user", "ctx-2")
+ assert second == "ticket-ok"
+ assert channel._api_post.await_count == 1
+
+ # Before backoff expiry, no extra fetch should happen.
+ now["value"] += 1
+ third = await channel._get_typing_ticket("wx-user", "ctx-3")
+ assert third == "ticket-ok"
+ assert channel._api_post.await_count == 1
+
+
+ @pytest.mark.asyncio
+ async def test_qr_login_treats_temporary_connect_error_as_wait_and_recovers() -> None:
+ channel, _bus = _make_channel()
+ channel._running = True
+ channel._save_state = lambda: None
+ channel._print_qr_code = lambda url: None
+ channel._fetch_qr_code = AsyncMock(return_value=("qr-1", "url-1"))
+
+ request = httpx.Request("GET", "https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status")
+ channel._api_get_with_base = AsyncMock(
+ side_effect=[
+ httpx.ConnectError("temporary network", request=request),
+ {
+ "status": "confirmed",
+ "bot_token": "token-net-ok",
+ "ilink_bot_id": "bot-id",
+ "baseurl": "https://example.test",
+ "ilink_user_id": "wx-user",
+ },
+ ]
+ )
+
+ ok = await channel._qr_login()
+
+ assert ok is True
+ assert channel._token == "token-net-ok"
+
+
+ @pytest.mark.asyncio
+ async def test_qr_login_treats_5xx_gateway_response_error_as_wait_and_recovers() -> None:
+ channel, _bus = _make_channel()
+ channel._running = True
+ channel._save_state = lambda: None
+ channel._print_qr_code = lambda url: None
+ channel._fetch_qr_code = AsyncMock(return_value=("qr-1", "url-1"))
+
+ request = httpx.Request("GET", "https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_status")
+ response = httpx.Response(status_code=524, request=request)
+ channel._api_get_with_base = AsyncMock(
+ side_effect=[
+ httpx.HTTPStatusError("gateway timeout", request=request, response=response),
+ {
+ "status": "confirmed",
+ "bot_token": "token-5xx-ok",
+ "ilink_bot_id": "bot-id",
+ "baseurl": "https://example.test",
+ "ilink_user_id": "wx-user",
+ },
+ ]
+ )
+
+ ok = await channel._qr_login()
+
+ assert ok is True
+ assert channel._token == "token-5xx-ok"
+
+
+ def test_decrypt_aes_ecb_strips_valid_pkcs7_padding() -> None:
+ key_b64 = "MDEyMzQ1Njc4OWFiY2RlZg==" # base64("0123456789abcdef")
+ plaintext = b"hello-weixin-padding"
+
+ ciphertext = _encrypt_aes_ecb(plaintext, key_b64)
+ decrypted = _decrypt_aes_ecb(ciphertext, key_b64)
+
+ assert decrypted == plaintext
+
+
+ class _DummyDownloadResponse:
+ def __init__(self, content: bytes, status_code: int = 200) -> None:
+ self.content = content
+ self.status_code = status_code
+
+ def raise_for_status(self) -> None:
+ return None
+
+
+ class _DummyErrorDownloadResponse(_DummyDownloadResponse):
+ def __init__(self, url: str, status_code: int) -> None:
+ super().__init__(content=b"", status_code=status_code)
+ self._url = url
+
+ def raise_for_status(self) -> None:
+ request = httpx.Request("GET", self._url)
+ response = httpx.Response(self.status_code, request=request)
+ raise httpx.HTTPStatusError(
+ f"download failed with status {self.status_code}",
+ request=request,
+ response=response,
+ )
+
+
+ @pytest.mark.asyncio
+ async def test_download_media_item_uses_full_url_when_present(tmp_path) -> None:
+ channel, _bus = _make_channel()
+ weixin_mod.get_media_dir = lambda _name: tmp_path
+
+ full_url = "https://cdn.example.test/download/full"
+ channel._client = SimpleNamespace(
+ get=AsyncMock(return_value=_DummyDownloadResponse(content=b"raw-image-bytes"))
+ )
+
+ item = {
+ "media": {
+ "full_url": full_url,
+ "encrypt_query_param": "enc-fallback-should-not-be-used",
+ },
+ }
+ saved_path = await channel._download_media_item(item, "image")
+
+ assert saved_path is not None
+ assert Path(saved_path).read_bytes() == b"raw-image-bytes"
+ channel._client.get.assert_awaited_once_with(full_url)
+
+
+ @pytest.mark.asyncio
+ async def test_download_media_item_falls_back_when_full_url_returns_retryable_error(tmp_path) -> None:
+ channel, _bus = _make_channel()
+ weixin_mod.get_media_dir = lambda _name: tmp_path
+
+ full_url = "https://cdn.example.test/download/full?taskid=123"
+ channel._client = SimpleNamespace(
+ get=AsyncMock(
+ side_effect=[
+ _DummyErrorDownloadResponse(full_url, 500),
+ _DummyDownloadResponse(content=b"fallback-bytes"),
+ ]
+ )
+ )
+
+ item = {
+ "media": {
+ "full_url": full_url,
+ "encrypt_query_param": "enc-fallback",
+ },
+ }
+ saved_path = await channel._download_media_item(item, "image")
+
+ assert saved_path is not None
+ assert Path(saved_path).read_bytes() == b"fallback-bytes"
+ assert channel._client.get.await_count == 2
+ assert channel._client.get.await_args_list[0].args[0] == full_url
+ fallback_url = channel._client.get.await_args_list[1].args[0]
+ assert fallback_url.startswith(f"{channel.config.cdn_base_url}/download?encrypted_query_param=enc-fallback")
+
+
+ @pytest.mark.asyncio
+ async def test_download_media_item_falls_back_to_encrypt_query_param(tmp_path) -> None:
+ channel, _bus = _make_channel()
+ weixin_mod.get_media_dir = lambda _name: tmp_path
+
+ channel._client = SimpleNamespace(
+ get=AsyncMock(return_value=_DummyDownloadResponse(content=b"fallback-bytes"))
+ )
+
+ item = {"media": {"encrypt_query_param": "enc-fallback"}}
+ saved_path = await channel._download_media_item(item, "image")
+
+ assert saved_path is not None
+ assert Path(saved_path).read_bytes() == b"fallback-bytes"
+ called_url = channel._client.get.await_args_list[0].args[0]
+ assert called_url.startswith(f"{channel.config.cdn_base_url}/download?encrypted_query_param=enc-fallback")
+
+
+ @pytest.mark.asyncio
+ async def test_download_media_item_does_not_retry_when_full_url_fails_without_fallback(tmp_path) -> None:
+ channel, _bus = _make_channel()
+ weixin_mod.get_media_dir = lambda _name: tmp_path
+
+ full_url = "https://cdn.example.test/download/full"
+ channel._client = SimpleNamespace(
+ get=AsyncMock(return_value=_DummyErrorDownloadResponse(full_url, 500))
+ )
+
+ item = {"media": {"full_url": full_url}}
+ saved_path = await channel._download_media_item(item, "image")
+
+ assert saved_path is None
+ channel._client.get.assert_awaited_once_with(full_url)
+
+
+ @pytest.mark.asyncio
+ async def test_download_media_item_non_image_requires_aes_key_even_with_full_url(tmp_path) -> None:
+ channel, _bus = _make_channel()
+ weixin_mod.get_media_dir = lambda _name: tmp_path
+
+ full_url = "https://cdn.example.test/download/voice"
+ channel._client = SimpleNamespace(
+ get=AsyncMock(return_value=_DummyDownloadResponse(content=b"ciphertext-or-unknown"))
+ )
+
+ item = {
+ "media": {
+ "full_url": full_url,
+ },
+ }
+ saved_path = await channel._download_media_item(item, "voice")
+
+ assert saved_path is None
+ channel._client.get.assert_not_awaited()