Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(channels): stop wechat file downloads overwriting same-named attachments

Lanre Shittue3ee3ab76ff7
diff --git a/agent/src/channels/weixin.py b/agent/src/channels/weixin.py
index fcbcbd42f..e98e601e5 100644
--- a/agent/src/channels/weixin.py
+++ b/agent/src/channels/weixin.py
@@ -914,12 +914,20 @@ class WeixinChannel(BaseChannel):
media_dir = get_media_dir("weixin")
ext = _ext_for_type(media_type)
- if not filename:
- ts = int(time.time())
- hash_seed = encrypt_query_param or full_url
- h = abs(hash(hash_seed)) % 100000
- filename = f"{media_type}_{ts}_{h}{ext}"
- safe_name = os.path.basename(filename)
+ # Always make the on-disk name unique, even when the sender
+ # supplied a filename (ITEM_FILE): two different messages can
+ # share the same original filename (e.g. repeated "report.pdf"),
+ # and without a unique stem the second download silently
+ # overwrites the first on disk, corrupting any earlier
+ # conversation turn that already referenced that path.
+ ts = int(time.time())
+ hash_seed = encrypt_query_param or full_url
+ h = abs(hash(hash_seed)) % 100000
+ if filename:
+ stem, orig_ext = os.path.splitext(os.path.basename(filename))
+ safe_name = f"{stem}_{ts}_{h}{orig_ext or ext}"
+ else:
+ safe_name = f"{media_type}_{ts}_{h}{ext}"
file_path = media_dir / safe_name
file_path.write_bytes(data)
return str(file_path)
diff --git a/agent/tests/test_weixin_media_filename_collision.py b/agent/tests/test_weixin_media_filename_collision.py
new file mode 100644
index 000000000..672150587
--- /dev/null
+++ b/agent/tests/test_weixin_media_filename_collision.py
@@ -0,0 +1,87 @@
+"""Regression: two WeChat file attachments with the same sender-supplied
+filename must not overwrite each other on disk.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import pytest
+
+import src.channels.weixin as weixin_mod
+from src.channels.weixin import WeixinChannel
+
+_FAKE_AES_KEY_B64 = "ZmFrZWtleWZha2VrZXkxNg=="
+
+
+class _FakeResponse:
+ def __init__(self, content: bytes) -> None:
+ self.content = content
+
+ def raise_for_status(self) -> None:
+ pass
+
+
+class _FakeClient:
+ def __init__(self, payload: bytes) -> None:
+ self._payload = payload
+
+ async def get(self, url: str) -> _FakeResponse:
+ return _FakeResponse(self._payload)
+
+
+def channel(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> WeixinChannel:
+ monkeypatch.setattr(weixin_mod, "get_media_dir", lambda name: tmp_path)
+ monkeypatch.setattr(weixin_mod, "_decrypt_aes_ecb", lambda data, key: data)
+ return WeixinChannel({}, bus=None)
+
+
+def _file_item(encrypt_query_param: str, full_url: str) -> dict:
+ return {
+ "media": {
+ "encrypt_query_param": encrypt_query_param,
+ "full_url": full_url,
+ "aes_key": _FAKE_AES_KEY_B64,
+ },
+ "aeskey": "",
+ }
+
+
+class TestFileDownloadFilenameCollision:
+ def test_same_filename_from_two_messages_does_not_overwrite(
+ self, channel: WeixinChannel
+ ) -> None:
+ async def run() -> tuple[str | None, str | None]:
+ channel._client = _FakeClient(b"FIRST FILE CONTENT")
+ path1 = await channel._download_media_item(
+ _file_item("q1", "https://cdn/1"), "file", "report.pdf"
+ )
+ channel._client = _FakeClient(b"SECOND FILE CONTENT")
+ path2 = await channel._download_media_item(
+ _file_item("q2", "https://cdn/2"), "file", "report.pdf"
+ )
+ return path1, path2
+
+ path1, path2 = asyncio.run(run())
+
+ assert path1 is not None and path2 is not None
+ assert path1 != path2
+ assert Path(path1).read_bytes() == b"FIRST FILE CONTENT"
+ assert Path(path2).read_bytes() == b"SECOND FILE CONTENT"
+
+ def test_unique_name_still_keeps_the_original_extension(
+ self, channel: WeixinChannel
+ ) -> None:
+ async def run() -> str | None:
+ channel._client = _FakeClient(b"content")
+ return await channel._download_media_item(
+ _file_item("q1", "https://cdn/1"), "file", "report.pdf"
+ )
+
+ path = asyncio.run(run())
+
+ assert path is not None
+ assert path.endswith(".pdf")
+ assert Path(path).stem.startswith("report_")