From 4e9a64c0f03ddcff161b48244a15a2a620d10666 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Tue, 15 Sep 2026 23:56:55 +0800 Subject: [PATCH] =?UTF-8?q?refactor(application):=20=E6=8C=89=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E5=AD=90=E7=9B=AE=E5=BD=95=E7=BB=9F=E4=B8=80=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/agent/tools/base.py | 2 +- app/agent/tools/impl/ask_user_choice.py | 2 +- app/api/dependencies/history.py | 2 +- app/api/endpoints/agent.py | 4 +- .../{history.py => history/__init__.py} | 36 +- .../contracts.py} | 0 .../mutation.py} | 0 .../{history_retry.py => history/retry.py} | 2 +- app/application/messaging/agent.py | 311 +----------------- app/application/messaging/channel/__init__.py | 1 + .../{channel_admin.py => channel/admin.py} | 0 .../__init__.py} | 0 .../agent.py} | 0 .../messaging/webagent/__init__.py | 1 + app/application/messaging/webagent/events.py | 251 ++++++++++++++ .../{webagentstream.py => webagent/stream.py} | 0 app/chain/_messaging.py | 4 +- app/chain/message.py | 2 +- app/chain/transfer/execution.py | 2 +- app/chain/transfer/filter.py | 2 +- app/chain/transfer/format.py | 2 +- app/chain/transfer/records.py | 3 +- app/chain/transfer/settlement.py | 2 + app/chain/transfer/workflow.py | 2 +- app/db/adapters/history/transfer.py | 2 + app/modules/_base/notification.py | 2 +- app/modules/discord/__init__.py | 2 +- app/modules/feishu/__init__.py | 2 +- app/modules/feishu/feishu.py | 2 +- app/modules/qqbot/module.py | 2 +- app/modules/slack/__init__.py | 2 +- app/modules/synologychat/__init__.py | 2 +- app/modules/telegram/module.py | 2 +- app/modules/vocechat/__init__.py | 2 +- app/modules/wechat/__init__.py | 2 +- app/modules/wechat/wechatbot.py | 2 +- app/modules/wechatclawbot/__init__.py | 2 +- app/monitor/dispatcher.py | 4 +- app/startup/initializers/modules.py | 2 +- tests/test_agent_channel_admin_identity.py | 5 +- tests/test_agent_interaction.py | 2 +- tests/test_agent_message_routing.py | 5 +- ...pplication_messaging_agent_architecture.py | 67 +++- tests/test_application_shared_utilities.py | 42 +++ tests/test_architecture_dependencies.py | 2 +- tests/test_manual_transfer_history.py | 2 + tests/test_monitor_dispatcher_history.py | 2 +- tests/test_transfer_failed_retry_budget.py | 4 +- tests/test_transfer_history_architecture.py | 10 +- tests/test_transfer_history_gate.py | 4 +- tests/test_transfer_job_manager.py | 2 +- tests/test_web_agent_stream.py | 12 +- 52 files changed, 439 insertions(+), 383 deletions(-) rename app/application/{history.py => history/__init__.py} (95%) rename app/application/{history_contracts.py => history/contracts.py} (100%) rename app/application/{historymutation.py => history/mutation.py} (100%) rename app/application/{history_retry.py => history/retry.py} (99%) create mode 100644 app/application/messaging/channel/__init__.py rename app/application/messaging/{channel_admin.py => channel/admin.py} (100%) rename app/application/messaging/{interaction.py => interaction/__init__.py} (100%) rename app/application/messaging/{agent_interaction.py => interaction/agent.py} (100%) create mode 100644 app/application/messaging/webagent/__init__.py create mode 100644 app/application/messaging/webagent/events.py rename app/application/messaging/{webagentstream.py => webagent/stream.py} (100%) diff --git a/app/agent/tools/base.py b/app/agent/tools/base.py index 0919517e2..e34363148 100644 --- a/app/agent/tools/base.py +++ b/app/agent/tools/base.py @@ -22,7 +22,7 @@ from app.agent.policy.sanitizer import ( from app.agent.tools.result import ToolExecutionError, inspect_tool_result from app.agent.tools.tags import ToolTag from app.application.agent import AgentDataContext -from app.application.messaging.channel_admin import matches_channel_admin +from app.application.messaging.channel.admin import matches_channel_admin from app.application.notification import get_notification_configs from app.chain.base import ChainBase from app.runtime.log import logger diff --git a/app/agent/tools/impl/ask_user_choice.py b/app/agent/tools/impl/ask_user_choice.py index df3bf10b1..739ad8bea 100644 --- a/app/agent/tools/impl/ask_user_choice.py +++ b/app/agent/tools/impl/ask_user_choice.py @@ -6,7 +6,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.messaging.agent_interaction import ( +from app.application.messaging.interaction.agent import ( AgentInteractionOption, agent_interaction_manager, build_agent_choice_callback, diff --git a/app/api/dependencies/history.py b/app/api/dependencies/history.py index bafa16fcd..9f2db9bf4 100644 --- a/app/api/dependencies/history.py +++ b/app/api/dependencies/history.py @@ -11,8 +11,8 @@ from app.application.history import ( HistoryQueryService, TransferHistoryLookupService, TransferHistoryMutationCommand, - clear_transfer_failures, ) +from app.application.history.retry import clear_transfer_failures from app.application.mediaserver import MediaServerQueryService from app.application.transfer.execution import TransferExecutionRepository from app.chain.storage import StorageChain diff --git a/app/api/endpoints/agent.py b/app/api/endpoints/agent.py index 4972160f7..78f70e5f8 100644 --- a/app/api/endpoints/agent.py +++ b/app/api/endpoints/agent.py @@ -31,15 +31,13 @@ from app.api.response import ( ) from app.application import agent as agent_application from app.application.messaging import agent as web_agent_application -from app.application.messaging.agent import ( - parse_agent_choice_callback, -) from app.application.messaging.chat import ( AgentChatPersistenceService, AgentChatService, get_configured_agent_chat_persistence, get_configured_agent_chat_service, ) +from app.application.messaging.interaction.agent import parse_agent_choice_callback from app.runtime.events import eventmanager from app.runtime.localization import LocaleHelper from app.runtime.log import logger diff --git a/app/application/history.py b/app/application/history/__init__.py similarity index 95% rename from app/application/history.py rename to app/application/history/__init__.py index 5d4164c34..460e838dd 100644 --- a/app/application/history.py +++ b/app/application/history/__init__.py @@ -3,27 +3,7 @@ from __future__ import annotations from dataclasses import asdict, dataclass from typing import Any, Callable, Dict, Optional, Protocol, Union -from app.application.history_retry import ( - HistoryGateAction, - _failed_retry_counts, - clear_transfer_failures, - coerce_fileid, - coerce_modify_time, - coerce_size, - describe_history_gate, - evaluate_history_gate, - failed_retry_count, - failed_retry_key, - file_fingerprint, - history_src_fingerprint, - history_src_size, - is_skip_action, - max_failed_retries, - next_failed_retry_count, - record_transfer_failure, - resolve_history, -) -from app.application.history_contracts import ( +from app.application.history.contracts import ( _freeze_json, TransferHistoryMonthlyStatistics, TransferHistoryQueryPort, @@ -38,25 +18,25 @@ from app.application.history_contracts import ( get_transfer_history_repository, reset_transfer_history_repository, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( DownloadFileMutationRepository as DownloadFileMutationRepository, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( DownloadHistoryMutationCommand as DownloadHistoryMutationCommand, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( DownloadHistoryMutationRepository as DownloadHistoryMutationRepository, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( HistoryMutationResult as HistoryMutationResult, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( HistoryUnitOfWork as HistoryUnitOfWork, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( TransferHistoryMutationCommand as TransferHistoryMutationCommand, ) -from app.application.historymutation import ( +from app.application.history.mutation import ( TransferHistoryMutationRepository as TransferHistoryMutationRepository, ) from app.application.transfer import history as history_projection diff --git a/app/application/history_contracts.py b/app/application/history/contracts.py similarity index 100% rename from app/application/history_contracts.py rename to app/application/history/contracts.py diff --git a/app/application/historymutation.py b/app/application/history/mutation.py similarity index 100% rename from app/application/historymutation.py rename to app/application/history/mutation.py diff --git a/app/application/history_retry.py b/app/application/history/retry.py similarity index 99% rename from app/application/history_retry.py rename to app/application/history/retry.py index fb5814dc4..3d1853ca1 100644 --- a/app/application/history_retry.py +++ b/app/application/history/retry.py @@ -5,7 +5,7 @@ from __future__ import annotations from typing import Any, Dict, Optional from app.application.configuration import TransferRetryConfig, get_transfer_retry_config -from app.application.history_contracts import ( +from app.application.history.contracts import ( TransferHistoryQueryPort, TransferHistorySnapshot, get_transfer_history_repository, diff --git a/app/application/messaging/agent.py b/app/application/messaging/agent.py index 0aa4d9bc6..615341d62 100644 --- a/app/application/messaging/agent.py +++ b/app/application/messaging/agent.py @@ -10,7 +10,6 @@ from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from queue import Empty, Queue -from threading import Lock from typing import ( Any, AsyncIterator, @@ -36,23 +35,9 @@ from app.application.messaging.chat import ( get_configured_agent_chat_persistence, get_configured_agent_chat_service, ) -from app.application.messaging.agent_interaction import ( - AGENT_CHOICE_PREFIX, - LEGACY_AGENT_CHOICE_PREFIX, - AgentInteractionManager, - AgentInteractionOption, - PendingAgentInteraction, - agent_interaction_manager, - build_agent_choice_button_rows, - build_agent_choice_callback, - parse_agent_choice_callback, -) -from app.application.messaging.channel_admin import ( - matches_channel_admin, - register_channel_admin_resolver, - resolve_config_principal_ids, -) +from app.application.messaging.interaction import agent as agent_interaction from app.application.messaging.router import has_pending_interaction +from app.application.messaging.webagent import events as web_agent_events from app.runtime.execution import run_in_threadpool from app.runtime.log import logger from app.runtime.tasks import get_task_registry @@ -62,10 +47,6 @@ from app.schemas.types import NotificationChannel __all__ = ["dispatch_command"] -_WEB_AGENT_EDIT_QUEUES: dict[str, list[Queue[dict[str, Any]]]] = {} -_WEB_AGENT_EDIT_LOCK = Lock() -_WEB_AGENT_MESSAGE_QUEUES: dict[str, list[Queue[Message]]] = {} -_WEB_AGENT_MESSAGE_LOCK = Lock() _WEB_AGENT_BACKGROUND_TASKS: set[asyncio.Task[object]] = set() @@ -103,272 +84,6 @@ async def wait_web_agent_background_tasks() -> None: await asyncio.gather(*tasks, return_exceptions=True) -def normalize_web_agent_button_rows(buttons: Optional[list[list[dict[str, Any]]]]) -> list[list[dict[str, Any]]]: - """ - 将消息按钮转换为 WebAgent 前端可识别的按钮行。 - - :param buttons: 传统消息模块返回的按钮二维数组 - :return: WebAgent 前端选项按钮二维数组 - """ - button_rows: list[list[dict[str, Any]]] = [] - for row in buttons or []: - normalized_row = [] - for button in row or []: - label = str(button.get("text") or button.get("label") or "").strip() - callback_data = str(button.get("callback_data") or "").strip() - if not label or not callback_data: - continue - normalized_button = { - "label": label, - "callback_data": callback_data, - } - if button.get("description"): - normalized_button["description"] = str(button.get("description")) - normalized_row.append(normalized_button) - if normalized_row: - button_rows.append(normalized_row) - return button_rows - - -def _resolve_web_agent_choice_id( - message_id: Union[str, int], - button_rows: list[list[dict[str, Any]]], -) -> str: - """ - 从按钮回调中提取稳定的 WebAgent 选项 ID。 - - :param message_id: 前端助手消息 ID - :param button_rows: 已规范化的按钮行 - :return: 选项卡片 ID - """ - for row in button_rows: - for button in row: - callback_data = str(button.get("callback_data") or "").strip() - if not callback_data: - continue - parts = callback_data.split(":") - if len(parts) >= 2 and parts[1]: - return parts[1] - return callback_data - return str(message_id) - - -def build_web_agent_message_update_event( - *, - message_id: Union[str, int], - title: Optional[str], - text: str, - buttons: Optional[list[list[dict[str, Any]]]], -) -> dict[str, Any]: - """ - 构造 WebAgent 原消息更新事件。 - - :param message_id: 前端助手消息 ID - :param title: 更新后的标题 - :param text: 更新后的正文 - :param buttons: 更新后的按钮 - :return: 前端可应用到原消息的 SSE 事件 - """ - button_rows = normalize_web_agent_button_rows(buttons) - content_parts = [part for part in (title, text) if part] - target_message = { - "id": str(message_id), - "content": "" if button_rows else "\n\n".join(content_parts), - "choices": [], - "attachments": [], - "tools": [], - "status": "done", - } - if button_rows: - target_message["choices"].append( - { - "id": _resolve_web_agent_choice_id(message_id, button_rows), - "title": title, - "prompt": text or "", - "buttons": [button for row in button_rows for button in row], - "button_rows": button_rows, - "status": "pending", - } - ) - return { - "type": "message_update", - "target_message": target_message, - } - - -def extract_web_agent_message_from_event_data(data: dict[str, Any]) -> Optional[Message]: - """ - 从 NoticeMessage 事件数据中提取 WebAgent 通知。 - - :param data: NoticeMessage 事件数据,兼容扁平字段和 message 包装格式 - :return: WebAgent 通知,不属于 WebAgent 或数据无效时返回 None - """ - if not isinstance(data, dict): - return None - - try: - message = data.get("message") - if isinstance(message, Message): - message = message - elif isinstance(message, dict): - message_data = copy.deepcopy(message) - message_data.pop("type", None) - message = Message(**message_data) - else: - message_data = copy.deepcopy(data) - message_data.pop("type", None) - message_data.pop("current_time", None) - message = Message(**message_data) - except Exception as err: - logger.debug(f"解析WebAgent通知事件失败: {err}") - return None - - channel = message.channel - channel_value = channel.value if isinstance(channel, NotificationChannel) else channel - if channel_value != NotificationChannel.WebAgent.value: - return None - return message - - -def is_web_agent_message_for_user(message: Message, user_id: str) -> bool: - """ - 判断 NoticeMessage 事件是否属于当前 WebAgent 用户。 - - :param message: NoticeMessage 中的通知消息 - :param user_id: 当前登录用户 ID - :return: 可被本次 WebAgent 请求消费时返回 True - """ - try: - target_user = message.userid - return target_user is None or str(target_user) == str(user_id) - except Exception: - return False - - -def _get_web_agent_message_user_id(message: Message) -> Optional[str]: - """返回 WebAgent 通知的目标用户 ID,无目标时返回 None。""" - try: - channel = message.channel - channel_value = channel.value if isinstance(channel, NotificationChannel) else channel - if channel_value != NotificationChannel.WebAgent.value: - return None - user_id = message.userid - return str(user_id) if user_id is not None else None - except Exception: - return None - - -def dispatch_web_agent_message_event(event: object) -> None: - """将 WebAgent NoticeMessage 分发给正在等待的请求队列。""" - event_data = getattr(event, "event_data", None) - data = event_data if isinstance(event_data, dict) else {} - message = extract_web_agent_message_from_event_data(data) - if not message: - return - with _WEB_AGENT_MESSAGE_LOCK: - user_id = _get_web_agent_message_user_id(message) - if user_id is None: - queues = [ - message_queue for user_queues in _WEB_AGENT_MESSAGE_QUEUES.values() for message_queue in user_queues - ] - else: - queues = list(_WEB_AGENT_MESSAGE_QUEUES.get(user_id) or []) - for message_queue in queues: - message_queue.put(message) - - -def attach_web_agent_message_queue(user_id: str, message_queue: Queue[Message]) -> None: - """为当前 WebAgent 请求挂载通知收集队列。""" - with _WEB_AGENT_MESSAGE_LOCK: - _WEB_AGENT_MESSAGE_QUEUES.setdefault(str(user_id), []).append(message_queue) - - -def detach_web_agent_message_queue(user_id: str, message_queue: Queue[Message]) -> None: - """移除当前 WebAgent 请求的通知收集队列。""" - with _WEB_AGENT_MESSAGE_LOCK: - queues = _WEB_AGENT_MESSAGE_QUEUES.get(str(user_id)) - if not queues: - return - _WEB_AGENT_MESSAGE_QUEUES[str(user_id)] = [item for item in queues if item is not message_queue] - if not _WEB_AGENT_MESSAGE_QUEUES[str(user_id)]: - _WEB_AGENT_MESSAGE_QUEUES.pop(str(user_id), None) - - -def attach_web_agent_edit_queue(user_id: str, edit_queue: Queue[dict[str, Any]]) -> None: - """ - 为当前 WebAgent 请求挂载原消息编辑事件队列。 - - :param user_id: 当前用户 ID - :param edit_queue: 用于接收编辑事件的队列 - """ - with _WEB_AGENT_EDIT_LOCK: - _WEB_AGENT_EDIT_QUEUES.setdefault(str(user_id), []).append(edit_queue) - - -def detach_web_agent_edit_queue(user_id: str, edit_queue: Queue[dict[str, Any]]) -> None: - """ - 移除当前 WebAgent 请求的原消息编辑事件队列。 - - :param user_id: 当前用户 ID - :param edit_queue: 需要移除的队列 - """ - with _WEB_AGENT_EDIT_LOCK: - queues = _WEB_AGENT_EDIT_QUEUES.get(str(user_id)) - if not queues: - return - _WEB_AGENT_EDIT_QUEUES[str(user_id)] = [item for item in queues if item is not edit_queue] - if not _WEB_AGENT_EDIT_QUEUES[str(user_id)]: - _WEB_AGENT_EDIT_QUEUES.pop(str(user_id), None) - - -def dispatch_web_agent_edit_event( - *, - user_id: str, - event: dict[str, Any], -) -> bool: - """ - 将 WebAgent 原消息编辑事件分发给正在等待的请求队列。 - - :param user_id: 当前用户 ID - :param event: 前端可应用的 SSE 事件 - :return: 是否存在接收本次编辑事件的请求队列 - """ - with _WEB_AGENT_EDIT_LOCK: - queues = list(_WEB_AGENT_EDIT_QUEUES.get(str(user_id)) or []) - for edit_queue in queues: - edit_queue.put(event) - return bool(queues) - - -def edit_web_agent_message( - *, - user_id: str, - message_id: Union[str, int], - title: Optional[str], - text: str, - buttons: Optional[list[list[dict[str, Any]]]] = None, -) -> bool: - """ - 原地更新 WebAgent 前端消息卡片。 - - :param user_id: 当前用户 ID - :param message_id: 前端助手消息 ID - :param title: 更新后的标题 - :param text: 更新后的正文 - :param buttons: 更新后的按钮 - :return: 是否已投递编辑事件 - """ - if not user_id: - return False - event = build_web_agent_message_update_event( - message_id=message_id, - title=title, - text=text, - buttons=buttons, - ) - return dispatch_web_agent_edit_event(user_id=user_id, event=event) - - WEB_AGENT_SESSION_PREFIX = "web-agent:" WEB_AGENT_SOURCE = "web-agent" WEB_AGENT_FILE_TTL_SECONDS = 6 * 60 * 60 @@ -1248,13 +963,13 @@ def build_web_agent_choice_event(message: Message) -> Optional[dict[str, Any]]: :param message: Agent 工具发出的按钮通知 :return: 选择卡片事件,按钮为空时返回 None """ - button_rows = normalize_web_agent_button_rows(message.buttons) + button_rows = web_agent_events.normalize_web_agent_button_rows(message.buttons) buttons = [button for row in button_rows for button in row] if not buttons: return None choice_id = None - parsed = parse_agent_choice_callback(buttons[0]["callback_data"]) + parsed = agent_interaction.parse_agent_choice_callback(buttons[0]["callback_data"]) if parsed: choice_id = parsed[0] @@ -1278,12 +993,12 @@ def resolve_web_agent_choice_payload(callback_data: str, user_id: str) -> Option :param user_id: 当前登录用户 ID :return: 可返回给前端的数据,选择无效时返回 None """ - parsed = parse_agent_choice_callback(callback_data) + parsed = agent_interaction.parse_agent_choice_callback(callback_data) if not parsed: return None request_id, option_index = parsed - resolved = agent_interaction_manager.resolve( + resolved = agent_interaction.agent_interaction_manager.resolve( request_id=request_id, option_index=option_index, user_id=str(user_id), @@ -1292,7 +1007,7 @@ def resolve_web_agent_choice_payload(callback_data: str, user_id: str) -> Option return None request, option = resolved - buttons, button_rows = build_agent_choice_button_rows(request) + buttons, button_rows = agent_interaction.build_agent_choice_button_rows(request) selected_description = option.description or option.label return { "message": option.value, @@ -1577,8 +1292,8 @@ async def collect_web_agent_traditional_events( edit_queue: Queue[dict[str, Any]] = Queue() user_id = str(current_user.id) - attach_web_agent_message_queue(user_id, message_queue) - attach_web_agent_edit_queue(user_id, edit_queue) + web_agent_events.attach_web_agent_message_queue(user_id, message_queue) + web_agent_events.attach_web_agent_edit_queue(user_id, edit_queue) try: await run_in_threadpool( _handle_web_agent_message, @@ -1616,14 +1331,14 @@ async def collect_web_agent_traditional_events( break continue - if not is_web_agent_message_for_user(message, user_id): + if not web_agent_events.is_web_agent_message_for_user(message, user_id): continue events.extend(await build_web_agent_message_events_async(message)) idle_deadline = time.monotonic() + WEB_AGENT_TRADITIONAL_IDLE_TIMEOUT_SECONDS return events finally: - detach_web_agent_message_queue(user_id, message_queue) - detach_web_agent_edit_queue(user_id, edit_queue) + web_agent_events.detach_web_agent_message_queue(user_id, message_queue) + web_agent_events.detach_web_agent_edit_queue(user_id, edit_queue) def build_web_agent_traditional_callback_payload( @@ -1819,7 +1534,7 @@ async def build_web_agent_stream( } ) ) - from app.application.messaging.webagentstream import ( + from app.application.messaging.webagent.stream import ( WebAgentStreamDependencies, _build_steering_ack_stream, build_agent_web_agent_stream, diff --git a/app/application/messaging/channel/__init__.py b/app/application/messaging/channel/__init__.py new file mode 100644 index 000000000..4bf55c6f4 --- /dev/null +++ b/app/application/messaging/channel/__init__.py @@ -0,0 +1 @@ +"""消息渠道共享应用契约。""" diff --git a/app/application/messaging/channel_admin.py b/app/application/messaging/channel/admin.py similarity index 100% rename from app/application/messaging/channel_admin.py rename to app/application/messaging/channel/admin.py diff --git a/app/application/messaging/interaction.py b/app/application/messaging/interaction/__init__.py similarity index 100% rename from app/application/messaging/interaction.py rename to app/application/messaging/interaction/__init__.py diff --git a/app/application/messaging/agent_interaction.py b/app/application/messaging/interaction/agent.py similarity index 100% rename from app/application/messaging/agent_interaction.py rename to app/application/messaging/interaction/agent.py diff --git a/app/application/messaging/webagent/__init__.py b/app/application/messaging/webagent/__init__.py new file mode 100644 index 000000000..91b60419b --- /dev/null +++ b/app/application/messaging/webagent/__init__.py @@ -0,0 +1 @@ +"""WebAgent 消息事件与流编排子域。""" diff --git a/app/application/messaging/webagent/events.py b/app/application/messaging/webagent/events.py new file mode 100644 index 000000000..8a7f684b5 --- /dev/null +++ b/app/application/messaging/webagent/events.py @@ -0,0 +1,251 @@ +"""WebAgent 通知与原消息编辑事件桥接。""" + +import copy +from queue import Queue +from threading import Lock +from typing import Any, Optional, Union + +from app.runtime.log import logger +from app.schemas.message import Message +from app.schemas.types import NotificationChannel + +_WEB_AGENT_EDIT_QUEUES: dict[str, list[Queue[dict[str, Any]]]] = {} +_WEB_AGENT_EDIT_LOCK = Lock() +_WEB_AGENT_MESSAGE_QUEUES: dict[str, list[Queue[Message]]] = {} +_WEB_AGENT_MESSAGE_LOCK = Lock() + + +def normalize_web_agent_button_rows( + buttons: Optional[list[list[dict[str, Any]]]], +) -> list[list[dict[str, Any]]]: + """将消息按钮转换为 WebAgent 前端可识别的按钮行。""" + button_rows: list[list[dict[str, Any]]] = [] + for row in buttons or []: + normalized_row = [] + for button in row or []: + label = str(button.get("text") or button.get("label") or "").strip() + callback_data = str(button.get("callback_data") or "").strip() + if not label or not callback_data: + continue + normalized_button = { + "label": label, + "callback_data": callback_data, + } + if button.get("description"): + normalized_button["description"] = str(button.get("description")) + normalized_row.append(normalized_button) + if normalized_row: + button_rows.append(normalized_row) + return button_rows + + +def _resolve_web_agent_choice_id( + message_id: Union[str, int], + button_rows: list[list[dict[str, Any]]], +) -> str: + """从按钮回调中提取稳定的 WebAgent 选项 ID。""" + for row in button_rows: + for button in row: + callback_data = str(button.get("callback_data") or "").strip() + if not callback_data: + continue + parts = callback_data.split(":") + if len(parts) >= 2 and parts[1]: + return parts[1] + return callback_data + return str(message_id) + + +def build_web_agent_message_update_event( + *, + message_id: Union[str, int], + title: Optional[str], + text: str, + buttons: Optional[list[list[dict[str, Any]]]], +) -> dict[str, Any]: + """构造可应用到 WebAgent 原消息的 SSE 更新事件。""" + button_rows = normalize_web_agent_button_rows(buttons) + content_parts = [part for part in (title, text) if part] + target_message = { + "id": str(message_id), + "content": "" if button_rows else "\n\n".join(content_parts), + "choices": [], + "attachments": [], + "tools": [], + "status": "done", + } + if button_rows: + target_message["choices"].append( + { + "id": _resolve_web_agent_choice_id(message_id, button_rows), + "title": title, + "prompt": text or "", + "buttons": [button for row in button_rows for button in row], + "button_rows": button_rows, + "status": "pending", + } + ) + return { + "type": "message_update", + "target_message": target_message, + } + + +def extract_web_agent_message_from_event_data( + data: dict[str, Any], +) -> Optional[Message]: + """从兼容新旧结构的 NoticeMessage 事件数据中提取 WebAgent 通知。""" + if not isinstance(data, dict): + return None + try: + message = data.get("message") + if isinstance(message, Message): + resolved_message = message + elif isinstance(message, dict): + message_data = copy.deepcopy(message) + message_data.pop("type", None) + resolved_message = Message(**message_data) + else: + message_data = copy.deepcopy(data) + message_data.pop("type", None) + message_data.pop("current_time", None) + resolved_message = Message(**message_data) + except Exception as err: + logger.debug(f"解析WebAgent通知事件失败: {err}") + return None + + channel = resolved_message.channel + channel_value = ( + channel.value if isinstance(channel, NotificationChannel) else channel + ) + if channel_value != NotificationChannel.WebAgent.value: + return None + return resolved_message + + +def is_web_agent_message_for_user(message: Message, user_id: str) -> bool: + """判断 NoticeMessage 事件是否属于当前 WebAgent 用户。""" + try: + target_user = message.userid + return target_user is None or str(target_user) == str(user_id) + except Exception: + return False + + +def _get_web_agent_message_user_id(message: Message) -> Optional[str]: + """返回 WebAgent 通知的目标用户 ID,无目标时返回 None。""" + try: + channel = message.channel + channel_value = ( + channel.value if isinstance(channel, NotificationChannel) else channel + ) + if channel_value != NotificationChannel.WebAgent.value: + return None + user_id = message.userid + return str(user_id) if user_id is not None else None + except Exception: + return None + + +def dispatch_web_agent_message_event(event: object) -> None: + """将 WebAgent NoticeMessage 分发给正在等待的请求队列。""" + event_data = getattr(event, "event_data", None) + data = event_data if isinstance(event_data, dict) else {} + message = extract_web_agent_message_from_event_data(data) + if not message: + return + with _WEB_AGENT_MESSAGE_LOCK: + user_id = _get_web_agent_message_user_id(message) + if user_id is None: + queues = [ + message_queue + for user_queues in _WEB_AGENT_MESSAGE_QUEUES.values() + for message_queue in user_queues + ] + else: + queues = list(_WEB_AGENT_MESSAGE_QUEUES.get(user_id) or []) + for message_queue in queues: + message_queue.put(message) + + +def attach_web_agent_message_queue( + user_id: str, + message_queue: Queue[Message], +) -> None: + """为当前 WebAgent 请求挂载通知收集队列。""" + with _WEB_AGENT_MESSAGE_LOCK: + _WEB_AGENT_MESSAGE_QUEUES.setdefault(str(user_id), []).append(message_queue) + + +def detach_web_agent_message_queue( + user_id: str, + message_queue: Queue[Message], +) -> None: + """移除当前 WebAgent 请求的通知收集队列。""" + with _WEB_AGENT_MESSAGE_LOCK: + queues = _WEB_AGENT_MESSAGE_QUEUES.get(str(user_id)) + if not queues: + return + _WEB_AGENT_MESSAGE_QUEUES[str(user_id)] = [ + item for item in queues if item is not message_queue + ] + if not _WEB_AGENT_MESSAGE_QUEUES[str(user_id)]: + _WEB_AGENT_MESSAGE_QUEUES.pop(str(user_id), None) + + +def attach_web_agent_edit_queue( + user_id: str, + edit_queue: Queue[dict[str, Any]], +) -> None: + """为当前 WebAgent 请求挂载原消息编辑事件队列。""" + with _WEB_AGENT_EDIT_LOCK: + _WEB_AGENT_EDIT_QUEUES.setdefault(str(user_id), []).append(edit_queue) + + +def detach_web_agent_edit_queue( + user_id: str, + edit_queue: Queue[dict[str, Any]], +) -> None: + """移除当前 WebAgent 请求的原消息编辑事件队列。""" + with _WEB_AGENT_EDIT_LOCK: + queues = _WEB_AGENT_EDIT_QUEUES.get(str(user_id)) + if not queues: + return + _WEB_AGENT_EDIT_QUEUES[str(user_id)] = [ + item for item in queues if item is not edit_queue + ] + if not _WEB_AGENT_EDIT_QUEUES[str(user_id)]: + _WEB_AGENT_EDIT_QUEUES.pop(str(user_id), None) + + +def dispatch_web_agent_edit_event( + *, + user_id: str, + event: dict[str, Any], +) -> bool: + """将 WebAgent 原消息编辑事件分发给正在等待的请求队列。""" + with _WEB_AGENT_EDIT_LOCK: + queues = list(_WEB_AGENT_EDIT_QUEUES.get(str(user_id)) or []) + for edit_queue in queues: + edit_queue.put(event) + return bool(queues) + + +def edit_web_agent_message( + *, + user_id: str, + message_id: Union[str, int], + title: Optional[str], + text: str, + buttons: Optional[list[list[dict[str, Any]]]] = None, +) -> bool: + """构造并投递 WebAgent 原消息更新事件。""" + if not user_id: + return False + event = build_web_agent_message_update_event( + message_id=message_id, + title=title, + text=text, + buttons=buttons, + ) + return dispatch_web_agent_edit_event(user_id=user_id, event=event) diff --git a/app/application/messaging/webagentstream.py b/app/application/messaging/webagent/stream.py similarity index 100% rename from app/application/messaging/webagentstream.py rename to app/application/messaging/webagent/stream.py diff --git a/app/chain/_messaging.py b/app/chain/_messaging.py index ad9bb4514..9ad3f095c 100644 --- a/app/chain/_messaging.py +++ b/app/chain/_messaging.py @@ -549,7 +549,9 @@ class NotificationMixin: """ if channel == NotificationChannel.WebAgent: try: - from app.application.messaging.agent import edit_web_agent_message + from app.application.messaging.webagent.events import ( + edit_web_agent_message, + ) return edit_web_agent_message( user_id=str((metadata or {}).get("userid") or ""), diff --git a/app/chain/message.py b/app/chain/message.py index aca25e40c..6530cdec4 100644 --- a/app/chain/message.py +++ b/app/chain/message.py @@ -19,7 +19,7 @@ from app.application.agent import ( transcribe_audio, ) from app.application.messaging import router as interaction_router -from app.application.messaging.agent_interaction import ( +from app.application.messaging.interaction.agent import ( agent_interaction_manager, parse_agent_choice_callback, ) diff --git a/app/chain/transfer/execution.py b/app/chain/transfer/execution.py index 47ac0b8bb..407fd027f 100644 --- a/app/chain/transfer/execution.py +++ b/app/chain/transfer/execution.py @@ -7,7 +7,7 @@ from pathlib import Path from typing import Any, Callable, Mapping, Optional, Tuple, Union, cast from app.application.directory import DirectoryHelper -from app.application.history import ( +from app.application.history.retry import ( max_failed_retries, ) from app.application.transfer.execution import ( diff --git a/app/chain/transfer/filter.py b/app/chain/transfer/filter.py index 887f015ba..19cf704d5 100644 --- a/app/chain/transfer/filter.py +++ b/app/chain/transfer/filter.py @@ -16,8 +16,8 @@ from app.application.history import ( DownloadHistorySnapshot, TransferHistoryRepository, TransferHistorySnapshot, - resolve_history, ) +from app.application.history.retry import resolve_history from app.application.transfer.workflow import TransferTask from app.chain._contracts import TransferMixinHost from app.chain.media import MediaChain diff --git a/app/chain/transfer/format.py b/app/chain/transfer/format.py index c6729dd29..6d3799bf0 100644 --- a/app/chain/transfer/format.py +++ b/app/chain/transfer/format.py @@ -7,7 +7,7 @@ from app.application.configuration import ( get_configured_system_config, ) from app.application.formatting import EpisodeFormatRuleHelper -from app.application.history import max_failed_retries +from app.application.history.retry import max_failed_retries from app.application.transfer.feedback import TransferFailureNotification, classify_transfer_failure from app.application.transfer.workflow import TransferTask from app.chain._contracts import TransferMixinHost diff --git a/app/chain/transfer/records.py b/app/chain/transfer/records.py index e3edd2510..b35df2ed0 100644 --- a/app/chain/transfer/records.py +++ b/app/chain/transfer/records.py @@ -13,9 +13,8 @@ from app.application.history import ( DownloadHistorySnapshot, TransferHistoryRepository, TransferHistorySnapshot, - clear_transfer_failures, - resolve_history, ) +from app.application.history.retry import clear_transfer_failures, resolve_history from app.application.transfer.execution import ( TransferExecutionRepository, ) diff --git a/app/chain/transfer/settlement.py b/app/chain/transfer/settlement.py index e8b565e47..4b3ac1144 100644 --- a/app/chain/transfer/settlement.py +++ b/app/chain/transfer/settlement.py @@ -11,6 +11,8 @@ from app.application.history import ( TransferHistoryStagingPort, add_transfer_fail, add_transfer_success, +) +from app.application.history.retry import ( clear_transfer_failures, max_failed_retries, next_failed_retry_count, diff --git a/app/chain/transfer/workflow.py b/app/chain/transfer/workflow.py index 4b01604f9..21b07f6e5 100644 --- a/app/chain/transfer/workflow.py +++ b/app/chain/transfer/workflow.py @@ -12,7 +12,7 @@ from app.application.classification.reference import ( from app.application.configuration import get_configured_system_config from app.application.directory import DirectoryHelper from app.application.formatting import FormatParser -from app.application.history import ( +from app.application.history.retry import ( describe_history_gate, evaluate_history_gate, is_skip_action, diff --git a/app/db/adapters/history/transfer.py b/app/db/adapters/history/transfer.py index b8008d3d6..d92fd6c5c 100644 --- a/app/db/adapters/history/transfer.py +++ b/app/db/adapters/history/transfer.py @@ -15,6 +15,8 @@ from app.application.history import ( TransferHistorySnapshot, TransferHistoryStatisticSnapshot, TransferHistoryWrite, +) +from app.application.history.retry import ( failed_retry_count, max_failed_retries, ) diff --git a/app/modules/_base/notification.py b/app/modules/_base/notification.py index 40a503a51..ce8caa125 100644 --- a/app/modules/_base/notification.py +++ b/app/modules/_base/notification.py @@ -7,7 +7,7 @@ import copy from typing import Dict, List, Optional, Tuple, Union -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, resolve_config_principal_ids, ) diff --git a/app/modules/discord/__init__.py b/app/modules/discord/__init__.py index 4b0e2f9d2..8362fc435 100644 --- a/app/modules/discord/__init__.py +++ b/app/modules/discord/__init__.py @@ -3,7 +3,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union from urllib.parse import quote, unquote from app.domain.context import MediaInfo, Context -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/feishu/__init__.py b/app/modules/feishu/__init__.py index 168ca6fda..9ddbd7406 100644 --- a/app/modules/feishu/__init__.py +++ b/app/modules/feishu/__init__.py @@ -1,7 +1,7 @@ from typing import Any, List, Optional, Tuple, Union from app.domain.context import Context, MediaInfo -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( register_channel_admin_resolver, resolve_config_principal_ids, ) diff --git a/app/modules/feishu/feishu.py b/app/modules/feishu/feishu.py index 468a8032e..6cdd1e2ee 100644 --- a/app/modules/feishu/feishu.py +++ b/app/modules/feishu/feishu.py @@ -51,7 +51,7 @@ from lark_oapi.event.callback.model.p2_card_action_trigger import ( ) from app.adapters.network.http import RequestUtils -from app.application.messaging.channel_admin import matches_channel_admin +from app.application.messaging.channel.admin import matches_channel_admin from app.application.messaging.ingress import submit_message_to_host from app.application.security.user import get_configured_user_channel_lookup from app.domain.context import Context, MediaInfo diff --git a/app/modules/qqbot/module.py b/app/modules/qqbot/module.py index 7858bc857..a1271a97d 100644 --- a/app/modules/qqbot/module.py +++ b/app/modules/qqbot/module.py @@ -9,7 +9,7 @@ from urllib.parse import quote, unquote from typing import Optional, List, Tuple, Union, Any from app.domain.context import MediaInfo, Context -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/slack/__init__.py b/app/modules/slack/__init__.py index 8c6850508..d1955cd82 100644 --- a/app/modules/slack/__init__.py +++ b/app/modules/slack/__init__.py @@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union from urllib.parse import quote, unquote from app.domain.context import MediaInfo, Context -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/synologychat/__init__.py b/app/modules/synologychat/__init__.py index 33b499ef3..54e830bc7 100644 --- a/app/modules/synologychat/__init__.py +++ b/app/modules/synologychat/__init__.py @@ -3,7 +3,7 @@ from typing import Optional, Union, List, Tuple, Any from urllib.parse import quote, unquote from app.domain.context import MediaInfo, Context -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/telegram/module.py b/app/modules/telegram/module.py index b8438ed6e..32f6ed078 100644 --- a/app/modules/telegram/module.py +++ b/app/modules/telegram/module.py @@ -3,7 +3,7 @@ import re from typing import Optional, Union, List, Tuple, Any from app.domain.context import MediaInfo, Context -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/vocechat/__init__.py b/app/modules/vocechat/__init__.py index 8003531a7..7ec109934 100644 --- a/app/modules/vocechat/__init__.py +++ b/app/modules/vocechat/__init__.py @@ -3,7 +3,7 @@ from urllib.parse import quote, unquote from typing import Optional, Union, List, Tuple, Any, Dict from app.domain.context import Context, MediaInfo -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/wechat/__init__.py b/app/modules/wechat/__init__.py index 9db3f766b..2e5e5b570 100644 --- a/app/modules/wechat/__init__.py +++ b/app/modules/wechat/__init__.py @@ -5,7 +5,7 @@ from typing import Optional, Union, List, Tuple, Any, Dict from urllib.parse import quote from app.domain.context import Context, MediaInfo -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/modules/wechat/wechatbot.py b/app/modules/wechat/wechatbot.py index c70ece143..23106a938 100644 --- a/app/modules/wechat/wechatbot.py +++ b/app/modules/wechat/wechatbot.py @@ -12,7 +12,7 @@ import websocket from Crypto.Cipher import AES from app.adapters.network.http import RequestUtils -from app.application.messaging.channel_admin import matches_channel_admin +from app.application.messaging.channel.admin import matches_channel_admin from app.application.messaging.ingress import submit_message_to_host from app.domain.context import Context, MediaInfo from app.domain.metainfo import MetaInfo diff --git a/app/modules/wechatclawbot/__init__.py b/app/modules/wechatclawbot/__init__.py index 846d3785a..1c4aa8372 100644 --- a/app/modules/wechatclawbot/__init__.py +++ b/app/modules/wechatclawbot/__init__.py @@ -3,7 +3,7 @@ from typing import Any, Dict, List, Optional, Tuple, Union from app.runtime.cache import TTLCache from app.domain.context import Context, MediaInfo -from app.application.messaging.channel_admin import ( +from app.application.messaging.channel.admin import ( matches_channel_admin, register_channel_admin_resolver, resolve_config_principal_ids, diff --git a/app/monitor/dispatcher.py b/app/monitor/dispatcher.py index 7891055f0..15bb6a0fd 100644 --- a/app/monitor/dispatcher.py +++ b/app/monitor/dispatcher.py @@ -7,10 +7,12 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, cast from app.adapters.system.fsproxy import fsproxy from app.application.directory import DirectoryHelper from app.application.history import ( + get_transfer_history_repository, +) +from app.application.history.retry import ( HistoryGateAction, describe_history_gate, evaluate_history_gate, - get_transfer_history_repository, is_skip_action, max_failed_retries, resolve_history, diff --git a/app/startup/initializers/modules.py b/app/startup/initializers/modules.py index 548adaf87..5face7633 100644 --- a/app/startup/initializers/modules.py +++ b/app/startup/initializers/modules.py @@ -23,10 +23,10 @@ from app.application.configuration import ( reset_transfer_retry_config, ) from app.application.messaging.agent import ( - dispatch_web_agent_message_event, shutdown_web_agent_background_tasks, wait_web_agent_background_tasks, ) +from app.application.messaging.webagent.events import dispatch_web_agent_message_event from app.application.messaging.chat import ( get_configured_agent_chat_persistence, ) diff --git a/tests/test_agent_channel_admin_identity.py b/tests/test_agent_channel_admin_identity.py index 43527ba83..3457bd59e 100644 --- a/tests/test_agent_channel_admin_identity.py +++ b/tests/test_agent_channel_admin_identity.py @@ -4,7 +4,10 @@ from unittest.mock import Mock, patch import pytest -from app.application.messaging.agent import matches_channel_admin, resolve_config_principal_ids +from app.application.messaging.channel.admin import ( + matches_channel_admin, + resolve_config_principal_ids, +) from app.modules.discord import DiscordModule from app.modules.feishu.feishu import Feishu from app.modules.qqbot.module import QQBotModule diff --git a/tests/test_agent_interaction.py b/tests/test_agent_interaction.py index 58c683c53..5dae8c206 100644 --- a/tests/test_agent_interaction.py +++ b/tests/test_agent_interaction.py @@ -11,7 +11,7 @@ from app.agent.tools.impl.ask_user_choice import ( UserChoiceOptionInput, ) from app.agent.tools.impl.send_message import SendMessageTool -from app.application.messaging.agent import ( +from app.application.messaging.interaction.agent import ( AgentInteractionOption, agent_interaction_manager, ) diff --git a/tests/test_agent_message_routing.py b/tests/test_agent_message_routing.py index 6569bf1cc..6d0575918 100644 --- a/tests/test_agent_message_routing.py +++ b/tests/test_agent_message_routing.py @@ -9,8 +9,11 @@ from app.agent.tools.impl.ask_user_choice import ( UserChoiceOptionInput, ) from app.agent.tools.impl.send_message import SendMessageTool -from app.application.messaging.agent import AgentInteractionOption, agent_interaction_manager from app.application.messaging.interaction import InteractionContext +from app.application.messaging.interaction.agent import ( + AgentInteractionOption, + agent_interaction_manager, +) from app.application.messaging.media import media_interaction_manager from app.chain.message import MessageChain from app.db.models.message import Message diff --git a/tests/test_application_messaging_agent_architecture.py b/tests/test_application_messaging_agent_architecture.py index 1b25b3dd6..670766baf 100644 --- a/tests/test_application_messaging_agent_architecture.py +++ b/tests/test_application_messaging_agent_architecture.py @@ -7,8 +7,11 @@ from pathlib import Path PROJECT_ROOT = Path(__file__).parents[1] MESSAGING_ROOT = PROJECT_ROOT / "app" / "application" / "messaging" AGENT_FACADE_PATH = MESSAGING_ROOT / "agent.py" -AGENT_INTERACTION_PATH = MESSAGING_ROOT / "agent_interaction.py" -CHANNEL_ADMIN_PATH = MESSAGING_ROOT / "channel_admin.py" +AGENT_INTERACTION_PATH = MESSAGING_ROOT / "interaction" / "agent.py" +CHANNEL_ADMIN_PATH = MESSAGING_ROOT / "channel" / "admin.py" +WEB_AGENT_ROOT = MESSAGING_ROOT / "webagent" +WEB_AGENT_EVENTS_PATH = WEB_AGENT_ROOT / "events.py" +WEB_AGENT_STREAM_PATH = WEB_AGENT_ROOT / "stream.py" def _top_level_owners(path: Path) -> set[str]: @@ -22,7 +25,7 @@ def _top_level_owners(path: Path) -> set[str]: def test_agent_interaction_has_one_canonical_owner() -> None: - """Agent 选择交互只能在独立模块实现,旧入口保留对象级兼容导出。""" + """Agent 选择交互只能在独立模块实现,根模块不再暴露重复入口。""" names = { "AgentInteractionManager", "AgentInteractionOption", @@ -33,17 +36,16 @@ def test_agent_interaction_has_one_canonical_owner() -> None: } facade = importlib.import_module("app.application.messaging.agent") interaction = importlib.import_module( - "app.application.messaging.agent_interaction" + "app.application.messaging.interaction.agent" ) assert names <= _top_level_owners(AGENT_INTERACTION_PATH) assert names.isdisjoint(_top_level_owners(AGENT_FACADE_PATH)) - for name in names | {"agent_interaction_manager"}: - assert getattr(facade, name) is getattr(interaction, name) + assert all(not hasattr(facade, name) for name in names | {"agent_interaction_manager"}) def test_channel_admin_has_one_canonical_owner() -> None: - """渠道管理员匹配只能在权限模块实现,旧 Agent 入口保留兼容导出。""" + """渠道管理员匹配只能在权限模块实现,根 Agent 模块不再暴露重复入口。""" names = { "matches_channel_admin", "register_channel_admin_resolver", @@ -51,10 +53,55 @@ def test_channel_admin_has_one_canonical_owner() -> None: } facade = importlib.import_module("app.application.messaging.agent") channel_admin = importlib.import_module( - "app.application.messaging.channel_admin" + "app.application.messaging.channel.admin" ) assert names <= _top_level_owners(CHANNEL_ADMIN_PATH) assert names.isdisjoint(_top_level_owners(AGENT_FACADE_PATH)) - for name in names: - assert getattr(facade, name) is getattr(channel_admin, name) + assert all(not hasattr(facade, name) for name in names) + + +def test_web_agent_event_bridge_has_one_canonical_owner() -> None: + """WebAgent 通知与编辑桥接只能在独立模块实现,根 Agent 模块不再暴露重复入口。""" + names = { + "attach_web_agent_edit_queue", + "attach_web_agent_message_queue", + "build_web_agent_message_update_event", + "detach_web_agent_edit_queue", + "detach_web_agent_message_queue", + "dispatch_web_agent_edit_event", + "dispatch_web_agent_message_event", + "edit_web_agent_message", + "extract_web_agent_message_from_event_data", + "is_web_agent_message_for_user", + "normalize_web_agent_button_rows", + } + facade = importlib.import_module("app.application.messaging.agent") + events = importlib.import_module( + "app.application.messaging.webagent.events" + ) + + assert names <= _top_level_owners(WEB_AGENT_EVENTS_PATH) + assert names.isdisjoint(_top_level_owners(AGENT_FACADE_PATH)) + assert all(not hasattr(facade, name) for name in names) + + +def test_web_agent_modules_share_one_subpackage() -> None: + """同前缀 WebAgent 实现集中在子包,根目录不得保留平级门面。""" + names = { + "WebAgentStreamDependencies", + "build_agent_web_agent_stream", + "submit_web_agent_steering", + } + canonical = importlib.import_module( + "app.application.messaging.webagent.stream" + ) + + assert names <= _top_level_owners(WEB_AGENT_STREAM_PATH) + assert {path.name for path in WEB_AGENT_ROOT.glob("*.py")} == { + "__init__.py", + "events.py", + "stream.py", + } + assert not list(MESSAGING_ROOT.glob("webagent*.py")) + assert all(hasattr(canonical, name) for name in names) diff --git a/tests/test_application_shared_utilities.py b/tests/test_application_shared_utilities.py index 68fc22bd4..da749d7fc 100644 --- a/tests/test_application_shared_utilities.py +++ b/tests/test_application_shared_utilities.py @@ -1,5 +1,6 @@ """Application 重复逻辑收敛后的共享纯函数回归测试。""" +from pathlib import Path from types import SimpleNamespace import pytest @@ -10,6 +11,47 @@ from app.domain.classification.conditions import condition_field_ids from app.schemas.category import ClassificationCondition, ClassificationConditionGroup +PROJECT_ROOT = Path(__file__).parents[1] + + +def test_application_refactor_modules_follow_single_word_leaf_names() -> None: + """本轮新增应用模块使用单词文件名,并按同一模块进入子目录。""" + application_root = PROJECT_ROOT / "app" / "application" + refactored_files = [ + application_root / "download" / "validation.py", + application_root / "history" / "__init__.py", + application_root / "history" / "contracts.py", + application_root / "history" / "mutation.py", + application_root / "history" / "retry.py", + application_root / "messaging" / "channel" / "__init__.py", + application_root / "messaging" / "channel" / "admin.py", + application_root / "messaging" / "interaction" / "__init__.py", + application_root / "messaging" / "interaction" / "agent.py", + application_root / "messaging" / "webagent" / "__init__.py", + application_root / "messaging" / "webagent" / "events.py", + application_root / "messaging" / "webagent" / "stream.py", + application_root / "server" / "payload.py", + application_root / "transfer" / "jobs.py", + application_root / "transfer" / "models.py", + application_root / "transfer" / "notifications.py", + application_root / "transfer" / "projection.py", + ] + assert all(path.is_file() for path in refactored_files) + assert all(path.stem == "__init__" or "_" not in path.stem for path in refactored_files) + + obsolete_files = [ + application_root / "history.py", + application_root / "history_contracts.py", + application_root / "history_retry.py", + application_root / "historymutation.py", + application_root / "messaging" / "agent_interaction.py", + application_root / "messaging" / "channel_admin.py", + application_root / "messaging" / "web_agent_events.py", + application_root / "messaging" / "webagentstream.py", + ] + assert all(not path.exists() for path in obsolete_files) + + def test_condition_field_ids_preserves_nested_declaration_order() -> None: """条件树公共遍历必须保留 all/any/not 的声明顺序。""" node = ClassificationConditionGroup( diff --git a/tests/test_architecture_dependencies.py b/tests/test_architecture_dependencies.py index 3e89a6e7d..210f05d62 100644 --- a/tests/test_architecture_dependencies.py +++ b/tests/test_architecture_dependencies.py @@ -806,7 +806,7 @@ def test_startup_composes_typed_chain_and_agent_data_contexts(): def test_download_history_ports_are_typed_detached_and_canonically_injected(): """下载历史宿主调用面只能消费冻结快照和显式事务 adapter。""" - history_path = APP_ROOT / "application" / "history.py" + history_path = APP_ROOT / "application" / "history" / "__init__.py" history_tree = ast.parse( history_path.read_text(encoding="utf-8"), filename=str(history_path), diff --git a/tests/test_manual_transfer_history.py b/tests/test_manual_transfer_history.py index 505f0af4a..8382ddb2b 100644 --- a/tests/test_manual_transfer_history.py +++ b/tests/test_manual_transfer_history.py @@ -12,6 +12,8 @@ from app.api.endpoints.transfer import ( ) from app.application.history import ( TransferHistoryWrite, +) +from app.application.history.retry import ( clear_transfer_failures, failed_retry_count, max_failed_retries, diff --git a/tests/test_monitor_dispatcher_history.py b/tests/test_monitor_dispatcher_history.py index ffc0d63f5..ba6d84457 100644 --- a/tests/test_monitor_dispatcher_history.py +++ b/tests/test_monitor_dispatcher_history.py @@ -3,7 +3,7 @@ from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock -from app.application.history import ( +from app.application.history.retry import ( clear_transfer_failures, record_transfer_failure, ) diff --git a/tests/test_transfer_failed_retry_budget.py b/tests/test_transfer_failed_retry_budget.py index 6f8e69b6a..1f57fb191 100644 --- a/tests/test_transfer_failed_retry_budget.py +++ b/tests/test_transfer_failed_retry_budget.py @@ -11,8 +11,10 @@ from unittest.mock import Mock from app import schemas from app.application.history import ( - HistoryGateAction, TransferHistoryMutationCommand, +) +from app.application.history.retry import ( + HistoryGateAction, clear_transfer_failures, evaluate_history_gate, failed_retry_count, diff --git a/tests/test_transfer_history_architecture.py b/tests/test_transfer_history_architecture.py index 96c94ee08..38d352cb1 100644 --- a/tests/test_transfer_history_architecture.py +++ b/tests/test_transfer_history_architecture.py @@ -6,9 +6,9 @@ from pathlib import Path PROJECT_ROOT = Path(__file__).parents[1] APP_ROOT = PROJECT_ROOT / "app" -HISTORY_APPLICATION_PATH = APP_ROOT / "application" / "history.py" -HISTORY_CONTRACTS_APPLICATION_PATH = APP_ROOT / "application" / "history_contracts.py" -HISTORY_RETRY_APPLICATION_PATH = APP_ROOT / "application" / "history_retry.py" +HISTORY_APPLICATION_PATH = APP_ROOT / "application" / "history" / "__init__.py" +HISTORY_CONTRACTS_APPLICATION_PATH = APP_ROOT / "application" / "history" / "contracts.py" +HISTORY_RETRY_APPLICATION_PATH = APP_ROOT / "application" / "history" / "retry.py" QUERY_APPLICATION_PATH = APP_ROOT / "application" / "query.py" HISTORY_ADAPTER_PACKAGE = APP_ROOT / "db" / "adapters" / "history" CANONICAL_CONSUMER_PATHS = ( @@ -127,7 +127,7 @@ def test_transfer_history_contract_has_one_canonical_owner() -> None: filename=str(HISTORY_APPLICATION_PATH), ) facade = importlib.import_module("app.application.history") - contracts = importlib.import_module("app.application.history_contracts") + contracts = importlib.import_module("app.application.history.contracts") assert { node.name @@ -193,7 +193,7 @@ def test_transfer_history_retires_dynamic_writer_facade() -> None: def test_history_retry_policy_has_one_canonical_owner() -> None: - """失败重试与查重闸逻辑只能由独立模块实现,旧模块仅保留兼容导出。""" + """失败重试与查重闸逻辑只能由独立模块实现,包入口不再转发。""" retry_tree = ast.parse( HISTORY_RETRY_APPLICATION_PATH.read_text(encoding="utf-8-sig"), filename=str(HISTORY_RETRY_APPLICATION_PATH), diff --git a/tests/test_transfer_history_gate.py b/tests/test_transfer_history_gate.py index faf609dba..41a3a6d85 100644 --- a/tests/test_transfer_history_gate.py +++ b/tests/test_transfer_history_gate.py @@ -8,8 +8,7 @@ from types import SimpleNamespace import pytest -from app.application import history as transfer_history_helper -from app.application.history import ( +from app.application.history.retry import ( HistoryGateAction, clear_transfer_failures, coerce_size, @@ -23,6 +22,7 @@ from app.application.history import ( record_transfer_failure, resolve_history, ) +from app.application.history import retry as transfer_history_helper from app.runtime.config import settings diff --git a/tests/test_transfer_job_manager.py b/tests/test_transfer_job_manager.py index bdffe7ce9..4bf7ea278 100644 --- a/tests/test_transfer_job_manager.py +++ b/tests/test_transfer_job_manager.py @@ -3,7 +3,7 @@ from pathlib import Path from types import SimpleNamespace from unittest.mock import MagicMock, patch -from app.application.history import ( +from app.application.history.retry import ( clear_transfer_failures, failed_retry_count, record_transfer_failure, diff --git a/tests/test_web_agent_stream.py b/tests/test_web_agent_stream.py index ccc05590d..c4d2d5aa4 100644 --- a/tests/test_web_agent_stream.py +++ b/tests/test_web_agent_stream.py @@ -20,16 +20,20 @@ from app.api.endpoints.agent import web_agent_stream from app.application.messaging import agent as agent_application from app.application.messaging.agent import ( _WEB_AGENT_FILE_REGISTRY, + configure_web_agent_message_runtime, + reset_web_agent_message_runtime, + wait_web_agent_background_tasks, +) +from app.application.messaging.interaction.agent import ( AgentInteractionOption, agent_interaction_manager, +) +from app.application.messaging.webagent.events import ( attach_web_agent_message_queue, build_web_agent_message_update_event, - configure_web_agent_message_runtime, detach_web_agent_message_queue, dispatch_web_agent_message_event, extract_web_agent_message_from_event_data, - reset_web_agent_message_runtime, - wait_web_agent_background_tasks, ) from app.application.messaging.agent import ( WebAgentEventPublisher as _WebAgentEventPublisher, @@ -81,7 +85,7 @@ from app.application.messaging.agent import ( ) from app.application.messaging.chat import AgentChatService, configure_agent_chat_service from app.application.messaging.skill import skill_interaction_manager -from app.application.messaging.webagentstream import ( +from app.application.messaging.webagent.stream import ( _build_steering_ack_stream, _build_web_agent_output_callback, _build_web_agent_steering_callback,