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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(memory): materialize IM attachments safely (#1461)
rkrkrkk61a639e427d1
diff --git a/core/handlers/inbound_attachments.py b/core/handlers/inbound_attachments.pynew file mode 100644index 000000000..132461206--- /dev/null+++ b/core/handlers/inbound_attachments.py@@ -0,0 +1,675 @@+"""Shared, leased materialization for native inbound attachments."""++from __future__ import annotations++import asyncio+import hashlib+import inspect+import os+import re+import secrets+import stat+import threading+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from config import paths+from core.audio_asr import AUDIO_SIGNATURE_SAMPLE_BYTES, detect_audio_mime_from_sample+from modules.im.base import FileAttachment, FileDownloadResult, MessageContext+from vibe.i18n import t as i18n_t+++_MAX_FILENAME_BYTES = 200+_SAFE_FILENAME = re.compile(r"[^\w.\-]", re.UNICODE)+_LEASE_ID = re.compile(r"[0-9a-f]{32}")+++@dataclass(frozen=True, slots=True)+class _LeasedAttachmentRecord:+ name: str+ mimetype: str+ declared_size: int | None+ size: int+ path: Path+ device: int+ inode: int+ sha256: str+++class _LeaseState:+ def __init__(+ self,+ root: Path,+ directory: Path,+ root_fd: int,+ directory_fd: int,+ ) -> None:+ self.root = root+ self.directory = directory+ self.root_fd = root_fd+ self.directory_fd = directory_fd+ self.records: tuple[_LeasedAttachmentRecord, ...] = ()+ self.references = 1+ self.adopted = False+ self.lock = threading.Lock()+++class InboundAttachmentLease:+ """Opaque reference to one private set of materialized native files."""++ __slots__ = ("__state", "__released")++ def __init__(self, state: _LeaseState) -> None:+ self.__state = state+ self.__released = False++ def retain(self) -> "InboundAttachmentLease":+ """Return an independent reference to the same immutable file set."""++ state = self.__state+ with state.lock:+ if self.__released or state.references <= 0:+ raise RuntimeError("attachment lease is no longer active")+ state.references += 1+ return InboundAttachmentLease(state)++ def adopt(self) -> None:+ """Transfer final-file ownership to the ordinary Agent attachment path."""++ state = self.__state+ with state.lock:+ if self.__released or state.references <= 0:+ raise RuntimeError("attachment lease is no longer active")+ state.adopted = True++ def release(self) -> None:+ """Release this reference and remove unadopted files after the last user."""++ state = self.__state+ with state.lock:+ if self.__released:+ return+ self.__released = True+ state.references -= 1+ last_reference = state.references == 0+ remove = last_reference and (not state.adopted or not state.records)+ if remove:+ _remove_lease_directory(state)+ elif last_reference:+ os.close(state.directory_fd)+ os.close(state.root_fd)+++@dataclass(frozen=True, slots=True)+class MaterializedAttachmentBatch:+ """Agent-facing snapshots plus an opaque lease for independent consumers."""++ attachments: tuple[FileAttachment, ...]+ errors: tuple[str, ...]+ lease: InboundAttachmentLease+ display_errors: tuple[str, ...] = field(default=(), repr=False)+++@dataclass(frozen=True, slots=True)+class _MaterializationFailure:+ reason: str+ display_error: str+++class InboundAttachmentMaterializer:+ """Download native files once into an Avibe-owned private lease directory."""++ def __init__(+ self,+ *,+ effective_home: Path | str | None = None,+ attachments_root: Path | str | None = None,+ ) -> None:+ home = paths.get_vibe_remote_dir() if effective_home is None else effective_home+ self._home = Path(os.path.abspath(os.path.expanduser(os.fspath(home))))+ self._root = (+ self._home / "attachments" / "im"+ if attachments_root is None+ else Path(attachments_root) / "im"+ )++ async def materialize(+ self,+ context: MessageContext,+ im_client: Any,+ *,+ max_bytes: int | None = None,+ timeout_seconds: int = 30,+ max_concurrency: int = 1,+ language: str = "en",+ ) -> MaterializedAttachmentBatch:+ root_fd = _open_or_create_private_directory(self._root)+ lease_id = secrets.token_hex(16)+ lease_dir = self._root / lease_id+ lease_fd: int | None = None+ try:+ os.mkdir(lease_id, mode=0o700, dir_fd=root_fd)+ lease_fd = os.open(lease_id, _directory_open_flags(), dir_fd=root_fd)+ _make_private_directory(lease_fd, "attachment lease directory")+ except BaseException:+ if lease_fd is not None:+ os.close(lease_fd)+ os.close(root_fd)+ raise+ state = _LeaseState(self._root, lease_dir, root_fd, lease_fd)+ lease = InboundAttachmentLease(state)++ candidates = tuple(+ attachment+ for attachment in (context.files or ())+ if isinstance(attachment, FileAttachment)+ )+ semaphore = asyncio.Semaphore(max(1, min(2, int(max_concurrency))))++ async def acquire(index: int, attachment: FileAttachment):+ async with semaphore:+ return await self._materialize_one(+ context,+ im_client,+ lease_dir,+ lease_fd,+ index,+ attachment,+ max_bytes=max_bytes,+ timeout_seconds=timeout_seconds,+ language=language,+ )++ try:+ outcomes = await asyncio.gather(+ *(acquire(index, attachment) for index, attachment in enumerate(candidates))+ )+ _verify_lease_directory_entry(state)+ except BaseException:+ lease.release()+ raise++ attachments: list[FileAttachment] = []+ records: list[_LeasedAttachmentRecord] = []+ errors: list[str] = []+ display_errors: list[str] = []+ for outcome in outcomes:+ if isinstance(outcome, _MaterializationFailure):+ errors.append(outcome.reason)+ display_errors.append(outcome.display_error)+ continue+ attachment, record = outcome+ attachments.append(attachment)+ if record is not None:+ records.append(record)+ state.records = tuple(records)+ return MaterializedAttachmentBatch(+ tuple(attachments),+ tuple(errors),+ lease,+ tuple(display_errors),+ )++ async def _materialize_one(+ self,+ context: MessageContext,+ im_client: Any,+ lease_dir: Path,+ lease_fd: int,+ index: int,+ attachment: FileAttachment,+ *,+ max_bytes: int | None,+ timeout_seconds: int,+ language: str,+ ) -> tuple[FileAttachment, _LeasedAttachmentRecord | None] | _MaterializationFailure:+ if attachment.local_path and Path(attachment.local_path).is_file():+ size = attachment.size+ if size is None:+ try:+ size = Path(attachment.local_path).stat().st_size+ except OSError:+ size = None+ return (+ FileAttachment(+ name=attachment.name,+ mimetype=attachment.mimetype,+ url=attachment.url,+ content=attachment.content,+ local_path=attachment.local_path,+ size=size,+ ),+ None,+ )++ safe_name = _sanitize_filename(attachment.name)+ declared_size = _normalized_declared_size(attachment.size)+ if max_bytes is not None and declared_size is not None and declared_size > max_bytes:+ return _materialization_failure("file_too_large", attachment.name, language)+ final_name = f"{index:02d}-{safe_name}"+ partial_name = f"{final_name}.part"+ file_info = _download_info(context, attachment)+ published_names: set[str] = set()+ partial_fd: int | None = None+ materialized = False+ try:+ partial_fd = os.open(+ partial_name,+ _file_create_flags(),+ 0o600,+ dir_fd=lease_fd,+ )+ stream_download = getattr(im_client, "download_file_to_path", None)+ if callable(stream_download):+ result = await stream_download(+ file_info,+ _descriptor_path(partial_fd),+ **_supported_download_options(+ stream_download,+ max_bytes=max_bytes,+ timeout_seconds=timeout_seconds,+ target_fd=partial_fd,+ ),+ )+ if not isinstance(result, FileDownloadResult):+ result = FileDownloadResult(bool(result))+ if not result.success:+ reason = (+ "file_too_large"+ if result.failure_reason == "file_too_large"+ else "download_failed"+ )+ return _materialization_failure(reason, attachment.name, language)+ else:+ download = getattr(im_client, "download_file", None)+ if not callable(download):+ return _materialization_failure("download_failed", attachment.name, language)+ content = await download(file_info)+ if not content:+ return _materialization_failure("download_failed", attachment.name, language)+ os.ftruncate(partial_fd, 0)+ os.lseek(partial_fd, 0, os.SEEK_SET)+ _write_all(partial_fd, content)+ size = os.fstat(partial_fd).st_size+ if max_bytes is not None and size > max_bytes:+ return _materialization_failure("file_too_large", attachment.name, language)+ os.fchmod(partial_fd, 0o600)+ os.rename(+ partial_name,+ final_name,+ src_dir_fd=lease_fd,+ dst_dir_fd=lease_fd,+ )+ published_names.add(final_name)+ name, mimetype, final_name = _normalize_detected_media(+ attachment.name,+ attachment.mimetype,+ partial_fd,+ lease_fd,+ final_name,+ )+ published_names.add(final_name)+ os.fchmod(partial_fd, 0o600)+ published_info = os.fstat(partial_fd)+ published_sha256 = _sha256_fd(partial_fd)+ final_path = lease_dir / final_name+ snapshot = FileAttachment(+ name=name,+ mimetype=mimetype,+ local_path=str(final_path),+ size=size,+ )+ outcome = snapshot, _LeasedAttachmentRecord(+ name=name,+ mimetype=mimetype,+ declared_size=declared_size,+ size=size,+ path=final_path,+ device=published_info.st_dev,+ inode=published_info.st_ino,+ sha256=published_sha256,+ )+ materialized = True+ return outcome+ except asyncio.CancelledError:+ raise+ except Exception:+ return _materialization_failure("download_failed", attachment.name, language)+ finally:+ _unlink_at_quietly(lease_fd, partial_name)+ if not materialized:+ for published_name in published_names:+ _unlink_at_quietly(lease_fd, published_name)+ if partial_fd is not None:+ try:+ os.close(partial_fd)+ except OSError:+ pass+++def leased_attachment_records(+ lease: InboundAttachmentLease,+) -> tuple[Path, int, tuple[_LeasedAttachmentRecord, ...]]:+ """Snapshot an active lease and duplicate its anchored directory descriptor."""++ if type(lease) is not InboundAttachmentLease:+ raise ValueError("invalid attachment lease")+ state = lease._InboundAttachmentLease__state+ released = lease._InboundAttachmentLease__released+ with state.lock:+ if released or state.references <= 0 or _LEASE_ID.fullmatch(state.directory.name) is None:+ raise ValueError("attachment lease is no longer active")+ records = state.records+ try:+ directory_fd = os.dup(state.directory_fd)+ except OSError as error:+ raise ValueError("attachment lease is no longer active") from error+ return state.root, directory_fd, records+++def open_leased_attachment_record(+ directory_fd: int,+ record: _LeasedAttachmentRecord,+) -> tuple[int, os.stat_result]:+ """Open the exact materialized inode relative to its retained lease directory."""++ if type(record) is not _LeasedAttachmentRecord:+ raise ValueError("invalid leased attachment record")+ filename = record.path.name+ if not filename or Path(filename).name != filename:+ raise ValueError("invalid leased attachment record")+ try:+ descriptor = os.open(filename, _file_read_flags(), dir_fd=directory_fd)+ except OSError as error:+ raise ValueError("leased attachment is unavailable") from error+ try:+ info = os.fstat(descriptor)+ getuid = getattr(os, "getuid", None)+ if (+ not stat.S_ISREG(info.st_mode)+ or stat.S_IMODE(info.st_mode) != 0o600+ or (callable(getuid) and info.st_uid != getuid())+ or info.st_dev != record.device+ or info.st_ino != record.inode+ or info.st_size != record.size+ ):+ raise ValueError("leased attachment no longer matches its materialized inode")+ return descriptor, info+ except BaseException:+ os.close(descriptor)+ raise+++def _download_info(context: MessageContext, attachment: FileAttachment) -> dict[str, Any]:+ info: dict[str, Any] = {+ "url": attachment.url,+ "name": attachment.name,+ "size": attachment.size,+ "platform": context.platform,+ }+ if attachment.url:+ info["url_private_download"] = attachment.url+ for key, value in getattr(attachment, "__dict__", {}).items():+ if key not in {"name", "mimetype", "url", "content", "local_path", "size"}:+ info[key] = value+ return info+++def _supported_download_options(+ download: Any,+ *,+ max_bytes: int | None,+ timeout_seconds: int,+ target_fd: int,+) -> dict[str, Any]:+ """Pass optional bounds only to clients whose method contract accepts them."""++ try:+ parameters = inspect.signature(download).parameters+ except (TypeError, ValueError):+ return {}+ accepts_kwargs = any(+ parameter.kind is inspect.Parameter.VAR_KEYWORD+ for parameter in parameters.values()+ )+ options: dict[str, Any] = {}+ if accepts_kwargs or "max_bytes" in parameters:+ options["max_bytes"] = max_bytes+ if accepts_kwargs or "timeout_seconds" in parameters:+ options["timeout_seconds"] = timeout_seconds+ if accepts_kwargs or "target_fd" in parameters:+ options["target_fd"] = target_fd+ return options+++def _materialization_failure(+ reason: str,+ attachment_name: str,+ language: str,+) -> _MaterializationFailure:+ key = "tooLarge" if reason == "file_too_large" else "failed"+ return _MaterializationFailure(+ reason,+ i18n_t(+ f"error.attachmentDownload.{key}",+ language,+ name=attachment_name,+ ),+ )+++def _normalized_declared_size(value: object) -> int | None:+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ return None+ return value+++def _directory_open_flags() -> int:+ no_follow = getattr(os, "O_NOFOLLOW", None)+ if no_follow is None:+ raise RuntimeError("attachment leases require no-follow filesystem support")+ return (+ os.O_RDONLY+ | int(no_follow)+ | int(getattr(os, "O_DIRECTORY", 0))+ | int(getattr(os, "O_CLOEXEC", 0))+ )+++def _file_create_flags() -> int:+ no_follow = getattr(os, "O_NOFOLLOW", None)+ if no_follow is None:+ raise RuntimeError("attachment leases require no-follow filesystem support")+ return (+ os.O_RDWR+ | os.O_CREAT+ | os.O_EXCL+ | int(no_follow)+ | int(getattr(os, "O_CLOEXEC", 0))+ )+++def _file_read_flags() -> int:+ no_follow = getattr(os, "O_NOFOLLOW", None)+ if no_follow is None:+ raise RuntimeError("attachment leases require no-follow filesystem support")+ return (+ os.O_RDONLY+ | int(no_follow)+ | int(getattr(os, "O_NONBLOCK", 0))+ | int(getattr(os, "O_CLOEXEC", 0))+ )+++def _descriptor_path(descriptor: int) -> str:+ root = "/dev/fd" if Path("/dev/fd").is_dir() else "/proc/self/fd"+ return f"{root}/{descriptor}"+++def _write_all(descriptor: int, content: bytes) -> None:+ view = memoryview(content)+ while view:+ written = os.write(descriptor, view)+ if written <= 0:+ raise OSError("attachment write made no progress")+ view = view[written:]+++def _sha256_fd(descriptor: int) -> str:+ position = os.lseek(descriptor, 0, os.SEEK_CUR)+ digest = hashlib.sha256()+ try:+ os.lseek(descriptor, 0, os.SEEK_SET)+ while chunk := os.read(descriptor, 1024 * 1024):+ digest.update(chunk)+ finally:+ os.lseek(descriptor, position, os.SEEK_SET)+ return digest.hexdigest()+++def _unlink_at_quietly(parent_fd: int, name: str) -> None:+ try:+ os.unlink(name, dir_fd=parent_fd)+ except FileNotFoundError:+ pass+++def _verify_lease_directory_entry(state: _LeaseState) -> None:+ expected = os.fstat(state.directory_fd)+ observed = os.stat(+ state.directory.name,+ dir_fd=state.root_fd,+ follow_symlinks=False,+ )+ if (+ not stat.S_ISDIR(observed.st_mode)+ or observed.st_dev != expected.st_dev+ or observed.st_ino != expected.st_ino+ ):+ raise OSError("attachment lease directory changed during materialization")+++def _remove_lease_directory(state: _LeaseState) -> None:+ try:+ try:+ names = os.listdir(state.directory_fd)+ except OSError:+ names = []+ for name in names:+ try:+ os.unlink(name, dir_fd=state.directory_fd)+ except OSError:+ pass+ try:+ _verify_lease_directory_entry(state)+ os.rmdir(state.directory.name, dir_fd=state.root_fd)+ except OSError:+ pass+ finally:+ os.close(state.directory_fd)+ os.close(state.root_fd)+++def _open_or_create_private_directory(directory: Path) -> int:+ """Create a private root while refusing symlinks in every path component."""++ if not directory.is_absolute():+ raise RuntimeError("attachment lease root must be absolute")+ descriptor = os.open(directory.anchor, _directory_open_flags())+ try:+ for component in directory.parts[1:]:+ try:+ next_descriptor = os.open(+ component,+ _directory_open_flags(),+ dir_fd=descriptor,+ )+ except FileNotFoundError:+ try:+ os.mkdir(component, mode=0o700, dir_fd=descriptor)+ except FileExistsError:+ pass+ next_descriptor = os.open(+ component,+ _directory_open_flags(),+ dir_fd=descriptor,+ )+ os.close(descriptor)+ descriptor = next_descriptor+ _make_private_directory(descriptor, "attachment lease root")+ return descriptor+ except BaseException:+ os.close(descriptor)+ raise+++def _make_private_directory(descriptor: int, label: str) -> None:+ info = os.fstat(descriptor)+ getuid = getattr(os, "getuid", None)+ if not stat.S_ISDIR(info.st_mode) or (+ callable(getuid) and info.st_uid != getuid()+ ):+ raise RuntimeError(f"{label} has unsafe ownership or type")+ os.fchmod(descriptor, 0o700)+ if stat.S_IMODE(os.fstat(descriptor).st_mode) != 0o700:+ raise RuntimeError(f"{label} is not private")+++def _sanitize_filename(name: object) -> str:+ raw = Path(str(name or "attachment")).name or "attachment"+ safe = _SAFE_FILENAME.sub("_", raw).replace("..", "_")+ suffix = Path(safe).suffix+ suffix_bytes = suffix.encode("utf-8", errors="ignore")+ if not suffix or len(suffix_bytes) >= _MAX_FILENAME_BYTES:+ return _truncate_utf8(safe, _MAX_FILENAME_BYTES) or "attachment"+ stem = safe[: -len(suffix)]+ stem_budget = _MAX_FILENAME_BYTES - len(suffix_bytes)+ stem = _truncate_utf8(stem, stem_budget)+ return f"{stem or _truncate_utf8('attachment', stem_budget)}{suffix}"+++def _truncate_utf8(value: str, max_bytes: int) -> str:+ encoded = value.encode("utf-8", errors="ignore")[:max_bytes]+ return encoded.decode("utf-8", errors="ignore")+++def _normalize_detected_media(+ name: str,+ mimetype: str,+ file_fd: int,+ lease_fd: int,+ filename: str,+) -> tuple[str, str, str]:+ os.lseek(file_fd, 0, os.SEEK_SET)+ sample = os.read(file_fd, AUDIO_SIGNATURE_SAMPLE_BYTES)+ detected = _detect_image_mime(sample) or detect_audio_mime_from_sample(sample)+ if detected is None:+ return _sanitize_filename(name), mimetype, filename+ detected_mime, suffix = detected+ display = f"{Path(_sanitize_filename(name)).stem}{suffix}"+ corrected = str(Path(filename).with_suffix(suffix))+ if corrected != filename:+ os.rename(+ filename,+ corrected,+ src_dir_fd=lease_fd,+ dst_dir_fd=lease_fd,+ )+ return display, detected_mime, corrected+++def _detect_image_mime(data: bytes) -> tuple[str, str] | None:+ if data.startswith(b"\xff\xd8\xff"):+ return "image/jpeg", ".jpg"+ if data.startswith(b"\x89PNG\r\n\x1a\n"):+ return "image/png", ".png"+ if data.startswith((b"GIF87a", b"GIF89a")):+ return "image/gif", ".gif"+ if data.startswith((b"II*\x00", b"MM\x00*")):+ return "image/tiff", ".tiff"+ if data.startswith(b"BM"):+ return "image/bmp", ".bmp"+ if len(data) >= 12 and data.startswith(b"RIFF") and data[8:12] == b"WEBP":+ return "image/webp", ".webp"+ return Nonediff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 3357370b4..c8b547cde 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -198,6 +198,7 @@ class MessageHandler(BaseHandler):# async result is coming, so the ``finally`` releases any streaming SSE# waiter for this turn instead of leaving it open until the timeout.agent_dispatched = False+ attachment_lease = Nonetry:is_human = source == self.TURN_SOURCE_HUMANdurable_delivery_owned = bool(@@ -702,10 +703,13 @@ class MessageHandler(BaseHandler):if isinstance(attachment, FileAttachment)and attachment.local_path}- processed_files, attachment_errors = await self._process_file_attachments(+ attachment_batch = await self._materialize_file_attachments(context,working_path,)+ attachment_lease = attachment_batch.lease+ processed_files = list(attachment_batch.attachments) or None+ attachment_errors = list(attachment_batch.display_errors)if processed_files:downloaded_attachment_paths = [str(attachment.local_path)@@ -737,6 +741,7 @@ class MessageHandler(BaseHandler):vibe_agent=vibe_agent,delivery_intent=delivery_intent,downloaded_attachment_paths=downloaded_attachment_paths,+ attachment_lease=attachment_lease,admission_context={# The reaction target is not always the sender's own# message (a quick reply reacts on its bot echo), and it@@ -760,8 +765,14 @@ class MessageHandler(BaseHandler):},)if admitted:+ attachment_lease = Nonereturn None+ if attachment_lease is not None:+ attachment_lease.adopt()+ attachment_lease.release()+ attachment_lease = None+if is_human:# The concise status bubble (footer-only at turn start) is now# posted by AgentService.handle_message after the runtime gate is acquired,@@ -915,6 +926,8 @@ class MessageHandler(BaseHandler):await self._emit_agent_dispatch_failure(context, request, e)return str(e)finally:+ if attachment_lease is not None:+ attachment_lease.release()release_lifecycle_admission = getattr(turn_lifecycle_admission,"release",@@ -967,6 +980,7 @@ class MessageHandler(BaseHandler):delivery_intent: str,downloaded_attachment_paths: List[str],admission_context: dict[str, Any],+ attachment_lease: Any = None,) -> bool:"""Transfer one IM input to its durable owner before native work."""@@ -1084,11 +1098,17 @@ class MessageHandler(BaseHandler):"native Delivery appeared after writer reservation")except Exception:- self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)+ if attachment_lease is not None:+ attachment_lease.release()+ else:+ self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)raiseif duplicate_delivery_id is not None:- self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)+ if attachment_lease is not None:+ attachment_lease.release()+ else:+ self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)if duplicate_delivery_id:payload = dict(context.platform_specific or {})payload["delivery_id"] = duplicate_delivery_id@@ -1097,6 +1117,9 @@ class MessageHandler(BaseHandler):if request is None:raise RuntimeError("Delivery reservation did not produce a request")+ if attachment_lease is not None:+ attachment_lease.adopt()+ attachment_lease.release()result = await manager.deliver(request, context=context)payload = dict(context.platform_specific or {})payload["delivery_id"] = result.delivery_id@@ -1740,146 +1763,34 @@ class MessageHandler(BaseHandler):async def _process_file_attachments(self, context: MessageContext, working_path: str) -> Tuple[Optional[List[FileAttachment]], List[str]]:- """Download and process file attachments from the message.+ """Materialize native files once and preserve ordinary Agent ownership."""- All files (including images) are saved to ~/.vibe_remote/attachments/{channel_id}/- to avoid polluting the working directory (which is often a git repo).- The agent can then use Read tools to access them.+ batch = await self._materialize_file_attachments(context, working_path)+ batch.lease.adopt()+ batch.lease.release()+ processed = list(batch.attachments)+ return (processed if processed else None), list(batch.display_errors)- Args:- context: Message context with file attachments- working_path: Working directory path (not used for storage, kept for API compat)+ async def _materialize_file_attachments(+ self,+ context: MessageContext,+ working_path: str,+ ):+ """Return an untransferred lease so admission decides final ownership."""- Returns:- Tuple of processed attachments and download error messages- """- import os- import timefrom config.paths import get_attachments_dir- from modules.im.base import FileAttachment, FileDownloadResult+ from core.handlers.inbound_attachments import InboundAttachmentMaterializerif not context.files:- return None, []-- # Create channel-specific attachments directory- # Path: ~/.vibe_remote/attachments/{channel_id}/- attachments_dir = get_attachments_dir() / context.channel_id- attachments_dir.mkdir(parents=True, exist_ok=True)-- processed = []- errors: List[str] = []- for attachment in context.files:- if not isinstance(attachment, FileAttachment):- continue-- # Already on local disk (e.g. an avibe workbench upload, saved by the- # UI server before dispatch) — there is nothing to download, so pass- # it straight through to the agent turn. IM attachments arrive with a- # ``url`` and no ``local_path`` and fall through to the download path.- if attachment.local_path and os.path.isfile(attachment.local_path):- if attachment.size is None:- try:- attachment.size = os.path.getsize(attachment.local_path)- except OSError:- pass- processed.append(attachment)- continue-- try:- im_client = self._get_im_client(context)- # Download the file content. Some platforms receive a thin- # attachment event first and resolve the actual URL from- # platform metadata such as a Slack file id.- can_download = hasattr(im_client, "download_file_to_path") or hasattr(im_client, "download_file")- if can_download:- # Platform-agnostic download info dict- file_info = {- "url": attachment.url,- "name": attachment.name,- "size": attachment.size,- "platform": context.platform,- }- if attachment.url:- file_info["url_private_download"] = attachment.url # Slack compat- attachment_data = getattr(attachment, "__dict__", {})- for key, value in attachment_data.items():- if key in {"name", "mimetype", "url", "content", "local_path", "size"}:- continue- file_info[key] = value- timestamp = time.time_ns()- safe_name = self._sanitize_filename(attachment.name)- filename = f"{timestamp}_{safe_name}"- local_path = attachments_dir / filename- temp_path = attachments_dir / f"{filename}.part"- content = None- detected_sample = None- content_size = None-- if hasattr(im_client, "download_file_to_path"):- self._cleanup_partial_attachment(temp_path)- result = await im_client.download_file_to_path(file_info, str(temp_path))- if not isinstance(result, FileDownloadResult):- result = FileDownloadResult(bool(result), None if result else "Download failed")-- if result.success:- os.replace(temp_path, local_path)- content_size = local_path.stat().st_size- with open(local_path, "rb") as file_obj:- detected_sample = file_obj.read(AUDIO_SIGNATURE_SAMPLE_BYTES)- else:- self._cleanup_partial_attachment(temp_path)- error_text = result.error or "Download failed"- logger.warning("Failed to download file %s: %s", attachment.name, error_text)- errors.append(f"Attachment '{attachment.name}' could not be downloaded: {error_text}")- else:- content = await im_client.download_file(file_info)- if content:- with open(local_path, "wb") as f:- f.write(content)- content_size = len(content)- detected_sample = content[:AUDIO_SIGNATURE_SAMPLE_BYTES]- else:- logger.warning("Failed to download file %s: download returned no content", attachment.name)- errors.append(- f"Attachment '{attachment.name}' could not be downloaded: Download returned no content"- )-- if content is not None or content_size is not None:- # Detect actual MIME type from magic bytes for media- # (some platforms don't provide accurate MIME, e.g. Feishu and Slack)- detected = self._detect_image_mime(detected_sample or b"")- if not detected:- detected = detect_audio_mime_from_sample(detected_sample or b"")- if detected:- attachment.mimetype = detected[0]- # Fix filename extension to match actual type- ext = detected[1]- base = os.path.splitext(attachment.name)[0]- attachment.name = f"{base}{ext}"-- attachment.local_path = str(local_path)- attachment.size = content_size-- # Determine file type for logging- is_image = (attachment.mimetype or "").startswith("image/")- file_type = "image" if is_image else "file"-- logger.info(f"Saved {file_type} '{attachment.name}' ({content_size} bytes) to '{local_path}'")-- processed.append(attachment)- else:- logger.warning(f"Failed to download file: {attachment.name}")- else:- logger.warning(f"Cannot download file: {attachment.name} (no URL or download method)")- errors.append(f"Attachment '{attachment.name}' could not be downloaded: No URL or download method")-- except Exception as e:- self._cleanup_partial_attachment(locals().get("temp_path"))- logger.error(f"Error processing file attachment {attachment.name}: {e}")- errors.append(f"Attachment '{attachment.name}' could not be downloaded: {e}")- continue-- return (processed if processed else None), errors+ raise ValueError("attachment materialization requires input files")+ batch = await InboundAttachmentMaterializer(+ attachments_root=get_attachments_dir(),+ ).materialize(+ context,+ self._get_im_client(context),+ language=self._get_lang(),+ )+ return batch@staticmethoddef _cleanup_partial_attachment(path) -> None:@@ -1890,12 +1801,16 @@ class MessageHandler(BaseHandler):except Exception as err:logger.debug("Failed to remove partial attachment %s: %s", path, err)- @staticmethod- def _append_attachment_errors(message: str, errors: List[str]) -> str:+ def _append_attachment_errors(self, message: str, errors: List[str]) -> str:if not errors:return message- error_block = "\n".join(["[Attachment Download Errors]", *[f"- {error}" for error in errors]])+ error_block = "\n".join(+ [+ f"[{self._t('error.attachmentDownload.title')}]",+ *[f"- {error}" for error in errors],+ ]+ )if not message or not message.strip():return error_blockreturn f"{message}\n\n{error_block}"diff --git a/core/memory/attachments.py b/core/memory/attachments.pyindex 2a8a50aa7..072cd1b77 100644--- a/core/memory/attachments.py+++ b/core/memory/attachments.py@@ -13,6 +13,7 @@ import threadingfrom collections.abc import Collection, Sequencefrom dataclasses import dataclassfrom pathlib import Path, PurePosixPath+from typing import TYPE_CHECKINGfrom urllib.parse import unquote_to_bytes, urlsplitfrom config import paths@@ -28,6 +29,12 @@ from core.memory.types import (MemoryErrorCode,)+if TYPE_CHECKING:+ from core.handlers.inbound_attachments import (+ InboundAttachmentLease,+ _LeasedAttachmentRecord,+ )+MAX_PINNED_ATTACHMENTS = 8MAX_PINNED_ATTACHMENT_BYTES = 25 * 1024 * 1024@@ -238,7 +245,12 @@ class AttachmentPinStore:with self._lock:self._prepare_private_layout()- def pin(self, sources: Sequence[CaptureAttachment]) -> PinnedBundle:+ def pin(+ self,+ sources: Sequence[CaptureAttachment],+ *,+ source_lease: InboundAttachmentLease | None = None,+ ) -> PinnedBundle:"""Copy one bounded source set and publish it only after durable rename."""try:@@ -246,6 +258,7 @@ class AttachmentPinStore:except TypeError as error:raise AttachmentPinError("memory_invalid_input", "attachments are invalid") from errorself._validate_sources(source_items)+ source_root, allowed_records = self._pin_source(source_lease)with self._lock:self._verify_private_layout()staging_fd = _open_private_directory(self._staging, "attachment staging root")@@ -267,7 +280,12 @@ class AttachmentPinStore:total_bytes = 0try:for index, source in enumerate(source_items):- source_fd, source_info = self._open_source(source)+ source_fd, source_info, source_sha256 = self._open_source(+ source,+ source_root=source_root,+ allowed_records=allowed_records,+ source_lease=source_lease,+ )try:filename = _bundle_filename(index, source.ext)size_bytes, digest = _copy_source_file(@@ -276,6 +294,7 @@ class AttachmentPinStore:stage_fd,filename,total_before=total_bytes,+ expected_sha256=source_sha256,)finally:os.close(source_fd)@@ -535,10 +554,63 @@ class AttachmentPinStore:"attachment staging bundle could not be reserved",)- def _open_source(self, source: CaptureAttachment) -> tuple[int, os.stat_result]:+ def _pin_source(+ self,+ source_lease: InboundAttachmentLease | None,+ ) -> tuple[Path, dict[Path, _LeasedAttachmentRecord] | None]:+ if source_lease is None:+ return self._source_root, None+ from core.handlers.inbound_attachments import (+ InboundAttachmentLease,+ leased_attachment_records,+ )++ if type(source_lease) is not InboundAttachmentLease:+ raise AttachmentPinError(+ "memory_invalid_input",+ "attachment source lease is invalid",+ )+ directory_fd: int | None = None+ try:+ root, directory_fd, records = leased_attachment_records(source_lease)+ except (TypeError, ValueError) as error:+ raise AttachmentPinError(+ "memory_invalid_input",+ "attachment source lease is invalid",+ ) from error+ finally:+ if directory_fd is not None:+ os.close(directory_fd)+ expected_root = self._effective_home / "attachments" / "im"+ if _absolute_lexical(root) != expected_root:+ raise AttachmentPinError(+ "memory_invalid_input",+ "attachment source lease belongs to another Avibe home",+ )+ _require_path_below(root, self._effective_home, "leased attachment source root")+ if _paths_overlap(self._root, root):+ raise AttachmentPinError(+ "memory_store_unavailable",+ "attachment source and storage roots must be disjoint",+ )+ return root, {record.path: record for record in records}++ def _open_source(+ self,+ source: CaptureAttachment,+ *,+ source_root: Path,+ allowed_records: dict[Path, _LeasedAttachmentRecord] | None,+ source_lease: InboundAttachmentLease | None,+ ) -> tuple[int, os.stat_result, str | None]:source_path = _path_from_file_uri(source.uri)+ if allowed_records is not None and source_path not in allowed_records:+ raise AttachmentPinError(+ "memory_invalid_input",+ "attachment is not part of the source lease",+ )try:- relative = source_path.relative_to(self._source_root)+ relative = source_path.relative_to(source_root)except ValueError as error:raise AttachmentPinError("memory_invalid_input",@@ -549,7 +621,30 @@ class AttachmentPinStore:if source_path.suffix.lstrip(".").lower() != source.ext:raise AttachmentPinError("memory_invalid_input", "attachment extension is inconsistent")- current_fd = _open_source_directory_path(self._source_root)+ if source_lease is not None:+ from core.handlers.inbound_attachments import (+ leased_attachment_records,+ open_leased_attachment_record,+ )++ directory_fd: int | None = None+ try:+ current_root, directory_fd, current_records = leased_attachment_records(source_lease)+ current = {record.path: record for record in current_records}.get(source_path)+ if current_root != source_root or current != allowed_records[source_path]:+ raise ValueError("attachment source lease changed")+ descriptor, info = open_leased_attachment_record(directory_fd, current)+ return descriptor, info, current.sha256+ except (TypeError, ValueError) as error:+ raise AttachmentPinError(+ "memory_invalid_input",+ "attachment is not part of the source lease",+ ) from error+ finally:+ if directory_fd is not None:+ os.close(directory_fd)++ current_fd = _open_source_directory_path(source_root)try:for component in relative.parts[:-1]:next_fd = _open_source_directory_at(current_fd, component)@@ -559,7 +654,7 @@ class AttachmentPinStore:finally:os.close(current_fd)try:- return file_fd, os.fstat(file_fd)+ return file_fd, os.fstat(file_fd), Noneexcept OSError as error:os.close(file_fd)raise AttachmentPinError(@@ -893,6 +988,7 @@ def _copy_source_file(filename: str,*,total_before: int,+ expected_sha256: str | None,) -> tuple[int, str]:if source_info.st_size > MAX_PINNED_ATTACHMENT_BYTES:raise AttachmentPinError("memory_input_too_large", "attachment exceeds the file size limit")@@ -943,6 +1039,12 @@ def _copy_source_file("memory_invalid_input","attachment source changed while it was pinned",)+ observed_sha256 = digest.hexdigest()+ if expected_sha256 is not None and observed_sha256 != expected_sha256:+ raise AttachmentPinError(+ "memory_invalid_input",+ "attachment source content changed after materialization",+ )destination_info = os.fstat(destination_fd)_require_private_file(destination_info, "pinned attachment")if destination_info.st_size != copied:@@ -957,7 +1059,7 @@ def _copy_source_file(raise _storage_failure(error, "pinned attachment could not be written") from errorfinally:os.close(destination_fd)- return copied, digest.hexdigest()+ return copied, observed_sha256def _read_source_chunk(descriptor: int) -> bytes:diff --git a/core/memory/im_attachments.py b/core/memory/im_attachments.pynew file mode 100644index 000000000..a56eff2df--- /dev/null+++ b/core/memory/im_attachments.py@@ -0,0 +1,89 @@+"""Memory-only filtering for materialized IM attachment leases."""++from __future__ import annotations++import os+from dataclasses import dataclass+from typing import Literal++from core.handlers.inbound_attachments import (+ InboundAttachmentLease,+ leased_attachment_records,+ open_leased_attachment_record,+)+from core.memory.attachments import (+ MAX_PINNED_ATTACHMENTS,+ MAX_PINNED_ATTACHMENT_BYTES,+ MAX_PINNED_BUNDLE_BYTES,+)+from core.memory.modality import classify_pinned_attachment+from core.memory.types import CaptureAttachment+++AttachmentSkipReason = Literal[+ "count_limit",+ "file_too_large",+ "bundle_too_large",+ "unsupported_type",+]+++@dataclass(frozen=True, slots=True)+class MemoryAttachmentSelection:+ attachments: tuple[CaptureAttachment, ...]+ skipped: tuple[AttachmentSkipReason, ...]+++def select_memory_attachments(+ lease: InboundAttachmentLease,+) -> MemoryAttachmentSelection:+ """Keep valid siblings from one active shared-materializer lease."""++ _root, directory_fd, records = leased_attachment_records(lease)+ selected: list[CaptureAttachment] = []+ skipped: list[AttachmentSkipReason] = []+ total = 0+ try:+ for record in records:+ if (+ record.declared_size is not None+ and record.declared_size > MAX_PINNED_ATTACHMENT_BYTES+ ) or record.size > MAX_PINNED_ATTACHMENT_BYTES:+ skipped.append("file_too_large")+ continue+ file_fd: int | None = None+ try:+ file_fd, _source_info = open_leased_attachment_record(directory_fd, record)+ classification = classify_pinned_attachment(+ record.name,+ record.mimetype,+ record.path,+ file_fd=file_fd,+ )+ except (OSError, ValueError):+ classification = None+ finally:+ if file_fd is not None:+ os.close(file_fd)+ if classification is None:+ skipped.append("unsupported_type")+ continue+ if len(selected) >= MAX_PINNED_ATTACHMENTS:+ skipped.append("count_limit")+ continue+ if total + record.size > MAX_PINNED_BUNDLE_BYTES:+ skipped.append("bundle_too_large")+ continue+ kind, extension = classification+ selected.append(+ CaptureAttachment(+ kind=kind,+ name=record.name,+ uri=record.path.as_uri(),+ ext=extension,+ )+ )+ total += record.size+ finally:+ os.close(directory_fd)+ return MemoryAttachmentSelection(tuple(selected), tuple(skipped))diff --git a/core/memory/modality.py b/core/memory/modality.pyindex 7dd0e6005..d87e82231 100644--- a/core/memory/modality.py+++ b/core/memory/modality.py@@ -19,6 +19,12 @@ runtime child process, which runs with a minimal environment.from __future__ import annotations+import codecs+import os+from pathlib import Path++from core.memory.types import MemoryContentKind+SUPPORTED_ATTACHMENT_EXTENSIONS: frozenset[str] = frozenset({@@ -76,6 +82,144 @@ PINNED_UPSTREAM_EXCLUDED_EXTENSIONS: frozenset[str] = frozenset(})+_IMAGE_EXTENSIONS = frozenset({"png", "jpg", "jpeg", "webp", "tiff", "tif", "bmp"})+_AUDIO_EXTENSIONS = frozenset({"mp3", "wav", "m4a", "amr", "aiff", "aac", "ogg", "flac"})+_TEXT_EXTENSIONS = frozenset({"txt", "md", "vtt", "csv", "tsv"})+++def classify_pinned_attachment(+ name: str,+ mimetype: object,+ path: Path,+ *,+ file_fd: int | None = None,+) -> tuple[MemoryContentKind, str] | None:+ """Classify one acquired file only when extension, MIME, and bytes agree."""++ extension = path.suffix.lstrip(".").lower()+ if extension not in SUPPORTED_ATTACHMENT_EXTENSIONS:+ return None+ if Path(name).suffix.lstrip(".").lower() != extension:+ return None+ normalized_mime = (+ mimetype.lower().split(";", 1)[0].strip()+ if isinstance(mimetype, str) and mimetype.strip()+ else "application/octet-stream"+ )+ try:+ with _open_attachment_file(path, file_fd) as file_obj:+ file_obj.seek(0)+ sample = file_obj.read(4096)+ except OSError:+ return None++ if extension in _IMAGE_EXTENSIONS:+ detected = _image_extension(sample)+ if detected is None or not _extension_aliases_match(extension, detected):+ return None+ if normalized_mime not in {"application/octet-stream", "image/unknown"} and not normalized_mime.startswith("image/"):+ return None+ return "image", extension+ if extension in _AUDIO_EXTENSIONS:+ detected = _audio_extension(sample)+ if detected is None or not _extension_aliases_match(extension, detected):+ return None+ if normalized_mime != "application/octet-stream" and not normalized_mime.startswith("audio/"):+ return None+ return "audio", extension+ if extension == "pdf":+ if not sample.startswith(b"%PDF-") or normalized_mime not in {+ "application/pdf",+ "application/octet-stream",+ }:+ return None+ return "pdf", extension+ if not _valid_utf8_text_file(path, file_fd):+ return None+ if normalized_mime != "application/octet-stream" and not (+ normalized_mime.startswith("text/")+ or normalized_mime in {"message/rfc822", "application/csv"}+ ):+ return None+ if extension in {"html", "htm"}:+ return "html", extension+ if extension == "eml":+ return "email", extension+ if extension in _TEXT_EXTENSIONS:+ return "doc", extension+ return None+++def _open_attachment_file(path: Path, file_fd: int | None):+ if file_fd is None:+ return path.open("rb")+ return os.fdopen(os.dup(file_fd), "rb")+++def _valid_utf8_text_file(path: Path, file_fd: int | None) -> bool:+ decoder = codecs.getincrementaldecoder("utf-8")()+ try:+ with _open_attachment_file(path, file_fd) as file_obj:+ file_obj.seek(0)+ while chunk := file_obj.read(64 * 1024):+ if b"\x00" in chunk:+ return False+ decoder.decode(chunk, final=False)+ decoder.decode(b"", final=True)+ except (OSError, UnicodeDecodeError):+ return False+ return True+++def _extension_aliases_match(expected: str, detected: str) -> bool:+ aliases = ({"jpg", "jpeg"}, {"tif", "tiff"}, {"m4a", "mp4"})+ return expected == detected or any({expected, detected} <= group for group in aliases)+++def _image_extension(data: bytes) -> str | None:+ if data.startswith(b"\x89PNG\r\n\x1a\n"):+ return "png"+ if data.startswith(b"\xff\xd8\xff"):+ return "jpg"+ if data.startswith((b"II*\x00", b"MM\x00*")):+ return "tiff"+ if data.startswith(b"BM"):+ return "bmp"+ if len(data) >= 12 and data.startswith(b"RIFF") and data[8:12] == b"WEBP":+ return "webp"+ return None+++def _audio_extension(data: bytes) -> str | None:+ if data.startswith(b"ID3"):+ return "mp3"+ if len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xF6) == 0xF0:+ return "aac"+ if len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0 and (data[1] & 0x06) != 0:+ return "mp3"+ if len(data) >= 12 and data.startswith(b"RIFF") and data[8:12] == b"WAVE":+ return "wav"+ if len(data) >= 12 and data[4:8] == b"ftyp":+ box_size = int.from_bytes(data[:4], "big")+ if box_size < 16 or box_size > len(data) or box_size % 4:+ return None+ brands = (+ data[8:12],+ *(data[offset : offset + 4] for offset in range(16, box_size, 4)),+ )+ if any(brand in {b"M4A ", b"M4B "} for brand in brands):+ return "m4a"+ return None+ if data.startswith(b"#!AMR"):+ return "amr"+ if len(data) >= 12 and data.startswith(b"FORM") and data[8:12] in {b"AIFF", b"AIFC"}:+ return "aiff"+ if data.startswith(b"OggS"):+ return "ogg"+ if data.startswith(b"fLaC"):+ return "flac"+ return None+def pinned_modality_contract_matches(upstream_extensions: object) -> bool:"""Verify the pinned artifact's extension set without changing runtime policy."""diff --git a/core/memory/sidecar.py b/core/memory/sidecar.pyindex ce3f73609..b65f8ad2d 100644--- a/core/memory/sidecar.py+++ b/core/memory/sidecar.py@@ -461,12 +461,12 @@ def _validate_add(if set(item) != {"type", "text"} or not isinstance(item.get("text"), str):return "add"continue- if not _valid_workbench_attachment(item, attachments_root):+ if not _valid_pinned_attachment(item, attachments_root):return "add"return None-def _valid_workbench_attachment(item: dict[str, Any], attachments_root: Path | None) -> bool:+def _valid_pinned_attachment(item: dict[str, Any], attachments_root: Path | None) -> bool:if set(item) != {"type", "name", "uri", "ext"}:return Falseif item.get("type") not in {"image", "audio", "doc", "pdf", "html", "email"}:diff --git a/docs/plans/memory-im-attachments-1425.md b/docs/plans/memory-im-attachments-1425.mdindex 71eb7a809..0a79a1a41 100644--- a/docs/plans/memory-im-attachments-1425.md+++ b/docs/plans/memory-im-attachments-1425.md@@ -63,6 +63,22 @@ It calls the platform's `BaseIMClient.download_file_to_path` implementation,uses sanitized names, removes partial files, and publishes only an opaque,reference-counted local lease. Consumers never receive a native URL, token,encryption material, or mutable `MessageContext` as their durable contract.+Lease files live below the fixed private+`<effective-home>/attachments/im/<opaque-lease-id>/` root. A rejected or+unclaimed batch is removed after its final reference; ordinary Agent delivery+adopts its existing local-file lifetime, while a retained Memory reference can+finish pinning first. Empty and failed batches are never preserved by adoption.+The materializer keeps no-follow root and lease descriptors open for the lease+lifetime. It pre-creates each partial file with descriptor-relative+`O_EXCL | O_NOFOLLOW`, passes a duplicate file descriptor to bounded platform+writers, and performs normalization, publication, and cleanup relative to the+verified lease descriptor. Replacing the directory entry during materialization+fails closed and cannot redirect writes outside the private lease.+Each published record binds its original device/inode. Memory selection and+durable pinning reopen that record relative to a duplicated retained lease+descriptor and reject inode mismatches. The record also binds a materialization+SHA-256 that durable pinning verifies while copying, so neither public pathname+replacement nor same-inode modification can substitute bytes after acquisition.The message handler materializes before scheduling Memory capture. Agent deliveryand Memory retain independent lease references, so Agent cleanup, retry, or@@ -74,12 +90,20 @@ downloads with declared, response-header, and streamed-byte limits. Telegram ischanged to a bounded-to-disk Bot API download; it must not buffer the entire filebefore checking the limit. WeChat checks declared size before acquisition andbounds ciphertext/decrypted output while writing; a post-download-only check is-not sufficient.+not sufficient. The shared materializer normalizes non-negative integer declared+sizes and rejects an over-limit item before creating a partial or invoking any+platform adapter.`core/memory/im_attachments.py` accepts only shared-materializer leases. It checksdeclared size before retaining a Memory consumer and checks final size, MIME,extension, and magic after acquisition through the closed modality table. It-produces immutable `CaptureAttachment` values for surviving files.+produces immutable `CaptureAttachment` values for surviving files. Missing or+non-string native MIME metadata normalizes to `application/octet-stream` at this+shared boundary. Text-like formats stream their complete bounded file through+incremental UTF-8 and NUL validation; checking only the leading magic sample is+insufficient. M4A admission parses brands only from the declared,+four-byte-aligned `ftyp` brand table; brand-like bytes in later ISO-BMFF boxes do+not admit excluded video.`core/memory/attachments.py` accepts either the fixed Workbench upload root or afixed leased-IM source handle. Both paths keep no-follow opens, owner and modediff --git a/modules/im/base.py b/modules/im/base.pyindex 2fe3bd491..097450ce1 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -3,9 +3,11 @@import loggingfrom pathlib import Pathfrom abc import ABC, abstractmethod-from typing import Optional, Callable, Dict, Any, List, Tuple, cast+from typing import Optional, Callable, Dict, Any, List, Tuple, Literal, castfrom dataclasses import dataclass+from .download_target import open_download_target+logger = logging.getLogger(__name__)@@ -28,6 +30,7 @@ class FileDownloadResult:success: boolerror: Optional[str] = None+ failure_reason: Optional[Literal["file_too_large"]] = None@dataclass@@ -447,6 +450,7 @@ class BaseIMClient(ABC):target_path: str,max_bytes: Optional[int] = None,timeout_seconds: int = 30,+ target_fd: Optional[int] = None,) -> FileDownloadResult:"""Download a remote file directly to a local path.@@ -459,10 +463,9 @@ class BaseIMClient(ABC):if content is None:return FileDownloadResult(False, "Download returned no content")- path = Path(target_path)- path.parent.mkdir(parents=True, exist_ok=True)try:- path.write_bytes(content)+ with open_download_target(target_path, target_fd=target_fd) as file_obj:+ file_obj.write(content)except Exception as err:return FileDownloadResult(False, f"Failed to write downloaded file: {err}")return FileDownloadResult(True)diff --git a/modules/im/discord.py b/modules/im/discord.pyindex f94119038..1be9629ae 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -19,6 +19,7 @@ from .base import (FileAttachment,)from .message_facts import is_ordinary_discord_text+from .download_target import open_download_targetfrom config.v2_config import DiscordConfigfrom .formatters import DiscordFormatterfrom vibe.i18n import get_supported_languages, t as i18n_t@@ -824,6 +825,7 @@ class DiscordBot(BaseIMClient):target_path: str,max_bytes: Optional[int] = None,timeout_seconds: int = 30,+ target_fd: Optional[int] = None,) -> FileDownloadResult:url = file_info.get("url") or file_info.get("url_private_download") or file_info.get("url_private")if not url:@@ -836,15 +838,21 @@ class DiscordBot(BaseIMClient):return FileDownloadResult(False, f"Download failed with HTTP {response.status}")content_length = response.headers.get("Content-Length")if max_bytes is not None and content_length and int(content_length) > max_bytes:- return FileDownloadResult(False, f"File exceeds the allowed size limit ({max_bytes} bytes)")+ return FileDownloadResult(+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",+ )total_size = 0- with open(target_path, "wb") as file_obj:+ with open_download_target(target_path, target_fd=target_fd) as file_obj:async for chunk in response.content.iter_chunked(64 * 1024):total_size += len(chunk)if max_bytes is not None and total_size > max_bytes:return FileDownloadResult(- False, f"File exceeds the allowed size limit ({max_bytes} bytes)"+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",)file_obj.write(chunk)return FileDownloadResult(True)diff --git a/modules/im/download_target.py b/modules/im/download_target.pynew file mode 100644index 000000000..39606bc40--- /dev/null+++ b/modules/im/download_target.py@@ -0,0 +1,38 @@+"""Shared file-target handling for bounded IM downloads."""++from __future__ import annotations++import os+from contextlib import contextmanager+from pathlib import Path+from typing import BinaryIO, Iterator+++@contextmanager+def open_download_target(+ target_path: Path | str,+ *,+ target_fd: int | None = None,+ exclusive_path: bool = False,+) -> Iterator[BinaryIO]:+ """Open a path normally or write through a caller-owned anchored descriptor."""++ if target_fd is not None:+ duplicate = os.dup(target_fd)+ try:+ os.ftruncate(duplicate, 0)+ os.lseek(duplicate, 0, os.SEEK_SET)+ with os.fdopen(duplicate, "wb") as file_obj:+ duplicate = -1+ yield file_obj+ finally:+ if duplicate >= 0:+ os.close(duplicate)+ return++ target = Path(target_path)+ target.parent.mkdir(parents=True, exist_ok=True)+ if exclusive_path:+ target.unlink(missing_ok=True)+ with target.open("xb" if exclusive_path else "wb") as file_obj:+ yield file_objdiff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 02dde1f4a..ed6d0732a 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -21,6 +21,7 @@ from .base import ()from .formatters import FeishuFormatterfrom .message_facts import is_ordinary_feishu_text+from .download_target import open_download_targetfrom config.v2_config import LarkConfigfrom vibe.i18n import get_supported_languages, t as i18n_tfrom modules.agents.opencode.utils import (@@ -1391,6 +1392,7 @@ class FeishuBot(BaseIMClient):target_path: str,max_bytes: Optional[int] = None,timeout_seconds: int = 30,+ target_fd: Optional[int] = None,) -> FileDownloadResult:message_id = file_info.get("message_id")file_key = file_info.get("file_key")@@ -1408,12 +1410,14 @@ class FeishuBot(BaseIMClient):if resp.status != 200:return FileDownloadResult(False, f"Download failed with HTTP {resp.status}")total = 0- with open(target_path, "wb") as file_obj:+ with open_download_target(target_path, target_fd=target_fd) as file_obj:async for chunk in resp.content.iter_chunked(64 * 1024):total += len(chunk)if max_bytes is not None and total > max_bytes:return FileDownloadResult(- False, f"File exceeds the allowed size limit ({max_bytes} bytes)"+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",)file_obj.write(chunk)return FileDownloadResult(True)@@ -1433,13 +1437,15 @@ class FeishuBot(BaseIMClient):logger.error("Failed to download Feishu file: HTTP %s", resp.status)return FileDownloadResult(False, f"Download failed with HTTP {resp.status}")total = 0- with open(target_path, "wb") as file_obj:+ with open_download_target(target_path, target_fd=target_fd) as file_obj:async for chunk in resp.content.iter_chunked(64 * 1024):total += len(chunk)if max_bytes is not None and total > max_bytes:logger.warning("Feishu file exceeds max size, aborting")return FileDownloadResult(- False, f"File exceeds the allowed size limit ({max_bytes} bytes)"+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",)file_obj.write(chunk)return FileDownloadResult(True)diff --git a/modules/im/multi.py b/modules/im/multi.pyindex 651702278..95820e133 100644--- a/modules/im/multi.py+++ b/modules/im/multi.py@@ -370,13 +370,19 @@ class MultiIMClient(BaseIMClient):target_path: str,max_bytes: Optional[int] = None,timeout_seconds: int = 30,+ target_fd: Optional[int] = None,):client = self.get_client(self._resolve_platform_from_file_info(file_info))+ options = {+ "max_bytes": max_bytes,+ "timeout_seconds": timeout_seconds,+ }+ if target_fd is not None:+ options["target_fd"] = target_fdreturn await client.download_file_to_path(file_info,target_path,- max_bytes=max_bytes,- timeout_seconds=timeout_seconds,+ **options,)async def edit_message(diff --git a/modules/im/slack.py b/modules/im/slack.pyindex b8283b3f0..01c28d7cd 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -22,6 +22,7 @@ from .base import (FileAttachment,)from .message_facts import is_ordinary_slack_text+from .download_target import open_download_targetfrom config.v2_config import SlackConfigfrom core.auth import AuthResultfrom .formatters import SlackFormatter@@ -1097,6 +1098,7 @@ class SlackBot(BaseIMClient):target_path: str,max_bytes: Optional[int] = None,timeout_seconds: int = 30,+ target_fd: Optional[int] = None,) -> FileDownloadResult:file_info = await self._resolve_downloadable_file_info(file_info)url = file_info.get("url_private_download") or file_info.get("url_private") or file_info.get("url")@@ -1107,7 +1109,11 @@ class SlackBot(BaseIMClient):file_size = file_info.get("size")if max_bytes is not None and file_size and file_size > max_bytes:logger.warning(f"File too large ({file_size} bytes > {max_bytes}), skipping: {file_info.get('name')}")- return FileDownloadResult(False, f"File exceeds the allowed size limit ({max_bytes} bytes)")+ return FileDownloadResult(+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",+ )try:headers = {"Authorization": f"Bearer {self.config.bot_token}"}@@ -1121,10 +1127,14 @@ class SlackBot(BaseIMClient):content_length = response.headers.get("Content-Length")if max_bytes is not None and content_length and int(content_length) > max_bytes:logger.warning(f"File too large ({content_length} bytes), skipping: {file_info.get('name')}")- return FileDownloadResult(False, f"File exceeds the allowed size limit ({max_bytes} bytes)")+ return FileDownloadResult(+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",+ )total_size = 0- with open(target_path, "wb") as file_obj:+ with open_download_target(target_path, target_fd=target_fd) as file_obj:async for chunk in response.content.iter_chunked(64 * 1024):total_size += len(chunk)if max_bytes is not None and total_size > max_bytes:@@ -1132,7 +1142,9 @@ class SlackBot(BaseIMClient):f"File exceeds max size during download, aborting: {file_info.get('name')}")return FileDownloadResult(- False, f"File exceeds the allowed size limit ({max_bytes} bytes)"+ False,+ f"File exceeds the allowed size limit ({max_bytes} bytes)",+ "file_too_large",)file_obj.write(chunk)return FileDownloadResult(True)diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 31095822d..10faff24c 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -19,7 +19,14 @@ from vibe.proxy import resolve_proxyfrom modules.agents.native_sessions import AgentNativeSessionService, NativeResumeSessionfrom modules.agents.opencode.utils import format_claude_model_label-from .base import BaseIMClient, FileAttachment, MessageContext, InlineButton, InlineKeyboard+from .base import (+ BaseIMClient,+ FileAttachment,+ FileDownloadResult,+ MessageContext,+ InlineButton,+ InlineKeyboard,+)from .formatters import TelegramFormatterfrom .message_facts import is_ordinary_telegram_textfrom . import telegram_api@@ -27,6 +34,16 @@ from . import telegram_apilogger = logging.getLogger(__name__)+def _telegram_size_exceeds(value: object, max_bytes: int | None) -> bool:+ if max_bytes is None:+ return False+ try:+ size = int(value) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return False+ return size >= 0 and size > max_bytes++@dataclassclass _TelegramCwdPrompt:message_id: str@@ -1531,6 +1548,60 @@ class TelegramBot(BaseIMClient):raise ValueError("Downloaded file exceeds max_bytes")return content+ async def download_file_to_path(+ self,+ file_info: Dict[str, Any],+ target_path: str,+ max_bytes: Optional[int] = None,+ timeout_seconds: int = 30,+ target_fd: Optional[int] = None,+ ) -> FileDownloadResult:+ """Resolve and stream a Telegram file without buffering it in memory."""++ file_id = (+ file_info.get("telegram_file_id")+ or file_info.get("url")+ or file_info.get("file_id")+ )+ if not file_id:+ return FileDownloadResult(False, "Telegram file_id is required")+ if _telegram_size_exceeds(file_info.get("size"), max_bytes):+ return FileDownloadResult(False, "File exceeds max_bytes", "file_too_large")+ target = Path(target_path)+ try:+ file_result = await telegram_api.get_file(+ self.config.bot_token,+ str(file_id),+ proxy_url=self._proxy_url,+ )+ resolved = file_result.get("result")+ if not isinstance(resolved, dict) or not resolved.get("file_path"):+ return FileDownloadResult(False, "Telegram file metadata is invalid")+ if _telegram_size_exceeds(resolved.get("file_size"), max_bytes):+ return FileDownloadResult(False, "File exceeds max_bytes", "file_too_large")+ download_options: Dict[str, Any] = {+ "max_bytes": max_bytes,+ "timeout_seconds": timeout_seconds,+ "proxy_url": self._proxy_url,+ }+ if target_fd is not None:+ download_options["target_fd"] = target_fd+ await telegram_api.download_file_to_path(+ self.config.bot_token,+ str(resolved["file_path"]),+ target,+ **download_options,+ )+ return FileDownloadResult(True)+ except telegram_api.TelegramFileTooLargeError:+ if target_fd is None:+ target.unlink(missing_ok=True)+ return FileDownloadResult(False, "File exceeds max_bytes", "file_too_large")+ except Exception:+ if target_fd is None:+ target.unlink(missing_ok=True)+ return FileDownloadResult(False, "Telegram file download failed")+async def open_change_cwd_modal(self, trigger_id: Any, current_cwd: str, channel_id: str = None):context = trigger_id if isinstance(trigger_id, MessageContext) else Noneif context is None:diff --git a/modules/im/telegram_api.py b/modules/im/telegram_api.pyindex 3a8649e46..349225b7b 100644--- a/modules/im/telegram_api.py+++ b/modules/im/telegram_api.py@@ -9,6 +9,12 @@ from typing import Any, Optionalimport aiohttpfrom aiohttp_socks import ProxyConnector+from .download_target import open_download_target+++class TelegramFileTooLargeError(ValueError):+ """The streamed Telegram file exceeded its configured byte bound."""+def _api_url(bot_token: str, method: str) -> str:return f"https://api.telegram.org/bot{bot_token}/{method}"@@ -72,6 +78,57 @@ async def download_file(bot_token: str, file_path: str, *, timeout_seconds: intreturn await resp.read()+async def download_file_to_path(+ bot_token: str,+ file_path: str,+ target_path: Path | str,+ *,+ max_bytes: int | None = None,+ timeout_seconds: int = 60,+ proxy_url: Optional[str] = None,+ target_fd: int | None = None,+) -> int:+ """Stream one Bot API file to disk with header and byte-count bounds."""++ timeout = aiohttp.ClientTimeout(total=timeout_seconds)+ connector = ProxyConnector.from_url(proxy_url) if proxy_url else None+ target = Path(target_path)+ if target_fd is None:+ target.parent.mkdir(parents=True, exist_ok=True)+ target.unlink(missing_ok=True)+ try:+ async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session:+ async with session.get(_file_url(bot_token, file_path)) as resp:+ resp.raise_for_status()+ content_length = _positive_content_length(resp.headers.get("Content-Length"))+ if max_bytes is not None and content_length is not None and content_length > max_bytes:+ raise TelegramFileTooLargeError("Downloaded file exceeds max_bytes")+ total = 0+ with open_download_target(+ target,+ target_fd=target_fd,+ exclusive_path=True,+ ) as file_obj:+ async for chunk in resp.content.iter_chunked(64 * 1024):+ total += len(chunk)+ if max_bytes is not None and total > max_bytes:+ raise TelegramFileTooLargeError("Downloaded file exceeds max_bytes")+ file_obj.write(chunk)+ return total+ except BaseException:+ if target_fd is None:+ target.unlink(missing_ok=True)+ raise+++def _positive_content_length(value: object) -> int | None:+ try:+ parsed = int(value) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return None+ return parsed if parsed >= 0 else None++async def get_file(bot_token: str, file_id: str, proxy_url: Optional[str] = None) -> dict[str, Any]:return await call_api(bot_token, "getFile", {"file_id": file_id}, proxy_url=proxy_url)diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex bf8dd9eeb..07eb564c6 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -83,6 +83,44 @@ _SHORT_RETRY_SECONDS = 2_LONG_RETRY_SECONDS = 30_MAX_CONSECUTIVE_FAILURES = 3_DEDUP_SET_MAX = 1000+++def _wechat_declared_size_exceeds(file_info: Dict[str, Any], max_bytes: int | None) -> bool:+ if max_bytes is None:+ return False+ cdn_info = file_info.get("cdn_info")+ cdn_info = cdn_info if isinstance(cdn_info, dict) else {}+ wechat_item = file_info.get("wechat_item")+ wechat_item = wechat_item if isinstance(wechat_item, dict) else {}+ plaintext_values = (+ file_info.get("size"),+ cdn_info.get("file_size"),+ wechat_item.get("len"),+ )+ ciphertext_values = (+ cdn_info.get("file_size_ciphertext"),+ wechat_item.get("file_size_ciphertext"),+ wechat_item.get("mid_size"),+ wechat_item.get("video_size"),+ )+ for value in plaintext_values:+ size = _nonnegative_size(value)+ if size is not None and size > max_bytes:+ return True+ ciphertext_limit = _wechat_cdn_mod.aes_ecb_padded_size(max_bytes)+ for value in ciphertext_values:+ size = _nonnegative_size(value)+ if size is not None and size > ciphertext_limit:+ return True+ return False+++def _nonnegative_size(value: object) -> int | None:+ try:+ size = int(value) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return None+ return size if size >= 0 else None_DEDUP_CLEAN_INTERVAL_SECONDS = 300_SESSION_EXPIRED_ERRCODE = -14_CONTEXT_TOKEN_CACHE_VERSION = 1@@ -274,8 +312,11 @@ class _WeChatCDN:cdn_base_url: str,file_info: Dict[str, Any],target_path: str,+ max_bytes: Optional[int] = None,+ timeout_seconds: int = 30,proxy: Optional[str] = None,- ) -> bool:+ target_fd: Optional[int] = None,+ ) -> FileDownloadResult:"""Download and decrypt a CDN file to a local path."""cdn_info = file_info.get("cdn_info") or {}wechat_item = file_info.get("wechat_item") or {}@@ -289,33 +330,52 @@ class _WeChatCDN:aes_key_b64 = base64.b64encode(bytes.fromhex(item_aes_hex)).decode("ascii")except ValueError:logger.error("Invalid WeChat image aeskey hex for file %s", file_info.get("name", ""))- return False+ return FileDownloadResult(False, "CDN download/decrypt failed")if not encrypted_query_param:logger.error("Missing encrypt_query_param for WeChat attachment: %s", file_info)- return False+ return FileDownloadResult(False, "CDN download/decrypt failed")dest = Path(target_path)- dest.parent.mkdir(parents=True, exist_ok=True)+ if target_fd is None:+ dest.parent.mkdir(parents=True, exist_ok=True)try:if aes_key_b64:- content = await _wechat_cdn_mod.download_and_decrypt(+ await _wechat_cdn_mod.download_and_decrypt_to_path(cdn_base_url,encrypted_query_param,aes_key_b64,+ dest,+ max_bytes=max_bytes,+ timeout_seconds=timeout_seconds,+ target_fd=target_fd,)else:- content = await _wechat_cdn_mod.download_plain(+ await _wechat_cdn_mod.download_plain_to_path(cdn_base_url,encrypted_query_param,+ dest,+ max_bytes=max_bytes,+ timeout_seconds=timeout_seconds,+ target_fd=target_fd,)-- dest.write_bytes(content)- return True+ return FileDownloadResult(True)+ except ValueError as exc:+ if target_fd is None:+ dest.unlink(missing_ok=True)+ logger.warning("WeChat CDN download failed: %s", type(exc).__name__)+ reason = (+ "file_too_large"+ if str(exc) == "Downloaded file exceeds max_bytes"+ else None+ )+ return FileDownloadResult(False, "CDN download/decrypt failed", reason)except Exception as exc:- logger.error("CDN download error: %s", exc)- return False+ if target_fd is None:+ dest.unlink(missing_ok=True)+ logger.warning("WeChat CDN download failed: %s", type(exc).__name__)+ return FileDownloadResult(False, "CDN download/decrypt failed")wechat_cdn = _WeChatCDN()@@ -904,30 +964,25 @@ class WeChatBot(BaseIMClient):target_path: str,max_bytes: Optional[int] = None,timeout_seconds: int = 30,+ target_fd: Optional[int] = None,) -> FileDownloadResult:"""Download a CDN file to a local path."""- success = await wechat_cdn.download_and_decrypt(+ if _wechat_declared_size_exceeds(file_info, max_bytes):+ return FileDownloadResult(False, "File exceeds max_bytes", "file_too_large")+ result = await wechat_cdn.download_and_decrypt(self.config.base_url,self.config.bot_token,getattr(self.config, "cdn_base_url", self.config.base_url),file_info,target_path,+ max_bytes=max_bytes,+ timeout_seconds=timeout_seconds,proxy=self._proxy_url,+ target_fd=target_fd,)- if not success:- return FileDownloadResult(False, "CDN download/decrypt failed")-- # Enforce max_bytes after download if specified- if max_bytes is not None:- dest = Path(target_path)- if dest.exists() and dest.stat().st_size > max_bytes:- dest.unlink(missing_ok=True)- return FileDownloadResult(- False,- f"File exceeds max_bytes ({max_bytes})",- )-- return FileDownloadResult(True)+ if isinstance(result, FileDownloadResult):+ return result+ return FileDownloadResult(bool(result), None if result else "CDN download/decrypt failed")async def download_file(self,diff --git a/modules/im/wechat_cdn.py b/modules/im/wechat_cdn.pyindex 0fd109765..8b3968e2e 100644--- a/modules/im/wechat_cdn.py+++ b/modules/im/wechat_cdn.py@@ -21,6 +21,8 @@ import aiohttpfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modesfrom cryptography.hazmat.primitives.padding import PKCS7+from modules.im.download_target import open_download_target+from modules.im.wechat_api import (UPLOAD_MEDIA_FILE,UPLOAD_MEDIA_IMAGE,@@ -438,6 +440,124 @@ async def download_and_decrypt(return decrypted+async def download_and_decrypt_to_path(+ cdn_base_url: str,+ encrypted_query_param: str,+ aes_key_b64: str,+ target_path: Path | str,+ *,+ max_bytes: int | None = None,+ timeout_seconds: int = 60,+ target_fd: int | None = None,+) -> int:+ """Stream, decrypt, unpad, and bound one CDN object directly to disk."""++ key = parse_aes_key(aes_key_b64)+ url = _build_cdn_download_url(cdn_base_url, encrypted_query_param)+ target = Path(target_path)+ if target_fd is None:+ target.parent.mkdir(parents=True, exist_ok=True)+ target.unlink(missing_ok=True)+ ciphertext_limit = aes_ecb_padded_size(max_bytes) if max_bytes is not None else None+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)+ cipher = Cipher(algorithms.AES(key), modes.ECB())+ decryptor = cipher.decryptor()+ unpadder = PKCS7(_AES_BLOCK_BITS).unpadder()+ encrypted_total = 0+ plaintext_total = 0++ def write_bounded(file_obj, plaintext: bytes) -> None:+ nonlocal plaintext_total+ plaintext_total += len(plaintext)+ if max_bytes is not None and plaintext_total > max_bytes:+ raise ValueError("Downloaded file exceeds max_bytes")+ file_obj.write(plaintext)++ try:+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(url) as resp:+ if not resp.ok:+ raise RuntimeError(f"CDN download failed with HTTP {resp.status}")+ content_length = _nonnegative_int(resp.headers.get("Content-Length"))+ if (+ ciphertext_limit is not None+ and content_length is not None+ and content_length > ciphertext_limit+ ):+ raise ValueError("Downloaded file exceeds max_bytes")+ with open_download_target(+ target,+ target_fd=target_fd,+ exclusive_path=True,+ ) as file_obj:+ async for chunk in resp.content.iter_chunked(64 * 1024):+ encrypted_total += len(chunk)+ if ciphertext_limit is not None and encrypted_total > ciphertext_limit:+ raise ValueError("Downloaded file exceeds max_bytes")+ write_bounded(file_obj, unpadder.update(decryptor.update(chunk)))+ padded_tail = decryptor.finalize()+ write_bounded(+ file_obj,+ unpadder.update(padded_tail) + unpadder.finalize(),+ )+ return plaintext_total+ except BaseException:+ if target_fd is None:+ target.unlink(missing_ok=True)+ raise+++async def download_plain_to_path(+ cdn_base_url: str,+ encrypted_query_param: str,+ target_path: Path | str,+ *,+ max_bytes: int | None = None,+ timeout_seconds: int = 60,+ target_fd: int | None = None,+) -> int:+ """Stream one unencrypted CDN object directly to a bounded local path."""++ url = _build_cdn_download_url(cdn_base_url, encrypted_query_param)+ target = Path(target_path)+ if target_fd is None:+ target.parent.mkdir(parents=True, exist_ok=True)+ target.unlink(missing_ok=True)+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)+ total = 0+ try:+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(url) as resp:+ if not resp.ok:+ raise RuntimeError(f"CDN download failed with HTTP {resp.status}")+ content_length = _nonnegative_int(resp.headers.get("Content-Length"))+ if max_bytes is not None and content_length is not None and content_length > max_bytes:+ raise ValueError("Downloaded file exceeds max_bytes")+ with open_download_target(+ target,+ target_fd=target_fd,+ exclusive_path=True,+ ) as file_obj:+ async for chunk in resp.content.iter_chunked(64 * 1024):+ total += len(chunk)+ if max_bytes is not None and total > max_bytes:+ raise ValueError("Downloaded file exceeds max_bytes")+ file_obj.write(chunk)+ return total+ except BaseException:+ if target_fd is None:+ target.unlink(missing_ok=True)+ raise+++def _nonnegative_int(value: object) -> int | None:+ try:+ parsed = int(value) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return None+ return parsed if parsed >= 0 else None++async def download_plain(cdn_base_url: str,encrypted_query_param: str,diff --git a/tests/test_audio_asr.py b/tests/test_audio_asr.pyindex 94c8c682e..08f0ca72c 100644--- a/tests/test_audio_asr.py+++ b/tests/test_audio_asr.py@@ -507,7 +507,7 @@ class MessageHandlerAudioAsrTests(unittest.IsolatedAsyncioTestCase):context = MessageContext(user_id="U1", channel_id="C1", message_id="M1", files=[attachment])with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):await handler.handle_user_message(context, "please transcribe")return controllerdiff --git a/tests/test_inbound_attachments.py b/tests/test_inbound_attachments.pynew file mode 100644index 000000000..809bfb34a--- /dev/null+++ b/tests/test_inbound_attachments.py@@ -0,0 +1,390 @@+from __future__ import annotations++import os+import stat+from pathlib import Path++import pytest++import core.handlers.inbound_attachments as inbound_attachment_module+from core.handlers.inbound_attachments import InboundAttachmentMaterializer+from modules.im.base import FileAttachment, FileDownloadResult, MessageContext+++class _StubClient:+ def __init__(self, payloads: dict[str, bytes | None]) -> None:+ self.payloads = payloads+ self.calls: list[tuple[str, int | None, int]] = []++ async def download_file_to_path(+ self,+ file_info,+ target_path,+ max_bytes=None,+ timeout_seconds=30,+ ):+ self.calls.append((file_info["name"], max_bytes, timeout_seconds))+ payload = self.payloads[file_info["name"]]+ if payload is None:+ Path(target_path).write_bytes(b"partial")+ return FileDownloadResult(False, "native secret must not escape")+ Path(target_path).write_bytes(payload)+ return FileDownloadResult(True)+++class _LegacyPathClient:+ def __init__(self) -> None:+ self.calls = 0++ async def download_file_to_path(self, file_info, target_path):+ self.calls += 1+ Path(target_path).write_bytes(b"legacy")+ return FileDownloadResult(True)+++class _OversizedClient:+ async def download_file_to_path(+ self,+ file_info,+ target_path,+ max_bytes=None,+ timeout_seconds=30,+ ):+ return FileDownloadResult(False, "native size detail", "file_too_large")+++class _DescriptorClient:+ def __init__(self, payload: bytes) -> None:+ self.payload = payload+ self.target_fds: list[int] = []++ async def download_file_to_path(+ self,+ file_info,+ target_path,+ max_bytes=None,+ timeout_seconds=30,+ target_fd=None,+ ):+ assert target_fd is not None+ self.target_fds.append(target_fd)+ os.write(target_fd, self.payload)+ return FileDownloadResult(True)+++class _LeaseSwapClient(_DescriptorClient):+ def __init__(self, payload: bytes, lease_root: Path, outside: Path) -> None:+ super().__init__(payload)+ self.lease_root = lease_root+ self.outside = outside++ async def download_file_to_path(self, *args, target_fd=None, **kwargs):+ lease_dir = next(self.lease_root.iterdir())+ moved = self.lease_root / f"{lease_dir.name}.moved"+ lease_dir.rename(moved)+ lease_dir.symlink_to(self.outside, target_is_directory=True)+ return await super().download_file_to_path(+ *args,+ target_fd=target_fd,+ **kwargs,+ )+++async def test_materializer_publishes_one_private_reference_counted_lease(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ client = _StubClient({"../report.pdf": b"%PDF-1.7\n"})+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[+ FileAttachment(+ name="../report.pdf",+ mimetype="application/pdf",+ url="private-native-reference",+ size=9,+ )+ ],+ )++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ client,+ )++ assert batch.errors == ()+ assert client.calls == [("../report.pdf", None, 30)]+ assert len(batch.attachments) == 1+ attachment = batch.attachments[0]+ assert attachment.name == "report.pdf"+ assert attachment.local_path is not None+ path = Path(attachment.local_path)+ assert path.read_bytes() == b"%PDF-1.7\n"+ assert path.is_relative_to(home / "attachments" / "im")+ assert path.stat().st_mode & 0o077 == 0++ retained = batch.lease.retain()+ batch.lease.release()+ assert path.exists()+ retained.release()+ assert not path.exists()+++async def test_materializer_degrades_failed_sibling_and_removes_partial_file(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ client = _StubClient({"valid.txt": b"valid", "failed.txt": None})+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[+ FileAttachment("valid.txt", "text/plain", url="valid", size=5),+ FileAttachment("failed.txt", "text/plain", url="failed", size=10),+ ],+ )++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ client,+ max_concurrency=2,+ )++ assert [item.name for item in batch.attachments] == ["valid.txt"]+ assert batch.errors == ("download_failed",)+ lease_root = home / "attachments" / "im"+ assert not list(lease_root.rglob("*.part"))+ assert "native secret" not in repr(batch)+ batch.lease.release()+ assert list(lease_root.iterdir()) == []+++async def test_adoption_does_not_preserve_an_empty_failed_batch(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ client = _StubClient({"failed.txt": None})+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[FileAttachment("failed.txt", "text/plain", url="failed", size=10)],+ )++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(context, client)+ batch.lease.adopt()+ batch.lease.release()++ assert list((home / "attachments" / "im").iterdir()) == []+++async def test_materializer_adoption_preserves_agent_owned_files(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ client = _StubClient({"notes.txt": b"notes"})+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[FileAttachment("notes.txt", "text/plain", url="ref", size=5)],+ )++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(context, client)+ path = Path(batch.attachments[0].local_path or "")+ batch.lease.adopt()+ batch.lease.release()++ assert path.read_bytes() == b"notes"+++async def test_materializer_preserves_legacy_two_argument_path_clients(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ client = _LegacyPathClient()+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[FileAttachment("legacy.txt", "text/plain", url="ref", size=6)],+ )++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ client,+ max_bytes=10,+ timeout_seconds=7,+ )++ assert client.calls == 1+ assert batch.attachments[0].size == 6+ batch.lease.release()+++async def test_materializer_rejects_symlinked_attachment_root(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ attachments = home / "attachments"+ outside = tmp_path / "outside"+ attachments.mkdir(parents=True)+ outside.mkdir()+ (attachments / "im").symlink_to(outside, target_is_directory=True)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[FileAttachment("notes.txt", "text/plain", url="ref", size=5)],+ )++ with pytest.raises(OSError):+ await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ _StubClient({"notes.txt": b"notes"}),+ )++ assert list(outside.iterdir()) == []+++async def test_materializer_keeps_download_writes_on_anchored_descriptor(+ tmp_path: Path,+) -> None:+ home = tmp_path / "avibe-home"+ client = _DescriptorClient(b"anchored")+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[FileAttachment("notes.txt", "text/plain", url="ref")],+ )++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ client,+ )++ assert len(client.target_fds) == 1+ assert Path(batch.attachments[0].local_path or "").read_bytes() == b"anchored"+ batch.lease.release()+++async def test_materializer_fails_closed_when_lease_directory_is_replaced(+ tmp_path: Path,+) -> None:+ home = tmp_path / "avibe-home"+ lease_root = home / "attachments" / "im"+ outside = tmp_path / "outside"+ outside.mkdir()+ client = _LeaseSwapClient(b"anchored", lease_root, outside)+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[FileAttachment("notes.txt", "text/plain", url="ref")],+ )++ with pytest.raises(OSError, match="lease directory changed"):+ await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ client,+ )++ assert list(outside.iterdir()) == []+++async def test_materializer_rejects_declared_oversize_before_adapter(+ tmp_path: Path,+) -> None:+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="telegram",+ files=[FileAttachment("large.pdf", "application/pdf", url="ref", size=20)],+ )++ client = _StubClient({"large.pdf": b"small"})+ batch = await InboundAttachmentMaterializer(effective_home=tmp_path / "home").materialize(+ context,+ client,+ max_bytes=10,+ language="zh",+ )++ assert client.calls == []+ assert batch.errors == ("file_too_large",)+ assert batch.display_errors == ("附件“large.pdf”超过附件大小限制。",)+ batch.lease.release()+++async def test_materializer_preserves_adapter_typed_size_reason(+ tmp_path: Path,+) -> None:+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="telegram",+ files=[FileAttachment("large.pdf", "application/pdf", url="ref")],+ )++ batch = await InboundAttachmentMaterializer(effective_home=tmp_path / "home").materialize(+ context,+ _OversizedClient(),+ max_bytes=10,+ language="zh",+ )++ assert batch.errors == ("file_too_large",)+ assert batch.display_errors == ("附件“large.pdf”超过附件大小限制。",)+ assert "native size detail" not in repr(batch)+ batch.lease.release()+++async def test_materializer_removes_corrected_final_file_when_post_processing_fails(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "avibe-home"+ client = _StubClient(+ {+ "failed.bin": b"\x89PNG\r\n\x1a\ncontent",+ "valid.txt": b"valid",+ }+ )+ context = MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=[+ FileAttachment("failed.bin", "application/octet-stream", url="failed"),+ FileAttachment("valid.txt", "text/plain", url="valid"),+ ],+ )+ original_fchmod = inbound_attachment_module.os.fchmod+ private_file_calls = 0++ def fail_corrected_chmod(descriptor: int, mode: int) -> None:+ nonlocal private_file_calls+ if stat.S_ISREG(os.fstat(descriptor).st_mode):+ private_file_calls += 1+ if private_file_calls == 2:+ raise OSError("post-download chmod failed")+ original_fchmod(descriptor, mode)++ monkeypatch.setattr(inbound_attachment_module.os, "fchmod", fail_corrected_chmod)++ batch = await InboundAttachmentMaterializer(effective_home=home).materialize(+ context,+ client,+ max_concurrency=2,+ )++ assert [attachment.name for attachment in batch.attachments] == ["valid.txt"]+ assert batch.errors == ("download_failed",)+ lease_root = home / "attachments" / "im"+ assert not list(lease_root.rglob("*failed*"))+ batch.lease.adopt()+ batch.lease.release()+ assert not list(lease_root.rglob("*failed*"))diff --git a/tests/test_memory_im_attachments.py b/tests/test_memory_im_attachments.pynew file mode 100644index 000000000..58032775e--- /dev/null+++ b/tests/test_memory_im_attachments.py@@ -0,0 +1,268 @@+from __future__ import annotations++import os+from pathlib import Path++import pytest++import core.memory.im_attachments as im_attachment_module+from core.handlers.inbound_attachments import InboundAttachmentMaterializer+from core.memory.attachments import AttachmentPinStore+from core.memory.im_attachments import select_memory_attachments+from core.memory.types import CaptureAttachment+from modules.im.base import FileAttachment, FileDownloadResult, MessageContext+++class _Client:+ def __init__(self, payloads: dict[str, bytes]) -> None:+ self.payloads = payloads++ async def download_file_to_path(self, file_info, target_path, max_bytes=None, timeout_seconds=30):+ Path(target_path).write_bytes(self.payloads[file_info["name"]])+ return FileDownloadResult(True)+++async def _materialize(+ home: Path,+ entries: list[tuple[str, object, bytes, int | None]],+):+ files = [+ FileAttachment(name=name, mimetype=mime, url=name, size=declared)+ for name, mime, _payload, declared in entries+ ]+ payloads = {name: payload for name, _mime, payload, _declared in entries}+ return await InboundAttachmentMaterializer(effective_home=home).materialize(+ MessageContext(+ user_id="U1",+ channel_id="D1",+ platform="slack",+ files=files,+ ),+ _Client(payloads),+ )+++async def test_memory_selection_normalizes_missing_mime_without_losing_siblings(+ tmp_path: Path,+) -> None:+ batch = await _materialize(+ tmp_path / "avibe-home",+ [+ ("unknown.txt", None, b"text", 4),+ ("valid.pdf", "application/pdf", b"%PDF-1.7\n", 9),+ ],+ )++ selected = select_memory_attachments(batch.lease)++ assert [item.name for item in selected.attachments] == [+ "unknown.txt",+ "valid.pdf",+ ]+ assert selected.skipped == ()+ batch.lease.release()+++async def test_memory_im_attach_004_invalid_items_preserve_valid_siblings(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """MEMORY-IM-ATTACH-004: per-item limits/type failures degrade independently."""++ home = tmp_path / "avibe-home"+ batch = await _materialize(+ home,+ [+ ("valid.pdf", "application/pdf", b"%PDF-1.7\nvalid", 14),+ ("video.mp4", "video/mp4", b"\x00\x00\x00\x18ftypmp42", 12),+ ("oversized.txt", "text/plain", b"12345", 20),+ ],+ )+ monkeypatch.setattr(im_attachment_module, "MAX_PINNED_ATTACHMENT_BYTES", 16)++ selected = select_memory_attachments(batch.lease)++ assert [item.name for item in selected.attachments] == ["valid.pdf"]+ assert selected.skipped == ("unsupported_type", "file_too_large")+ store = AttachmentPinStore(effective_home=home)+ bundle = store.pin(selected.attachments, source_lease=batch.lease)+ assert bundle.attachments[0].name == "valid.pdf"+ store.release(bundle.bundle_id)+ batch.lease.release()+ assert list((home / "attachments" / "im").iterdir()) == []+++async def test_memory_selection_checks_magic_and_bundle_limit(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "avibe-home"+ batch = await _materialize(+ home,+ [+ ("fake.png", "image/png", b"not a png", 9),+ ("first.txt", "text/plain", b"123", 3),+ ("second.txt", "text/plain", b"456", 3),+ ],+ )+ monkeypatch.setattr(im_attachment_module, "MAX_PINNED_BUNDLE_BYTES", 4)++ selected = select_memory_attachments(batch.lease)++ assert [item.name for item in selected.attachments] == ["first.txt"]+ assert selected.skipped == ("unsupported_type", "bundle_too_large")+ batch.lease.release()+++async def test_memory_selection_enforces_eight_file_limit(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ batch = await _materialize(+ home,+ [(f"item-{index}.txt", "text/plain", b"x", 1) for index in range(9)],+ )++ selected = select_memory_attachments(batch.lease)++ assert len(selected.attachments) == 8+ assert selected.skipped == ("count_limit",)+ batch.lease.release()+++async def test_memory_selection_counts_only_supported_survivors(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ entries = [+ (f"video-{index}.mp4", "video/mp4", b"\x00\x00\x00\x18ftypmp42", 12)+ for index in range(8)+ ]+ entries.append(("valid.pdf", "application/pdf", b"%PDF-1.7\n", 9))+ batch = await _materialize(home, entries)++ selected = select_memory_attachments(batch.lease)++ assert [item.name for item in selected.attachments] == ["valid.pdf"]+ assert selected.skipped == ("unsupported_type",) * 8+ batch.lease.release()+++async def test_long_materialized_filename_preserves_supported_extension(+ tmp_path: Path,+) -> None:+ home = tmp_path / "avibe-home"+ long_name = f"{'report' * 40}.pdf"+ batch = await _materialize(+ home,+ [(long_name, "application/pdf", b"%PDF-1.7\n", 9)],+ )++ selected = select_memory_attachments(batch.lease)++ assert len(selected.attachments) == 1+ assert selected.attachments[0].name.endswith(".pdf")+ assert len(selected.attachments[0].name.encode("utf-8")) <= 200+ batch.lease.release()+++async def test_pin_rejects_released_or_mismatched_im_lease(tmp_path: Path) -> None:+ first_home = tmp_path / "first-home"+ second_home = tmp_path / "second-home"+ batch = await _materialize(+ first_home,+ [("notes.txt", "text/plain", b"notes", 5)],+ )+ selected = select_memory_attachments(batch.lease)++ with pytest.raises(Exception) as mismatched:+ AttachmentPinStore(effective_home=second_home).pin(+ selected.attachments,+ source_lease=batch.lease,+ )+ assert getattr(mismatched.value, "error", None) == "memory_invalid_input"++ original = selected.attachments[0]+ extra = Path(original.uri.removeprefix("file://")).parent / "extra.txt"+ extra.write_text("extra", encoding="utf-8")+ extra.chmod(0o600)+ forged = CaptureAttachment(+ kind="doc",+ name="extra.txt",+ uri=extra.as_uri(),+ ext="txt",+ )+ with pytest.raises(Exception) as unleased:+ AttachmentPinStore(effective_home=first_home).pin(+ (forged,),+ source_lease=batch.lease,+ )+ assert getattr(unleased.value, "error", None) == "memory_invalid_input"++ batch.lease.release()+ with pytest.raises(Exception) as released:+ AttachmentPinStore(effective_home=first_home).pin(+ selected.attachments,+ source_lease=batch.lease,+ )+ assert getattr(released.value, "error", None) == "memory_invalid_input"+++async def test_pin_reads_original_inode_after_lease_entry_is_replaced(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ batch = await _materialize(+ home,+ [("notes.txt", "text/plain", b"original", 8)],+ )+ selected = select_memory_attachments(batch.lease)+ source = Path(selected.attachments[0].uri.removeprefix("file://"))+ lease_dir = source.parent+ moved = lease_dir.with_name(f"{lease_dir.name}.moved")+ lease_dir.rename(moved)+ lease_dir.mkdir(mode=0o700)+ replacement = lease_dir / source.name+ replacement.write_bytes(b"replacement")+ replacement.chmod(0o600)++ selected_after_replacement = select_memory_attachments(batch.lease)+ assert [item.name for item in selected_after_replacement.attachments] == ["notes.txt"]++ store = AttachmentPinStore(effective_home=home)+ bundle = store.pin(selected_after_replacement.attachments, source_lease=batch.lease)+ pinned = home / "memory" / "attachments" / bundle.attachments[0].storage_key++ assert pinned.read_bytes() == b"original"++ store.release(bundle.bundle_id)+ os.unlink(replacement)+ os.rmdir(lease_dir)+ moved.rename(lease_dir)+ batch.lease.release()+++async def test_pin_rejects_same_inode_same_size_content_replacement(tmp_path: Path) -> None:+ home = tmp_path / "avibe-home"+ batch = await _materialize(+ home,+ [("notes.txt", "text/plain", b"original", 8)],+ )+ selected = select_memory_attachments(batch.lease)+ source = Path(selected.attachments[0].uri.removeprefix("file://"))+ original_inode = source.stat().st_ino+ source.write_bytes(b"tampered")+ source.chmod(0o600)+ assert source.stat().st_ino == original_inode++ with pytest.raises(Exception) as changed:+ AttachmentPinStore(effective_home=home).pin(+ selected.attachments,+ source_lease=batch.lease,+ )++ assert getattr(changed.value, "error", None) == "memory_invalid_input"+ batch.lease.release()diff --git a/tests/test_memory_modality.py b/tests/test_memory_modality.pyindex 840fc3d75..129fe796e 100644--- a/tests/test_memory_modality.py+++ b/tests/test_memory_modality.py@@ -1,4 +1,5 @@import sys+from pathlib import Pathfrom types import ModuleTypeimport pytest@@ -6,11 +7,74 @@ import pytestfrom core.memory.modality import (PINNED_UPSTREAM_EXCLUDED_EXTENSIONS,SUPPORTED_ATTACHMENT_EXTENSIONS,+ classify_pinned_attachment,pinned_modality_contract_matches,pinned_modality_contract_script,)+def _write_private(path: Path, payload: bytes) -> Path:+ path.write_bytes(payload)+ path.chmod(0o600)+ return path+++def test_classifier_accepts_mpeg_2_5_mp3_frame_sync(tmp_path: Path) -> None:+ path = _write_private(tmp_path / "voice.mp3", b"\xff\xe3\x18\x00payload")++ assert classify_pinned_attachment("voice.mp3", "audio/mpeg", path) == (+ "audio",+ "mp3",+ )+++def test_classifier_requires_an_audio_brand_for_m4a(tmp_path: Path) -> None:+ video = _write_private(+ tmp_path / "clip.m4a",+ b"\x00\x00\x00\x10ftypisom\x00\x00\x00\x0cfreeM4A ",+ )+ audio = _write_private(+ tmp_path / "voice.m4a",+ b"\x00\x00\x00\x18ftypisom\x00\x00\x00\x00M4A mp42",+ )++ assert classify_pinned_attachment("clip.m4a", "audio/mp4", video) is None+ assert classify_pinned_attachment("voice.m4a", "audio/mp4", audio) == (+ "audio",+ "m4a",+ )+++def test_classifier_accepts_utf8_sample_with_incomplete_trailing_codepoint(+ tmp_path: Path,+) -> None:+ path = _write_private(tmp_path / "notes.txt", b"a" * (64 * 1024 - 1) + "你".encode())++ assert classify_pinned_attachment("notes.txt", "text/plain", path) == (+ "doc",+ "txt",+ )+++def test_classifier_still_rejects_invalid_utf8_inside_sample(tmp_path: Path) -> None:+ path = _write_private(tmp_path / "notes.txt", b"valid\xffinvalid")++ assert classify_pinned_attachment("notes.txt", "text/plain", path) is None++[email protected]("tail", [b"\x00", b"\xff"], ids=["nul", "invalid-utf8"])+def test_classifier_validates_complete_text_file(tmp_path: Path, tail: bytes) -> None:+ path = _write_private(tmp_path / "notes.txt", b"a" * 4096 + tail)++ assert classify_pinned_attachment("notes.txt", "text/plain", path) is None+++def test_classifier_normalizes_missing_mime_to_octet_stream(tmp_path: Path) -> None:+ path = _write_private(tmp_path / "notes.txt", b"valid text")++ assert classify_pinned_attachment("notes.txt", None, path) == ("doc", "txt")++def test_pinned_modality_contract_allows_exact_upstream_set_minus_exclusions() -> None:upstream = SUPPORTED_ATTACHMENT_EXTENSIONS | PINNED_UPSTREAM_EXCLUDED_EXTENSIONSdiff --git a/tests/test_memory_sidecar.py b/tests/test_memory_sidecar.pyindex 2106ac001..b31c4dca8 100644--- a/tests/test_memory_sidecar.py+++ b/tests/test_memory_sidecar.py@@ -600,7 +600,7 @@ def test_sidecar_guard_keeps_profile_exact_and_allows_only_bounded_episode_lists)-def test_sidecar_guard_allows_workbench_attachment_file_uri_only(tmp_path: Path) -> None:+def test_sidecar_guard_allows_pinned_attachment_file_uri_only(tmp_path: Path) -> None:attachments_root = tmp_path / "attachments" / "avibe"asset = attachments_root / "session-1" / "diagram.png"asset.parent.mkdir(parents=True)diff --git a/tests/test_message_handler_attachments.py b/tests/test_message_handler_attachments.pyindex ebcd149a7..5bd459e39 100644--- a/tests/test_message_handler_attachments.py+++ b/tests/test_message_handler_attachments.py@@ -127,7 +127,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):context = MessageContext(user_id="U1", channel_id="C1", thread_id="T1", files=[attachment])with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):processed, errors = await handler._process_file_attachments(context, "/tmp/work")self.assertIsNotNone(processed)@@ -152,7 +152,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):context = MessageContext(user_id="U1", channel_id="C1", files=[attachment])with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):processed, errors = await handler._process_file_attachments(context, "/tmp/work")self.assertIsNotNone(processed)@@ -178,7 +178,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):with tempfile.TemporaryDirectory() as tmpdir:attachments_dir = Path(tmpdir) / "C1"- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):processed, errors = await handler._process_file_attachments(context, "/tmp/work")residual_files = list(attachments_dir.glob("*")) if attachments_dir.exists() else []@@ -186,7 +186,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(processed)self.assertEqual(errors,- ["Attachment 'blocked.pdf' could not be downloaded: Download failed with HTTP 403"],+ ["Attachment 'blocked.pdf' could not be downloaded."],)self.assertEqual(residual_files, [])@@ -204,7 +204,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):context = MessageContext(user_id="U1", channel_id="C1", files=[attachment])with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):processed, errors = await handler._process_file_attachments(context, "/tmp/work")self.assertIsNotNone(processed)@@ -227,7 +227,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):context = MessageContext(user_id="U1", channel_id="C1", platform="slack", files=[attachment])with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):processed, errors = await handler._process_file_attachments(context, "/tmp/work")self.assertIsNotNone(processed)@@ -253,7 +253,7 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):context = MessageContext(user_id="U1", channel_id="C1", platform="slack", files=[attachment])with tempfile.TemporaryDirectory() as tmpdir:- with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir).resolve()):processed, errors = await handler._process_file_attachments(context, "/tmp/work")self.assertIsNotNone(processed)@@ -275,5 +275,19 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):self.assertIn("Download failed with HTTP 403", message)self.assertNotIn("/.vibe_remote/attachments/", message)+ def test_append_attachment_errors_localizes_the_entire_display_block(self):+ controller = _StubController(_StubIMClient())+ controller.config.language = "zh"+ handler = MessageHandler(controller)++ message = handler._append_attachment_errors(+ "请检查附件",+ ["无法下载附件“blocked.pdf”。"],+ )++ self.assertIn("[附件下载错误]", message)+ self.assertIn("无法下载附件“blocked.pdf”。", message)+ self.assertNotIn("Attachment Download Errors", message)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex bd820c2f8..30ffa4bd2 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -390,7 +390,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())handler._is_duplicate_human_delivery = Mock(return_value=True)- handler._process_file_attachments = AsyncMock()+ handler._materialize_file_attachments = AsyncMock()context = MessageContext(user_id="U1",channel_id="C1",@@ -407,10 +407,104 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):await handler.handle_user_message(context, "review this")- handler._process_file_attachments.assert_not_awaited()+ handler._materialize_file_attachments.assert_not_awaited()controller.session_turns.deliver.assert_not_awaited()self.assertEqual(controller.agent_service.requests, [])+ async def test_durable_attachment_lease_stays_active_until_admission_owns_it(self):+ from modules.im.base import FileAttachment++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ lease = Mock()+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )++ async def admit(**kwargs):+ self.assertIs(kwargs["attachment_lease"], lease)+ lease.adopt.assert_not_called()+ lease.release.assert_not_called()+ lease.adopt()+ lease.release()+ return True++ handler._admit_human_delivery = AsyncMock(side_effect=admit)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-attachment",+ platform="slack",+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ )++ await handler.handle_user_message(context, "review this")++ lease.adopt.assert_called_once_with()+ lease.release.assert_called_once_with()++ async def test_failed_durable_admission_releases_unowned_attachment_lease(self):+ from modules.im.base import FileAttachment++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="review this")+ handler._emit_agent_dispatch_failure = AsyncMock()+ lease = Mock()+ attachment = FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ local_path="/tmp/leased-report.pdf",+ size=10,+ )+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(attachment,),+ display_errors=(),+ lease=lease,+ )+ )+ handler._admit_human_delivery = AsyncMock(+ side_effect=RuntimeError("admission rejected")+ )+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-rejected-attachment",+ platform="slack",+ files=[FileAttachment("report.pdf", "application/pdf", url="private")],+ )++ await handler.handle_user_message(context, "review this")++ lease.adopt.assert_not_called()+ lease.release.assert_called_once_with()+async def test_inline_stop_uses_durable_empty_p0_owner(self):controller = _StubController(platform="slack",@@ -1503,8 +1597,13 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())handler._build_current_time_line = lambda: "[Current Time: 2026-07-26 16:00:00 UTC+08:00]"- handler._process_file_attachments = AsyncMock(- return_value=([object()], ["report.pdf could not be downloaded"])+ attachment_lease = Mock()+ handler._materialize_file_attachments = AsyncMock(+ return_value=types.SimpleNamespace(+ attachments=(object(),),+ display_errors=("report.pdf could not be downloaded",),+ lease=attachment_lease,+ ))handler._transcribe_audio_attachments = AsyncMock(return_value=[diff --git a/tests/test_telegram_attachment_download.py b/tests/test_telegram_attachment_download.pynew file mode 100644index 000000000..46c5e8310--- /dev/null+++ b/tests/test_telegram_attachment_download.py@@ -0,0 +1,240 @@+from __future__ import annotations++import os+from pathlib import Path+from unittest.mock import AsyncMock++import pytest++from config.v2_config import TelegramConfig+from modules.im import telegram_api+from modules.im.telegram import TelegramBot+++class _Content:+ def __init__(self, chunks: list[bytes]) -> None:+ self._chunks = chunks++ async def iter_chunked(self, _size: int):+ for chunk in self._chunks:+ yield chunk+++class _Response:+ def __init__(self, chunks: list[bytes], content_length: int | None = None) -> None:+ self.content = _Content(chunks)+ self.headers = {}+ if content_length is not None:+ self.headers["Content-Length"] = str(content_length)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ def raise_for_status(self) -> None:+ return None+++class _Session:+ def __init__(self, response: _Response) -> None:+ self.response = response++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ def get(self, _url: str):+ return self.response+++async def test_telegram_api_streams_to_disk_and_removes_midstream_overflow(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ target = tmp_path / "telegram.bin"+ response = _Response([b"123", b"456"])+ monkeypatch.setattr(+ telegram_api.aiohttp,+ "ClientSession",+ lambda **_kwargs: _Session(response),+ )++ with pytest.raises(telegram_api.TelegramFileTooLargeError, match="max_bytes"):+ await telegram_api.download_file_to_path(+ "token",+ "documents/file.bin",+ target,+ max_bytes=5,+ )++ assert not target.exists()+++async def test_telegram_api_rejects_response_header_before_writing(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ target = tmp_path / "telegram.bin"+ response = _Response([b"never-written"], content_length=6)+ monkeypatch.setattr(+ telegram_api.aiohttp,+ "ClientSession",+ lambda **_kwargs: _Session(response),+ )++ with pytest.raises(telegram_api.TelegramFileTooLargeError, match="max_bytes"):+ await telegram_api.download_file_to_path(+ "token",+ "documents/file.bin",+ target,+ max_bytes=5,+ )++ assert not target.exists()+++async def test_telegram_api_writes_through_caller_owned_descriptor(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ anchored = tmp_path / "anchored.bin"+ decoy = tmp_path / "decoy.bin"+ descriptor = os.open(anchored, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o600)+ response = _Response([b"anchored"])+ monkeypatch.setattr(+ telegram_api.aiohttp,+ "ClientSession",+ lambda **_kwargs: _Session(response),+ )++ try:+ await telegram_api.download_file_to_path(+ "token",+ "documents/file.bin",+ decoy,+ target_fd=descriptor,+ )+ finally:+ os.close(descriptor)++ assert anchored.read_bytes() == b"anchored"+ assert not decoy.exists()+++async def test_telegram_adapter_checks_declared_size_before_bot_api(monkeypatch, tmp_path: Path) -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ get_file = AsyncMock()+ monkeypatch.setattr(telegram_api, "get_file", get_file)++ result = await bot.download_file_to_path(+ {"url": "file-id", "size": 6},+ str(tmp_path / "file.bin"),+ max_bytes=5,+ )++ assert result.success is False+ assert result.error == "File exceeds max_bytes"+ assert result.failure_reason == "file_too_large"+ get_file.assert_not_awaited()+++async def test_telegram_adapter_streams_resolved_file_with_bound(monkeypatch, tmp_path: Path) -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ monkeypatch.setattr(+ telegram_api,+ "get_file",+ AsyncMock(return_value={"result": {"file_path": "docs/file.pdf", "file_size": 5}}),+ )+ stream = AsyncMock(return_value=5)+ monkeypatch.setattr(telegram_api, "download_file_to_path", stream)+ target = tmp_path / "file.pdf"++ result = await bot.download_file_to_path(+ {"url": "file-id", "size": 5},+ str(target),+ max_bytes=5,+ timeout_seconds=17,+ )++ assert result.success is True+ stream.assert_awaited_once_with(+ "123456:test-token",+ "docs/file.pdf",+ target,+ max_bytes=5,+ timeout_seconds=17,+ proxy_url=bot._proxy_url,+ )+++async def test_telegram_adapter_does_not_classify_unrelated_value_error_as_overflow(+ monkeypatch,+ tmp_path: Path,+) -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ monkeypatch.setattr(+ telegram_api,+ "get_file",+ AsyncMock(return_value={"result": {"file_path": "docs/file.pdf"}}),+ )+ monkeypatch.setattr(+ telegram_api,+ "download_file_to_path",+ AsyncMock(side_effect=ValueError("malformed proxy or file URL")),+ )+ target = tmp_path / "file.pdf"++ result = await bot.download_file_to_path(+ {"url": "file-id"},+ str(target),+ max_bytes=None,+ )++ assert result.success is False+ assert result.error == "Telegram file download failed"+ assert result.failure_reason is None+ assert not target.exists()+++async def test_telegram_adapter_preserves_streaming_overflow_reason(+ monkeypatch,+ tmp_path: Path,+) -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ monkeypatch.setattr(+ telegram_api,+ "get_file",+ AsyncMock(return_value={"result": {"file_path": "docs/file.pdf"}}),+ )+ monkeypatch.setattr(+ telegram_api,+ "download_file_to_path",+ AsyncMock(+ side_effect=telegram_api.TelegramFileTooLargeError(+ "Downloaded file exceeds max_bytes"+ )+ ),+ )+ target = tmp_path / "file.pdf"++ result = await bot.download_file_to_path(+ {"url": "file-id"},+ str(target),+ max_bytes=5,+ )++ assert result.success is False+ assert result.error == "File exceeds max_bytes"+ assert result.failure_reason == "file_too_large"+ assert not target.exists()diff --git a/tests/test_wechat_attachment_download.py b/tests/test_wechat_attachment_download.pynew file mode 100644index 000000000..a79066767--- /dev/null+++ b/tests/test_wechat_attachment_download.py@@ -0,0 +1,219 @@+from __future__ import annotations++from pathlib import Path++import pytest++from config.v2_config import WeChatConfig+from modules.im import wechat_cdn+from modules.im.wechat import WeChatBot, wechat_cdn as wechat_cdn_client+++class _Content:+ def __init__(self, chunks: list[bytes]) -> None:+ self._chunks = chunks++ async def iter_chunked(self, _size: int):+ for chunk in self._chunks:+ yield chunk+++class _Response:+ ok = True+ status = 200+ reason = "OK"++ def __init__(self, chunks: list[bytes], content_length: int | None = None) -> None:+ self.content = _Content(chunks)+ self.headers = {}+ if content_length is not None:+ self.headers["Content-Length"] = str(content_length)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None+++class _Session:+ def __init__(self, response: _Response) -> None:+ self.response = response++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ def get(self, _url: str):+ return self.response+++async def test_wechat_decrypts_incrementally_to_bounded_path(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ key = b"0123456789abcdef"+ plaintext = b"bounded plaintext"+ encrypted = wechat_cdn.aes_ecb_encrypt(plaintext, key)+ response = _Response([encrypted[:7], encrypted[7:]])+ monkeypatch.setattr(+ wechat_cdn.aiohttp,+ "ClientSession",+ lambda **_kwargs: _Session(response),+ )+ target = tmp_path / "wechat.bin"++ size = await wechat_cdn.download_and_decrypt_to_path(+ "https://cdn.example.test",+ "opaque-query",+ "MDEyMzQ1Njc4OWFiY2RlZg==",+ target,+ max_bytes=len(plaintext),+ timeout_seconds=11,+ )++ assert size == len(plaintext)+ assert target.read_bytes() == plaintext+++async def test_wechat_decrypt_removes_partial_plaintext_on_final_overflow(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ key = b"0123456789abcdef"+ encrypted = wechat_cdn.aes_ecb_encrypt(b"123456789", key)+ response = _Response([encrypted])+ monkeypatch.setattr(+ wechat_cdn.aiohttp,+ "ClientSession",+ lambda **_kwargs: _Session(response),+ )+ target = tmp_path / "wechat.bin"++ with pytest.raises(ValueError, match="max_bytes"):+ await wechat_cdn.download_and_decrypt_to_path(+ "https://cdn.example.test",+ "opaque-query",+ "MDEyMzQ1Njc4OWFiY2RlZg==",+ target,+ max_bytes=8,+ )++ assert not target.exists()+++async def test_wechat_decrypt_rejects_ciphertext_header_before_writing(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ response = _Response([b"never-written"], content_length=33)+ monkeypatch.setattr(+ wechat_cdn.aiohttp,+ "ClientSession",+ lambda **_kwargs: _Session(response),+ )+ target = tmp_path / "wechat.bin"++ with pytest.raises(ValueError, match="max_bytes"):+ await wechat_cdn.download_and_decrypt_to_path(+ "https://cdn.example.test",+ "opaque-query",+ "MDEyMzQ1Njc4OWFiY2RlZg==",+ target,+ max_bytes=16,+ )++ assert not target.exists()+++async def test_wechat_adapter_rejects_declared_plaintext_before_acquisition(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ bot = WeChatBot(WeChatConfig(bot_token="test-token"))+ called = False++ async def acquire(*_args, **_kwargs):+ nonlocal called+ called = True+ return True++ monkeypatch.setattr(wechat_cdn_client, "download_and_decrypt", acquire)++ result = await bot.download_file_to_path(+ {+ "url": "opaque-query",+ "size": 9,+ "cdn_info": {"aes_key": "key"},+ },+ str(tmp_path / "wechat.bin"),+ max_bytes=8,+ )++ assert result.success is False+ assert result.error == "File exceeds max_bytes"+ assert result.failure_reason == "file_too_large"+ assert called is False++[email protected]("declared_field", ["mid_size", "video_size"])+async def test_wechat_adapter_rejects_native_declared_ciphertext_before_acquisition(+ declared_field: str,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ bot = WeChatBot(WeChatConfig(bot_token="test-token"))+ called = False++ async def acquire(*_args, **_kwargs):+ nonlocal called+ called = True+ return True++ monkeypatch.setattr(wechat_cdn_client, "download_and_decrypt", acquire)++ result = await bot.download_file_to_path(+ {+ "url": "opaque-query",+ "wechat_item": {declared_field: "33"},+ },+ str(tmp_path / "wechat.bin"),+ max_bytes=16,+ )++ assert result.success is False+ assert result.failure_reason == "file_too_large"+ assert called is False+++async def test_wechat_adapter_preserves_streamed_plaintext_overflow_reason(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ bot = WeChatBot(WeChatConfig(bot_token="test-token"))++ async def overflow(*_args, **_kwargs):+ raise ValueError("Downloaded file exceeds max_bytes")++ monkeypatch.setattr(wechat_cdn, "download_and_decrypt_to_path", overflow)++ result = await bot.download_file_to_path(+ {+ "url": "opaque-query",+ "cdn_info": {"aes_key": "MDEyMzQ1Njc4OWFiY2RlZg=="},+ },+ str(tmp_path / "wechat.bin"),+ max_bytes=8,+ )++ assert result.success is False+ assert result.failure_reason == "file_too_large"+ assert not (tmp_path / "wechat.bin").exists()diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.pyindex e8cfdd89c..48b26bab5 100644--- a/tests/test_wechat_bot.py+++ b/tests/test_wechat_bot.py@@ -756,8 +756,13 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):with tempfile.TemporaryDirectory() as tmpdir:target_path = str(Path(tmpdir) / "wechat-test-image.bin")+ async def download_to_path(_base, _query, _key, target, **_kwargs):+ Path(target).write_bytes(b"img")+ return 3+with patch(- "modules.im.wechat._wechat_cdn_mod.download_and_decrypt", new=AsyncMock(return_value=b"img")+ "modules.im.wechat._wechat_cdn_mod.download_and_decrypt_to_path",+ new=AsyncMock(side_effect=download_to_path),) as mock_dl:result = await bot.download_file_to_path(file_info, target_path)@@ -767,6 +772,7 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(args[0], "https://novac2c.cdn.weixin.qq.com/c2c")self.assertEqual(args[1], "encrypted-param")self.assertTrue(isinstance(args[2], str) and len(args[2]) > 0)+ self.assertEqual(args[3], Path(target_path))async def test_download_file_to_path_uses_voice_media_aes_key(self):bot = self._make_bot()@@ -780,16 +786,26 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):with tempfile.TemporaryDirectory() as tmpdir:target_path = str(Path(tmpdir) / "wechat-test-voice.bin")+ async def download_to_path(_base, _query, _key, target, **_kwargs):+ Path(target).write_bytes(b"voice")+ return 5+with patch(- "modules.im.wechat._wechat_cdn_mod.download_and_decrypt", new=AsyncMock(return_value=b"voice")+ "modules.im.wechat._wechat_cdn_mod.download_and_decrypt_to_path",+ new=AsyncMock(side_effect=download_to_path),) as mock_dl:result = await bot.download_file_to_path(file_info, target_path)self.assertTrue(result.success)- mock_dl.assert_awaited_once_with(- "https://novac2c.cdn.weixin.qq.com/c2c",- "voice-param",- "dm9pY2Uta2V5",+ args = mock_dl.await_args.args # type: ignore[union-attr]+ self.assertEqual(+ args,+ (+ "https://novac2c.cdn.weixin.qq.com/c2c",+ "voice-param",+ "dm9pY2Uta2V5",+ Path(target_path),+ ),)async def test_upload_image_from_path_uses_cdn_workflow(self):diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 0ca64002c..265e0515a 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -271,6 +271,11 @@"invalid_upload": "The file upload is invalid.","upload_failed": "The file could not be saved. Please try again."},+ "attachmentDownload": {+ "title": "Attachment Download Errors",+ "failed": "Attachment '{name}' could not be downloaded.",+ "tooLarge": "Attachment '{name}' exceeds the attachment size limit."+ },"agentArchive": {"agent_builtin": {"message": "Agent `{agent}` is built in and cannot be deleted.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 253cdbee4..744b4c619 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -271,6 +271,11 @@"invalid_upload": "文件上传请求无效。","upload_failed": "文件保存失败,请重试。"},+ "attachmentDownload": {+ "title": "附件下载错误",+ "failed": "无法下载附件“{name}”。",+ "tooLarge": "附件“{name}”超过附件大小限制。"+ },"agentArchive": {"agent_builtin": {"message": "Agent `{agent}` 是内置 Agent,无法删除。",