mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-29 15:36:02 +08:00
fix(messaging): route special-prefix text to plugins (#7480)
Refs #7479
This commit is contained in:
@@ -8,6 +8,7 @@ import json
|
||||
import mimetypes
|
||||
import re
|
||||
import threading
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from concurrent.futures import CancelledError as FutureCancelledError
|
||||
@@ -324,11 +325,22 @@ class MessageChain(ChainBase):
|
||||
callback_data: Optional[str] = None,
|
||||
) -> None:
|
||||
"""
|
||||
识别消息内容,执行操作
|
||||
识别消息内容并执行对应操作。
|
||||
|
||||
外部渠道中以标点或符号开头的纯文本优先交给插件,避免验证码等插件输入被
|
||||
智能体拦截或写入普通消息历史;斜杠命令和 Web 聊天仍按原路由处理。
|
||||
"""
|
||||
text = text or ""
|
||||
images = IncomingMessage.MessageImage.normalize_list(images)
|
||||
if self._handle_channel_authorization(channel, source, userid, username, text, callback_data):
|
||||
is_special_plugin_text = (
|
||||
channel not in {NotificationChannel.Web, NotificationChannel.WebAgent}
|
||||
and not (images or audio_refs or files or callback_data)
|
||||
and self._is_special_plugin_text(text)
|
||||
)
|
||||
if self._handle_channel_authorization(
|
||||
channel, source, userid, username, text, callback_data,
|
||||
allow_plugin_input=is_special_plugin_text,
|
||||
):
|
||||
return
|
||||
|
||||
# 兼容归一化:结构化回调优先,CALLBACK: 文本前缀作为旧渠道和插件直接调用的兼容入口
|
||||
@@ -395,6 +407,12 @@ class MessageChain(ChainBase):
|
||||
original_chat_id=original_chat_id,
|
||||
is_channel_admin=is_channel_admin,
|
||||
)
|
||||
|
||||
if is_special_plugin_text:
|
||||
# 插件验证码等专用输入不进入 Agent、普通历史或传统命令路由。
|
||||
self._dispatch_plugin_text(interaction_context, text, reply_to_message_id)
|
||||
return
|
||||
|
||||
member_result = self._handle_channel_member_message(
|
||||
interaction_context, text, normalized_callback, images, files, has_audio_input,
|
||||
) if channel_managed else None
|
||||
@@ -470,6 +488,44 @@ class MessageChain(ChainBase):
|
||||
original_chat_id=original_chat_id,
|
||||
)
|
||||
|
||||
def _dispatch_plugin_text(
|
||||
self, context: InteractionContext, text: str, reply_to_message_id: Optional[Union[str, int]],
|
||||
) -> None:
|
||||
"""
|
||||
将插件专用文本优先投递给活动输入会话,无会话时广播原有用户消息事件。
|
||||
|
||||
:param context: 本次消息的渠道、发送者及会话信息
|
||||
:param text: 已确认以标点或符号开头的原始纯文本
|
||||
:param reply_to_message_id: 回复目标,用于匹配插件输入会话
|
||||
"""
|
||||
if self._plugin_input_interaction_handler().handle_text(
|
||||
context=context, text=text, reply_to_message_id=reply_to_message_id,
|
||||
):
|
||||
return
|
||||
self._publish_user_message(context, text, reply_to_message_id)
|
||||
|
||||
def _publish_user_message(
|
||||
self, context: InteractionContext, text: str, reply_to_message_id: Optional[Union[str, int]],
|
||||
) -> None:
|
||||
"""
|
||||
按原有事件契约向插件发布用户文本,供普通路由和专用输入共用。
|
||||
|
||||
:param context: 本次消息的渠道、发送者及会话信息
|
||||
:param text: 发给插件处理的原始用户文本
|
||||
:param reply_to_message_id: 保留的回复目标消息标识
|
||||
"""
|
||||
self.eventmanager.send_event(
|
||||
EventType.UserMessage,
|
||||
{
|
||||
"text": text,
|
||||
"userid": context.user_id,
|
||||
"channel": context.channel,
|
||||
"source": context.source,
|
||||
"chat_id": context.original_chat_id,
|
||||
"reply_to_message_id": reply_to_message_id,
|
||||
},
|
||||
)
|
||||
|
||||
def _handle_channel_member_message(
|
||||
self, context: InteractionContext, text: str, callback_data: Optional[str],
|
||||
images: Optional[List[IncomingMessage.MessageImage]], files: Optional[List[IncomingMessage.MessageAttachment]],
|
||||
@@ -506,11 +562,16 @@ class MessageChain(ChainBase):
|
||||
def _handle_channel_authorization(
|
||||
self, channel: NotificationChannel, source: str, userid: Union[str, int],
|
||||
username: str, text: str, callback_data: Optional[str],
|
||||
*, allow_plugin_input: bool = False,
|
||||
) -> bool:
|
||||
"""
|
||||
在语音、传统交互和 Agent 执行前处理申请并统一检查渠道成员状态。
|
||||
|
||||
未授权身份只收到申请入口,不自动执行原业务请求。已授权普通成员不能执行传统管理命令。
|
||||
缺失或待审批成员的标点/符号开头纯文本可继续交给插件消息入口;其它未授权消息
|
||||
仍只收到申请入口。已授权普通成员不能执行传统管理命令。
|
||||
|
||||
:param allow_plugin_input: 调用方已排除回调、附件及 Web 聊天的插件专用纯文本标记
|
||||
:return: 已处理授权控制或拒绝本次消息时返回 True
|
||||
"""
|
||||
service = get_channel_authorization()
|
||||
if service is None or channel in {NotificationChannel.Web, NotificationChannel.WebAgent}:
|
||||
@@ -520,6 +581,10 @@ class MessageChain(ChainBase):
|
||||
value = value[9:].strip()
|
||||
try:
|
||||
member = service.find(channel.value, source, str(userid))
|
||||
if (
|
||||
member is None or member.status == "pending"
|
||||
) and allow_plugin_input:
|
||||
return False
|
||||
if value.startswith("绑定账号 "):
|
||||
member = service.bind(channel.value, source, str(userid), username, value[5:].strip())
|
||||
self.post_message(Message(channel=channel, source=source, userid=userid,
|
||||
@@ -756,17 +821,7 @@ class MessageChain(ChainBase):
|
||||
):
|
||||
return False
|
||||
|
||||
self.eventmanager.send_event(
|
||||
EventType.UserMessage,
|
||||
{
|
||||
"text": text,
|
||||
"userid": userid,
|
||||
"channel": channel,
|
||||
"source": source,
|
||||
"chat_id": original_chat_id,
|
||||
"reply_to_message_id": reply_to_message_id,
|
||||
},
|
||||
)
|
||||
self._publish_user_message(context, text, reply_to_message_id)
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
@@ -788,6 +843,21 @@ class MessageChain(ChainBase):
|
||||
"""
|
||||
return (text or "").lower().startswith(cls._ai_prefix)
|
||||
|
||||
@staticmethod
|
||||
def _is_special_plugin_text(text: Optional[str]) -> bool:
|
||||
"""
|
||||
判断纯文本是否以标点或符号开头,可作为插件消息输入。
|
||||
|
||||
斜杠命令保留宿主路由;调用方负责排除回调、附件及 Web 聊天。
|
||||
|
||||
:param text: 渠道收到的原始文本
|
||||
:return: 首个非空白字符为标点或符号且不是斜杠时返回 True
|
||||
"""
|
||||
normalized = (text or "").lstrip()
|
||||
if not normalized or normalized.startswith("/"):
|
||||
return False
|
||||
return unicodedata.category(normalized[0])[0] in {"P", "S"}
|
||||
|
||||
def _is_agent_message(
|
||||
self,
|
||||
userid: Union[str, int],
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
普通成员通过受控 Agent 搜索、订阅和下载;定时任务另行开启。传统管理命令和旧式业务按钮仅渠道管理员可用,普通文本不再进入旧管理会话。管理员角色允许实例管理操作,设置时应单独核对。成员身份按通知实例和平台用户 ID 隔离,同一个人在不同机器人中分别授权。昵称、群组 ID 和机器人 ID 不能代替用户身份。
|
||||
|
||||
外部渠道中以标点或符号开头的纯文本(如 `#123456`、`?930441`)优先交给插件输入会话;没有匹配会话时,通过 `UserMessage` 事件交给插件处理,不进入 Agent 或普通消息历史。这类插件输入无需开启 Agent 或添加 `/ai` 前缀,尚未申请或待审批的成员也可发送,已停用或被拒绝的成员仍会被拦截。斜杠命令、按钮回调、带附件消息和网页聊天继续使用原有路由与权限检查。
|
||||
|
||||
只使用机器人无需创建网页登录账号。系统为订阅、下载和任务保存内部归属,该身份不会出现在网页登录用户列表,也没有密码、PassKey 或网页登录能力。停用成员后,后续 API、工具、子代理和定时任务都重新校验授权;已经发出的外部业务请求不会因为停用而自动撤销。
|
||||
|
||||
## 关联已有账号
|
||||
|
||||
@@ -2021,7 +2021,7 @@
|
||||
"EventType.UserMessage": {
|
||||
"consumer_fingerprints": [],
|
||||
"producer_fingerprints": [
|
||||
"6e4d8de098b200f04c1089fc9a5a67e1064a5fac50a1c0ce0a13ea0f6cece32f"
|
||||
"9934766390c1470e31c1c04239785b21af3fcdba636898b752c920bee8143e11"
|
||||
]
|
||||
},
|
||||
"EventType.WebhookMessage": {
|
||||
@@ -2407,18 +2407,6 @@
|
||||
"qualname": "MediaProjectionOwner._dispatch_projection_event",
|
||||
"receiver_kind": "injected_event_manager"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.message",
|
||||
"dynamic": false,
|
||||
"events": [
|
||||
"EventType.UserMessage"
|
||||
],
|
||||
"fingerprint": "6e4d8de098b200f04c1089fc9a5a67e1064a5fac50a1c0ce0a13ea0f6cece32f",
|
||||
"invalid": false,
|
||||
"method": "send_event",
|
||||
"qualname": "MessageChain._handle_message_core",
|
||||
"receiver_kind": "injected_event_manager"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.message",
|
||||
"dynamic": false,
|
||||
@@ -2443,6 +2431,18 @@
|
||||
"qualname": "MessageChain._interaction_router._dispatch_plugin_callback",
|
||||
"receiver_kind": "injected_event_manager"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.message",
|
||||
"dynamic": false,
|
||||
"events": [
|
||||
"EventType.UserMessage"
|
||||
],
|
||||
"fingerprint": "9934766390c1470e31c1c04239785b21af3fcdba636898b752c920bee8143e11",
|
||||
"invalid": false,
|
||||
"method": "send_event",
|
||||
"qualname": "MessageChain._publish_user_message",
|
||||
"receiver_kind": "injected_event_manager"
|
||||
},
|
||||
{
|
||||
"caller": "app.chain.site",
|
||||
"dynamic": false,
|
||||
|
||||
@@ -14,6 +14,7 @@ from sqlalchemy import delete, select
|
||||
|
||||
from app.agent.api.executor import ApiExecutionContext, ApiExecutionError, MoviePilotApiExecutor
|
||||
from app.agent.identity import AgentIdentityError, require_execution_user, resolve_task_user
|
||||
from app.application.messaging.plugin import plugin_input_interaction_manager
|
||||
from app.application.security import authorization as authorization_module
|
||||
from app.application.security.auth import AuthService
|
||||
from app.application.security.authorization import ChannelAuthorizationService
|
||||
@@ -23,9 +24,10 @@ from app.db.adapters.user import TransactionalUserRepository
|
||||
from app.db.models.authorization import ChannelAuthorization, ChannelBinding
|
||||
from app.db.models.user import User
|
||||
from app.db.session import SessionFactory, async_session_scope
|
||||
from app.schemas.message import IncomingMessage
|
||||
from app.schemas.system import NotificationConf
|
||||
from app.schemas.token import TokenPayload
|
||||
from app.schemas.types import NotificationChannel
|
||||
from app.schemas.types import EventType, NotificationChannel
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -259,6 +261,212 @@ def test_channel_member_text_cannot_reenter_legacy_admin_sessions(channel_author
|
||||
assert "管理员" in post.call_args.args[0].title
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["#123456", "?930441", "?930441", "🔥123456", " \n#123456"])
|
||||
@pytest.mark.parametrize(("ai_enabled", "ai_global"), [(False, False), (True, False), (True, True)])
|
||||
@pytest.mark.parametrize("member_status", ["missing", "pending", "member", "admin", "unmanaged"])
|
||||
@pytest.mark.parametrize(("channel", "source"), [
|
||||
(NotificationChannel.Telegram, "机器人A"), (NotificationChannel.Wechat, "企微A"),
|
||||
])
|
||||
def test_special_prefix_text_is_routed_to_plugins_without_agent_or_history(
|
||||
channel_authorization, monkeypatch, text, ai_enabled, ai_global, member_status, channel, source,
|
||||
):
|
||||
"""
|
||||
企微和 Telegram 插件验证码在不同 Agent 模式和成员身份下均交给插件且不保存普通历史。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
service, configs, _ = channel_authorization
|
||||
if channel == NotificationChannel.Wechat:
|
||||
configs.append(NotificationConf(id="wechat-enterprise", name=source, type="wechat", enabled=True))
|
||||
if member_status in {"pending", "member", "admin"}:
|
||||
member = service.request(channel.value, source, "42", "成员")
|
||||
if member_status != "pending":
|
||||
service.update(member.id, status="approved", role=member_status, scopes=(), reviewer_id=1)
|
||||
if member_status == "unmanaged":
|
||||
authorization_module.configure_channel_authorization(None)
|
||||
|
||||
chain = MessageChain()
|
||||
monkeypatch.setattr(
|
||||
chain,
|
||||
"runtime_config",
|
||||
replace(chain.runtime_config, ai_agent_enable=ai_enabled, ai_agent_global=ai_global),
|
||||
)
|
||||
event_handler = Mock()
|
||||
event_handler.handle_text.return_value = False
|
||||
agent_handler = Mock()
|
||||
post_message = Mock()
|
||||
record_message = Mock()
|
||||
send_event = Mock()
|
||||
monkeypatch.setattr(chain, "_plugin_input_interaction_handler", lambda: event_handler)
|
||||
monkeypatch.setattr(chain, "_handle_ai_message", agent_handler)
|
||||
monkeypatch.setattr(chain, "post_message", post_message)
|
||||
monkeypatch.setattr(chain, "_record_user_message", record_message)
|
||||
monkeypatch.setattr(chain.eventmanager, "send_event", send_event)
|
||||
|
||||
chain.handle_message(
|
||||
channel=channel,
|
||||
source=source,
|
||||
userid="42",
|
||||
username="成员",
|
||||
text=text,
|
||||
original_chat_id="chat-7479",
|
||||
reply_to_message_id="prompt-7479",
|
||||
)
|
||||
|
||||
event_handler.handle_text.assert_called_once()
|
||||
agent_handler.assert_not_called()
|
||||
post_message.assert_not_called()
|
||||
record_message.assert_not_called()
|
||||
send_event.assert_called_once_with(
|
||||
EventType.UserMessage,
|
||||
{
|
||||
"text": text,
|
||||
"userid": "42",
|
||||
"channel": channel,
|
||||
"source": source,
|
||||
"chat_id": "chat-7479",
|
||||
"reply_to_message_id": "prompt-7479",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["disabled", "rejected"])
|
||||
def test_special_prefix_text_remains_blocked_for_disabled_channel_member(channel_authorization, monkeypatch, status):
|
||||
"""
|
||||
标点开头的插件输入不能绕过已停用或拒绝成员的渠道授权。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
service, _, _ = channel_authorization
|
||||
member = service.request("Telegram", "机器人A", "42", "成员")
|
||||
service.update(member.id, status=status, role="member", scopes=(), reviewer_id=1)
|
||||
|
||||
chain = MessageChain()
|
||||
monkeypatch.setattr(
|
||||
chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=False, ai_agent_global=False)
|
||||
)
|
||||
post_message = Mock()
|
||||
send_event = Mock()
|
||||
monkeypatch.setattr(chain, "post_message", post_message)
|
||||
monkeypatch.setattr(chain.eventmanager, "send_event", send_event)
|
||||
|
||||
chain.handle_message(
|
||||
channel=NotificationChannel.Telegram,
|
||||
source="机器人A",
|
||||
userid="42",
|
||||
username="成员",
|
||||
text="#123456",
|
||||
)
|
||||
|
||||
post_message.assert_called_once()
|
||||
assert not any(call.args[0] == EventType.UserMessage for call in send_event.call_args_list)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["pending", "approved"])
|
||||
def test_special_prefix_text_consumes_plugin_session_before_broadcast(channel_authorization, monkeypatch, status):
|
||||
"""
|
||||
插件活动输入会话先收到验证码,并保留回复定位且不重复广播或写入消息历史。
|
||||
"""
|
||||
service, _, _ = channel_authorization
|
||||
member = service.request("Telegram", "机器人A", "42", "成员")
|
||||
if status == "approved":
|
||||
service.update(member.id, status=status, role="member", scopes=(), reviewer_id=1)
|
||||
chain = MessageChain()
|
||||
post = Mock()
|
||||
record = Mock()
|
||||
agent = Mock()
|
||||
send_event = Mock()
|
||||
monkeypatch.setattr(chain, "post_message", post)
|
||||
monkeypatch.setattr(chain, "_record_user_message", record)
|
||||
monkeypatch.setattr(chain, "_handle_ai_message", agent)
|
||||
monkeypatch.setattr(chain.eventmanager, "send_event", send_event)
|
||||
request = plugin_input_interaction_manager.create_or_replace(
|
||||
user_id="42", plugin_id="example_plugin", channel=NotificationChannel.Telegram,
|
||||
source="机器人A", username="成员", chat_id="chat-7479", prompt_message_id="prompt-7479",
|
||||
)
|
||||
try:
|
||||
chain.handle_message(
|
||||
NotificationChannel.Telegram, "机器人A", "42", "成员", "#123456",
|
||||
original_chat_id="chat-7479", reply_to_message_id="prompt-7479",
|
||||
)
|
||||
send_event.assert_called_once()
|
||||
event_type, payload = send_event.call_args.args
|
||||
assert event_type == EventType.MessageAction
|
||||
assert payload["input_text"] == "#123456"
|
||||
assert payload["input_session_id"] == request.request_id
|
||||
assert payload["__mp_target_plugin_id"] == "example_plugin"
|
||||
assert payload["chat_id"] == "chat-7479"
|
||||
assert payload["reply_to_message_id"] == "prompt-7479"
|
||||
assert plugin_input_interaction_manager.get_by_user(
|
||||
"42", NotificationChannel.Telegram, "机器人A", "chat-7479",
|
||||
) is None
|
||||
post.assert_not_called()
|
||||
record.assert_not_called()
|
||||
agent.assert_not_called()
|
||||
finally:
|
||||
plugin_input_interaction_manager.remove(request.request_id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("text", "attachments"), [
|
||||
("/help", {}), ("/ai 查询", {}), ("123456", {}), ("普通文本", {}), ("", {}),
|
||||
("#123456", {"images": [{"ref": "synthetic-image"}]}),
|
||||
("#123456", {"files": [IncomingMessage.MessageAttachment(ref="synthetic-file")]}),
|
||||
("#123456", {"audio_refs": ["synthetic-audio"]}),
|
||||
("#123456", {"callback_data": "plugin:callback"}),
|
||||
])
|
||||
def test_plugin_input_exception_does_not_bypass_other_authorization(
|
||||
channel_authorization, monkeypatch, text, attachments,
|
||||
):
|
||||
"""
|
||||
插件纯文本豁免不放开普通文本、斜杠命令、附件或按钮回调的授权要求。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
chain = MessageChain()
|
||||
monkeypatch.setattr(chain, "runtime_config", replace(chain.runtime_config, ai_agent_enable=False))
|
||||
post = Mock()
|
||||
plugin = Mock()
|
||||
monkeypatch.setattr(chain, "post_message", post)
|
||||
monkeypatch.setattr(chain, "_plugin_input_interaction_handler", plugin)
|
||||
chain.handle_message(NotificationChannel.Telegram, "机器人A", "42", "成员", text, **attachments)
|
||||
post.assert_called_once()
|
||||
plugin.assert_not_called()
|
||||
assert "授权" in post.call_args.args[0].title
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("channel", "text", "attachments"), [
|
||||
(NotificationChannel.Web, "#123456", {}),
|
||||
(NotificationChannel.WebAgent, "#123456", {}),
|
||||
(NotificationChannel.Telegram, "/help", {}),
|
||||
(NotificationChannel.Telegram, "/ai 查询", {}),
|
||||
(NotificationChannel.Telegram, "普通文本", {}),
|
||||
(NotificationChannel.Telegram, "#123456", {"callback_data": "plugin:callback"}),
|
||||
(NotificationChannel.Telegram, "#123456", {"images": [{"ref": "synthetic-image"}]}),
|
||||
(NotificationChannel.Telegram, "#123456", {"audio_refs": ["synthetic-audio"]}),
|
||||
])
|
||||
def test_special_plugin_route_preserves_web_commands_and_attachments(
|
||||
channel_authorization, monkeypatch, channel, text, attachments,
|
||||
):
|
||||
"""
|
||||
网页会话、命令、回调及带附件消息仍进入既有核心路由。
|
||||
"""
|
||||
_approve(channel_authorization[0], role="admin")
|
||||
chain = MessageChain()
|
||||
core = Mock(return_value=False)
|
||||
plugin = Mock()
|
||||
plugin.handle_text.return_value = False
|
||||
dispatch = Mock()
|
||||
monkeypatch.setattr(chain, "_handle_message_core", core)
|
||||
monkeypatch.setattr(chain, "_plugin_input_interaction_handler", lambda: plugin)
|
||||
monkeypatch.setattr(chain, "_dispatch_plugin_text", dispatch)
|
||||
monkeypatch.setattr(chain, "_transcribe_audio_refs", Mock(return_value="语音转写"))
|
||||
monkeypatch.setattr(chain, "_record_user_message", Mock())
|
||||
monkeypatch.setattr(chain, "_mark_message_processing_started", Mock(return_value=None))
|
||||
chain.handle_message(channel, "机器人A", "42", "成员", text, **attachments)
|
||||
dispatch.assert_not_called()
|
||||
core.assert_called_once()
|
||||
|
||||
|
||||
def test_account_binding_requires_both_sides_and_never_approves_pending_member(channel_authorization, db):
|
||||
"""
|
||||
网页账号生成的码只能消费一次,关联不会替代渠道审批或解除管理员停用。
|
||||
|
||||
Reference in New Issue
Block a user