Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(wechat): harden CDN file upload fallback

cyh573e173cf2f2
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 14741e3fc..197e64932 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -8,8 +8,10 @@ from __future__ import annotations
import logging
import asyncio
+from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
+from urllib.parse import urljoin
from config.platform_registry import get_platform_descriptor
from modules.im import MessageContext
@@ -303,6 +305,13 @@ class ConsolidatedMessageDispatcher:
def _supports_quick_replies(self, context: MessageContext) -> bool:
return self._capabilities(context).supports_quick_replies
+ def _is_wechat_context(self, context: MessageContext) -> bool:
+ return (
+ context.platform
+ or (context.platform_specific or {}).get("platform")
+ or self.controller.config.platform
+ ) == "wechat"
+
def _supports_message_editing(self, im_client, context: MessageContext) -> bool:
supports_editing = getattr(im_client, "supports_message_editing", None)
if callable(supports_editing):
@@ -989,6 +998,8 @@ class ConsolidatedMessageDispatcher:
logger.debug("IM client does not support upload_file_from_path; skipping file uploads")
return
+ notify_wechat_failure = self._is_wechat_context(context)
+
for fl in files:
if not os.path.isfile(fl.path):
logger.warning("File not found, skipping upload: %s", fl.path)
@@ -1008,38 +1019,127 @@ class ConsolidatedMessageDispatcher:
upload_title = f"{upload_title}{src_ext}"
try:
+ upload_result = None
if self._is_video_path(str(resolved)):
- await im_client.upload_video_from_path(
+ upload_result = await im_client.upload_video_from_path(
context,
file_path=str(resolved),
title=upload_title,
)
elif getattr(fl, "is_image", False):
try:
- await im_client.upload_image_from_path(
+ upload_result = await im_client.upload_image_from_path(
context,
file_path=str(resolved),
title=upload_title,
)
+ if notify_wechat_failure and not upload_result:
+ raise RuntimeError("image upload returned no message id")
except Exception as image_err:
logger.warning(
"Image upload failed for %s, fallback to file upload: %r",
fl.path,
image_err,
)
- await im_client.upload_file_from_path(
+ upload_result = await im_client.upload_file_from_path(
context,
file_path=str(resolved),
title=upload_title,
)
else:
- await im_client.upload_file_from_path(
+ upload_result = await im_client.upload_file_from_path(
context,
file_path=str(resolved),
title=upload_title,
)
+ if notify_wechat_failure and not upload_result:
+ await self._send_file_upload_failure_notice(
+ im_client,
+ context,
+ file_path=str(resolved),
+ file_name=upload_title,
+ )
except NotImplementedError:
logger.debug("IM client does not implement file uploads; skipping")
return
except Exception as err:
logger.warning("Failed to upload file %s: %r", fl.path, err)
+ if notify_wechat_failure:
+ await self._send_file_upload_failure_notice(
+ im_client,
+ context,
+ file_path=str(resolved),
+ file_name=upload_title,
+ )
+
+ def _register_public_file_download_url(
+ self,
+ context: MessageContext,
+ *,
+ file_path: str,
+ file_name: str,
+ ) -> Optional[str]:
+ """Register a local file under the existing media proxy and return a public URL."""
+ try:
+ from core.avibe_cloud import base_public_url
+ from core.message_mirror import DEFAULT_SCOPE_TYPE
+ from core.workbench_media import register_agent_reply_media
+ from storage import settings_service
+ from storage.db import create_sqlite_engine
+ from sqlalchemy import select
+ from storage.models import agent_sessions
+
+ base = base_public_url(getattr(self.controller, "config", None))
+ if not base:
+ return None
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = settings_service.upsert_scope(
+ conn,
+ platform=context.platform or "wechat",
+ scope_type=DEFAULT_SCOPE_TYPE,
+ native_id=context.channel_id or context.user_id or "wechat",
+ now=datetime.now(timezone.utc).isoformat(),
+ supports_threads=bool(context.thread_id),
+ )
+ session_id = (context.platform_specific or {}).get("agent_session_id")
+ if session_id:
+ existing_session_id = conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.id == str(session_id))
+ ).scalar_one_or_none()
+ session_id = existing_session_id
+ token = register_agent_reply_media(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind="file",
+ local_path=file_path,
+ file_name=file_name,
+ )
+ except Exception:
+ logger.warning("Failed to register fallback download link for %s", file_path, exc_info=True)
+ return None
+
+ return urljoin(base.rstrip("/") + "/", f"api/media/{token}?download=1")
+
+ async def _send_file_upload_failure_notice(
+ self,
+ im_client,
+ context: MessageContext,
+ *,
+ file_path: str,
+ file_name: str,
+ ) -> None:
+ """Tell WeChat users when native file upload failed instead of leaving only a filename."""
+ public_url = self._register_public_file_download_url(
+ context,
+ file_path=file_path,
+ file_name=file_name,
+ )
+ key = "error.fileAttachmentUploadFailedWithLink" if public_url else "error.fileAttachmentUploadFailedNoLink"
+ message = self._t(key, filename=file_name, url=public_url or "")
+ try:
+ await im_client.send_message(context, message, parse_mode="plain")
+ except Exception:
+ logger.warning("Failed to send file upload failure notice for %s", file_path, exc_info=True)
diff --git a/core/workbench_media.py b/core/workbench_media.py
index ed699c012..2aa339b8f 100644
--- a/core/workbench_media.py
+++ b/core/workbench_media.py
@@ -29,6 +29,27 @@ from storage import media_service
logger = logging.getLogger(__name__)
+def register_agent_reply_media(
+ conn: Connection,
+ *,
+ scope_id: str,
+ session_id: str | None,
+ kind: str,
+ local_path: str,
+ file_name: str,
+) -> str:
+ """Register a local agent-reply file under the shared media proxy."""
+ return media_service.register(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ kind=kind,
+ source="agent_reply",
+ local_path=local_path,
+ file_name=file_name,
+ )
+
+
def rewrite_agent_media(conn: Connection, *, scope_id: str, session_id: str, text: str) -> str:
"""Return *text* with ``file://`` links rewritten to media-proxy URLs.
@@ -62,12 +83,11 @@ def rewrite_agent_media(conn: Connection, *, scope_id: str, session_id: str, tex
logger.warning("workbench_media: could not resolve file link: %s", url)
return match.group(0)
try:
- token = media_service.register(
+ token = register_agent_reply_media(
conn,
scope_id=scope_id,
session_id=session_id,
kind="image" if bang == "!" else "file",
- source="agent_reply",
local_path=safe_path,
file_name=label or os.path.basename(safe_path),
)
diff --git a/modules/im/wechat_api.py b/modules/im/wechat_api.py
index ae5b99a25..a4247da57 100644
--- a/modules/im/wechat_api.py
+++ b/modules/im/wechat_api.py
@@ -267,7 +267,8 @@ async def get_upload_url(
and optionally thumbnail fields.
Returns:
- Parsed JSON dict with ``upload_param`` (and possibly ``thumb_upload_param``).
+ Parsed JSON dict with either ``upload_full_url`` or ``upload_param``
+ (and possibly thumbnail upload fields).
"""
return await _api_fetch(
base_url,
diff --git a/modules/im/wechat_cdn.py b/modules/im/wechat_cdn.py
index 7a37a22c3..0fd109765 100644
--- a/modules/im/wechat_cdn.py
+++ b/modules/im/wechat_cdn.py
@@ -15,7 +15,7 @@ import logging
import os
from pathlib import Path
from typing import Any, Dict, Optional
-from urllib.parse import quote
+from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlunparse
import aiohttp
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
@@ -36,6 +36,16 @@ _AES_BLOCK_BITS = 128
_AES_BLOCK_BYTES = 16
# Maximum retry attempts for CDN upload
_UPLOAD_MAX_RETRIES = 3
+_CDN_ERROR_BODY_LIMIT = 500
+
+
+class _CdnUploadStatusError(RuntimeError):
+ """CDN upload response error with explicit retry semantics."""
+
+ def __init__(self, status: int, message: str, *, retryable: bool):
+ super().__init__(message)
+ self.status = status
+ self.retryable = retryable
# ---------------------------------------------------------------------------
@@ -144,15 +154,75 @@ def _build_cdn_download_url(cdn_base_url: str, encrypted_query_param: str) -> st
return f"{cdn_base_url}/download?encrypted_query_param={quote(encrypted_query_param)}"
+def _extract_upload_full_url(upload_resp: Dict[str, Any]) -> Optional[str]:
+ """Return a direct CDN upload URL from known iLink response variants."""
+ for key in ("upload_full_url", "uploadFullUrl", "upload_url", "uploadUrl"):
+ value = upload_resp.get(key)
+ if isinstance(value, str) and value.strip():
+ return html.unescape(value.strip())
+ return None
+
+
+def _upload_url_host(upload_url: str) -> str:
+ """Return the upload URL host for diagnostics."""
+ try:
+ return urlparse(upload_url).netloc or "(unknown)"
+ except Exception:
+ return "(invalid)"
+
+
+def _upload_url_for_log(upload_url: str) -> str:
+ """Return a diagnostic upload URL without credential-bearing query values."""
+ try:
+ parsed = urlparse(upload_url)
+ redacted_query = urlencode([(key, "<redacted>") for key, _value in parse_qsl(parsed.query, keep_blank_values=True)])
+ return urlunparse((parsed.scheme, parsed.netloc, parsed.path, parsed.params, redacted_query, ""))
+ except Exception:
+ return "(invalid)"
+
+
+def _truncate_cdn_error_body(body: str) -> str:
+ body = (body or "").strip()
+ if len(body) <= _CDN_ERROR_BODY_LIMIT:
+ return body
+ return f"{body[:_CDN_ERROR_BODY_LIMIT]}...(truncated)"
+
+
+def _cdn_error_message(resp: aiohttp.ClientResponse, body: str) -> str:
+ header_msg = (resp.headers.get("x-error-message") or "").strip()
+ body_msg = _truncate_cdn_error_body(body)
+ if header_msg and body_msg:
+ return f"{header_msg}; body={body_msg}"
+ if header_msg:
+ return header_msg
+ if body_msg:
+ return body_msg
+ return f"status {resp.status}"
+
+
+async def _read_cdn_error_body(resp: aiohttp.ClientResponse) -> str:
+ try:
+ return await resp.text()
+ except Exception as exc:
+ return f"(failed to read response body: {type(exc).__name__})"
+
+
def _resolve_cdn_upload_url(cdn_base_url: str, upload_resp: Dict[str, Any], filekey: str, label: str) -> str:
"""Resolve a CDN upload URL from legacy or full-url getUploadUrl responses."""
- upload_full_url = upload_resp.get("upload_full_url")
+ upload_full_url = _extract_upload_full_url(upload_resp)
if upload_full_url:
- return html.unescape(str(upload_full_url))
+ logger.debug("%s: using upload_full_url host=%s", label, _upload_url_host(upload_full_url))
+ return upload_full_url
upload_param = upload_resp.get("upload_param")
if upload_param:
- return _build_cdn_upload_url(cdn_base_url, str(upload_param), filekey)
+ fallback_url = _build_cdn_upload_url(cdn_base_url, str(upload_param), filekey)
+ logger.info(
+ "%s: getUploadUrl returned no upload_full_url; falling back to configured CDN host=%s",
+ label,
+ _upload_url_host(fallback_url),
+ )
+ return fallback_url
logger.error(
"%s: getUploadUrl returned neither upload_param nor upload_full_url, resp=%s",
@@ -190,7 +260,15 @@ async def upload_buffer_to_cdn(
the expected header.
"""
ciphertext = aes_ecb_encrypt(data, aes_key)
- logger.debug("CDN upload: POST url=%s ciphertext_size=%d", upload_url[:80], len(ciphertext))
+ upload_host = _upload_url_host(upload_url)
+ upload_log_url = _upload_url_for_log(upload_url)
+ logger.debug(
+ "CDN upload: POST host=%s url=%s raw_size=%d ciphertext_size=%d",
+ upload_host,
+ upload_log_url,
+ len(data),
+ len(ciphertext),
+ )
download_param: Optional[str] = None
last_error: Optional[Exception] = None
@@ -205,23 +283,41 @@ async def upload_buffer_to_cdn(
headers={"Content-Type": "application/octet-stream"},
) as resp:
if 400 <= resp.status < 500:
- err_msg = resp.headers.get("x-error-message") or await resp.text()
+ body = await _read_cdn_error_body(resp)
+ err_msg = _cdn_error_message(resp, body)
logger.error(
- "CDN client error attempt=%d status=%d err=%s",
+ "CDN client error attempt=%d status=%d host=%s url=%s raw_size=%d ciphertext_size=%d err=%s",
attempt,
resp.status,
+ upload_host,
+ upload_log_url,
+ len(data),
+ len(ciphertext),
err_msg,
)
- raise RuntimeError(f"CDN upload client error {resp.status}: {err_msg}")
+ raise _CdnUploadStatusError(
+ resp.status,
+ f"CDN upload client error {resp.status}: {err_msg}",
+ retryable=False,
+ )
if resp.status != 200:
- err_msg = resp.headers.get("x-error-message") or f"status {resp.status}"
- logger.error(
- "CDN server error attempt=%d status=%d err=%s",
+ body = await _read_cdn_error_body(resp)
+ err_msg = _cdn_error_message(resp, body)
+ logger.warning(
+ "CDN server error attempt=%d status=%d host=%s url=%s raw_size=%d ciphertext_size=%d err=%s",
attempt,
resp.status,
+ upload_host,
+ upload_log_url,
+ len(data),
+ len(ciphertext),
err_msg,
)
- raise RuntimeError(f"CDN upload server error: {err_msg}")
+ raise _CdnUploadStatusError(
+ resp.status,
+ f"CDN upload server error {resp.status}: {err_msg}",
+ retryable=True,
+ )
download_param = resp.headers.get("x-encrypted-param")
if not download_param:
@@ -233,34 +329,69 @@ async def upload_buffer_to_cdn(
logger.debug("CDN upload success attempt=%d", attempt)
return download_param
- except RuntimeError as e:
+ except _CdnUploadStatusError as e:
last_error = e
- if "client error" in str(e):
+ if not e.retryable:
raise
if attempt < _UPLOAD_MAX_RETRIES:
+ logger.warning(
+ "CDN upload attempt %d failed, retrying host=%s raw_size=%d ciphertext_size=%d err=%s",
+ attempt,
+ upload_host,
+ len(data),
+ len(ciphertext),
+ e,
+ )
+ else:
logger.error(
- "CDN upload attempt %d failed, retrying: %s",
+ "CDN upload all %d attempts failed host=%s url=%s raw_size=%d ciphertext_size=%d err=%s",
+ _UPLOAD_MAX_RETRIES,
+ upload_host,
+ upload_log_url,
+ len(data),
+ len(ciphertext),
+ e,
+ )
+ except RuntimeError as e:
+ last_error = e
+ if attempt < _UPLOAD_MAX_RETRIES:
+ logger.warning(
+ "CDN upload attempt %d failed, retrying host=%s raw_size=%d ciphertext_size=%d err=%s",
attempt,
+ upload_host,
+ len(data),
+ len(ciphertext),
e,
)
else:
logger.error(
- "CDN upload all %d attempts failed: %s",
+ "CDN upload all %d attempts failed host=%s url=%s raw_size=%d ciphertext_size=%d err=%s",
_UPLOAD_MAX_RETRIES,
+ upload_host,
+ upload_log_url,
+ len(data),
+ len(ciphertext),
e,
)
except aiohttp.ClientError as e:
last_error = e
if attempt < _UPLOAD_MAX_RETRIES:
- logger.error(
- "CDN upload attempt %d network error, retrying: %s",
+ logger.warning(
+ "CDN upload attempt %d network error, retrying host=%s raw_size=%d ciphertext_size=%d err=%s",
attempt,
+ upload_host,
+ len(data),
+ len(ciphertext),
e,
)
else:
logger.error(
- "CDN upload all %d attempts failed: %s",
+ "CDN upload all %d attempts failed host=%s url=%s raw_size=%d ciphertext_size=%d err=%s",
_UPLOAD_MAX_RETRIES,
+ upload_host,
+ upload_log_url,
+ len(data),
+ len(ciphertext),
e,
)
@@ -390,11 +521,23 @@ async def _upload_media_to_cdn(
upload_url = _resolve_cdn_upload_url(cdn_base_url, upload_resp, filekey, label)
- download_param = await upload_buffer_to_cdn(
- upload_url=upload_url,
- data=plaintext,
- aes_key=aes_key,
- )
+ try:
+ download_param = await upload_buffer_to_cdn(
+ upload_url=upload_url,
+ data=plaintext,
+ aes_key=aes_key,
+ )
+ except Exception:
+ logger.warning(
+ "%s: CDN upload failed file=%s raw_size=%d ciphertext_size=%d upload_host=%s",
+ label,
+ file_path,
+ rawsize,
+ filesize,
+ _upload_url_host(upload_url),
+ exc_info=True,
+ )
+ raise
# Encode the AES key as hex then base64 for the CDNMedia.aes_key field
aes_key_b64 = base64.b64encode(aes_key.hex().encode("ascii")).decode("ascii")
diff --git a/tests/test_message_dispatcher_file_uploads.py b/tests/test_message_dispatcher_file_uploads.py
index 74682f0f2..07c593d14 100644
--- a/tests/test_message_dispatcher_file_uploads.py
+++ b/tests/test_message_dispatcher_file_uploads.py
@@ -1,6 +1,7 @@
import sys
import tempfile
import unittest
+from types import SimpleNamespace
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -8,11 +9,23 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.reply_enhancer import FileLink
from modules.im import MessageContext
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import media_objects
class _StubController:
- def __init__(self):
- self.config = type("Config", (), {"platform": "slack"})()
+ def __init__(self, *, platform="slack", language="en", public_url=""):
+ self.config = SimpleNamespace(
+ platform=platform,
+ language=language,
+ remote_access=SimpleNamespace(
+ vibe_cloud=SimpleNamespace(
+ enabled=bool(public_url),
+ public_url=public_url,
+ )
+ ),
+ )
class _StubIMClient:
@@ -31,6 +44,26 @@ class _StubIMClient:
self.video_uploads.append((context.channel_id, file_path, title))
+class _FailingWechatIMClient(_StubIMClient):
+ def __init__(self):
+ super().__init__()
+ self.sent_messages = []
+
+ async def upload_file_from_path(self, context, file_path, title=None):
+ self.file_uploads.append((context.channel_id, file_path, title))
+ return ""
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ self.sent_messages.append((context.channel_id, text, parse_mode))
+ return "notice-1"
+
+
+class _SuccessfulWechatIMClient(_FailingWechatIMClient):
+ async def upload_file_from_path(self, context, file_path, title=None):
+ self.file_uploads.append((context.channel_id, file_path, title))
+ return "wc-file-1"
+
+
class MessageDispatcherFileUploadTests(unittest.IsolatedAsyncioTestCase):
async def test_upload_file_link_allows_path_outside_cwd(self):
dispatcher = ConsolidatedMessageDispatcher(_StubController())
@@ -91,6 +124,93 @@ class MessageDispatcherFileUploadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(im_client.image_uploads, [])
self.assertEqual(im_client.video_uploads, [("C1", resolved_path, "preview.mp4")])
+ async def test_wechat_failed_file_upload_sends_public_download_link(self):
+ ensure_sqlite_state()
+ dispatcher = ConsolidatedMessageDispatcher(
+ _StubController(platform="wechat", language="en", public_url="https://alex.avibe.bot")
+ )
+ im_client = _FailingWechatIMClient()
+ context = MessageContext(
+ user_id="wx-user",
+ channel_id="wx-user",
+ platform="wechat",
+ platform_specific={"agent_session_id": "ses_1"},
+ )
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "report.xlsx"
+ file_path.write_bytes(b"xlsx")
+ resolved_path = str(file_path.resolve())
+
+ await dispatcher._upload_file_links(
+ im_client,
+ context,
+ [FileLink(label="report", path=str(file_path))],
+ )
+
+ self.assertEqual(im_client.file_uploads, [("wx-user", resolved_path, "report.xlsx")])
+ self.assertEqual(len(im_client.sent_messages), 1)
+ _, notice, parse_mode = im_client.sent_messages[0]
+ self.assertEqual(parse_mode, "plain")
+ self.assertIn("could not deliver report.xlsx as a WeChat file", notice)
+ self.assertIn("after signing in if prompted", notice)
+ self.assertIn("https://alex.avibe.bot/api/media/", notice)
+ self.assertIn("?download=1", notice)
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ rows = conn.execute(media_objects.select()).mappings().all()
+ self.assertEqual(len(rows), 1)
+ self.assertEqual(rows[0]["local_path"], resolved_path)
+ self.assertEqual(rows[0]["file_name"], "report.xlsx")
+
+ async def test_wechat_successful_file_upload_does_not_send_failure_notice(self):
+ ensure_sqlite_state()
+ dispatcher = ConsolidatedMessageDispatcher(
+ _StubController(platform="wechat", language="en", public_url="https://alex.avibe.bot")
+ )
+ im_client = _SuccessfulWechatIMClient()
+ context = MessageContext(user_id="wx-user", channel_id="wx-user", platform="wechat")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "report.xlsx"
+ file_path.write_bytes(b"xlsx")
+ resolved_path = str(file_path.resolve())
+
+ await dispatcher._upload_file_links(
+ im_client,
+ context,
+ [FileLink(label="report", path=str(file_path))],
+ )
+
+ self.assertEqual(im_client.file_uploads, [("wx-user", resolved_path, "report.xlsx")])
+ self.assertEqual(im_client.sent_messages, [])
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ rows = conn.execute(media_objects.select()).mappings().all()
+ self.assertEqual(rows, [])
+
+ async def test_wechat_failed_file_upload_without_public_url_sends_clear_notice(self):
+ dispatcher = ConsolidatedMessageDispatcher(_StubController(platform="wechat", language="en"))
+ im_client = _FailingWechatIMClient()
+ context = MessageContext(user_id="wx-user", channel_id="wx-user", platform="wechat")
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ file_path = Path(tmpdir) / "report.xlsx"
+ file_path.write_bytes(b"xlsx")
+
+ await dispatcher._upload_file_links(
+ im_client,
+ context,
+ [FileLink(label="report", path=str(file_path))],
+ )
+
+ self.assertEqual(len(im_client.sent_messages), 1)
+ notice = im_client.sent_messages[0][1]
+ self.assertIn("could not deliver report.xlsx as a WeChat file", notice)
+ self.assertNotIn("/api/media/", notice)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_wechat_cdn.py b/tests/test_wechat_cdn.py
index d35ee56db..a6cb13a31 100644
--- a/tests/test_wechat_cdn.py
+++ b/tests/test_wechat_cdn.py
@@ -40,6 +40,24 @@ class WeChatCdnTests(unittest.IsolatedAsyncioTestCase):
"https://novac2c.cdn.weixin.qq.com/c2c/upload?encrypted_query_param=abc&filekey=file-key&taskid=task-1",
)
+ def test_resolve_cdn_upload_url_accepts_camel_case_full_url(self):
+ url = wechat_cdn._resolve_cdn_upload_url(
+ "https://novac2c.cdn.weixin.qq.com/c2c",
+ {
+ "uploadFullUrl": (
+ "https://dynamic-cdn.weixin.qq.com/c2c/upload?"
+ "encrypted_query_param=abc&amp;filekey=file-key"
+ )
+ },
+ "ignored-file-key",
+ "upload_file_to_cdn",
+ )
+
+ self.assertEqual(
+ url,
+ "https://dynamic-cdn.weixin.qq.com/c2c/upload?encrypted_query_param=abc&filekey=file-key",
+ )
+
async def test_upload_image_to_cdn_uses_upload_full_url_response(self):
with patch(
"modules.im.wechat_cdn.get_upload_url",
@@ -72,6 +90,117 @@ class WeChatCdnTests(unittest.IsolatedAsyncioTestCase):
"https://novac2c.cdn.weixin.qq.com/c2c/upload?encrypted_query_param=abc&filekey=file-key&taskid=task-1",
)
+ async def test_upload_file_to_cdn_logs_legacy_fallback_host(self):
+ with patch(
+ "modules.im.wechat_cdn.get_upload_url",
+ new=AsyncMock(return_value={"upload_param": "legacy-param"}),
+ ) as mock_get:
+ with patch(
+ "modules.im.wechat_cdn.upload_buffer_to_cdn", new=AsyncMock(return_value="download-param")
+ ) as mock_upload:
+ with patch("os.urandom", side_effect=[bytes.fromhex("11" * 16), bytes.fromhex("22" * 16)]):
+ with patch.object(Path, "read_bytes", return_value=b"doc"):
+ with self.assertLogs("modules.im.wechat_cdn", level="INFO") as captured:
+ result = await wechat_cdn.upload_file_to_cdn(
+ base_url="https://ilinkai.weixin.qq.com",
+ token="token",
+ cdn_base_url="https://novac2c.cdn.weixin.qq.com/c2c",
+ to_user_id="user-1",
+ file_path="/tmp/report.xlsx",
+ )
+
+ self.assertEqual(result["encrypt_query_param"], "download-param")
+ params = mock_get.await_args.kwargs["params"]
+ self.assertEqual(params["rawsize"], 3)
+ self.assertEqual(params["filesize"], 16)
+ self.assertEqual(
+ mock_upload.await_args.kwargs["upload_url"],
+ "https://novac2c.cdn.weixin.qq.com/c2c/upload?encrypted_query_param=legacy-param&filekey=11111111111111111111111111111111",
+ )
+ self.assertIn("falling back to configured CDN host=novac2c.cdn.weixin.qq.com", "\n".join(captured.output))
+
+ async def test_upload_buffer_to_cdn_logs_5xx_body_and_host(self):
+ class _Response:
+ status = 500
+ headers = {}
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ async def text(self):
+ return "gateway rejected large body"
+
+ class _Session:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ def post(self, url, data=None, headers=None):
+ return _Response()
+
+ with patch("modules.im.wechat_cdn.aiohttp.ClientSession", side_effect=lambda timeout: _Session()):
+ with self.assertLogs("modules.im.wechat_cdn", level="WARNING") as captured:
+ with self.assertRaises(RuntimeError):
+ await wechat_cdn.upload_buffer_to_cdn(
+ upload_url="https://dynamic-cdn.weixin.qq.com/c2c/upload?x=1",
+ data=b"xlsx-bytes",
+ aes_key=bytes.fromhex("22" * 16),
+ )
+
+ logs = "\n".join(captured.output)
+ self.assertIn("gateway rejected large body", logs)
+ self.assertIn("host=dynamic-cdn.weixin.qq.com", logs)
+ self.assertIn("raw_size=10", logs)
+ self.assertIn("x=%3Credacted%3E", logs)
+ self.assertNotIn("x=1", logs)
+
+ async def test_upload_buffer_to_cdn_retries_5xx_body_containing_client_error(self):
+ class _Response:
+ status = 500
+ headers = {}
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ async def text(self):
+ return "upstream client error while reading large body"
+
+ class _Session:
+ def __init__(self):
+ self.calls = 0
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ def post(self, url, data=None, headers=None):
+ self.calls += 1
+ return _Response()
+
+ session = _Session()
+ with patch("modules.im.wechat_cdn.aiohttp.ClientSession", side_effect=lambda timeout: session):
+ with self.assertRaises(RuntimeError):
+ await wechat_cdn.upload_buffer_to_cdn(
+ upload_url=(
+ "https://dynamic-cdn.weixin.qq.com/c2c/upload?"
+ "encrypted_query_param=secret&filekey=file-key"
+ ),
+ data=b"xlsx-bytes",
+ aes_key=bytes.fromhex("22" * 16),
+ )
+
+ self.assertEqual(session.calls, 3)
+
if __name__ == "__main__":
unittest.main()
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 3215a5788..816582154 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -49,6 +49,8 @@
"sessionGeneric": "An error occurred: {error}",
"resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?",
"resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it.",
+ "fileAttachmentUploadFailedWithLink": "⚠️ I could not deliver {filename} as a WeChat file. You can download it from Avibe after signing in if prompted:\n{url}",
+ "fileAttachmentUploadFailedNoLink": "⚠️ I could not deliver {filename} as a WeChat file. Please ask me to resend it or use another channel.",
"opencodeQuestionToolDisabled": "OpenCode asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction.",
"opencodeQuestionToolDisabledRestored": "Restored OpenCode session asked an interactive question, but Avibe disables the OpenCode question tool. Please send a new follow-up message with your answer or direction."
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 5d54d56df..5d541597b 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -49,6 +49,8 @@
"sessionGeneric": "发生错误:{error}",
"resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?",
"resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。",
+ "fileAttachmentUploadFailedWithLink": "⚠️ {filename} 没能作为微信文件直接发送。你可以通过 Avibe 下载;如提示登录,请先登录:\n{url}",
+ "fileAttachmentUploadFailedNoLink": "⚠️ {filename} 没能作为微信文件直接发送。请让我重新发送,或换一个渠道接收这个文件。",
"opencodeQuestionToolDisabled": "OpenCode 发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。",
"opencodeQuestionToolDisabledRestored": "恢复中的 OpenCode 会话发起了交互式提问,但 Avibe 已禁用 OpenCode 的 question 工具。请直接发送一条新消息,告诉我你的答案或下一步方向。"
},