diff --git a/app/agent/tools/impl/send_local_file.py b/app/agent/tools/impl/send_local_file.py index 54f9f06fd..3905c578d 100644 --- a/app/agent/tools/impl/send_local_file.py +++ b/app/agent/tools/impl/send_local_file.py @@ -9,6 +9,7 @@ from pydantic import BaseModel, Field, model_validator from app.agent.tools.base import MoviePilotTool from app.agent.tools.tags import ToolTag +from app.application.notification import get_notification_configs from app.runtime.log import logger from app.schemas.message import Message from app.schemas.notification import ChannelCapability, ChannelCapabilityManager @@ -121,6 +122,14 @@ class SendLocalFileTool(MoviePilotTool): ): return f"当前渠道 {channel.value} 暂不支持发送本地文件" + if channel == NotificationChannel.Wechat: + configs = await self.run_blocking("config", get_notification_configs) + if not any( + config.name == self._source and (config.config or {}).get("WECHAT_MODE", "app") != "bot" + for config in configs + ): + return "企业微信仅自建应用模式支持发送本地文件,请检查当前通知实例" + resolved_path = Path(file_path).expanduser() if not resolved_path.is_absolute(): resolved_path = resolved_path.resolve() diff --git a/app/modules/wechat/__init__.py b/app/modules/wechat/__init__.py index c9664e6ed..31f3c2005 100644 --- a/app/modules/wechat/__init__.py +++ b/app/modules/wechat/__init__.py @@ -335,9 +335,9 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): def post_message(self, message: Message, **kwargs: object) -> None: """ - 向符合通知规则的实例发送文本、图文、原生图片或语音。 + 向符合通知规则的实例发送文本、图文、原生图片、文件或语音。 - :param message: 通知内容及接收对象;语音发送失败时回退到文本或图文 + :param message: 通知内容及接收对象;文件优先于图片和语音,语音发送失败时回退到文本或图文 :param kwargs: 兼容模块分发的附加参数,当前不使用 """ for conf in self.get_configs().values(): @@ -347,6 +347,13 @@ class WechatModule(_MessageChannelModuleBase[WeChat | WeChatBot]): client = self.get_instance(conf.name) if client: text = message.channel_text(NotificationChannel.Wechat, conf.config) or message.text + if message.file_path: + if isinstance(client, WeChat): + client.send_file(file_path=message.file_path, file_name=message.file_name, + title=message.title, text=text, userid=userid) + else: + logger.warning("企业微信机器人模式暂不支持发送本地文件") + continue if message.native_image and message.image and isinstance(client, WeChat): client.send_msg(title=message.title, text=text, image=message.image, userid=userid, link=message.link, native_image=True) diff --git a/app/modules/wechat/wechat.py b/app/modules/wechat/wechat.py index 568cdcea6..c105d4f0e 100644 --- a/app/modules/wechat/wechat.py +++ b/app/modules/wechat/wechat.py @@ -24,6 +24,8 @@ lock = threading.Lock() # 企业微信临时图片素材上限为 10 MiB,仅接受 JPG、PNG。 _IMAGE_MAX_BYTES = 10 * 1024 * 1024 +# 企业微信普通文件素材上限为 20 MiB,不限制文件扩展名。 +_FILE_MAX_BYTES = 20 * 1024 * 1024 class RetryException(Exception): @@ -554,7 +556,7 @@ class WeChat: 上传临时素材并取得企业微信媒体标识。 :param media_path: 本地素材路径;传入 content 时仅使用文件名,不读取磁盘 - :param media_type: 企业微信素材类型,默认 voice + :param media_type: 企业微信素材类型,支持 voice、image 和 file,默认 voice :param content: 可直接上传的素材字节;为空时从 media_path 读取,保留语音调用兼容性 :return: 上传成功的 media_id;读取、请求或响应解析失败返回 None """ @@ -606,6 +608,43 @@ class WeChat: media_id = ret_json.get("media_id") return media_id if isinstance(media_id, str) else None + def send_file(self, file_path: str, file_name: Optional[str] = None, title: Optional[str] = None, + text: Optional[str] = None, userid: Optional[str] = None) -> Optional[bool]: + """ + 上传并发送普通文件,保留调用方文件且不回退为下载链接。 + + :param file_path: 本地文件路径,支持展开用户目录;内容须大于 5 字节且不超过 20 MiB + :param file_name: 接收端显示的文件名;为空时使用源文件名,仅保留名称部分 + :param title: 可选的说明标题,随正文独立发送为文本 + :param text: 可选的说明正文 + :param userid: 企业微信用户标识;为空时发送给全体应用成员 + :return: 文件及说明文字均成功时返回 True;失败返回 False;无访问令牌返回 None + """ + try: + if not self.__get_access_token(): + logger.error("获取微信access_token失败,请检查参数配置") + return None + source = Path(file_path).expanduser() + with source.open("rb") as media_file: + content = media_file.read(_FILE_MAX_BYTES + 1) + if not 5 < len(content) <= _FILE_MAX_BYTES: + logger.error("企业微信文件必须大于 5 字节且不超过 20MB") + return False + media_id = self._upload_temp_media(Path(file_name or source.name), media_type="file", content=content) + if not media_id: + return False + if (title or text) and not self.__send_message(title=title, text=text, userid=userid): + return False + return self.__post_request(self._send_msg_url, { + "touser": userid or "@all", + "msgtype": "file", + "agentid": self._appid, + "file": {"media_id": media_id}, + }) + except Exception as err: + logger.error(f"发送企业微信文件消息失败:{err}") + return False + def send_voice(self, voice_path: str, userid: Optional[str] = None) -> Optional[bool]: """ 转换并上传语音,然后通过自建应用发送。 diff --git a/app/schemas/notification.py b/app/schemas/notification.py index 7f2e936a9..e43d8b02c 100644 --- a/app/schemas/notification.py +++ b/app/schemas/notification.py @@ -156,6 +156,7 @@ class ChannelCapabilityManager: ChannelCapability.LINKS, ChannelCapability.AUDIO_OUTPUT, ChannelCapability.MENU_COMMANDS, + ChannelCapability.FILE_SENDING, }, fallback_enabled=True, ), diff --git a/app/sdk/plugin/base.py b/app/sdk/plugin/base.py index e78c108b7..791e1ce14 100644 --- a/app/sdk/plugin/base.py +++ b/app/sdk/plugin/base.py @@ -433,6 +433,7 @@ class _PluginBase(metaclass=ABCMeta): :param kwargs: 可传 rich_content 通用结构化通知;宿主按渠道能力排版,text 保留为纯文本回退。 传 native_image=True 可让企业微信自建应用发送完整原图,默认仍发送图文卡片。 + 传 file_path 和可选 file_name 可发送本地附件,企业微信自建应用上限为 20 MiB。 """ if not link: link = settings.MP_DOMAIN(f"#/plugins?tab=installed&id={self.__class__.__name__}") diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index 5474652fb..f04a179af 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -851,7 +851,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1185 | -| 内部导入边 | 10,380 | +| 内部导入边 | 10,382 | | 非平凡 SCC | 1(29 个模块的 TMDB vendor 精确 containment) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 52(精确 policy 准入,Application / Chain 均为 0;本知识 Adapter 仍复用宿主 HTTP 层) | diff --git a/docs/mcp-api.md b/docs/mcp-api.md index 9f0172017..ec3f0ed16 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -321,6 +321,12 @@ Web 会话沿用当前用户;无渠道调用不携带收件人,插件回执 下载、上传或发送失败会记录错误,不回退为图文卡片。省略开关时仍使用图文,机器人模式和其他渠道 保持原有行为;此开关不改变通知权限与收件人路由。 +企业微信自建应用还支持 `post_message(file_path=..., file_name=...)`,复用通用附件字段, +以 `msgtype=file` 发送大于 5 字节且不超过 20 MiB 的本地文件。`file_name` 可省略,默认使用源文件名; +有说明文字时另发文本,发送过程不删除源文件。显式附件优先于图片和语音;机器人模式暂不支持文件。 +Agent 的 `send_local_file` 也仅在企业微信自建应用实例开放该能力。微信插件端需先关注并开启接收应用消息, +应用管理端不要勾选“在微工作台中始终进入主页”;实际微信端展示仍需在用户账号上验证。 + `POST /api/v1/notification/config` 保存通知渠道时要求名称和稳定 `id` 各自唯一。 改名应保留原 `id`;复制为新的渠道实例应使用新的 `id`,避免共享登录凭据。 通过消息渠道发起普通重启时,完成回执保留发起时的 `source` 配置。 diff --git a/skills/create-moviepilot-plugin/SKILL.md b/skills/create-moviepilot-plugin/SKILL.md index 3752b8f9e..6b4a693a9 100644 --- a/skills/create-moviepilot-plugin/SKILL.md +++ b/skills/create-moviepilot-plugin/SKILL.md @@ -378,6 +378,10 @@ Use only the extension points the requested plugin actually needs: the link (including the default plugin-page link) is ignored. Images must be larger than 5 bytes and at most 10 MiB. The default remains a news card; other channels and WeCom bot mode keep their existing behavior. + WeCom custom applications also support local attachments through + `file_path=, file_name=` (larger than + 5 bytes, at most 20 MiB). Attachments take precedence over image/voice fields; + the source file is preserved, and bot mode does not support file sending. - APIs: return route definitions from `get_api()`; default auth is `apikey` when `auth` is omitted. Vue component APIs should normally use `auth: "bear"` and be called through the `api` prop passed by the frontend. diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 6151a65b4..82652746b 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -977,8 +977,8 @@ "runtime_only": true } }, - "edge_count": 10380, - "edge_sha256": "0edac718288e68fe94c78516a09d0b1ebf645892a90ce90f386c4e1cd6028e6c", + "edge_count": 10382, + "edge_sha256": "8c9c2816006ccbb7ed004a2fa4296447f4a300cbda8755150cb4312bd4dffe27", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -2177,6 +2177,8 @@ "app.agent.tools.impl.send_local_file -> app.agent.tools", "app.agent.tools.impl.send_local_file -> app.agent.tools.base", "app.agent.tools.impl.send_local_file -> app.agent.tools.tags", + "app.agent.tools.impl.send_local_file -> app.application", + "app.agent.tools.impl.send_local_file -> app.application.notification", "app.agent.tools.impl.send_local_file -> app.runtime", "app.agent.tools.impl.send_local_file -> app.runtime.log", "app.agent.tools.impl.send_local_file -> app.schemas", diff --git a/tests/test_wechat_file_message.py b/tests/test_wechat_file_message.py new file mode 100644 index 000000000..1e479fc3a --- /dev/null +++ b/tests/test_wechat_file_message.py @@ -0,0 +1,288 @@ +""" +验证企业微信普通文件上传、通知路由和 Agent 按实例模式开放附件能力。 +""" + +import asyncio +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from app.agent.tools.impl import send_local_file as file_tool +from app.agent.tools.impl.send_local_file import SendLocalFileTool +from app.modules.wechat import WechatModule +from app.modules.wechat import wechat as wechat_client +from app.modules.wechat.wechat import WeChat +from app.modules.wechat.wechatbot import WeChatBot +from app.schemas.message import Message +from app.schemas.notification import ChannelCapability, ChannelCapabilityManager +from app.schemas.types import NotificationChannel +from app.sdk.plugin import base as plugin_base +from app.sdk.plugin.base import _PluginBase + + +@pytest.fixture +def http(monkeypatch: pytest.MonkeyPatch) -> Mock: + """ + 隔离上传和消息发送接口,默认返回成功且不发起真实请求。 + """ + request_utils = Mock() + transport = request_utils.return_value + transport.request.return_value.json.return_value = {"errcode": 0, "media_id": "file-media"} + transport.post.return_value.status_code = 200 + transport.post.return_value.json.return_value = {"errcode": 0} + monkeypatch.setattr(wechat_client, "RequestUtils", request_utils) + return transport + + +@pytest.fixture +def client(monkeypatch: pytest.MonkeyPatch) -> WeChat: + """ + 创建固定令牌的应用客户端,跳过构造时的网络访问。 + """ + result = WeChat.__new__(WeChat) + result._appid = "1000002" + result._send_msg_url = "https://wecom.example/message/send?access_token={access_token}" + result._upload_media_url = "https://wecom.example/media/upload?access_token={access_token}&type={media_type}" + monkeypatch.setattr(result, "_WeChat__get_access_token", Mock(return_value="access-token")) + return result + + +@pytest.fixture +def attachment(tmp_path: Path) -> Path: + """ + 创建需要在发送成败后完整保留的字幕文件。 + """ + source = tmp_path / "电影字幕.srt" + source.write_bytes(b"1\n00:00:01,000 --> 00:00:02,000\nsubtitle\n") + return source + + +def _payloads(http: Mock) -> list[dict]: + """ + 按请求顺序解码实际发送的 JSON 字节。 + """ + return [json.loads(call.kwargs["data"]) for call in http.post.call_args_list] + + +@pytest.mark.parametrize("userid", [None, "member-1"]) +@pytest.mark.parametrize("file_name", [None, "展示名称.srt", "../字幕.srt"]) +def test_upload_and_send_file_preserves_source_and_display_name( + client: WeChat, http: Mock, attachment: Path, userid: str | None, file_name: str | None, +) -> None: + """ + 上传原始文件内容及展示名称,并分别发送说明文字与文件,不删除源文件。 + """ + content = attachment.read_bytes() + + assert client.send_file(str(attachment), file_name=file_name, title="字幕", text="请下载查看", userid=userid) is True + + upload = http.request.call_args.kwargs + assert upload["url"] == "https://wecom.example/media/upload?access_token=access-token&type=file" + assert upload["files"] == { + "media": (Path(file_name or attachment.name).name, content, "application/octet-stream"), + } + sent = _payloads(http) + assert [payload["msgtype"] for payload in sent] == ["text", "file"] + assert "字幕" in sent[0]["text"]["content"] + assert "请下载查看" in sent[0]["text"]["content"] + assert sent[1] == { + "touser": userid or "@all", "msgtype": "file", "agentid": "1000002", + "file": {"media_id": "file-media"}, + } + assert attachment.read_bytes() == content + + +def test_file_without_caption_sends_single_message(client: WeChat, http: Mock, attachment: Path) -> None: + """ + 纯附件通知只发送文件,不产生空文本。 + """ + assert client.send_file(str(attachment)) is True + assert [payload["msgtype"] for payload in _payloads(http)] == ["file"] + + +@pytest.mark.parametrize("size, accepted", [(0, False), (5, False), (6, True), (16, True), (17, False)]) +def test_file_size_boundary_is_enforced_before_upload( + client: WeChat, http: Mock, attachment: Path, monkeypatch: pytest.MonkeyPatch, size: int, accepted: bool, +) -> None: + """ + 小于等于 5 字节和超过上限的文件均在上传前拒绝,大小边界内允许发送。 + """ + monkeypatch.setattr(wechat_client, "_FILE_MAX_BYTES", 16) + attachment.write_bytes(b"x" * size) + + assert client.send_file(str(attachment)) is accepted + assert http.request.called is accepted + assert http.post.called is accepted + assert attachment.read_bytes() == b"x" * size + + +@pytest.mark.parametrize("source", ["missing.srt", "."]) +def test_unreadable_file_does_not_upload( + client: WeChat, http: Mock, tmp_path: Path, source: str, +) -> None: + """ + 文件缺失或传入目录时返回失败,不继续上传或发消息。 + """ + assert client.send_file(str(tmp_path / source)) is False + http.request.assert_not_called() + http.post.assert_not_called() + + +@pytest.mark.parametrize("payload", [{"errcode": 40005}, {"errcode": 0}, {"errcode": 0, "media_id": 1}]) +def test_failed_upload_preserves_file_without_sending_caption( + client: WeChat, http: Mock, attachment: Path, payload: dict, +) -> None: + """ + 上传失败或缺少合法素材 ID 时不发说明文字,且保留源文件。 + """ + content = attachment.read_bytes() + http.request.return_value.json.return_value = payload + + assert client.send_file(str(attachment), title="附件") is False + http.post.assert_not_called() + assert attachment.read_bytes() == content + + +@pytest.mark.parametrize("title", [None, "附件"]) +def test_rejected_message_returns_failure_and_preserves_file( + client: WeChat, http: Mock, attachment: Path, title: str | None, +) -> None: + """ + 文件消息或说明文字被拒绝时返回失败,不能删除源文件或当作成功。 + """ + http.post.return_value.json.return_value = {"errcode": 40003} + + assert client.send_file(str(attachment), title=title) is False + assert len(_payloads(http)) == 1 + assert attachment.exists() + + +def test_missing_token_does_not_read_file( + client: WeChat, http: Mock, attachment: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 无访问令牌时保留既有空返回值,不读取文件或上传。 + """ + monkeypatch.setattr(client, "_WeChat__get_access_token", Mock(return_value=None)) + read = Mock(side_effect=AssertionError("不应读取文件")) + monkeypatch.setattr(Path, "open", read) + + assert client.send_file(str(attachment)) is None + read.assert_not_called() + http.request.assert_not_called() + + +def _module(monkeypatch: pytest.MonkeyPatch, client: WeChat | WeChatBot) -> WechatModule: + """ + 装配单实例模块,保留真实通知过滤和接收人解析。 + """ + module = WechatModule() + module._channel = NotificationChannel.Wechat + conf = SimpleNamespace(name="wechat-test", config={}) + monkeypatch.setattr(module, "get_configs", lambda: {conf.name: conf}) + monkeypatch.setattr(module, "get_instance", lambda _: client) + return module + + +def test_plugin_file_fields_reach_application_client( + client: WeChat, http: Mock, attachment: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 插件通用附件字段及用户目标经消息序列化后到达文件发送接口,默认链接不会覆盖附件。 + """ + monkeypatch.setattr(plugin_base, "settings", SimpleNamespace(MP_DOMAIN=lambda path: f"https://mp.example/{path}")) + plugin = SimpleNamespace(chain=Mock()) + _PluginBase.post_message( + plugin, channel=NotificationChannel.Wechat, userid="member-1", title="附件", + file_path=str(attachment), file_name="download.srt", + ) + message = plugin.chain.post_message.call_args.args[0] + module = _module(monkeypatch, client) + + module.post_message(Message.model_validate(message.model_dump())) + + sent = _payloads(http) + assert [payload["msgtype"] for payload in sent] == ["text", "file"] + assert all(payload["touser"] == "member-1" for payload in sent) + assert "#/plugins" not in sent[0]["text"]["content"] + assert http.request.call_args.kwargs["files"]["media"][0] == "download.srt" + + +def test_file_notification_keeps_instance_and_channel_filters( + client: WeChat, http: Mock, attachment: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 原有来源与渠道过滤仍阻止文件被投递给错误实例。 + """ + module = _module(monkeypatch, client) + module.post_message(Message(file_path=str(attachment), userid="member-1", source="other")) + module.post_message(Message(file_path=str(attachment), userid="member-1", channel=NotificationChannel.Telegram)) + + http.request.assert_not_called() + http.post.assert_not_called() + + +def test_bot_does_not_silently_replace_file_with_text( + attachment: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 机器人模式拒绝文件发送,不将未送出的附件伪装为普通文本通知。 + """ + bot = WeChatBot.__new__(WeChatBot) + send = Mock() + monkeypatch.setattr(bot, "send_msg", send) + + _module(monkeypatch, bot).post_message(Message(file_path=str(attachment), title="附件", userid="member-1")) + + send.assert_not_called() + + +@pytest.mark.parametrize("mode, source_exists, accepted", [ + ("app", True, True), (None, True, True), ("bot", True, False), ("app", False, False), +]) +def test_agent_file_sending_checks_actual_wechat_mode( + attachment: Path, monkeypatch: pytest.MonkeyPatch, mode: str | None, source_exists: bool, accepted: bool, +) -> None: + """ + Agent 只向当前存在的自建应用实例发送附件,默认模式兼容旧配置。 + """ + config = {"WECHAT_MODE": mode} if mode else {} + conf = SimpleNamespace(name="wechat-test", config=config) + monkeypatch.setattr(file_tool, "get_notification_configs", lambda: [conf] if source_exists else []) + send = AsyncMock() + monkeypatch.setattr(SendLocalFileTool, "send_message", send) + tool = SendLocalFileTool(session_id="file-test", user_id="member-1") + tool.set_message_attr(channel=NotificationChannel.Wechat.value, source="wechat-test", username="member") + + result = asyncio.run(tool.run(str(attachment), file_name="download.srt")) + + assert ChannelCapabilityManager.supports_capability(NotificationChannel.Wechat, ChannelCapability.FILE_SENDING) + assert bool(send.await_count) is accepted + if accepted: + assert result == "本地附件已发送" + assert send.await_args.args[0].file_path == str(attachment) + assert send.await_args.args[0].file_name == "download.srt" + assert send.await_args.args[0].userid == "member-1" + else: + assert "仅自建应用" in result + + +def test_other_file_channels_do_not_require_wechat_configuration( + attachment: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """ + 现有附件渠道不读取企业微信实例配置,保持原有文件发送能力。 + """ + config_lookup = Mock(side_effect=AssertionError("其他渠道不应查询企业微信配置")) + monkeypatch.setattr(file_tool, "get_notification_configs", config_lookup) + send = AsyncMock() + monkeypatch.setattr(SendLocalFileTool, "send_message", send) + tool = SendLocalFileTool(session_id="file-test", user_id="member-1") + tool.set_message_attr(channel=NotificationChannel.Telegram.value, source="telegram-test", username="member") + + assert asyncio.run(tool.run(str(attachment))) == "本地附件已发送" + config_lookup.assert_not_called() + send.assert_awaited_once()